aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEnji Cooper <ngie@FreeBSD.org>2023-08-08 05:56:32 +0000
committerEnji Cooper <ngie@FreeBSD.org>2023-08-08 06:03:09 +0000
commit8ef491440fcaec96f899d73e08873426c78583a4 (patch)
tree842282f5843118e2e13ca96c08a6a915c7295684
parent1774e46c372e2c1e16d4bc78f81359605e15b1b6 (diff)
downloadsrc-vendor/google/googletest.tar.gz
src-vendor/google/googletest.zip
Import GoogleTest v1.14.0vendor/google/googletest
Imported via the following general commands: ``` git rm -rf * git archive --format=tar v1.14.0 | tar -xvf - -C /path/to/git/vendor/clone git commit -A ``` Obtained from: https://github.com/google/googletest
-rw-r--r--.github/ISSUE_TEMPLATE/00-bug_report.yml53
-rw-r--r--.github/ISSUE_TEMPLATE/10-feature_request.yml33
-rw-r--r--.github/ISSUE_TEMPLATE/config.yml5
-rw-r--r--.github/workflows/gtest-ci.yml43
-rw-r--r--.gitignore34
-rw-r--r--BUILD.bazel46
-rw-r--r--CMakeLists.txt19
-rw-r--r--CONTRIBUTING.md55
-rw-r--r--CONTRIBUTORS (renamed from googletest/CONTRIBUTORS)28
-rw-r--r--Makefile.am14
-rw-r--r--README.md178
-rw-r--r--WORKSPACE26
-rw-r--r--appveyor.yml154
-rwxr-xr-xci/build-linux-bazel.sh37
-rwxr-xr-xci/build-platformio.sh2
-rwxr-xr-xci/env-linux.sh41
-rwxr-xr-xci/install-linux.sh49
-rwxr-xr-xci/install-osx.sh40
-rwxr-xr-xci/install-platformio.sh5
-rw-r--r--ci/linux-presubmit.sh137
-rw-r--r--[-rwxr-xr-x]ci/macos-presubmit.sh (renamed from ci/get-nprocessors.sh)62
-rwxr-xr-xci/travis.sh44
-rw-r--r--ci/windows-presubmit.bat58
-rw-r--r--configure.ac16
-rw-r--r--docs/_config.yml1
-rw-r--r--docs/_data/navigation.yml43
-rw-r--r--docs/_layouts/default.html58
-rw-r--r--docs/_sass/main.scss200
-rw-r--r--docs/advanced.md (renamed from googletest/docs/advanced.md)1191
-rw-r--r--docs/assets/css/style.scss5
-rw-r--r--docs/community_created_documentation.md7
-rw-r--r--docs/faq.md (renamed from googletest/docs/faq.md)229
-rw-r--r--docs/gmock_cheat_sheet.md241
-rw-r--r--docs/gmock_cook_book.md (renamed from googlemock/docs/cook_book.md)892
-rw-r--r--docs/gmock_faq.md (renamed from googlemock/docs/gmock_faq.md)20
-rw-r--r--docs/gmock_for_dummies.md (renamed from googlemock/docs/for_dummies.md)110
-rw-r--r--docs/index.md22
-rw-r--r--docs/pkgconfig.md144
-rw-r--r--docs/platforms.md8
-rw-r--r--docs/primer.md (renamed from googletest/docs/primer.md)260
-rw-r--r--docs/quickstart-bazel.md153
-rw-r--r--docs/quickstart-cmake.md157
-rw-r--r--docs/reference/actions.md115
-rw-r--r--docs/reference/assertions.md633
-rw-r--r--docs/reference/matchers.md302
-rw-r--r--docs/reference/mocking.md589
-rw-r--r--docs/reference/testing.md1432
-rw-r--r--docs/samples.md (renamed from googletest/docs/samples.md)4
-rw-r--r--googlemock/CMakeLists.txt58
-rw-r--r--googlemock/CONTRIBUTORS40
-rw-r--r--googlemock/LICENSE28
-rw-r--r--googlemock/README.md48
-rw-r--r--googlemock/cmake/gmock.pc.in9
-rw-r--r--googlemock/cmake/gmock_main.pc.in9
-rw-r--r--googlemock/docs/README.md4
-rw-r--r--googlemock/docs/cheat_sheet.md781
-rw-r--r--googlemock/include/gmock/gmock-actions.h1593
-rw-r--r--googlemock/include/gmock/gmock-cardinalities.h18
-rw-r--r--googlemock/include/gmock/gmock-function-mocker.h445
-rw-r--r--googlemock/include/gmock/gmock-generated-actions.h1884
-rw-r--r--googlemock/include/gmock/gmock-generated-actions.h.pump627
-rw-r--r--googlemock/include/gmock/gmock-generated-function-mockers.h752
-rw-r--r--googlemock/include/gmock/gmock-generated-function-mockers.h.pump227
-rw-r--r--googlemock/include/gmock/gmock-generated-matchers.h1097
-rw-r--r--googlemock/include/gmock/gmock-generated-matchers.h.pump346
-rw-r--r--googlemock/include/gmock/gmock-matchers.h2047
-rw-r--r--googlemock/include/gmock/gmock-more-actions.h708
-rw-r--r--googlemock/include/gmock/gmock-more-matchers.h74
-rw-r--r--googlemock/include/gmock/gmock-nice-strict.h222
-rw-r--r--googlemock/include/gmock/gmock-spec-builders.h827
-rw-r--r--googlemock/include/gmock/gmock.h17
-rw-r--r--googlemock/include/gmock/internal/custom/README.md2
-rw-r--r--googlemock/include/gmock/internal/custom/gmock-generated-actions.h13
-rw-r--r--googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump12
-rw-r--r--googlemock/include/gmock/internal/custom/gmock-matchers.h13
-rw-r--r--googlemock/include/gmock/internal/custom/gmock-port.h11
-rw-r--r--googlemock/include/gmock/internal/gmock-internal-utils.h264
-rw-r--r--googlemock/include/gmock/internal/gmock-port.h92
-rw-r--r--googlemock/include/gmock/internal/gmock-pp.h122
-rwxr-xr-xgooglemock/scripts/fuse_gmock_files.py240
-rw-r--r--googlemock/scripts/generator/LICENSE203
-rw-r--r--googlemock/scripts/generator/README34
-rw-r--r--googlemock/scripts/generator/README.cppclean115
-rwxr-xr-xgooglemock/scripts/generator/cpp/__init__.py0
-rwxr-xr-xgooglemock/scripts/generator/cpp/ast.py1736
-rwxr-xr-xgooglemock/scripts/generator/cpp/gmock_class.py227
-rwxr-xr-xgooglemock/scripts/generator/cpp/gmock_class_test.py466
-rwxr-xr-xgooglemock/scripts/generator/cpp/keywords.py59
-rwxr-xr-xgooglemock/scripts/generator/cpp/tokenize.py287
-rwxr-xr-xgooglemock/scripts/generator/cpp/utils.py41
-rwxr-xr-xgooglemock/scripts/generator/gmock_gen.py31
-rwxr-xr-xgooglemock/scripts/gmock-config.in303
-rwxr-xr-xgooglemock/scripts/gmock_doctor.py640
-rwxr-xr-xgooglemock/scripts/upload.py1387
-rwxr-xr-xgooglemock/scripts/upload_gmock.py78
-rw-r--r--googlemock/src/gmock-cardinalities.cc12
-rw-r--r--googlemock/src/gmock-internal-utils.cc119
-rw-r--r--googlemock/src/gmock-matchers.cc33
-rw-r--r--googlemock/src/gmock-spec-builders.cc259
-rw-r--r--googlemock/src/gmock.cc64
-rw-r--r--googlemock/src/gmock_main.cc16
-rw-r--r--googlemock/test/BUILD.bazel18
-rw-r--r--googlemock/test/gmock-actions_test.cc1076
-rw-r--r--googlemock/test/gmock-cardinalities_test.cc115
-rw-r--r--googlemock/test/gmock-function-mocker_nc.cc16
-rw-r--r--googlemock/test/gmock-function-mocker_nc_test.py43
-rw-r--r--googlemock/test/gmock-function-mocker_test.cc654
-rw-r--r--googlemock/test/gmock-generated-actions_test.cc1064
-rw-r--r--googlemock/test/gmock-generated-function-mockers_test.cc659
-rw-r--r--googlemock/test/gmock-generated-matchers_test.cc1324
-rw-r--r--googlemock/test/gmock-internal-utils_test.cc271
-rw-r--r--googlemock/test/gmock-matchers-arithmetic_test.cc1516
-rw-r--r--googlemock/test/gmock-matchers-comparisons_test.cc2361
-rw-r--r--googlemock/test/gmock-matchers-containers_test.cc3137
-rw-r--r--googlemock/test/gmock-matchers-misc_test.cc1823
-rw-r--r--googlemock/test/gmock-matchers_test.cc6801
-rw-r--r--googlemock/test/gmock-matchers_test.h192
-rw-r--r--googlemock/test/gmock-more-actions_test.cc986
-rw-r--r--googlemock/test/gmock-nice-strict_test.cc113
-rw-r--r--googlemock/test/gmock-port_test.cc2
-rw-r--r--googlemock/test/gmock-pp-string_test.cc3
-rw-r--r--googlemock/test/gmock-pp_test.cc10
-rw-r--r--googlemock/test/gmock-spec-builders_test.cc1115
-rw-r--r--googlemock/test/gmock_all_test.cc8
-rw-r--r--googlemock/test/gmock_ex_test.cc4
-rwxr-xr-xgooglemock/test/gmock_leak_test.py61
-rw-r--r--googlemock/test/gmock_leak_test_.cc8
-rw-r--r--googlemock/test/gmock_link2_test.cc1
-rw-r--r--googlemock/test/gmock_link_test.cc1
-rw-r--r--googlemock/test/gmock_link_test.h56
-rwxr-xr-xgooglemock/test/gmock_output_test.py19
-rw-r--r--googlemock/test/gmock_output_test_.cc83
-rw-r--r--googlemock/test/gmock_output_test_golden.txt32
-rw-r--r--googlemock/test/gmock_stress_test.cc53
-rw-r--r--googlemock/test/gmock_test.cc38
-rwxr-xr-xgooglemock/test/gmock_test_utils.py19
-rw-r--r--googletest/CMakeLists.txt76
-rw-r--r--googletest/LICENSE28
-rw-r--r--googletest/README.md217
-rw-r--r--googletest/cmake/gtest.pc.in7
-rw-r--r--googletest/cmake/gtest_main.pc.in9
-rw-r--r--googletest/cmake/internal_utils.cmake138
-rw-r--r--googletest/docs/README.md4
-rw-r--r--googletest/docs/pkgconfig.md141
-rw-r--r--googletest/docs/pump_manual.md190
-rw-r--r--googletest/include/gtest/gtest-assertion-result.h237
-rw-r--r--googletest/include/gtest/gtest-death-test.h122
-rw-r--r--googletest/include/gtest/gtest-matchers.h509
-rw-r--r--googletest/include/gtest/gtest-message.h72
-rw-r--r--googletest/include/gtest/gtest-param-test.h143
-rw-r--r--googletest/include/gtest/gtest-printers.h837
-rw-r--r--googletest/include/gtest/gtest-spi.h138
-rw-r--r--googletest/include/gtest/gtest-test-part.h26
-rw-r--r--googletest/include/gtest/gtest-typed-test.h121
-rw-r--r--googletest/include/gtest/gtest.h707
-rw-r--r--googletest/include/gtest/gtest_pred_impl.h206
-rw-r--r--googletest/include/gtest/gtest_prod.h15
-rw-r--r--googletest/include/gtest/internal/custom/README.md12
-rw-r--r--googletest/include/gtest/internal/custom/gtest-port.h6
-rw-r--r--googletest/include/gtest/internal/custom/gtest-printers.h6
-rw-r--r--googletest/include/gtest/internal/custom/gtest.h6
-rw-r--r--googletest/include/gtest/internal/gtest-death-test-internal.h87
-rw-r--r--googletest/include/gtest/internal/gtest-filepath.h42
-rw-r--r--googletest/include/gtest/internal/gtest-internal.h706
-rw-r--r--googletest/include/gtest/internal/gtest-param-util.h329
-rw-r--r--googletest/include/gtest/internal/gtest-port-arch.h117
-rw-r--r--googletest/include/gtest/internal/gtest-port.h1582
-rw-r--r--googletest/include/gtest/internal/gtest-string.h33
-rw-r--r--googletest/include/gtest/internal/gtest-type-util.h3337
-rw-r--r--googletest/include/gtest/internal/gtest-type-util.h.pump302
-rw-r--r--googletest/samples/prime_tables.h27
-rw-r--r--googletest/samples/sample1.cc4
-rw-r--r--googletest/samples/sample1.h6
-rw-r--r--googletest/samples/sample10_unittest.cc9
-rw-r--r--googletest/samples/sample1_unittest.cc11
-rw-r--r--googletest/samples/sample2.cc2
-rw-r--r--googletest/samples/sample2.h8
-rw-r--r--googletest/samples/sample2_unittest.cc4
-rw-r--r--googletest/samples/sample3-inl.h15
-rw-r--r--googletest/samples/sample3_unittest.cc11
-rw-r--r--googletest/samples/sample4.cc14
-rw-r--r--googletest/samples/sample4.h6
-rw-r--r--googletest/samples/sample4_unittest.cc2
-rw-r--r--googletest/samples/sample5_unittest.cc13
-rw-r--r--googletest/samples/sample6_unittest.cc12
-rw-r--r--googletest/samples/sample7_unittest.cc6
-rw-r--r--googletest/samples/sample8_unittest.cc8
-rw-r--r--googletest/samples/sample9_unittest.cc28
-rw-r--r--googletest/scripts/common.py83
-rwxr-xr-xgoogletest/scripts/fuse_gtest_files.py253
-rwxr-xr-xgoogletest/scripts/gen_gtest_pred_impl.py730
-rwxr-xr-xgoogletest/scripts/gtest-config.in274
-rwxr-xr-xgoogletest/scripts/pump.py855
-rwxr-xr-xgoogletest/scripts/release_docs.py158
-rw-r--r--googletest/scripts/test/Makefile59
-rwxr-xr-xgoogletest/scripts/upload.py1387
-rwxr-xr-xgoogletest/scripts/upload_gtest.py78
-rw-r--r--googletest/src/gtest-all.cc3
-rw-r--r--googletest/src/gtest-assertion-result.cc77
-rw-r--r--googletest/src/gtest-death-test.cc674
-rw-r--r--googletest/src/gtest-filepath.cc217
-rw-r--r--googletest/src/gtest-internal-inl.h335
-rw-r--r--googletest/src/gtest-matchers.cc33
-rw-r--r--googletest/src/gtest-port.cc513
-rw-r--r--googletest/src/gtest-printers.cc281
-rw-r--r--googletest/src/gtest-test-part.cc30
-rw-r--r--googletest/src/gtest-typed-test.cc34
-rw-r--r--googletest/src/gtest.cc2953
-rw-r--r--googletest/src/gtest_main.cc27
-rw-r--r--googletest/test/BUILD.bazel82
-rwxr-xr-xgoogletest/test/googletest-break-on-failure-unittest.py79
-rw-r--r--googletest/test/googletest-break-on-failure-unittest_.cc25
-rwxr-xr-xgoogletest/test/googletest-catch-exceptions-test.py261
-rw-r--r--googletest/test/googletest-catch-exceptions-test_.cc16
-rwxr-xr-xgoogletest/test/googletest-color-test.py70
-rw-r--r--googletest/test/googletest-color-test_.cc4
-rw-r--r--googletest/test/googletest-death-test-test.cc482
-rw-r--r--googletest/test/googletest-death-test_ex_test.cc31
-rwxr-xr-xgoogletest/test/googletest-env-var-test.py7
-rw-r--r--googletest/test/googletest-env-var-test_.cc36
-rwxr-xr-xgoogletest/test/googletest-failfast-unittest.py461
-rw-r--r--googletest/test/googletest-failfast-unittest_.cc166
-rw-r--r--googletest/test/googletest-filepath-test.cc220
-rwxr-xr-xgoogletest/test/googletest-filter-unittest.py439
-rw-r--r--googletest/test/googletest-filter-unittest_.cc71
-rw-r--r--googletest/test/googletest-global-environment-unittest.py141
-rw-r--r--googletest/test/googletest-global-environment-unittest_.cc58
-rw-r--r--googletest/test/googletest-json-outfiles-test.py165
-rw-r--r--googletest/test/googletest-json-output-unittest.py1216
-rwxr-xr-xgoogletest/test/googletest-list-tests-unittest.py102
-rw-r--r--googletest/test/googletest-list-tests-unittest_.cc93
-rw-r--r--googletest/test/googletest-listener-test.cc45
-rw-r--r--googletest/test/googletest-message-test.cc44
-rw-r--r--googletest/test/googletest-options-test.cc94
-rw-r--r--googletest/test/googletest-output-test-golden-lin.txt74
-rwxr-xr-xgoogletest/test/googletest-output-test.py179
-rw-r--r--googletest/test/googletest-output-test_.cc377
-rw-r--r--googletest/test/googletest-param-test-invalid-name1-test.py4
-rw-r--r--googletest/test/googletest-param-test-invalid-name1-test_.cc8
-rw-r--r--googletest/test/googletest-param-test-invalid-name2-test.py5
-rw-r--r--googletest/test/googletest-param-test-invalid-name2-test_.cc11
-rw-r--r--googletest/test/googletest-param-test-test.cc278
-rw-r--r--googletest/test/googletest-param-test-test.h12
-rw-r--r--googletest/test/googletest-param-test2-test.cc9
-rw-r--r--googletest/test/googletest-port-test.cc253
-rw-r--r--googletest/test/googletest-printers-test.cc860
-rwxr-xr-xgoogletest/test/googletest-setuptestsuite-test.py (renamed from ci/log-config.sh)43
-rw-r--r--googletest/test/googletest-setuptestsuite-test_.cc (renamed from googletest/test/googletest-test2_test.cc)37
-rwxr-xr-xgoogletest/test/googletest-shuffle-test.py203
-rw-r--r--googletest/test/googletest-shuffle-test_.cc6
-rw-r--r--googletest/test/googletest-test-part-test.cc22
-rwxr-xr-xgoogletest/test/googletest-throw-on-failure-test.py70
-rw-r--r--googletest/test/googletest-throw-on-failure-test_.cc10
-rwxr-xr-xgoogletest/test/googletest-uninitialized-test.py9
-rw-r--r--googletest/test/googletest-uninitialized-test_.cc5
-rw-r--r--googletest/test/gtest-typed-test2_test.cc7
-rw-r--r--googletest/test/gtest-typed-test_test.cc103
-rw-r--r--googletest/test/gtest-typed-test_test.h22
-rw-r--r--googletest/test/gtest-unittest-api_test.cc50
-rw-r--r--googletest/test/gtest_assert_by_exception_test.cc24
-rw-r--r--googletest/test/gtest_dirs_test.cc101
-rw-r--r--googletest/test/gtest_environment_test.cc23
-rwxr-xr-xgoogletest/test/gtest_help_test.py129
-rw-r--r--googletest/test/gtest_help_test_.cc3
-rw-r--r--googletest/test/gtest_json_test_utils.py4
-rw-r--r--googletest/test/gtest_list_output_unittest.py184
-rw-r--r--googletest/test/gtest_list_output_unittest_.cc26
-rw-r--r--googletest/test/gtest_main_unittest.cc4
-rw-r--r--googletest/test/gtest_pred_impl_unittest.cc1753
-rw-r--r--googletest/test/gtest_premature_exit_test.cc22
-rw-r--r--googletest/test/gtest_repeat_test.cc69
-rwxr-xr-xgoogletest/test/gtest_skip_check_output_test.py (renamed from ci/env-osx.sh)47
-rwxr-xr-xgoogletest/test/gtest_skip_environment_check_output_test.py5
-rw-r--r--googletest/test/gtest_skip_in_environment_setup_test.cc1
-rw-r--r--googletest/test/gtest_skip_test.cc10
-rw-r--r--googletest/test/gtest_sole_header_test.cc4
-rw-r--r--googletest/test/gtest_stress_test.cc31
-rw-r--r--googletest/test/gtest_test_macro_stack_footprint_test.cc58
-rwxr-xr-xgoogletest/test/gtest_test_utils.py130
-rwxr-xr-xgoogletest/test/gtest_testbridge_test.py4
-rw-r--r--googletest/test/gtest_testbridge_test_.cc1
-rw-r--r--googletest/test/gtest_throw_on_failure_ex_test.cc16
-rw-r--r--googletest/test/gtest_unittest.cc2531
-rw-r--r--googletest/test/gtest_xml_outfile2_test_.cc38
-rwxr-xr-xgoogletest/test/gtest_xml_outfiles_test.py48
-rwxr-xr-xgoogletest/test/gtest_xml_output_unittest.py326
-rw-r--r--googletest/test/gtest_xml_output_unittest_.cc23
-rwxr-xr-xgoogletest/test/gtest_xml_test_utils.py166
-rw-r--r--googletest/test/production.h7
-rw-r--r--googletest_deps.bzl22
-rw-r--r--library.json59
-rw-r--r--platformio.ini31
292 files changed, 37872 insertions, 45258 deletions
diff --git a/.github/ISSUE_TEMPLATE/00-bug_report.yml b/.github/ISSUE_TEMPLATE/00-bug_report.yml
new file mode 100644
index 000000000000..586779ad2d61
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/00-bug_report.yml
@@ -0,0 +1,53 @@
+name: Bug Report
+description: Let us know that something does not work as expected.
+title: "[Bug]: Please title this bug report"
+body:
+ - type: textarea
+ id: what-happened
+ attributes:
+ label: Describe the issue
+ description: What happened, and what did you expect to happen?
+ validations:
+ required: true
+ - type: textarea
+ id: steps
+ attributes:
+ label: Steps to reproduce the problem
+ description: It is important that we are able to reproduce the problem that you are experiencing. Please provide all code and relevant steps to reproduce the problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the problem are also helpful.
+ validations:
+ required: true
+ - type: textarea
+ id: version
+ attributes:
+ label: What version of GoogleTest are you using?
+ description: Please include the output of `git rev-parse HEAD` or the GoogleTest release version number that you are using.
+ validations:
+ required: true
+ - type: textarea
+ id: os
+ attributes:
+ label: What operating system and version are you using?
+ description: If you are using a Linux distribution please include the name and version of the distribution as well.
+ validations:
+ required: true
+ - type: textarea
+ id: compiler
+ attributes:
+ label: What compiler and version are you using?
+ description: Please include the output of `gcc -v` or `clang -v`, or the equivalent for your compiler.
+ validations:
+ required: true
+ - type: textarea
+ id: buildsystem
+ attributes:
+ label: What build system are you using?
+ description: Please include the output of `bazel --version` or `cmake --version`, or the equivalent for your build system.
+ validations:
+ required: true
+ - type: textarea
+ id: additional
+ attributes:
+ label: Additional context
+ description: Add any other context about the problem here.
+ validations:
+ required: false
diff --git a/.github/ISSUE_TEMPLATE/10-feature_request.yml b/.github/ISSUE_TEMPLATE/10-feature_request.yml
new file mode 100644
index 000000000000..f3bbc091e8e9
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/10-feature_request.yml
@@ -0,0 +1,33 @@
+name: Feature request
+description: Propose a new feature.
+title: "[FR]: Please title this feature request"
+labels: "enhancement"
+body:
+ - type: textarea
+ id: version
+ attributes:
+ label: Does the feature exist in the most recent commit?
+ description: We recommend using the latest commit from GitHub in your projects.
+ validations:
+ required: true
+ - type: textarea
+ id: why
+ attributes:
+ label: Why do we need this feature?
+ description: Ideally, explain why a combination of existing features cannot be used instead.
+ validations:
+ required: true
+ - type: textarea
+ id: proposal
+ attributes:
+ label: Describe the proposal.
+ description: Include a detailed description of the feature, with usage examples.
+ validations:
+ required: true
+ - type: textarea
+ id: platform
+ attributes:
+ label: Is the feature specific to an operating system, compiler, or build system version?
+ description: If it is, please specify which versions.
+ validations:
+ required: true
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 000000000000..65170d10a782
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,5 @@
+blank_issues_enabled: false
+contact_links:
+ - name: Get Help
+ url: https://github.com/google/googletest/discussions
+ about: Please ask and answer questions here.
diff --git a/.github/workflows/gtest-ci.yml b/.github/workflows/gtest-ci.yml
new file mode 100644
index 000000000000..03a8cc5e287b
--- /dev/null
+++ b/.github/workflows/gtest-ci.yml
@@ -0,0 +1,43 @@
+name: ci
+
+on:
+ push:
+ pull_request:
+
+env:
+ BAZEL_CXXOPTS: -std=c++14
+
+jobs:
+ Linux:
+ runs-on: ubuntu-latest
+ steps:
+
+ - uses: actions/checkout@v3
+ with:
+ fetch-depth: 0
+
+ - name: Tests
+ run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ...
+
+ macOS:
+ runs-on: macos-latest
+ steps:
+
+ - uses: actions/checkout@v3
+ with:
+ fetch-depth: 0
+
+ - name: Tests
+ run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ...
+
+
+ Windows:
+ runs-on: windows-latest
+ steps:
+
+ - uses: actions/checkout@v3
+ with:
+ fetch-depth: 0
+
+ - name: Tests
+ run: bazel test --cxxopt=/std:c++14 --features=external_include_paths --test_output=errors ...
diff --git a/.gitignore b/.gitignore
index 73cdd2c203ff..fede02f65093 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,6 +12,7 @@ bazel-testlogs
*.pyc
# Visual Studio files
+.vs
*.sdf
*.opensdf
*.VC.opendb
@@ -23,6 +24,10 @@ Win32-Release/
x64-Debug/
x64-Release/
+# VSCode files
+.cache/
+cmake-variants.yaml
+
# Ignore autoconf / automake files
Makefile.in
aclocal.m4
@@ -34,6 +39,7 @@ googletest/m4/ltoptions.m4
googletest/m4/ltsugar.m4
googletest/m4/ltversion.m4
googletest/m4/lt~obsolete.m4
+googlemock/m4
# Ignore generated directories.
googlemock/fused-src/
@@ -41,6 +47,8 @@ googletest/fused-src/
# macOS files
.DS_Store
+googletest/.DS_Store
+googletest/xcode/.DS_Store
# Ignore cmake generated directories and files.
CMakeFiles
@@ -52,3 +60,29 @@ googlemock/CTestTestfile.cmake
googlemock/Makefile
googlemock/cmake_install.cmake
googlemock/gtest
+/bin
+/googlemock/gmock.dir
+/googlemock/gmock_main.dir
+/googlemock/RUN_TESTS.vcxproj.filters
+/googlemock/RUN_TESTS.vcxproj
+/googlemock/INSTALL.vcxproj.filters
+/googlemock/INSTALL.vcxproj
+/googlemock/gmock_main.vcxproj.filters
+/googlemock/gmock_main.vcxproj
+/googlemock/gmock.vcxproj.filters
+/googlemock/gmock.vcxproj
+/googlemock/gmock.sln
+/googlemock/ALL_BUILD.vcxproj.filters
+/googlemock/ALL_BUILD.vcxproj
+/lib
+/Win32
+/ZERO_CHECK.vcxproj.filters
+/ZERO_CHECK.vcxproj
+/RUN_TESTS.vcxproj.filters
+/RUN_TESTS.vcxproj
+/INSTALL.vcxproj.filters
+/INSTALL.vcxproj
+/googletest-distribution.sln
+/CMakeCache.txt
+/ALL_BUILD.vcxproj.filters
+/ALL_BUILD.vcxproj
diff --git a/BUILD.bazel b/BUILD.bazel
index 9b48aee53081..b1e3b7fba89a 100644
--- a/BUILD.bazel
+++ b/BUILD.bazel
@@ -30,15 +30,38 @@
#
# 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 = ["@bazel_tools//platforms: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 = {
+ "@bazel_tools//tools/cpp:compiler": "msvc-cl",
+ },
+ visibility = [":__subpackages__"],
)
config_setting(
@@ -76,6 +99,7 @@ cc_library(
"googlemock/include/gmock/*.h",
]),
copts = select({
+ ":qnx": [],
":windows": [],
"//conditions:default": ["-pthread"],
}),
@@ -94,17 +118,33 @@ cc_library(
"googletest/include",
],
linkopts = select({
+ ":qnx": ["-lregex"],
":windows": [],
+ ":freebsd": [
+ "-lm",
+ "-pthread",
+ ],
+ ":openbsd": [
+ "-lm",
+ "-pthread",
+ ],
"//conditions:default": ["-pthread"],
}),
deps = select({
":has_absl": [
+ "@com_google_absl//absl/container:flat_hash_set",
"@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": [],
}),
diff --git a/CMakeLists.txt b/CMakeLists.txt
index f11bbb521e38..089ac987fb60 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,23 +1,13 @@
# Note: CMake support is community-based. The maintainers do not use CMake
# internally.
-cmake_minimum_required(VERSION 2.8.8)
-
-if (POLICY CMP0048)
- cmake_policy(SET CMP0048 NEW)
-endif (POLICY CMP0048)
+cmake_minimum_required(VERSION 3.13)
project(googletest-distribution)
-set(GOOGLETEST_VERSION 1.10.0)
+set(GOOGLETEST_VERSION 1.14.0)
-if (CMAKE_VERSION VERSION_LESS "3.1")
- add_definitions(-std=c++11)
-else()
- set(CMAKE_CXX_STANDARD 11)
- set(CMAKE_CXX_STANDARD_REQUIRED ON)
- if(NOT CYGWIN)
- 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()
@@ -28,6 +18,7 @@ include(GNUInstallDirs)
#Note that googlemock target already builds googletest
option(BUILD_GMOCK "Builds the googlemock subproject" ON)
option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON)
+option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF)
if(BUILD_GMOCK)
add_subdirectory( googlemock )
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 30c8d8900b6d..8bed14b2666d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -21,14 +21,14 @@ 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
1. Submit an issue describing your proposed change to the
- [issue tracker](https://github.com/google/googletest).
+ [issue tracker](https://github.com/google/googletest/issues).
2. Please don't mix more than one logical change per submittal, because it
makes the history hard to follow. If you want to make a change that doesn't
have a corresponding issue in the issue tracker, please create one.
@@ -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.
@@ -79,17 +80,17 @@ fairly rigid coding style, as defined by the
[google-styleguide](https://github.com/google/styleguide) project. All patches
will be expected to conform to the style outlined
[here](https://google.github.io/styleguide/cppguide.html). Use
-[.clang-format](https://github.com/google/googletest/blob/master/.clang-format)
-to check your formatting
+[.clang-format](https://github.com/google/googletest/blob/main/.clang-format) to
+check your formatting.
## Requirements for Contributors
If you plan to contribute a patch, you need to build Google Test, Google Mock,
and their own tests from a git checkout, which has further requirements:
-* [Python](https://www.python.org/) v2.3 or newer (for running some of the
+* [Python](https://www.python.org/) v3.6 or newer (for running some of the
tests and re-generating certain source files from templates)
-* [CMake](https://cmake.org/) v2.6.4 or newer
+* [CMake](https://cmake.org/) v2.8.12 or newer
## Developing Google Test and Google Mock
@@ -101,42 +102,40 @@ To make sure your changes work as intended and don't break existing
functionality, you'll want to compile and run Google Test and GoogleMock's own
tests. For that you can use CMake:
- mkdir mybuild
- cd mybuild
- cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR}
+```
+mkdir mybuild
+cd mybuild
+cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR}
+```
To choose between building only Google Test or Google Mock, you may modify your
cmake command to be one of each
- cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests
- cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests
+```
+cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests
+cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests
+```
Make sure you have Python installed, as some of Google Test's tests are written
in Python. If the cmake command complains about not being able to find Python
(`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it
explicitly where your Python executable can be found:
- cmake -DPYTHON_EXECUTABLE=path/to/python ...
+```
+cmake -DPYTHON_EXECUTABLE=path/to/python ...
+```
Next, you can build Google Test and / or Google Mock and all desired tests. On
\*nix, this is usually done by
- make
+```
+make
+```
To run the tests, do
- make test
+```
+make test
+```
All tests should pass.
-
-### Regenerating Source Files
-
-Some of Google Test's source files are generated from templates (not in the C++
-sense) using a script. For example, the file
-include/gtest/internal/gtest-type-util.h.pump is used to generate
-gtest-type-util.h in the same directory.
-
-You don't need to worry about regenerating the source files unless you need to
-modify them. You would then modify the corresponding `.pump` files and run the
-'[pump.py](googletest/scripts/pump.py)' generator script. See the
-[Pump Manual](googletest/docs/pump_manual.md).
diff --git a/googletest/CONTRIBUTORS b/CONTRIBUTORS
index feae2fc04410..77397a5b53fe 100644
--- a/googletest/CONTRIBUTORS
+++ b/CONTRIBUTORS
@@ -5,33 +5,61 @@
Ajay Joshi <jaj@google.com>
Balázs Dán <balazs.dan@gmail.com>
+Benoit Sigoure <tsuna@google.com>
Bharat Mediratta <bharat@menalto.com>
+Bogdan Piloca <boo@google.com>
Chandler Carruth <chandlerc@google.com>
Chris Prince <cprince@google.com>
Chris Taylor <taylorc@google.com>
Dan Egnor <egnor@google.com>
+Dave MacLachlan <dmaclach@gmail.com>
+David Anderson <danderson@google.com>
+Dean Sturtevant
Eric Roman <eroman@chromium.org>
+Gene Volovich <gv@cite.com>
Hady Zalek <hady.zalek@gmail.com>
+Hal Burch <gmock@hburch.com>
Jeffrey Yasskin <jyasskin@google.com>
+Jim Keller <jimkeller@google.com>
+Joe Walnes <joe@truemesh.com>
+Jon Wray <jwray@google.com>
Jói Sigurðsson <joi@google.com>
Keir Mierle <mierle@gmail.com>
Keith Ray <keith.ray@gmail.com>
Kenton Varda <kenton@google.com>
+Kostya Serebryany <kcc@google.com>
+Krystian Kuzniarek <krystian.kuzniarek@gmail.com>
+Lev Makhlis
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>
Miklós Fazekas <mfazekas@szemafor.com>
+Neal Norwitz <nnorwitz@gmail.com>
+Nermin Ozkiranartli <nermin@google.com>
+Owen Carlsen <ocarlsen@google.com>
+Paneendra Ba <paneendra@google.com>
Pasi Valminen <pasi.valminen@gmail.com>
Patrick Hanna <phanna@google.com>
Patrick Riley <pfr@google.com>
+Paul Menage <menage@google.com>
Peter Kaminski <piotrk@google.com>
+Piotr Kaminski <piotrk@google.com>
Preston Jackson <preston.a.jackson@gmail.com>
Rainer Klaffenboeck <rainer.klaffenboeck@dynatrace.com>
Russ Cox <rsc@google.com>
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>
Vlad Losev <vladl@google.com>
+Wolfgang Klier <wklier@google.com>
Zhanyong Wan <wan@google.com>
diff --git a/Makefile.am b/Makefile.am
deleted file mode 100644
index 433eefeb0802..000000000000
--- a/Makefile.am
+++ /dev/null
@@ -1,14 +0,0 @@
-## Process this file with automake to produce Makefile.in
-ACLOCAL_AMFLAGS = -I m4
-
-AUTOMAKE_OPTIONS = foreign
-
-# Build . before src so that our all-local and clean-local hooks kicks in at
-# the right time.
-SUBDIRS = googletest googlemock
-
-EXTRA_DIST = \
- BUILD.bazel \
- CMakeLists.txt \
- README.md \
- WORKSPACE
diff --git a/README.md b/README.md
index 5b417fa883fa..443e02069581 100644
--- a/README.md
+++ b/README.md
@@ -1,78 +1,103 @@
-# Google Test
+# GoogleTest
-#### OSS Builds Status:
+### Announcements
-[![Build Status](https://api.travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest)
-[![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master)
+#### Live at Head
-### Future Plans
+GoogleTest now follows the
+[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support).
+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).
+We do publish occasional semantic versions, tagged with
+`v${major}.${minor}.${patch}` (e.g. `v1.13.0`).
-#### 1.8.x Release:
+#### Documentation Updates
-[the 1.8.x](https://github.com/google/googletest/releases/tag/release-1.8.1) is
-the last release that works with pre-C++11 compilers. The 1.8.x will not accept
-any requests for any new features and any bugfix requests will only be accepted
-if proven "critical"
+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.
-#### Post 1.8.x:
+#### Release 1.13.0
-On-going work to improve/cleanup/pay technical debt. When this work is completed
-there will be a 1.9.x tagged release
+[Release 1.13.0](https://github.com/google/googletest/releases/tag/v1.13.0) is
+now available.
-#### Post 1.9.x
+The 1.13.x branch requires at least C++14.
-Post 1.9.x googletest will follow
-[Abseil Live at Head philosophy](https://abseil.io/about/philosophy)
+#### Continuous Integration
-## Welcome to **Google Test**, Google's C++ test framework!
+We use Google's internal systems for continuous integration. \
+GitHub Actions were added for the convenience of open-source contributors. They
+are exclusively maintained by the open-source community and not used by the
+GoogleTest team.
+
+#### Coming Soon
+
+* We are planning to take a dependency on
+ [Abseil](https://github.com/abseil/abseil-cpp).
+* More documentation improvements are planned.
+
+## Welcome to **GoogleTest**, Google's C++ test framework!
This repository is a merger of the formerly separate GoogleTest and GoogleMock
projects. These were so closely related that it makes sense to maintain and
release them together.
-Please subscribe to the mailing list at googletestframework@googlegroups.com for
-questions, discussions, and development.
-
-### Getting started:
-
-The information for **Google Test** is available in the
-[Google Test Primer](googletest/docs/primer.md) documentation.
+### Getting Started
-**Google Mock** is an extension to Google Test for writing and using C++ mock
-classes. See the separate [Google Mock documentation](googlemock/README.md).
+See the [GoogleTest User's Guide](https://google.github.io/googletest/) for
+documentation. We recommend starting with the
+[GoogleTest Primer](https://google.github.io/googletest/primer.html).
-More detailed documentation for googletest is in its interior
-[googletest/README.md](googletest/README.md) file.
+More information about building GoogleTest can be found at
+[googletest/README.md](googletest/README.md).
## Features
-* An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework.
-* Test discovery.
-* A rich set of assertions.
-* User-defined assertions.
-* Death tests.
-* Fatal and non-fatal failures.
-* Value-parameterized tests.
-* Type-parameterized tests.
-* Various options for running the tests.
-* XML test report generation.
-
-## Platforms
-
-Google test has been used on a variety of platforms:
-
-* Linux
-* Mac OS X
-* Windows
-* Cygwin
-* MinGW
-* Windows Mobile
-* Symbian
-* PlatformIO
-
-## Who Is Using Google Test?
-
-In addition to many internal projects at Google, Google Test is also used by the
+* xUnit test framework: \
+ Googletest is based on the [xUnit](https://en.wikipedia.org/wiki/XUnit)
+ testing framework, a popular architecture for unit testing
+* Test discovery: \
+ Googletest automatically discovers and runs your tests, eliminating the need
+ to manually register your tests
+* Rich set of assertions: \
+ Googletest provides a variety of assertions, such as equality, inequality,
+ exceptions, and more, making it easy to test your code
+* User-defined assertions: \
+ You can define your own assertions with Googletest, making it simple to
+ write tests that are specific to your code
+* Death tests: \
+ Googletest supports death tests, which verify that your code exits in a
+ certain way, making it useful for testing error-handling code
+* Fatal and non-fatal failures: \
+ You can specify whether a test failure should be treated as fatal or
+ non-fatal with Googletest, allowing tests to continue running even if a
+ failure occurs
+* Value-parameterized tests: \
+ Googletest supports value-parameterized tests, which run multiple times with
+ different input values, making it useful for testing functions that take
+ different inputs
+* Type-parameterized tests: \
+ Googletest also supports type-parameterized tests, which run with different
+ data types, making it useful for testing functions that work with different
+ data types
+* Various options for running tests: \
+ Googletest provides many options for running tests including running
+ individual tests, running tests in a specific order and running tests in
+ parallel
+
+## Supported Platforms
+
+GoogleTest follows Google's
+[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
+See
+[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
+for a list of currently supported versions of compilers, platforms, and build
+tools.
+
+## Who Is Using GoogleTest?
+
+In addition to many internal projects at Google, GoogleTest is also used by the
following notable projects:
* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser
@@ -81,8 +106,6 @@ following notable projects:
* [Protocol Buffers](https://github.com/google/protobuf), Google's data
interchange format.
* The [OpenCV](http://opencv.org/) computer vision library.
-* [tiny-dnn](https://github.com/tiny-dnn/tiny-dnn): header only,
- dependency-free deep learning framework in C++11.
## Related Open Source Projects
@@ -90,13 +113,13 @@ following notable projects:
automated test-runner and Graphical User Interface with powerful features for
Windows and Linux platforms.
-[Google Test UI](https://github.com/ospector/gtest-gbar) is test runner that
+[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 Google Test that implements the
+listener for GoogleTest that implements the
[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test
result output. If your test runner understands TAP, you may find it useful.
@@ -104,31 +127,20 @@ 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 Google Tests in a tree view, and
-run/debug your tests.
-
-## Requirements
-
-Google Test is designed to have fairly minimal requirements to build and use
-with your projects, but there are some. If you notice any problems on your
-platform, please notify
-[googletestframework@googlegroups.com](https://groups.google.com/forum/#!forum/googletestframework).
-Patches for fixing them are welcome!
-
-### Build Requirements
-
-These are the base requirements to build and use Google Test from a source
-package:
+is a VS Code extension allowing to view GoogleTest in a tree view and run/debug
+your tests.
-* [Bazel](https://bazel.build/) or [CMake](https://cmake.org/). NOTE: Bazel is
- the build system that googletest is using internally and tests against.
- CMake is community-supported.
+[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
+tests.
-* a C++11-standard-compliant compiler
+[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser
+that generates stub code for GoogleTest.
-## Contributing change
+## Contributing Changes
-Please read the [`CONTRIBUTING.md`](CONTRIBUTING.md) for details on how to
-contribute to this project.
+Please read
+[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/main/CONTRIBUTING.md)
+for details on how to contribute to this project.
Happy testing!
diff --git a/WORKSPACE b/WORKSPACE
index 2289bdb7e8f0..f819ffe61b35 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -1,23 +1,27 @@
workspace(name = "com_google_googletest")
+load("//:googletest_deps.bzl", "googletest_deps")
+googletest_deps()
+
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
-# Abseil
http_archive(
- name = "com_google_absl",
- urls = ["https://github.com/abseil/abseil-cpp/archive/master.zip"],
- strip_prefix = "abseil-cpp-master",
+ name = "rules_python", # 2023-07-31T20:39:27Z
+ sha256 = "1250b59a33c591a1c4ba68c62e95fc88a84c334ec35a2e23f46cbc1b9a5a8b55",
+ strip_prefix = "rules_python-e355becc30275939d87116a4ec83dad4bb50d9e1",
+ urls = ["https://github.com/bazelbuild/rules_python/archive/e355becc30275939d87116a4ec83dad4bb50d9e1.zip"],
)
http_archive(
- name = "rules_cc",
- strip_prefix = "rules_cc-master",
- urls = ["https://github.com/bazelbuild/rules_cc/archive/master.zip"],
+ name = "bazel_skylib", # 2023-05-31T19:24:07Z
+ sha256 = "08c0386f45821ce246bbbf77503c973246ed6ee5c3463e41efc197fa9bc3a7f4",
+ strip_prefix = "bazel-skylib-288731ef9f7f688932bd50e704a91a45ec185f9b",
+ urls = ["https://github.com/bazelbuild/bazel-skylib/archive/288731ef9f7f688932bd50e704a91a45ec185f9b.zip"],
)
http_archive(
- name = "rules_python",
- strip_prefix = "rules_python-master",
- urls = ["https://github.com/bazelbuild/rules_python/archive/master.zip"],
+ name = "platforms", # 2023-07-28T19:44:27Z
+ sha256 = "40eb313613ff00a5c03eed20aba58890046f4d38dec7344f00bb9a8867853526",
+ strip_prefix = "platforms-4ad40ef271da8176d4fc0194d2089b8a76e19d7b",
+ urls = ["https://github.com/bazelbuild/platforms/archive/4ad40ef271da8176d4fc0194d2089b8a76e19d7b.zip"],
)
-
diff --git a/appveyor.yml b/appveyor.yml
deleted file mode 100644
index a58b7687d700..000000000000
--- a/appveyor.yml
+++ /dev/null
@@ -1,154 +0,0 @@
-version: '{build}'
-
-os: Visual Studio 2015
-
-environment:
- matrix:
- - compiler: msvc-15-seh
- generator: "Visual Studio 15 2017"
- build_system: cmake
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
-
- - compiler: msvc-15-seh
- generator: "Visual Studio 15 2017 Win64"
- build_system: cmake
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
- enabled_on_pr: yes
-
- - compiler: msvc-15-seh
- build_system: bazel
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
- enabled_on_pr: yes
-
- - compiler: msvc-14-seh
- build_system: cmake
- generator: "Visual Studio 14 2015"
- enabled_on_pr: yes
-
- - compiler: msvc-14-seh
- build_system: cmake
- generator: "Visual Studio 14 2015 Win64"
-
- - compiler: gcc-6.3.0-posix
- build_system: cmake
- generator: "MinGW Makefiles"
- cxx_path: 'C:\mingw-w64\i686-6.3.0-posix-dwarf-rt_v5-rev1\mingw32\bin'
- enabled_on_pr: yes
-
-configuration:
- - Debug
-
-build:
- verbosity: minimal
-
-install:
-- ps: |
- Write-Output "Compiler: $env:compiler"
- Write-Output "Generator: $env:generator"
- Write-Output "Env:Configuation: $env:configuration"
- Write-Output "Env: $env"
- if (-not (Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER)) {
- Write-Output "This is *NOT* a pull request build"
- } else {
- Write-Output "This is a pull request build"
- if (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes") {
- Write-Output "PR builds are *NOT* explicitly enabled"
- }
- }
-
- # install Bazel
- if ($env:build_system -eq "bazel") {
- appveyor DownloadFile https://github.com/bazelbuild/bazel/releases/download/0.28.1/bazel-0.28.1-windows-x86_64.exe -FileName bazel.exe
- }
-
- if ($env:build_system -eq "cmake") {
- # git bash conflicts with MinGW makefiles
- if ($env:generator -eq "MinGW Makefiles") {
- $env:path = $env:path.replace("C:\Program Files\Git\usr\bin;", "")
- if ($env:cxx_path -ne "") {
- $env:path += ";$env:cxx_path"
- }
- }
- }
-
-before_build:
-- ps: |
- $env:root=$env:APPVEYOR_BUILD_FOLDER
- Write-Output "env:root: $env:root"
-
-build_script:
-- ps: |
- # Only enable some builds for pull requests, the AppVeyor queue is too long.
- if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) {
- return
- } else {
- # special case - build with Bazel
- if ($env:build_system -eq "bazel") {
- & $env:root\bazel.exe build -c opt //:gtest_samples
- if ($LastExitCode -eq 0) { # bazel writes to StdErr and PowerShell interprets it as an error
- $host.SetShouldExit(0)
- } else { # a real error
- throw "Exec: $ErrorMessage"
- }
- return
- }
- }
- # by default build with CMake
- md _build -Force | Out-Null
- cd _build
-
- $conf = if ($env:generator -eq "MinGW Makefiles") {"-DCMAKE_BUILD_TYPE=$env:configuration"} else {"-DCMAKE_CONFIGURATION_TYPES=Debug;Release"}
- # Disable test for MinGW (gtest tests fail, gmock tests can not build)
- $gtest_build_tests = if ($env:generator -eq "MinGW Makefiles") {"-Dgtest_build_tests=OFF"} else {"-Dgtest_build_tests=ON"}
- $gmock_build_tests = if ($env:generator -eq "MinGW Makefiles") {"-Dgmock_build_tests=OFF"} else {"-Dgmock_build_tests=ON"}
- & cmake -G "$env:generator" $conf -Dgtest_build_samples=ON $gtest_build_tests $gmock_build_tests ..
- if ($LastExitCode -ne 0) {
- throw "Exec: $ErrorMessage"
- }
- $cmake_parallel = if ($env:generator -eq "MinGW Makefiles") {"-j2"} else {"/m"}
- & cmake --build . --config $env:configuration -- $cmake_parallel
- if ($LastExitCode -ne 0) {
- throw "Exec: $ErrorMessage"
- }
-
-
-skip_commits:
- files:
- - '**/*.md'
-
-test_script:
-- ps: |
- # Only enable some builds for pull requests, the AppVeyor queue is too long.
- if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) {
- return
- }
- if ($env:build_system -eq "bazel") {
- # special case - testing with Bazel
- & $env:root\bazel.exe test //:gtest_samples
- if ($LastExitCode -eq 0) { # bazel writes to StdErr and PowerShell interprets it as an error
- $host.SetShouldExit(0)
- } else { # a real error
- throw "Exec: $ErrorMessage"
- }
- }
- if ($env:build_system -eq "cmake") {
- # built with CMake - test with CTest
- if ($env:generator -eq "MinGW Makefiles") {
- return # No test available for MinGW
- }
-
- & ctest -C $env:configuration --timeout 600 --output-on-failure
- if ($LastExitCode -ne 0) {
- throw "Exec: $ErrorMessage"
- }
- }
-
-artifacts:
- - path: '_build/CMakeFiles/*.log'
- name: logs
- - path: '_build/Testing/**/*.xml'
- name: test_results
- - path: 'bazel-testlogs/**/test.log'
- name: test_logs
- - path: 'bazel-testlogs/**/test.xml'
- name: test_results
diff --git a/ci/build-linux-bazel.sh b/ci/build-linux-bazel.sh
deleted file mode 100755
index ae8fb75816f9..000000000000
--- a/ci/build-linux-bazel.sh
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/usr/bin/env bash
-# Copyright 2017 Google Inc.
-# All Rights Reserved.
-#
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-set -e
-
-bazel version
-bazel build --curses=no //...:all
-bazel test --curses=no //...:all
-bazel test --curses=no //...:all --define absl=1
diff --git a/ci/build-platformio.sh b/ci/build-platformio.sh
deleted file mode 100755
index 1d7658d8738b..000000000000
--- a/ci/build-platformio.sh
+++ /dev/null
@@ -1,2 +0,0 @@
-# run PlatformIO builds
-platformio run
diff --git a/ci/env-linux.sh b/ci/env-linux.sh
deleted file mode 100755
index 37800d6a355c..000000000000
--- a/ci/env-linux.sh
+++ /dev/null
@@ -1,41 +0,0 @@
-#!/usr/bin/env bash
-# Copyright 2017 Google Inc.
-# All Rights Reserved.
-#
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#
-# This file should be sourced, and not executed as a standalone script.
-#
-
-# TODO() - we can check if this is being sourced using $BASH_VERSION and $BASH_SOURCE[0] != ${0}.
-
-if [ "${TRAVIS_OS_NAME}" = "linux" ]; then
- if [ "$CXX" = "g++" ]; then export CXX="g++-4.9" CC="gcc-4.9"; fi
- if [ "$CXX" = "clang++" ]; then export CXX="clang++-3.9" CC="clang-3.9"; fi
-fi
diff --git a/ci/install-linux.sh b/ci/install-linux.sh
deleted file mode 100755
index 05e2cb280318..000000000000
--- a/ci/install-linux.sh
+++ /dev/null
@@ -1,49 +0,0 @@
-#!/usr/bin/env bash
-# Copyright 2017 Google Inc.
-# All Rights Reserved.
-#
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-set -eu
-
-if [ "${TRAVIS_OS_NAME}" != linux ]; then
- echo "Not a Linux build; skipping installation"
- exit 0
-fi
-
-
-if [ "${TRAVIS_SUDO}" = "true" ]; then
- echo "deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8" | \
- sudo tee /etc/apt/sources.list.d/bazel.list
- curl https://bazel.build/bazel-release.pub.gpg | sudo apt-key add -
- sudo apt-get update && sudo apt-get install -y bazel gcc-4.9 g++-4.9 clang-3.9
-elif [ "${CXX}" = "clang++" ]; then
- # Use ccache, assuming $HOME/bin is in the path, which is true in the Travis build environment.
- ln -sf /usr/bin/ccache $HOME/bin/${CXX};
- ln -sf /usr/bin/ccache $HOME/bin/${CC};
-fi
diff --git a/ci/install-osx.sh b/ci/install-osx.sh
deleted file mode 100755
index cc4750829ce5..000000000000
--- a/ci/install-osx.sh
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/env bash
-# Copyright 2017 Google Inc.
-# All Rights Reserved.
-#
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-set -eu
-
-if [ "${TRAVIS_OS_NAME}" != "osx" ]; then
- echo "Not a macOS build; skipping installation"
- exit 0
-fi
-
-brew update
-brew install ccache gcc@4.9
diff --git a/ci/install-platformio.sh b/ci/install-platformio.sh
deleted file mode 100755
index 4d7860a560c9..000000000000
--- a/ci/install-platformio.sh
+++ /dev/null
@@ -1,5 +0,0 @@
-# install PlatformIO
-sudo pip install -U platformio
-
-# update PlatformIO
-platformio update
diff --git a/ci/linux-presubmit.sh b/ci/linux-presubmit.sh
new file mode 100644
index 000000000000..6bac88787ff2
--- /dev/null
+++ b/ci/linux-presubmit.sh
@@ -0,0 +1,137 @@
+#!/bin/bash
+#
+# Copyright 2020, 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.
+
+set -euox pipefail
+
+readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20230217"
+readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20230120"
+
+if [[ -z ${GTEST_ROOT:-} ]]; then
+ GTEST_ROOT="$(realpath $(dirname ${0})/..)"
+fi
+
+if [[ -z ${STD:-} ]]; then
+ STD="c++14 c++17 c++20"
+fi
+
+# Test the CMake build
+for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do
+ for cmake_off_on in OFF ON; do
+ time docker run \
+ --volume="${GTEST_ROOT}:/src:ro" \
+ --tmpfs="/build:exec" \
+ --workdir="/build" \
+ --rm \
+ --env="CC=${cc}" \
+ --env=CXXFLAGS="-Werror -Wdeprecated" \
+ ${LINUX_LATEST_CONTAINER} \
+ /bin/bash -c "
+ cmake /src \
+ -DCMAKE_CXX_STANDARD=14 \
+ -Dgtest_build_samples=ON \
+ -Dgtest_build_tests=ON \
+ -Dgmock_build_tests=ON \
+ -Dcxx_no_exception=${cmake_off_on} \
+ -Dcxx_no_rtti=${cmake_off_on} && \
+ make -j$(nproc) && \
+ ctest -j$(nproc) --output-on-failure"
+ done
+done
+
+# Do one test with an older version of GCC
+time docker run \
+ --volume="${GTEST_ROOT}:/src:ro" \
+ --workdir="/src" \
+ --rm \
+ --env="CC=/usr/local/bin/gcc" \
+ --env="BAZEL_CXXOPTS=-std=c++14" \
+ ${LINUX_GCC_FLOOR_CONTAINER} \
+ /usr/local/bin/bazel test ... \
+ --copt="-Wall" \
+ --copt="-Werror" \
+ --copt="-Wuninitialized" \
+ --copt="-Wundef" \
+ --copt="-Wno-error=pragmas" \
+ --distdir="/bazel-distdir" \
+ --features=external_include_paths \
+ --keep_going \
+ --show_timestamps \
+ --test_output=errors
+
+# Test GCC
+for std in ${STD}; do
+ for absl in 0 1; do
+ time docker run \
+ --volume="${GTEST_ROOT}:/src:ro" \
+ --workdir="/src" \
+ --rm \
+ --env="CC=/usr/local/bin/gcc" \
+ --env="BAZEL_CXXOPTS=-std=${std}" \
+ ${LINUX_LATEST_CONTAINER} \
+ /usr/local/bin/bazel test ... \
+ --copt="-Wall" \
+ --copt="-Werror" \
+ --copt="-Wuninitialized" \
+ --copt="-Wundef" \
+ --define="absl=${absl}" \
+ --distdir="/bazel-distdir" \
+ --features=external_include_paths \
+ --keep_going \
+ --show_timestamps \
+ --test_output=errors
+ done
+done
+
+# Test Clang
+for std in ${STD}; do
+ for absl in 0 1; do
+ time docker run \
+ --volume="${GTEST_ROOT}:/src:ro" \
+ --workdir="/src" \
+ --rm \
+ --env="CC=/opt/llvm/clang/bin/clang" \
+ --env="BAZEL_CXXOPTS=-std=${std}" \
+ ${LINUX_LATEST_CONTAINER} \
+ /usr/local/bin/bazel test ... \
+ --copt="--gcc-toolchain=/usr/local" \
+ --copt="-Wall" \
+ --copt="-Werror" \
+ --copt="-Wuninitialized" \
+ --copt="-Wundef" \
+ --define="absl=${absl}" \
+ --distdir="/bazel-distdir" \
+ --features=external_include_paths \
+ --keep_going \
+ --linkopt="--gcc-toolchain=/usr/local" \
+ --show_timestamps \
+ --test_output=errors
+ done
+done
diff --git a/ci/get-nprocessors.sh b/ci/macos-presubmit.sh
index 43635e761e2d..681ebc2a91d9 100755..100644
--- a/ci/get-nprocessors.sh
+++ b/ci/macos-presubmit.sh
@@ -1,7 +1,7 @@
-#!/usr/bin/env bash
-# Copyright 2017 Google Inc.
-# All Rights Reserved.
+#!/bin/bash
#
+# Copyright 2020, 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
@@ -29,20 +29,48 @@
# (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 typically sourced by another script.
-# if possible, ask for the precise number of processors,
-# otherwise take 2 processors as reasonable default; see
-# https://docs.travis-ci.com/user/speeding-up-the-build/#Makefile-optimization
-if [ -x /usr/bin/getconf ]; then
- NPROCESSORS=$(/usr/bin/getconf _NPROCESSORS_ONLN)
-else
- NPROCESSORS=2
+set -euox pipefail
+
+if [[ -z ${GTEST_ROOT:-} ]]; then
+ GTEST_ROOT="$(realpath $(dirname ${0})/..)"
fi
-# as of 2017-09-04 Travis CI reports 32 processors, but GCC build
-# crashes if parallelized too much (maybe memory consumption problem),
-# so limit to 4 processors for the time being.
-if [ $NPROCESSORS -gt 4 ] ; then
- echo "$0:Note: Limiting processors to use by make from $NPROCESSORS to 4."
- NPROCESSORS=4
+# Test the CMake build
+for cmake_off_on in OFF ON; do
+ BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX)
+ cd ${BUILD_DIR}
+ time cmake ${GTEST_ROOT} \
+ -DCMAKE_CXX_STANDARD=14 \
+ -Dgtest_build_samples=ON \
+ -Dgtest_build_tests=ON \
+ -Dgmock_build_tests=ON \
+ -Dcxx_no_exception=${cmake_off_on} \
+ -Dcxx_no_rtti=${cmake_off_on}
+ time make
+ time ctest -j$(nproc) --output-on-failure
+done
+
+# Test the Bazel build
+
+# If we are running on Kokoro, check for a versioned Bazel binary.
+KOKORO_GFILE_BAZEL_BIN="bazel-5.1.1-darwin-x86_64"
+if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then
+ BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}"
+ chmod +x ${BAZEL_BIN}
+else
+ BAZEL_BIN="bazel"
fi
+
+cd ${GTEST_ROOT}
+for absl in 0 1; do
+ ${BAZEL_BIN} test ... \
+ --copt="-Wall" \
+ --copt="-Werror" \
+ --copt="-Wundef" \
+ --cxxopt="-std=c++14" \
+ --define="absl=${absl}" \
+ --features=external_include_paths \
+ --keep_going \
+ --show_timestamps \
+ --test_output=errors
+done
diff --git a/ci/travis.sh b/ci/travis.sh
deleted file mode 100755
index 9ff3bad3eebc..000000000000
--- a/ci/travis.sh
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/env sh
-set -evx
-
-. ci/get-nprocessors.sh
-
-# if possible, ask for the precise number of processors,
-# otherwise take 2 processors as reasonable default; see
-# https://docs.travis-ci.com/user/speeding-up-the-build/#Makefile-optimization
-if [ -x /usr/bin/getconf ]; then
- NPROCESSORS=$(/usr/bin/getconf _NPROCESSORS_ONLN)
-else
- NPROCESSORS=2
-fi
-# as of 2017-09-04 Travis CI reports 32 processors, but GCC build
-# crashes if parallelized too much (maybe memory consumption problem),
-# so limit to 4 processors for the time being.
-if [ $NPROCESSORS -gt 4 ] ; then
- echo "$0:Note: Limiting processors to use by make from $NPROCESSORS to 4."
- NPROCESSORS=4
-fi
-# Tell make to use the processors. No preceding '-' required.
-MAKEFLAGS="j${NPROCESSORS}"
-export MAKEFLAGS
-
-env | sort
-
-# Set default values to OFF for these variables if not specified.
-: "${NO_EXCEPTION:=OFF}"
-: "${NO_RTTI:=OFF}"
-: "${COMPILER_IS_GNUCXX:=OFF}"
-
-mkdir build || true
-cd build
-cmake -Dgtest_build_samples=ON \
- -Dgtest_build_tests=ON \
- -Dgmock_build_tests=ON \
- -Dcxx_no_exception=$NO_EXCEPTION \
- -Dcxx_no_rtti=$NO_RTTI \
- -DCMAKE_COMPILER_IS_GNUCXX=$COMPILER_IS_GNUCXX \
- -DCMAKE_CXX_FLAGS=$CXX_FLAGS \
- -DCMAKE_BUILD_TYPE=$BUILD_TYPE \
- ..
-make
-CTEST_OUTPUT_ON_FAILURE=1 make test
diff --git a/ci/windows-presubmit.bat b/ci/windows-presubmit.bat
new file mode 100644
index 000000000000..48962eb9e086
--- /dev/null
+++ b/ci/windows-presubmit.bat
@@ -0,0 +1,58 @@
+SETLOCAL ENABLEDELAYEDEXPANSION
+
+SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-5.1.1-windows-x86_64.exe
+
+SET PATH=C:\Python34;%PATH%
+SET BAZEL_PYTHON=C:\python34\python.exe
+SET BAZEL_SH=C:\tools\msys64\usr\bin\bash.exe
+SET CMAKE_BIN="cmake.exe"
+SET CTEST_BIN="ctest.exe"
+SET CTEST_OUTPUT_ON_FAILURE=1
+SET CMAKE_BUILD_PARALLEL_LEVEL=16
+SET CTEST_PARALLEL_LEVEL=16
+
+IF EXIST git\googletest (
+ CD git\googletest
+) ELSE IF EXIST github\googletest (
+ CD github\googletest
+)
+
+IF %errorlevel% neq 0 EXIT /B 1
+
+:: ----------------------------------------------------------------------------
+:: CMake
+MKDIR cmake_msvc2022
+CD cmake_msvc2022
+
+%CMAKE_BIN% .. ^
+ -G "Visual Studio 17 2022" ^
+ -DPYTHON_EXECUTABLE:FILEPATH=c:\python37\python.exe ^
+ -DPYTHON_INCLUDE_DIR:PATH=c:\python37\include ^
+ -DPYTHON_LIBRARY:FILEPATH=c:\python37\lib\site-packages\pip ^
+ -Dgtest_build_samples=ON ^
+ -Dgtest_build_tests=ON ^
+ -Dgmock_build_tests=ON
+IF %errorlevel% neq 0 EXIT /B 1
+
+%CMAKE_BIN% --build . --target ALL_BUILD --config Debug -- -maxcpucount
+IF %errorlevel% neq 0 EXIT /B 1
+
+%CTEST_BIN% -C Debug --timeout 600
+IF %errorlevel% neq 0 EXIT /B 1
+
+CD ..
+RMDIR /S /Q cmake_msvc2022
+
+:: ----------------------------------------------------------------------------
+:: Bazel
+
+SET BAZEL_VS=C:\Program Files\Microsoft Visual Studio\2022\Community
+%BAZEL_EXE% test ... ^
+ --compilation_mode=dbg ^
+ --copt=/std:c++14 ^
+ --copt=/WX ^
+ --features=external_include_paths ^
+ --keep_going ^
+ --test_output=errors ^
+ --test_tag_filters=-no_test_msvc2017
+IF %errorlevel% neq 0 EXIT /B 1
diff --git a/configure.ac b/configure.ac
deleted file mode 100644
index 751b9ba8f039..000000000000
--- a/configure.ac
+++ /dev/null
@@ -1,16 +0,0 @@
-AC_INIT([Google C++ Mocking and Testing Frameworks],
- [1.8.0],
- [googlemock@googlegroups.com],
- [googletest])
-
-# Provide various options to initialize the Autoconf and configure processes.
-AC_PREREQ([2.59])
-AC_CONFIG_SRCDIR([./README.md])
-AC_CONFIG_AUX_DIR([build-aux])
-AC_CONFIG_FILES([Makefile])
-AC_CONFIG_SUBDIRS([googletest googlemock])
-
-AM_INIT_AUTOMAKE
-
-# Output the generated files. No further autoconf macros may be used.
-AC_OUTPUT
diff --git a/docs/_config.yml b/docs/_config.yml
new file mode 100644
index 000000000000..d12867eab6b6
--- /dev/null
+++ b/docs/_config.yml
@@ -0,0 +1 @@
+title: GoogleTest
diff --git a/docs/_data/navigation.yml b/docs/_data/navigation.yml
new file mode 100644
index 000000000000..9f3332708eac
--- /dev/null
+++ b/docs/_data/navigation.yml
@@ -0,0 +1,43 @@
+nav:
+- section: "Get Started"
+ items:
+ - title: "Supported Platforms"
+ url: "/platforms.html"
+ - title: "Quickstart: Bazel"
+ url: "/quickstart-bazel.html"
+ - title: "Quickstart: CMake"
+ url: "/quickstart-cmake.html"
+- section: "Guides"
+ items:
+ - title: "GoogleTest Primer"
+ url: "/primer.html"
+ - title: "Advanced Topics"
+ url: "/advanced.html"
+ - title: "Mocking for Dummies"
+ url: "/gmock_for_dummies.html"
+ - title: "Mocking Cookbook"
+ url: "/gmock_cook_book.html"
+ - title: "Mocking Cheat Sheet"
+ url: "/gmock_cheat_sheet.html"
+- section: "References"
+ items:
+ - title: "Testing Reference"
+ url: "/reference/testing.html"
+ - title: "Mocking Reference"
+ url: "/reference/mocking.html"
+ - title: "Assertions"
+ url: "/reference/assertions.html"
+ - title: "Matchers"
+ url: "/reference/matchers.html"
+ - title: "Actions"
+ url: "/reference/actions.html"
+ - title: "Testing FAQ"
+ url: "/faq.html"
+ - title: "Mocking FAQ"
+ url: "/gmock_faq.html"
+ - title: "Code Samples"
+ url: "/samples.html"
+ - title: "Using pkg-config"
+ url: "/pkgconfig.html"
+ - title: "Community Documentation"
+ url: "/community_created_documentation.html"
diff --git a/docs/_layouts/default.html b/docs/_layouts/default.html
new file mode 100644
index 000000000000..c7f331b87d7d
--- /dev/null
+++ b/docs/_layouts/default.html
@@ -0,0 +1,58 @@
+<!DOCTYPE html>
+<html lang="{{ site.lang | default: "en-US" }}">
+ <head>
+ <meta charset="UTF-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+
+{% seo %}
+ <link rel="stylesheet" href="{{ "/assets/css/style.css?v=" | append: site.github.build_revision | relative_url }}">
+ <script>
+ window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
+ ga('create', 'UA-197576187-1', { 'storage': 'none' });
+ ga('set', 'referrer', document.referrer.split('?')[0]);
+ ga('set', 'location', window.location.href.split('?')[0]);
+ ga('set', 'anonymizeIp', true);
+ ga('send', 'pageview');
+ </script>
+ <script async src='https://www.google-analytics.com/analytics.js'></script>
+ </head>
+ <body>
+ <div class="sidebar">
+ <div class="header">
+ <h1><a href="{{ "/" | relative_url }}">{{ site.title | default: "Documentation" }}</a></h1>
+ </div>
+ <input type="checkbox" id="nav-toggle" class="nav-toggle">
+ <label for="nav-toggle" class="expander">
+ <span class="arrow"></span>
+ </label>
+ <nav>
+ {% for item in site.data.navigation.nav %}
+ <h2>{{ item.section }}</h2>
+ <ul>
+ {% for subitem in item.items %}
+ <a href="{{subitem.url | relative_url }}">
+ <li class="{% if subitem.url == page.url %}active{% endif %}">
+ {{ subitem.title }}
+ </li>
+ </a>
+ {% endfor %}
+ </ul>
+ {% endfor %}
+ </nav>
+ </div>
+ <div class="main markdown-body">
+ <div class="main-inner">
+ {{ content }}
+ </div>
+ <div class="footer">
+ GoogleTest &middot;
+ <a href="https://github.com/google/googletest">GitHub Repository</a> &middot;
+ <a href="https://github.com/google/googletest/blob/main/LICENSE">License</a> &middot;
+ <a href="https://policies.google.com/privacy">Privacy Policy</a>
+ </div>
+ </div>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/4.1.0/anchor.min.js" integrity="sha256-lZaRhKri35AyJSypXXs4o6OPFTbTmUoltBbDCbdzegg=" crossorigin="anonymous"></script>
+ <script>anchors.add('.main h2, .main h3, .main h4, .main h5, .main h6');</script>
+ </body>
+</html>
diff --git a/docs/_sass/main.scss b/docs/_sass/main.scss
new file mode 100644
index 000000000000..92edc877a592
--- /dev/null
+++ b/docs/_sass/main.scss
@@ -0,0 +1,200 @@
+// Styles for GoogleTest docs website on GitHub Pages.
+// Color variables are defined in
+// https://github.com/pages-themes/primer/tree/master/_sass/primer-support/lib/variables
+
+$sidebar-width: 260px;
+
+body {
+ display: flex;
+ margin: 0;
+}
+
+.sidebar {
+ background: $black;
+ color: $text-white;
+ flex-shrink: 0;
+ height: 100vh;
+ overflow: auto;
+ position: sticky;
+ top: 0;
+ width: $sidebar-width;
+}
+
+.sidebar h1 {
+ font-size: 1.5em;
+}
+
+.sidebar h2 {
+ color: $gray-light;
+ font-size: 0.8em;
+ font-weight: normal;
+ margin-bottom: 0.8em;
+ padding-left: 2.5em;
+ text-transform: uppercase;
+}
+
+.sidebar .header {
+ background: $black;
+ padding: 2em;
+ position: sticky;
+ top: 0;
+ width: 100%;
+}
+
+.sidebar .header a {
+ color: $text-white;
+ text-decoration: none;
+}
+
+.sidebar .nav-toggle {
+ display: none;
+}
+
+.sidebar .expander {
+ cursor: pointer;
+ display: none;
+ height: 3em;
+ position: absolute;
+ right: 1em;
+ top: 1.5em;
+ width: 3em;
+}
+
+.sidebar .expander .arrow {
+ border: solid $white;
+ border-width: 0 3px 3px 0;
+ display: block;
+ height: 0.7em;
+ margin: 1em auto;
+ transform: rotate(45deg);
+ transition: transform 0.5s;
+ width: 0.7em;
+}
+
+.sidebar nav {
+ width: 100%;
+}
+
+.sidebar nav ul {
+ list-style-type: none;
+ margin-bottom: 1em;
+ padding: 0;
+
+ &:last-child {
+ margin-bottom: 2em;
+ }
+
+ a {
+ text-decoration: none;
+ }
+
+ li {
+ color: $text-white;
+ padding-left: 2em;
+ text-decoration: none;
+ }
+
+ li.active {
+ background: $border-gray-darker;
+ font-weight: bold;
+ }
+
+ li:hover {
+ background: $border-gray-darker;
+ }
+}
+
+.main {
+ background-color: $bg-gray;
+ width: calc(100% - #{$sidebar-width});
+}
+
+.main .main-inner {
+ background-color: $white;
+ padding: 2em;
+}
+
+.main .footer {
+ margin: 0;
+ padding: 2em;
+}
+
+.main table th {
+ text-align: left;
+}
+
+.main .callout {
+ border-left: 0.25em solid $white;
+ padding: 1em;
+
+ a {
+ text-decoration: underline;
+ }
+
+ &.important {
+ background-color: $bg-yellow-light;
+ border-color: $bg-yellow;
+ color: $black;
+ }
+
+ &.note {
+ background-color: $bg-blue-light;
+ border-color: $text-blue;
+ color: $text-blue;
+ }
+
+ &.tip {
+ background-color: $green-000;
+ border-color: $green-700;
+ color: $green-700;
+ }
+
+ &.warning {
+ background-color: $red-000;
+ border-color: $text-red;
+ color: $text-red;
+ }
+}
+
+.main .good pre {
+ background-color: $bg-green-light;
+}
+
+.main .bad pre {
+ background-color: $red-000;
+}
+
+@media all and (max-width: 768px) {
+ body {
+ flex-direction: column;
+ }
+
+ .sidebar {
+ height: auto;
+ position: relative;
+ width: 100%;
+ }
+
+ .sidebar .expander {
+ display: block;
+ }
+
+ .sidebar nav {
+ height: 0;
+ overflow: hidden;
+ }
+
+ .sidebar .nav-toggle:checked {
+ & ~ nav {
+ height: auto;
+ }
+
+ & + .expander .arrow {
+ transform: rotate(-135deg);
+ }
+ }
+
+ .main {
+ width: 100%;
+ }
+}
diff --git a/googletest/docs/advanced.md b/docs/advanced.md
index 3e5f779d0ac8..3871db13b797 100644
--- a/googletest/docs/advanced.md
+++ b/docs/advanced.md
@@ -1,11 +1,9 @@
-# Advanced googletest Topics
-
-<!-- GOOGLETEST_CM0016 DO NOT DELETE -->
+# Advanced GoogleTest Topics
## Introduction
-Now that you have read the [googletest Primer](primer.md) and learned how to
-write tests using googletest, it's time to learn some new tricks. This document
+Now that you have read the [GoogleTest Primer](primer.md) and learned how to
+write tests using GoogleTest, it's time to learn some new tricks. This document
will show you more assertions as well as how to construct complex failure
messages, propagate fatal failures, reuse and speed up your test fixtures, and
use various flags with your tests.
@@ -17,73 +15,17 @@ assertions.
### Explicit Success and Failure
-These three assertions do not actually test a value or expression. Instead, they
-generate a success or failure directly. Like the macros that actually perform a
-test, you may stream a custom failure message into them.
-
-```c++
-SUCCEED();
-```
-
-Generates a success. This does **NOT** make the overall test succeed. A test is
-considered successful only if none of its assertions fail during its execution.
-
-NOTE: `SUCCEED()` is purely documentary and currently doesn't generate any
-user-visible output. However, we may add `SUCCEED()` messages to googletest's
-output in the future.
-
-```c++
-FAIL();
-ADD_FAILURE();
-ADD_FAILURE_AT("file_path", line_number);
-```
-
-`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()`
-generate a nonfatal failure. These are useful when control flow, rather than a
-Boolean expression, determines the test's success or failure. For example, you
-might want to write something like:
-
-```c++
-switch(expression) {
- case 1:
- ... some checks ...
- case 2:
- ... some other checks ...
- default:
- FAIL() << "We shouldn't get here.";
-}
-```
-
-NOTE: you can only use `FAIL()` in functions that return `void`. See the
-[Assertion Placement section](#assertion-placement) for more information.
+See [Explicit Success and Failure](reference/assertions.md#success-failure) in
+the Assertions Reference.
### Exception Assertions
-These are for verifying that a piece of code throws (or does not throw) an
-exception of the given type:
-
-Fatal assertion | Nonfatal assertion | Verifies
------------------------------------------- | ------------------------------------------ | --------
-`ASSERT_THROW(statement, exception_type);` | `EXPECT_THROW(statement, exception_type);` | `statement` throws an exception of the given type
-`ASSERT_ANY_THROW(statement);` | `EXPECT_ANY_THROW(statement);` | `statement` throws an exception of any type
-`ASSERT_NO_THROW(statement);` | `EXPECT_NO_THROW(statement);` | `statement` doesn't throw any exception
-
-Examples:
-
-```c++
-ASSERT_THROW(Foo(5), bar_exception);
-
-EXPECT_NO_THROW({
- int n = 5;
- Bar(&n);
-});
-```
-
-**Availability**: requires exceptions to be enabled in the build environment
+See [Exception Assertions](reference/assertions.md#exceptions) in the Assertions
+Reference.
### Predicate Assertions for Better Error Messages
-Even though googletest has a rich set of assertions, they can never be complete,
+Even though GoogleTest has a rich set of assertions, they can never be complete,
as it's impossible (nor a good idea) to anticipate all scenarios a user might
run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a
complex expression, for lack of a better macro. This has the problem of not
@@ -93,66 +35,15 @@ failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
is awkward especially when the expression has side-effects or is expensive to
evaluate.
-googletest gives you three different options to solve this problem:
+GoogleTest gives you three different options to solve this problem:
#### Using an Existing Boolean Function
If you already have a function or functor that returns `bool` (or a type that
can be implicitly converted to `bool`), you can use it in a *predicate
-assertion* to get the function arguments printed for free:
-
-<!-- mdformat off(github rendering does not support multiline tables) -->
-
-| Fatal assertion | Nonfatal assertion | Verifies |
-| --------------------------------- | --------------------------------- | --------------------------- |
-| `ASSERT_PRED1(pred1, val1)` | `EXPECT_PRED1(pred1, val1)` | `pred1(val1)` is true |
-| `ASSERT_PRED2(pred2, val1, val2)` | `EXPECT_PRED2(pred2, val1, val2)` | `pred1(val1, val2)` is true |
-| `...` | `...` | `...` |
-
-<!-- mdformat on-->
-In the above, `predn` is an `n`-ary predicate function or functor, where `val1`,
-`val2`, ..., and `valn` are its arguments. The assertion succeeds if the
-predicate returns `true` when applied to the given arguments, and fails
-otherwise. When the assertion fails, it prints the value of each argument. In
-either case, the arguments are evaluated exactly once.
-
-Here's an example. Given
-
-```c++
-// Returns true if m and n have no common divisors except 1.
-bool MutuallyPrime(int m, int n) { ... }
-
-const int a = 3;
-const int b = 4;
-const int c = 10;
-```
-
-the assertion
-
-```c++
- EXPECT_PRED2(MutuallyPrime, a, b);
-```
-
-will succeed, while the assertion
-
-```c++
- EXPECT_PRED2(MutuallyPrime, b, c);
-```
-
-will fail with the message
-
-```none
-MutuallyPrime(b, c) is false, where
-b is 4
-c is 10
-```
-
-> NOTE:
->
-> 1. If you see a compiler error "no matching function to call" when using
-> `ASSERT_PRED*` or `EXPECT_PRED*`, please see
-> [this](faq.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert-pred-how-do-i-fix-it)
-> for how to resolve it.
+assertion* to get the function arguments printed for free. See
+[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions
+Reference for details.
#### Using a Function That Returns an AssertionResult
@@ -187,11 +78,11 @@ write a predicate function that returns `AssertionResult` instead of `bool`. For
example, if you define `IsEven()` as:
```c++
-::testing::AssertionResult IsEven(int n) {
+testing::AssertionResult IsEven(int n) {
if ((n % 2) == 0)
- return ::testing::AssertionSuccess();
+ return testing::AssertionSuccess();
else
- return ::testing::AssertionFailure() << n << " is odd";
+ return testing::AssertionFailure() << n << " is odd";
}
```
@@ -225,11 +116,11 @@ are fine with making the predicate slower in the success case, you can supply a
success message:
```c++
-::testing::AssertionResult IsEven(int n) {
+testing::AssertionResult IsEven(int n) {
if ((n % 2) == 0)
- return ::testing::AssertionSuccess() << n << " is even";
+ return testing::AssertionSuccess() << n << " is even";
else
- return ::testing::AssertionFailure() << n << " is odd";
+ return testing::AssertionFailure() << n << " is odd";
}
```
@@ -243,176 +134,53 @@ Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print
#### Using a Predicate-Formatter
-If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and
-`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your
-predicate do not support streaming to `ostream`, you can instead use the
-following *predicate-formatter assertions* to *fully* customize how the message
-is formatted:
-
-Fatal assertion | Nonfatal assertion | Verifies
------------------------------------------------- | ------------------------------------------------ | --------
-`ASSERT_PRED_FORMAT1(pred_format1, val1);` | `EXPECT_PRED_FORMAT1(pred_format1, val1);` | `pred_format1(val1)` is successful
-`ASSERT_PRED_FORMAT2(pred_format2, val1, val2);` | `EXPECT_PRED_FORMAT2(pred_format2, val1, val2);` | `pred_format2(val1, val2)` is successful
-`...` | `...` | ...
-
-The difference between this and the previous group of macros is that instead of
-a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a *predicate-formatter*
-(`pred_formatn`), which is a function or functor with the signature:
-
-```c++
-::testing::AssertionResult PredicateFormattern(const char* expr1,
- const char* expr2,
- ...
- const char* exprn,
- T1 val1,
- T2 val2,
- ...
- Tn valn);
-```
-
-where `val1`, `val2`, ..., and `valn` are the values of the predicate arguments,
-and `expr1`, `expr2`, ..., and `exprn` are the corresponding expressions as they
-appear in the source code. The types `T1`, `T2`, ..., and `Tn` can be either
-value types or reference types. For example, if an argument has type `Foo`, you
-can declare it as either `Foo` or `const Foo&`, whichever is appropriate.
-
-As an example, let's improve the failure message in `MutuallyPrime()`, which was
-used with `EXPECT_PRED2()`:
-
-```c++
-// Returns the smallest prime common divisor of m and n,
-// or 1 when m and n are mutually prime.
-int SmallestPrimeCommonDivisor(int m, int n) { ... }
-
-// A predicate-formatter for asserting that two integers are mutually prime.
-::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
- const char* n_expr,
- int m,
- int n) {
- if (MutuallyPrime(m, n)) return ::testing::AssertionSuccess();
-
- return ::testing::AssertionFailure() << m_expr << " and " << n_expr
- << " (" << m << " and " << n << ") are not mutually prime, "
- << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n);
-}
-```
-
-With this predicate-formatter, we can use
-
-```c++
- EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c);
-```
-
-to generate the message
-
-```none
-b and c (4 and 10) are not mutually prime, as they have a common divisor 2.
-```
-
-As you may have realized, many of the built-in assertions we introduced earlier
-are special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are
-indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`.
+If you find the default message generated by
+[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) and
+[`EXPECT_TRUE`](reference/assertions.md#EXPECT_TRUE) unsatisfactory, or some
+arguments to your predicate do not support streaming to `ostream`, you can
+instead use *predicate-formatter assertions* to *fully* customize how the
+message is formatted. See
+[`EXPECT_PRED_FORMAT*`](reference/assertions.md#EXPECT_PRED_FORMAT) in the
+Assertions Reference for details.
### Floating-Point Comparison
-Comparing floating-point numbers is tricky. Due to round-off errors, it is very
-unlikely that two floating-points will match exactly. Therefore, `ASSERT_EQ` 's
-naive comparison usually doesn't work. And since floating-points can have a wide
-value range, no single fixed error bound works. It's better to compare by a
-fixed relative error bound, except for values close to 0 due to the loss of
-precision there.
-
-In general, for floating-point comparison to make sense, the user needs to
-carefully choose the error bound. If they don't want or care to, comparing in
-terms of Units in the Last Place (ULPs) is a good default, and googletest
-provides assertions to do this. Full details about ULPs are quite long; if you
-want to learn more, see
-[here](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
-
-#### Floating-Point Macros
-
-<!-- mdformat off(github rendering does not support multiline tables) -->
-
-| Fatal assertion | Nonfatal assertion | Verifies |
-| ------------------------------- | ------------------------------- | ---------------------------------------- |
-| `ASSERT_FLOAT_EQ(val1, val2);` | `EXPECT_FLOAT_EQ(val1, val2);` | the two `float` values are almost equal |
-| `ASSERT_DOUBLE_EQ(val1, val2);` | `EXPECT_DOUBLE_EQ(val1, val2);` | the two `double` values are almost equal |
-
-<!-- mdformat on-->
-
-By "almost equal" we mean the values are within 4 ULP's from each other.
-
-The following assertions allow you to choose the acceptable error bound:
-
-<!-- mdformat off(github rendering does not support multiline tables) -->
-
-| Fatal assertion | Nonfatal assertion | Verifies |
-| ------------------------------------- | ------------------------------------- | -------------------------------------------------------------------------------- |
-| `ASSERT_NEAR(val1, val2, abs_error);` | `EXPECT_NEAR(val1, val2, abs_error);` | the difference between `val1` and `val2` doesn't exceed the given absolute error |
-
-<!-- mdformat on-->
+See [Floating-Point Comparison](reference/assertions.md#floating-point) in the
+Assertions Reference.
#### Floating-Point Predicate-Format Functions
Some floating-point operations are useful, but not that often used. In order to
avoid an explosion of new macros, we provide them as predicate-format functions
-that can be used in predicate assertion macros (e.g. `EXPECT_PRED_FORMAT2`,
-etc).
-
-```c++
-EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2);
-EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2);
-```
-
-Verifies that `val1` is less than, or almost equal to, `val2`. You can replace
-`EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`.
-
-### Asserting Using gMock Matchers
-
-[gMock](../../googlemock) comes with a library of matchers for validating
-arguments passed to mock objects. A gMock *matcher* is basically a predicate
-that knows how to describe itself. It can be used in these assertion macros:
-
-<!-- mdformat off(github rendering does not support multiline tables) -->
-
-| Fatal assertion | Nonfatal assertion | Verifies |
-| ------------------------------ | ------------------------------ | --------------------- |
-| `ASSERT_THAT(value, matcher);` | `EXPECT_THAT(value, matcher);` | value matches matcher |
-
-<!-- mdformat on-->
-
-For example, `StartsWith(prefix)` is a matcher that matches a string starting
-with `prefix`, and you can write:
+that can be used in the predicate assertion macro
+[`EXPECT_PRED_FORMAT2`](reference/assertions.md#EXPECT_PRED_FORMAT), for
+example:
```c++
-using ::testing::StartsWith;
+using ::testing::FloatLE;
+using ::testing::DoubleLE;
...
- // Verifies that Foo() returns a string starting with "Hello".
- EXPECT_THAT(Foo(), StartsWith("Hello"));
+EXPECT_PRED_FORMAT2(FloatLE, val1, val2);
+EXPECT_PRED_FORMAT2(DoubleLE, val1, val2);
```
-Read this
-[recipe](../../googlemock/docs/cook_book.md#using-matchers-in-googletest-assertions)
-in the gMock Cookbook for more details.
+The above code verifies that `val1` is less than, or approximately equal to,
+`val2`.
-gMock has a rich set of matchers. You can do many things googletest cannot do
-alone with them. For a list of matchers gMock provides, read
-[this](../../googlemock/docs/cook_book.md##using-matchers). It's easy to write
-your [own matchers](../../googlemock/docs/cook_book.md#NewMatchers) too.
+### Asserting Using gMock Matchers
-gMock is bundled with googletest, so you don't need to add any build dependency
-in order to take advantage of this. Just include `"testing/base/public/gmock.h"`
-and you're ready to go.
+See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions
+Reference.
### More String Assertions
(Please read the [previous](#asserting-using-gmock-matchers) section first if
you haven't.)
-You can use the gMock
-[string matchers](../../googlemock/docs/cheat_sheet.md#string-matchers) with
-`EXPECT_THAT()` or `ASSERT_THAT()` to do more string comparison tricks
-(sub-string, prefix, suffix, regular expression, and etc). For example,
+You can use the gMock [string matchers](reference/matchers.md#string-matchers)
+with [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) to do more string
+comparison tricks (sub-string, prefix, suffix, regular expression, and etc). For
+example,
```c++
using ::testing::HasSubstr;
@@ -422,37 +190,10 @@ using ::testing::MatchesRegex;
EXPECT_THAT(bar_string, MatchesRegex("\\w*\\d+"));
```
-If the string contains a well-formed HTML or XML document, you can check whether
-its DOM tree matches an
-[XPath expression](http://www.w3.org/TR/xpath/#contents):
-
-```c++
-// Currently still in //template/prototemplate/testing:xpath_matcher
-#include "template/prototemplate/testing/xpath_matcher.h"
-using prototemplate::testing::MatchesXPath;
-EXPECT_THAT(html_string, MatchesXPath("//a[text()='click here']"));
-```
-
### Windows HRESULT assertions
-These assertions test for `HRESULT` success or failure.
-
-Fatal assertion | Nonfatal assertion | Verifies
--------------------------------------- | -------------------------------------- | --------
-`ASSERT_HRESULT_SUCCEEDED(expression)` | `EXPECT_HRESULT_SUCCEEDED(expression)` | `expression` is a success `HRESULT`
-`ASSERT_HRESULT_FAILED(expression)` | `EXPECT_HRESULT_FAILED(expression)` | `expression` is a failure `HRESULT`
-
-The generated output contains the human-readable error message associated with
-the `HRESULT` code returned by `expression`.
-
-You might use them like this:
-
-```c++
-CComPtr<IShellDispatch2> shell;
-ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application"));
-CComVariant empty;
-ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));
-```
+See [Windows HRESULT Assertions](reference/assertions.md#HRESULT) in the
+Assertions Reference.
### Type Assertions
@@ -464,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
-`type1 and type2 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
@@ -476,7 +216,7 @@ instantiated. For example, given:
```c++
template <typename T> class Foo {
public:
- void Bar() { ::testing::StaticAssertTypeEq<int, T>(); }
+ void Bar() { testing::StaticAssertTypeEq<int, T>(); }
};
```
@@ -516,6 +256,7 @@ any assertion inside of it.
If changing the function's type is not an option, you should just use assertions
that generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`.
+{: .callout .note}
NOTE: Constructors and destructors are not considered void-returning functions,
according to the C++ language specification, and so you may not use fatal
assertions in them; you'll get a compilation error if you try. Instead, either
@@ -523,16 +264,49 @@ call `abort` and crash the entire test executable, or put the fatal assertion in
a `SetUp`/`TearDown` function; see
[constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp)
+{: .callout .warning}
WARNING: A fatal assertion in a helper function (private void-returning method)
-called from a constructor or destructor does not does not terminate the current
-test, as your intuition might suggest: it merely returns from the constructor or
+called from a constructor or destructor does not terminate the current test, as
+your intuition might suggest: it merely returns from the constructor or
destructor early, possibly leaving your object in a partially-constructed or
partially-destructed state! You almost certainly want to `abort` or use
`SetUp`/`TearDown` instead.
-## Teaching googletest How to Print Your Values
+## Skipping test execution
+
+Related to the assertions `SUCCEED()` and `FAIL()`, you can prevent further test
+execution at runtime with the `GTEST_SKIP()` macro. This is useful when you need
+to check for preconditions of the system under test during runtime and skip
+tests in a meaningful way.
-When a test assertion such as `EXPECT_EQ` fails, googletest prints the argument
+`GTEST_SKIP()` can be used in individual test cases or in the `SetUp()` methods
+of classes derived from either `::testing::Environment` or `::testing::Test`.
+For example:
+
+```c++
+TEST(SkipTest, DoesSkip) {
+ GTEST_SKIP() << "Skipping single test";
+ EXPECT_EQ(0, 1); // Won't fail; it won't be executed
+}
+
+class SkipFixture : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ GTEST_SKIP() << "Skipping all tests for this fixture";
+ }
+};
+
+// Tests for SkipFixture won't be executed.
+TEST_F(SkipFixture, SkipsOneTest) {
+ EXPECT_EQ(5, 7); // Won't fail
+}
+```
+
+As with assertion macros, you can stream a custom message into `GTEST_SKIP()`.
+
+## Teaching GoogleTest How to Print Your Values
+
+When a test assertion such as `EXPECT_EQ` fails, GoogleTest prints the argument
values to help you debug. It does this using a user-extensible value printer.
This printer knows how to print built-in C++ types, native arrays, STL
@@ -541,80 +315,103 @@ prints the raw bytes in the value and hopes that you the user can figure it out.
As mentioned earlier, the printer is *extensible*. That means you can teach it
to do a better job at printing your particular type than to dump the bytes. To
-do that, define `<<` for your type:
-
-```c++
-#include <ostream>
+do that, define an `AbslStringify()` overload as a `friend` function template
+for your type:
+```cpp
namespace foo {
-class Bar { // We want googletest to be able to print instances of this.
-...
- // Create a free inline friend function.
- friend std::ostream& operator<<(std::ostream& os, const Bar& bar) {
- return os << bar.DebugString(); // whatever needed to print bar to os
+class Point { // We want GoogleTest to be able to print instances of this.
+ ...
+ // Provide a friend overload.
+ template <typename Sink>
+ friend void AbslStringify(Sink& sink, const Point& point) {
+ absl::Format(&sink, "(%d, %d)", point.x, point.y);
}
+
+ int x;
+ int y;
};
// If you can't declare the function in the class it's important that the
-// << operator is defined in the SAME namespace that defines Bar. C++'s look-up
-// rules rely on that.
-std::ostream& operator<<(std::ostream& os, const Bar& bar) {
- return os << bar.DebugString(); // whatever needed to print bar to os
+// AbslStringify overload is defined in the SAME namespace that defines Point.
+// C++'s look-up rules rely on that.
+enum class EnumWithStringify { kMany = 0, kChoices = 1 };
+
+template <typename Sink>
+void AbslStringify(Sink& sink, EnumWithStringify e) {
+ absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices");
}
} // namespace foo
```
-Sometimes, this might not be an option: your team may consider it bad style to
-have a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that
-doesn't do what you want (and you cannot change it). If so, you can instead
-define a `PrintTo()` function like this:
+{: .callout .note}
+Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its
+string. For more information about supported operations on `AbslStringify()`'s
+sink, see go/abslstringify.
+
+`AbslStringify()` can also use `absl::StrFormat`'s catch-all `%v` type specifier
+within its own format strings to perform type deduction. `Point` above could be
+formatted as `"(%v, %v)"` for example, and deduce the `int` values as `%d`.
+
+Sometimes, `AbslStringify()` might not be an option: your team may wish to print
+types with extra debugging information for testing purposes only. If so, you can
+instead define a `PrintTo()` function like this:
```c++
#include <ostream>
namespace foo {
-class Bar {
+class Point {
...
- friend void PrintTo(const Bar& bar, std::ostream* os) {
- *os << bar.DebugString(); // whatever needed to print bar to os
+ friend void PrintTo(const Point& point, std::ostream* os) {
+ *os << "(" << point.x << "," << point.y << ")";
}
+
+ int x;
+ int y;
};
// If you can't declare the function in the class it's important that PrintTo()
-// is defined in the SAME namespace that defines Bar. C++'s look-up rules rely
-// on that.
-void PrintTo(const Bar& bar, std::ostream* os) {
- *os << bar.DebugString(); // whatever needed to print bar to os
+// is defined in the SAME namespace that defines Point. C++'s look-up rules
+// rely on that.
+void PrintTo(const Point& point, std::ostream* os) {
+ *os << "(" << point.x << "," << point.y << ")";
}
} // namespace foo
```
-If you have defined both `<<` and `PrintTo()`, the latter will be used when
-googletest is concerned. This allows you to customize how the value appears in
-googletest's output without affecting code that relies on the behavior of its
-`<<` operator.
+If you have defined both `AbslStringify()` and `PrintTo()`, the latter will be
+used by GoogleTest. This allows you to customize how the value appears in
+GoogleTest's output without affecting code that relies on the behavior of
+`AbslStringify()`.
+
+If you have an existing `<<` operator and would like to define an
+`AbslStringify()`, the latter will be used for GoogleTest printing.
-If you want to print a value `x` using googletest's value printer yourself, just
+If you want to print a value `x` using GoogleTest's value printer yourself, just
call `::testing::PrintToString(x)`, which returns an `std::string`:
```c++
-vector<pair<Bar, int> > bar_ints = GetBarIntVector();
+vector<pair<Point, int> > point_ints = GetPointIntVector();
-EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
- << "bar_ints = " << ::testing::PrintToString(bar_ints);
+EXPECT_TRUE(IsCorrectPointIntVector(point_ints))
+ << "point_ints = " << testing::PrintToString(point_ints);
```
+For more details regarding `AbslStringify()` and its integration with other
+libraries, see go/abslstringify.
+
## 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.
@@ -628,73 +425,16 @@ exception and avoid the crash. If you want to verify exceptions thrown by your
code, see [Exception Assertions](#ExceptionAssertions).
If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see
-Catching Failures
+["Catching" Failures](#catching-failures).
### How to Write a Death Test
-googletest has the following macros to support death tests:
-
-Fatal assertion | Nonfatal assertion | Verifies
------------------------------------------------- | ------------------------------------------------ | --------
-`ASSERT_DEATH(statement, matcher);` | `EXPECT_DEATH(statement, matcher);` | `statement` crashes with the given error
-`ASSERT_DEATH_IF_SUPPORTED(statement, matcher);` | `EXPECT_DEATH_IF_SUPPORTED(statement, matcher);` | if death tests are supported, verifies that `statement` crashes with the given error; otherwise verifies nothing
-`ASSERT_EXIT(statement, predicate, matcher);` | `EXPECT_EXIT(statement, predicate, matcher);` | `statement` exits with the given error, and its exit code matches `predicate`
-
-where `statement` is a statement that is expected to cause the process to die,
-`predicate` is a function or function object that evaluates an integer exit
-status, and `matcher` is either a GMock matcher matching a `const std::string&`
-or a (Perl) regular expression - either of which is matched against the stderr
-output of `statement`. For legacy reasons, a bare string (i.e. with no matcher)
-is interpreted as `ContainsRegex(str)`, **not** `Eq(str)`. Note that `statement`
-can be *any valid statement* (including *compound statement*) and doesn't have
-to be an expression.
-
-As usual, the `ASSERT` variants abort the current test function, while the
-`EXPECT` variants do not.
-
-> NOTE: We use the word "crash" here to mean that the process terminates with a
-> *non-zero* exit status code. There are two possibilities: either the process
-> has called `exit()` or `_exit()` with a non-zero value, or it may be killed by
-> a signal.
->
-> This means that if `*statement*` terminates the process with a 0 exit code, it
-> is *not* considered a crash by `EXPECT_DEATH`. Use `EXPECT_EXIT` instead if
-> this is the case, or if you want to restrict the exit code more precisely.
-
-A predicate here must accept an `int` and return a `bool`. The death test
-succeeds only if the predicate returns `true`. googletest defines a few
-predicates that handle the most common cases:
-
-```c++
-::testing::ExitedWithCode(exit_code)
-```
-
-This expression is `true` if the program exited normally with the given exit
-code.
-
-```c++
-::testing::KilledBySignal(signal_number) // Not available on Windows.
-```
-
-This expression is `true` if the program was killed by the given signal.
-
-The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate
-that verifies the process' exit code is non-zero.
-
-Note that a death test only cares about three things:
-
-1. does `statement` abort or exit the process?
-2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status
- satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`)
- is the exit status non-zero? And
-3. does the stderr output match `regex`?
-
-In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it
-will **not** cause the death test to fail, as googletest assertions don't abort
-the process.
+GoogleTest provides assertion macros to support death tests. See
+[Death Assertions](reference/assertions.md#death) in the Assertions Reference
+for details.
-To write a death test, simply use one of the above macros inside your test
-function. For example,
+To write a death test, simply use one of the macros inside your test function.
+For example,
```c++
TEST(MyDeathTest, Foo) {
@@ -706,11 +446,11 @@ TEST(MyDeathTest, Foo) {
}
TEST(MyDeathTest, NormalExit) {
- EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success");
+ EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success");
}
-TEST(MyDeathTest, KillMyself) {
- EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL),
+TEST(MyDeathTest, KillProcess) {
+ EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL),
"Sending myself unblockable signal");
}
```
@@ -720,13 +460,26 @@ verifies that:
* calling `Foo(5)` causes the process to die with the given error message,
* calling `NormalExit()` causes the process to print `"Success"` to stderr and
exit with exit code 0, and
-* calling `KillMyself()` kills the process with signal `SIGKILL`.
+* calling `KillProcess()` kills the process with signal `SIGKILL`.
The test function body may contain other assertions and statements as well, if
necessary.
+Note that a death test only cares about three things:
+
+1. does `statement` abort or exit the process?
+2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status
+ satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`)
+ is the exit status non-zero? And
+3. does the stderr output match `matcher`?
+
+In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it
+will **not** cause the death test to fail, as GoogleTest assertions don't abort
+the process.
+
### Death Test Naming
+{: .callout .important}
IMPORTANT: We strongly recommend you to follow the convention of naming your
**test suite** (not test) `*DeathTest` when it contains a death test, as
demonstrated in the above example. The
@@ -737,7 +490,7 @@ If a test fixture class is shared by normal tests and death tests, you can use
duplicating its code:
```c++
-class FooTest : public ::testing::Test { ... };
+class FooTest : public testing::Test { ... };
using FooDeathTest = FooTest;
@@ -752,12 +505,14 @@ 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
-[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
+syntax. To learn about POSIX syntax, you may want to read this
+[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_extended).
-On Windows, googletest uses its own simple regular expression implementation. It
+On Windows, GoogleTest uses its own simple regular expression implementation. It
lacks many features. For example, we don't support union (`"x|y"`), grouping
(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among
others. Below is what we do support (`A` denotes a literal character, period
@@ -787,7 +542,7 @@ Expression | Meaning
`$` | matches the end of a string (not that of each line)
`xy` | matches `x` followed by `y`
-To help you determine which capability is available on your system, googletest
+To help you determine which capability is available on your system, GoogleTest
defines macros to govern which regular expression it is using. The macros are:
`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death
tests to work in all cases, you can either `#if` on these macros or use the more
@@ -795,31 +550,8 @@ limited syntax only.
### How It Works
-Under the hood, `ASSERT_EXIT()` spawns a new process and executes the death test
-statement in that process. The details of how precisely that happens depend on
-the platform and the variable ::testing::GTEST_FLAG(death_test_style) (which is
-initialized from the command-line flag `--gtest_death_test_style`).
-
-* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the
- child, after which:
- * If the variable's value is `"fast"`, the death test statement is
- immediately executed.
- * If the variable's value is `"threadsafe"`, the child process re-executes
- the unit test binary just as it was originally invoked, but with some
- extra flags to cause just the single death test under consideration to
- be run.
-* On Windows, the child is spawned using the `CreateProcess()` API, and
- re-executes the binary to cause just the single death test under
- consideration to be run - much like the `threadsafe` mode on POSIX.
-
-Other values for the variable are illegal and will cause the death test to fail.
-Currently, the flag's default value is **"fast"**
-
-1. the child's exit status satisfies the predicate, and
-2. the child's stderr matches the regular expression.
-
-If the death test statement runs to completion without dying, the child process
-will nonetheless terminate, and the assertion fails.
+See [Death Assertions](reference/assertions.md#death) in the Assertions
+Reference.
### Death Tests And Threads
@@ -830,7 +562,7 @@ arrange that kind of environment. For example, statically-initialized modules
may start threads before main is ever reached. Once threads have been created,
it may be difficult or impossible to clean them up.
-googletest has three features intended to raise awareness of threading issues.
+GoogleTest has three features intended to raise awareness of threading issues.
1. A warning is emitted if multiple threads are running when a death test is
encountered.
@@ -853,7 +585,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,
@@ -862,13 +594,13 @@ restored afterwards, so you need not do that yourself. For example:
```c++
int main(int argc, char** argv) {
- InitGoogle(argv[0], &argc, &argv, true);
- ::testing::FLAGS_gtest_death_test_style = "fast";
+ testing::InitGoogleTest(&argc, argv);
+ 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(), "");
}
@@ -883,7 +615,7 @@ TEST(MyDeathTest, TestTwo) {
The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If
it leaves the current function via a `return` statement or by throwing an
-exception, the death test is considered to have failed. Some googletest macros
+exception, the death test is considered to have failed. Some GoogleTest macros
may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid
them in `statement`.
@@ -905,9 +637,15 @@ 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.
+
### Adding Traces to Assertions
If a test sub-routine is called from several places, when an assertion inside it
@@ -918,6 +656,9 @@ the `SCOPED_TRACE` macro or the `ScopedTrace` utility:
```c++
SCOPED_TRACE(message);
+```
+
+```c++
ScopedTrace trace("file_path", line_number, message);
```
@@ -953,7 +694,7 @@ path/to/foo_test.cc:11: Failure
Value of: Bar(n)
Expected: 1
Actual: 2
- Trace:
+Google Test trace:
path/to/foo_test.cc:17: A
path/to/foo_test.cc:12: Failure
@@ -1003,12 +744,12 @@ TEST(FooTest, Bar) {
// in Subroutine() to abort the entire test.
// The actual behavior: the function goes on after Subroutine() returns.
- int* p = NULL;
+ int* p = nullptr;
*p = 3; // Segfault!
}
```
-To alleviate this, googletest provides three different solutions. You could use
+To alleviate this, GoogleTest provides three different solutions. You could use
either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
`HasFatalFailure()` function. They are described in the following two
subsections.
@@ -1042,7 +783,7 @@ in it, the test will continue after the subroutine returns. This may not be what
you want.
Often people want fatal failures to propagate like exceptions. For that
-googletest offers the following macros:
+GoogleTest offers the following macros:
Fatal assertion | Nonfatal assertion | Verifies
------------------------------------- | ------------------------------------- | --------
@@ -1097,7 +838,7 @@ If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test
fixture, you must add the `::testing::Test::` prefix, as in:
```c++
-if (::testing::Test::HasFatalFailure()) return;
+if (testing::Test::HasFatalFailure()) return;
```
Similarly, `HasNonfatalFailure()` returns `true` if the current test has at
@@ -1123,17 +864,18 @@ 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" />
...
```
+{: .callout .note}
> NOTE:
>
> * `RecordProperty()` is a static member of the `Test` class. Therefore it
> needs to be prefixed with `::testing::Test::` if used outside of the
> `TEST` body and the test fixture class.
-> * `*key*` must be a valid XML attribute name, and cannot conflict with the
-> ones already used by googletest (`name`, `status`, `time`, `classname`,
+> * *`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`).
> * Calling `RecordProperty()` outside of the lifespan of a test is allowed.
> If it's called outside of a test but between a test suite's
@@ -1144,13 +886,13 @@ will output XML like this:
## Sharing Resources Between Tests in the Same Test Suite
-googletest creates a new test fixture object for each test in order to make
+GoogleTest creates a new test fixture object for each test in order to make
tests independent and easier to debug. However, sometimes tests use resources
that are expensive to set up, making the one-copy-per-test model prohibitively
expensive.
If the tests don't change the resource, there's no harm in their sharing a
-single resource copy. So, in addition to per-test set-up/tear-down, googletest
+single resource copy. So, in addition to per-test set-up/tear-down, GoogleTest
also supports per-test-suite set-up/tear-down. To use it:
1. In your test fixture class (say `FooTest` ), declare as `static` some member
@@ -1162,7 +904,7 @@ also supports per-test-suite set-up/tear-down. To use it:
`u`!) to set up the shared resources and a `static void TearDownTestSuite()`
function to tear them down.
-That's it! googletest automatically calls `SetUpTestSuite()` before running the
+That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the
*first test* in the `FooTest` test suite (i.e. before creating the first
`FooTest` object), and calls `TearDownTestSuite()` after running the *last test*
in it (i.e. after deleting the last `FooTest` object). In between, the tests can
@@ -1173,16 +915,31 @@ 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 if shared resources are not
+properly cleaned up in `TearDownTestSuite()`.
+
Here's an example of per-test-suite set-up and tear-down:
```c++
-class FooTest : public ::testing::Test {
+class FooTest : public testing::Test {
protected:
// Per-test-suite set-up.
// Called before the first test in this test suite.
// Can be omitted if not needed.
static void SetUpTestSuite() {
shared_resource_ = new ...;
+
+ // If `shared_resource_` is **not deleted** in `TearDownTestSuite()`,
+ // reallocation should be prevented because `SetUpTestSuite()` may be called
+ // in subclasses of FooTest and lead to memory leak.
+ //
+ // if (shared_resource_ == nullptr) {
+ // shared_resource_ = new ...;
+ // }
}
// Per-test-suite tear-down.
@@ -1190,20 +947,20 @@ class FooTest : public ::testing::Test {
// Can be omitted if not needed.
static void TearDownTestSuite() {
delete shared_resource_;
- shared_resource_ = NULL;
+ shared_resource_ = nullptr;
}
// You can define per-test set-up logic as usual.
- virtual void SetUp() { ... }
+ void SetUp() override { ... }
// You can define per-test tear-down logic as usual.
- virtual void TearDown() { ... }
+ void TearDown() override { ... }
// Some expensive resource shared by all tests.
static T* shared_resource_;
};
-T* FooTest::shared_resource_ = NULL;
+T* FooTest::shared_resource_ = nullptr;
TEST_F(FooTest, Test1) {
... you can refer to shared_resource_ here ...
@@ -1214,6 +971,7 @@ TEST_F(FooTest, Test2) {
}
```
+{: .callout .note}
NOTE: Though the above code declares `SetUpTestSuite()` protected, it may
sometimes be necessary to declare it public, such as when using it with
`TEST_P`.
@@ -1229,7 +987,7 @@ environment, which knows how to set-up and tear-down:
```c++
class Environment : public ::testing::Environment {
public:
- virtual ~Environment() {}
+ ~Environment() override {}
// Override this to define how to set up the environment.
void SetUp() override {}
@@ -1239,7 +997,7 @@ class Environment : public ::testing::Environment {
};
```
-Then, you register an instance of your environment class with googletest by
+Then, you register an instance of your environment class with GoogleTest by
calling the `::testing::AddGlobalTestEnvironment()` function:
```c++
@@ -1256,7 +1014,7 @@ It's OK to register multiple environment objects. In this suite, their `SetUp()`
will be called in the order they are registered, and their `TearDown()` will be
called in the reverse order.
-Note that googletest takes ownership of the registered environment objects.
+Note that GoogleTest takes ownership of the registered environment objects.
Therefore **do not delete them** by yourself.
You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called,
@@ -1265,8 +1023,8 @@ probably in `main()`. If you use `gtest_main`, you need to call this before
variable like this:
```c++
-::testing::Environment* const foo_env =
- ::testing::AddGlobalTestEnvironment(new FooEnvironment);
+testing::Environment* const foo_env =
+ testing::AddGlobalTestEnvironment(new FooEnvironment);
```
However, we strongly recommend you to write your own `main()` and call
@@ -1301,13 +1059,14 @@ and `testing::WithParamInterface<T>`. `T` can be any copyable type. If it's a
raw pointer, you are responsible for managing the lifespan of the pointed
values.
+{: .callout .note}
NOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()`
they must be declared **public** rather than **protected** in order to use
`TEST_P`.
```c++
class FooTest :
- public testing::TestWithParam<const char*> {
+ public testing::TestWithParam<absl::string_view> {
// You can implement all the usual fixture class members here.
// To access the test parameter, call GetParam() from class
// TestWithParam<T>.
@@ -1318,7 +1077,7 @@ class BaseTest : public testing::Test {
...
};
class BarTest : public BaseTest,
- public testing::WithParamInterface<const char*> {
+ public testing::WithParamInterface<absl::string_view> {
...
};
```
@@ -1340,80 +1099,85 @@ TEST_P(FooTest, HasBlahBlah) {
}
```
-Finally, you can use `INSTANTIATE_TEST_SUITE_P` to instantiate the test suite
-with any set of parameters you want. googletest defines a number of functions
-for generating test parameters. They return what we call (surprise!) *parameter
-generators*. Here is a summary of them, which are all in the `testing`
-namespace:
-
-<!-- mdformat off(github rendering does not support multiline tables) -->
-
-| Parameter Generator | Behavior |
-| ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
-| `Range(begin, end [, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. |
-| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. |
-| `ValuesIn(container)` and `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)` |
-| `Bool()` | Yields sequence `{false, true}`. |
-| `Combine(g1, g2, ..., gN)` | Yields all combinations (Cartesian product) as std\:\:tuples of the values generated by the `N` generators. |
+Finally, you can use the `INSTANTIATE_TEST_SUITE_P` macro to instantiate the
+test suite with any set of parameters you want. GoogleTest defines a number of
+functions for generating test parameters—see details at
+[`INSTANTIATE_TEST_SUITE_P`](reference/testing.md#INSTANTIATE_TEST_SUITE_P) in
+the Testing Reference.
-<!-- mdformat on-->
-
-For more details, see the comments at the definitions of these functions.
-
-The following statement will instantiate tests from the `FooTest` test suite
-each with parameter values `"meeny"`, `"miny"`, and `"moe"`.
+For example, the following statement will instantiate tests from the `FooTest`
+test suite each with parameter values `"meeny"`, `"miny"`, and `"moe"` using the
+[`Values`](reference/testing.md#param-generators) parameter generator:
```c++
-INSTANTIATE_TEST_SUITE_P(InstantiationName,
+INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe,
FooTest,
testing::Values("meeny", "miny", "moe"));
```
+{: .callout .note}
NOTE: The code above must be placed at global or namespace scope, not at
function scope.
-NOTE: Don't forget this step! If you do your test will silently pass, but none
-of its suites will ever run!
+The first argument to `INSTANTIATE_TEST_SUITE_P` is a unique name for the
+instantiation of the test suite. The next argument is the name of the test
+pattern, and the last is the
+[parameter generator](reference/testing.md#param-generators).
-To distinguish different instances of the pattern (yes, you can instantiate it
-more than once), the first argument to `INSTANTIATE_TEST_SUITE_P` is a prefix
-that will be added to the actual test suite name. Remember to pick unique
-prefixes for different instantiations. The tests from the instantiation above
-will have these names:
+The parameter generator expression is not evaluated until GoogleTest is
+initialized (via `InitGoogleTest()`). Any prior initialization done in the
+`main` function will be accessible from the parameter generator, for example,
+the results of flag parsing.
+
+You can instantiate a test pattern more than once, so to distinguish different
+instances of the pattern, the instantiation name is added as a prefix to the
+actual test suite name. Remember to pick unique prefixes for different
+instantiations. The tests from the instantiation above will have these names:
-* `InstantiationName/FooTest.DoesBlah/0` for `"meeny"`
-* `InstantiationName/FooTest.DoesBlah/1` for `"miny"`
-* `InstantiationName/FooTest.DoesBlah/2` for `"moe"`
-* `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"`
-* `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"`
-* `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"`
+* `MeenyMinyMoe/FooTest.DoesBlah/0` for `"meeny"`
+* `MeenyMinyMoe/FooTest.DoesBlah/1` for `"miny"`
+* `MeenyMinyMoe/FooTest.DoesBlah/2` for `"moe"`
+* `MeenyMinyMoe/FooTest.HasBlahBlah/0` for `"meeny"`
+* `MeenyMinyMoe/FooTest.HasBlahBlah/1` for `"miny"`
+* `MeenyMinyMoe/FooTest.HasBlahBlah/2` for `"moe"`
You can use these names in [`--gtest_filter`](#running-a-subset-of-the-tests).
-This statement will instantiate all tests from `FooTest` again, each with
-parameter values `"cat"` and `"dog"`:
+The following statement will instantiate all tests from `FooTest` again, each
+with parameter values `"cat"` and `"dog"` using the
+[`ValuesIn`](reference/testing.md#param-generators) parameter generator:
```c++
-const char* pets[] = {"cat", "dog"};
-INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest,
- testing::ValuesIn(pets));
+constexpr absl::string_view kPets[] = {"cat", "dog"};
+INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets));
```
The tests from the instantiation above will have these names:
-* `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"`
-* `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"`
-* `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"`
-* `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"`
+* `Pets/FooTest.DoesBlah/0` for `"cat"`
+* `Pets/FooTest.DoesBlah/1` for `"dog"`
+* `Pets/FooTest.HasBlahBlah/0` for `"cat"`
+* `Pets/FooTest.HasBlahBlah/1` for `"dog"`
Please note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the
given test suite, whether their definitions come before or *after* the
`INSTANTIATE_TEST_SUITE_P` statement.
+Additionally, by default, every `TEST_P` without a corresponding
+`INSTANTIATE_TEST_SUITE_P` causes a failing test in test suite
+`GoogleTestVerification`. If you have a test suite where that omission is not an
+error, for example it is in a library that may be linked in for other reasons or
+where the list of test cases is dynamic and may be empty, then this check can be
+suppressed by tagging the test suite:
+
+```c++
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest);
+```
+
You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples.
-[sample7_unittest.cc]: ../samples/sample7_unittest.cc "Parameterized Test example"
-[sample8_unittest.cc]: ../samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
+[sample7_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc "Parameterized Test example"
+[sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
### Creating Value-Parameterized Abstract Tests
@@ -1450,6 +1214,7 @@ the test parameters. The function should accept one argument of type
returns the value of `testing::PrintToString(GetParam())`. It does not work for
`std::string` or C strings.
+{: .callout .note}
NOTE: test names must be non-empty, unique, and may only contain ASCII
alphanumeric characters. In particular, they
[should not contain underscores](faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore)
@@ -1476,17 +1241,17 @@ for conciseness:
```c++
enum class MyType { MY_FOO = 0, MY_BAR = 1 };
-class MyTestSuite : public testing::TestWithParam<std::tuple<MyType, string>> {
+class MyTestSuite : public testing::TestWithParam<std::tuple<MyType, std::string>> {
};
INSTANTIATE_TEST_SUITE_P(
MyGroup, MyTestSuite,
testing::Combine(
- testing::Values(MyType::VALUE_0, MyType::VALUE_1),
- testing::ValuesIn("", "")),
+ testing::Values(MyType::MY_FOO, MyType::MY_BAR),
+ testing::Values("A", "B")),
[](const testing::TestParamInfo<MyTestSuite::ParamType>& info) {
- string name = absl::StrCat(
- std::get<0>(info.param) == MY_FOO ? "Foo" : "Bar", "_",
+ std::string name = absl::StrCat(
+ std::get<0>(info.param) == MyType::MY_FOO ? "Foo" : "Bar",
std::get<1>(info.param));
absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_');
return name;
@@ -1515,10 +1280,10 @@ Remember to derive it from `::testing::Test`:
```c++
template <typename T>
-class FooTest : public ::testing::Test {
+class FooTest : public testing::Test {
public:
...
- typedef std::list<T> List;
+ using List = std::list<T>;
static T shared_;
T value_;
};
@@ -1563,7 +1328,7 @@ TYPED_TEST(FooTest, HasPropertyA) { ... }
You can see [sample6_unittest.cc] for a complete example.
-[sample6_unittest.cc]: ../samples/sample6_unittest.cc "Typed Test example"
+[sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example"
## Type-Parameterized Tests
@@ -1583,7 +1348,8 @@ First, define a fixture class template, as we did with typed tests:
```c++
template <typename T>
-class FooTest : public ::testing::Test {
+class FooTest : public testing::Test {
+ void DoSomethingInteresting();
...
};
```
@@ -1601,6 +1367,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()
...
}
@@ -1622,7 +1391,7 @@ put the above code in a header file, you can `#include` it in multiple C++
source files and instantiate it multiple times.
```c++
-typedef ::testing::Types<char, int, unsigned int> MyTypes;
+using MyTypes = ::testing::Types<char, int, unsigned int>;
INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
```
@@ -1718,10 +1487,11 @@ To test them, we use the following special techniques:
}
```
- Pay special attention when your class is defined in a namespace, as you
- should define your test fixtures and tests in the same namespace if you want
- them to be friends of your class. For example, if the code to be tested
- looks like:
+ Pay special attention when your class is defined in a namespace. If you want
+ your test fixtures and tests to be friends of your class, then they must be
+ defined in the exact same namespace (no anonymous or inline namespaces).
+
+ For example, if the code to be tested looks like:
```c++
namespace my_namespace {
@@ -1741,7 +1511,7 @@ To test them, we use the following special techniques:
```c++
namespace my_namespace {
- class FooTest : public ::testing::Test {
+ class FooTest : public testing::Test {
protected:
...
};
@@ -1754,16 +1524,16 @@ To test them, we use the following special techniques:
## "Catching" Failures
-If you are building a testing utility on top of googletest, you'll want to test
-your utility. What framework would you use to test it? googletest, of course.
+If you are building a testing utility on top of GoogleTest, you'll want to test
+your utility. What framework would you use to test it? GoogleTest, of course.
The challenge is to verify that your testing utility reports failures correctly.
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
+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?
-gunit-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);
@@ -1788,6 +1558,7 @@ well, use one of the following macros instead:
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring);
```
+{: .callout .note}
NOTE: Assertions from multiple threads are currently not supported on Windows.
For technical reasons, there are some caveats:
@@ -1803,7 +1574,7 @@ For technical reasons, there are some caveats:
## Registering tests programmatically
The `TEST` macros handle the vast majority of all use cases, but there are few
-were runtime registration logic is required. For those cases, the framework
+where runtime registration logic is required. For those cases, the framework
provides the `::testing::RegisterTest` that allows callers to register arbitrary
tests dynamically.
@@ -1836,7 +1607,7 @@ undefined.
Use case example:
```c++
-class MyFixture : public ::testing::Test {
+class MyFixture : public testing::Test {
public:
// All of these optional, just like in regular macro usage.
static void SetUpTestSuite() { ... }
@@ -1856,7 +1627,7 @@ class MyTest : public MyFixture {
void RegisterMyTests(const std::vector<int>& values) {
for (int v : values) {
- ::testing::RegisterTest(
+ testing::RegisterTest(
"MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
std::to_string(v).c_str(),
__FILE__, __LINE__,
@@ -1866,45 +1637,30 @@ 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.
For example, you may be using the `SetUp()` method of your test fixture to set
-the golden file name based on which test is running. The `::testing::TestInfo`
-class has this information:
-
-```c++
-namespace testing {
-
-class TestInfo {
- public:
- // Returns the test suite name and the test name, respectively.
- //
- // Do NOT delete or free the return value - it's managed by the
- // TestInfo class.
- const char* test_suite_name() const;
- const char* name() const;
-};
-
-}
-```
+the golden file name based on which test is running. The
+[`TestInfo`](reference/testing.md#TestInfo) class has this information.
To obtain a `TestInfo` object for the currently running test, call
-`current_test_info()` on the `UnitTest` singleton object:
+`current_test_info()` on the [`UnitTest`](reference/testing.md#UnitTest)
+singleton object:
```c++
// Gets information about the currently running test.
// Do NOT delete the returned object - it's managed by the UnitTest class.
- const ::testing::TestInfo* const test_info =
- ::testing::UnitTest::GetInstance()->current_test_info();
-
-
+ const testing::TestInfo* const test_info =
+ testing::UnitTest::GetInstance()->current_test_info();
printf("We are in test %s of test suite %s.\n",
test_info->name(),
@@ -1912,13 +1668,13 @@ To obtain a `TestInfo` object for the currently running test, call
```
`current_test_info()` returns a null pointer if no test is running. In
-particular, you cannot find the test suite name in `TestSuiteSetUp()`,
-`TestSuiteTearDown()` (where you know the test suite name implicitly), or
+particular, you cannot find the test suite name in `SetUpTestSuite()`,
+`TearDownTestSuite()` (where you know the test suite name implicitly), or
functions called from them.
-## Extending googletest by Handling Test Events
+## Extending GoogleTest by Handling Test Events
-googletest provides an **event listener API** to let you receive notifications
+GoogleTest provides an **event listener API** to let you receive notifications
about the progress of a test program and test failures. The events you can
listen to include the start and end of the test program, a test suite, or a test
method, among others. You may use this API to augment or replace the standard
@@ -1928,12 +1684,14 @@ checkpoints to implement a resource leak checker, for example.
### Defining Event Listeners
-To define a event listener, you subclass either testing::TestEventListener or
-testing::EmptyTestEventListener The former is an (abstract) interface, where
-*each pure virtual method can be overridden to handle a test event* (For
-example, when a test starts, the `OnTestStart()` method will be called.). The
-latter provides an empty implementation of all methods in the interface, such
-that a subclass only needs to override the methods it cares about.
+To define a event listener, you subclass either
+[`testing::TestEventListener`](reference/testing.md#TestEventListener) or
+[`testing::EmptyTestEventListener`](reference/testing.md#EmptyTestEventListener)
+The former is an (abstract) interface, where *each pure virtual method can be
+overridden to handle a test event* (For example, when a test starts, the
+`OnTestStart()` method will be called.). The latter provides an empty
+implementation of all methods in the interface, such that a subclass only needs
+to override the methods it cares about.
When an event is fired, its context is passed to the handler function as an
argument. The following argument types are used:
@@ -1950,15 +1708,15 @@ interesting information about the event and the test program's state.
Here's an example:
```c++
- class MinimalistPrinter : public ::testing::EmptyTestEventListener {
+ class MinimalistPrinter : public testing::EmptyTestEventListener {
// Called before a test starts.
- virtual void OnTestStart(const ::testing::TestInfo& test_info) {
+ void OnTestStart(const testing::TestInfo& test_info) override {
printf("*** Test %s.%s starting.\n",
test_info.test_suite_name(), test_info.name());
}
// Called after a failed assertion or a SUCCESS().
- virtual void OnTestPartResult(const ::testing::TestPartResult& test_part_result) {
+ void OnTestPartResult(const testing::TestPartResult& test_part_result) override {
printf("%s in %s:%d\n%s\n",
test_part_result.failed() ? "*** Failure" : "Success",
test_part_result.file_name(),
@@ -1967,7 +1725,7 @@ Here's an example:
}
// Called after a test ends.
- virtual void OnTestEnd(const ::testing::TestInfo& test_info) {
+ void OnTestEnd(const testing::TestInfo& test_info) override {
printf("*** Test %s.%s ending.\n",
test_info.test_suite_name(), test_info.name());
}
@@ -1977,17 +1735,18 @@ Here's an example:
### Using Event Listeners
To use the event listener you have defined, add an instance of it to the
-googletest event listener list (represented by class TestEventListeners - note
-the "s" at the end of the name) in your `main()` function, before calling
+GoogleTest event listener list (represented by class
+[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s"
+at the end of the name) in your `main()` function, before calling
`RUN_ALL_TESTS()`:
```c++
int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
+ testing::InitGoogleTest(&argc, argv);
// Gets hold of the event listener list.
- ::testing::TestEventListeners& listeners =
- ::testing::UnitTest::GetInstance()->listeners();
- // Adds a listener to the end. googletest takes the ownership.
+ testing::TestEventListeners& listeners =
+ testing::UnitTest::GetInstance()->listeners();
+ // Adds a listener to the end. GoogleTest takes the ownership.
listeners.Append(new MinimalistPrinter);
return RUN_ALL_TESTS();
}
@@ -2008,7 +1767,7 @@ You can do so by adding one line:
Now, sit back and enjoy a completely different output from your tests. For more
details, see [sample9_unittest.cc].
-[sample9_unittest.cc]: ../samples/sample9_unittest.cc "Event listener example"
+[sample9_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc "Event listener example"
You may append more than one listener to the list. When an `On*Start()` or
`OnTestPartResult()` event is fired, the listeners will receive it in the order
@@ -2035,11 +1794,11 @@ by the former.
See [sample10_unittest.cc] for an example of a failure-raising listener.
-[sample10_unittest.cc]: ../samples/sample10_unittest.cc "Failure-raising listener example"
+[sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example"
## Running Test Programs: Advanced Options
-googletest test programs are ordinary executables. Once built, you can run them
+GoogleTest test programs are ordinary executables. Once built, you can run them
directly and affect their behavior via the following environment variables
and/or command line flags. For the flags to work, your programs must call
`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
@@ -2072,10 +1831,10 @@ corresponding environment variable for this flag.
#### Running a Subset of the Tests
-By default, a googletest program runs all tests the user has defined. Sometimes,
+By default, a GoogleTest program runs all tests the user has defined. Sometimes,
you want to run only a subset of the tests (e.g. for debugging or quickly
verifying a change). If you set the `GTEST_FILTER` environment variable or the
-`--gtest_filter` flag to a filter string, googletest will only run the tests
+`--gtest_filter` flag to a filter string, GoogleTest will only run the tests
whose full names (in the form of `TestSuiteName.TestName`) match the filter.
The format of a filter is a '`:`'-separated list of wildcard patterns (called
@@ -2104,6 +1863,14 @@ For example:
everything in test suite `FooTest` except `FooTest.Bar` and everything in
test suite `BarTest` except `BarTest.Foo`.
+#### Stop test execution upon first failure
+
+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.
+
#### Temporarily Disabling Tests
If you have a broken test that you cannot fix right away, you can add the
@@ -2115,26 +1882,28 @@ If you need to disable all tests in a test suite, you can either add `DISABLED_`
to the front of the name of each test, or alternatively add it to the front of
the test suite name.
-For example, the following tests won't be run by googletest, even though they
+For example, the following tests won't be run by GoogleTest, even though they
will still be compiled:
```c++
// Tests that Foo does Abc.
TEST(FooTest, DISABLED_DoesAbc) { ... }
-class DISABLED_BarTest : public ::testing::Test { ... };
+class DISABLED_BarTest : public testing::Test { ... };
// Tests that Bar does Xyz.
TEST_F(DISABLED_BarTest, DoesXyz) { ... }
```
+{: .callout .note}
NOTE: This feature should only be used for temporary pain-relief. You still have
-to fix the disabled tests at a later date. As a reminder, googletest will print
+to fix the disabled tests at a later date. As a reminder, GoogleTest will print
a banner warning you if a test program contains any disabled tests.
-TIP: You can easily count the number of disabled tests you have using `gsearch`
-and/or `grep`. This number can be used as a metric for improving your test
-quality.
+{: .callout .tip}
+TIP: You can easily count the number of disabled tests you have using
+`grep`. This number can be used as a metric for
+improving your test quality.
#### Temporarily Enabling Disabled Tests
@@ -2173,8 +1942,12 @@ Repeat the tests whose name matches the filter 1000 times.
If your test program contains
[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be
-repeated in each iteration as well, as the flakiness may be in it. You can also
-specify the repeat count by setting the `GTEST_REPEAT` environment variable.
+repeated in each iteration as well, as the flakiness may be in it. To avoid
+repeating global set-up/tear-down, specify
+`--gtest_recreate_environments_when_repeating=false`{.nowrap}.
+
+You can also specify the repeat count by setting the `GTEST_REPEAT` environment
+variable.
### Shuffling the Tests
@@ -2182,87 +1955,129 @@ You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`
environment variable to `1`) to run the tests in a program in a random order.
This helps to reveal bad dependencies between tests.
-By default, googletest uses a random seed calculated from the current time.
+By default, GoogleTest uses a random seed calculated from the current time.
Therefore you'll get a different order every time. The console output includes
the random seed value, such that you can reproduce an order-related test failure
later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED`
flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an
integer in the range [0, 99999]. The seed value 0 is special: it tells
-googletest to do the default behavior of calculating the seed from the current
+GoogleTest to do the default behavior of calculating the seed from the current
time.
-If you combine this with `--gtest_repeat=N`, googletest will pick a different
+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
-googletest can use colors in its terminal output to make it easier to spot the
+GoogleTest can use colors in its terminal output to make it easier to spot the
important information:
-<code>
-...<br/>
- <font color="green">[----------]</font><font color="black"> 1 test from
- FooTest</font><br/>
- <font color="green">[ RUN &nbsp; &nbsp; &nbsp;]</font><font color="black">
- FooTest.DoesAbc</font><br/>
- <font color="green">[ &nbsp; &nbsp; &nbsp; OK ]</font><font color="black">
- FooTest.DoesAbc </font><br/>
- <font color="green">[----------]</font><font color="black">
- 2 tests from BarTest</font><br/>
- <font color="green">[ RUN &nbsp; &nbsp; &nbsp;]</font><font color="black">
- BarTest.HasXyzProperty </font><br/>
- <font color="green">[ &nbsp; &nbsp; &nbsp; OK ]</font><font color="black">
- BarTest.HasXyzProperty</font><br/>
- <font color="green">[ RUN &nbsp; &nbsp; &nbsp;]</font><font color="black">
- BarTest.ReturnsTrueOnSuccess ... some error messages ...</font><br/>
- <font color="red">[ &nbsp; FAILED ]</font><font color="black">
- BarTest.ReturnsTrueOnSuccess ...</font><br/>
- <font color="green">[==========]</font><font color="black">
- 30 tests from 14 test suites ran.</font><br/>
- <font color="green">[ &nbsp; PASSED ]</font><font color="black">
- 28 tests.</font><br/>
- <font color="red">[ &nbsp; FAILED ]</font><font color="black">
- 2 tests, listed below:</font><br/>
- <font color="red">[ &nbsp; FAILED ]</font><font color="black">
- BarTest.ReturnsTrueOnSuccess</font><br/>
- <font color="red">[ &nbsp; FAILED ]</font><font color="black">
- AnotherTest.DoesXyz<br/>
-<br/>
- 2 FAILED TESTS
- </font>
-</code>
+<pre>...
+<font color="green">[----------]</font> 1 test from FooTest
+<font color="green">[ RUN ]</font> FooTest.DoesAbc
+<font color="green">[ OK ]</font> FooTest.DoesAbc
+<font color="green">[----------]</font> 2 tests from BarTest
+<font color="green">[ RUN ]</font> BarTest.HasXyzProperty
+<font color="green">[ OK ]</font> BarTest.HasXyzProperty
+<font color="green">[ RUN ]</font> BarTest.ReturnsTrueOnSuccess
+... some error messages ...
+<font color="red">[ FAILED ]</font> BarTest.ReturnsTrueOnSuccess
+...
+<font color="green">[==========]</font> 30 tests from 14 test suites ran.
+<font color="green">[ PASSED ]</font> 28 tests.
+<font color="red">[ FAILED ]</font> 2 tests, listed below:
+<font color="red">[ FAILED ]</font> BarTest.ReturnsTrueOnSuccess
+<font color="red">[ FAILED ]</font> AnotherTest.DoesXyz
+
+ 2 FAILED TESTS
+</pre>
You can set the `GTEST_COLOR` environment variable or the `--gtest_color`
command line flag to `yes`, `no`, or `auto` (the default) to enable colors,
-disable colors, or let googletest decide. When the value is `auto`, googletest
+disable colors, or let GoogleTest decide. When the value is `auto`, GoogleTest
will use colors if and only if the output goes to a terminal and (on non-Windows
platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`.
+#### Suppressing test passes
+
+By default, GoogleTest prints 1 line of output for each test, indicating if it
+passed or failed. To show only test failures, run the test program with
+`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`.
+
#### Suppressing the Elapsed Time
-By default, googletest prints the time it takes to run each test. To disable
+By default, GoogleTest prints the time it takes to run each test. To disable
that, run the test program with the `--gtest_print_time=0` command line flag, or
set the GTEST_PRINT_TIME environment variable to `0`.
#### Suppressing UTF-8 Text Output
-In case of assertion failures, googletest prints expected and actual values of
+In case of assertion failures, GoogleTest prints expected and actual values of
type `string` both as hex-encoded strings as well as in readable UTF-8 text if
they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8
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
+GoogleTest can emit a detailed XML report to a file in addition to its normal
textual output. The report contains the duration of each test, and thus can help
-you identify slow tests. The report is also used by the http://unittest
-dashboard to show per-test-method error messages.
+you identify slow tests.
To generate the XML report, set the `GTEST_OUTPUT` environment variable or the
`--gtest_output` flag to the string `"xml:path_to_output_file"`, which will
@@ -2271,15 +2086,15 @@ in which case the output can be found in the `test_detail.xml` file in the
current directory.
If you specify a directory (for example, `"xml:output/directory/"` on Linux or
-`"xml:output\directory\"` on Windows), googletest will create the XML file in
+`"xml:output\directory\"` on Windows), GoogleTest will create the XML file in
that directory, named after the test executable (e.g. `foo_test.xml` for test
program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left
-over from a previous run), googletest will pick a different name (e.g.
+over from a previous run), GoogleTest will pick a different name (e.g.
`foo_test_1.xml`) to avoid overwriting it.
The report is based on the `junitreport` Ant task. Since that format was
originally intended for Java, a little interpretation is required to make it
-apply to googletest tests, as shown here:
+apply to GoogleTest tests, as shown here:
```xml
<testsuites name="AllTests" ...>
@@ -2294,8 +2109,8 @@ apply to googletest tests, as shown here:
```
* The root `<testsuites>` element corresponds to the entire test program.
-* `<testsuite>` elements correspond to googletest test suites.
-* `<testcase>` elements correspond to googletest test functions.
+* `<testsuite>` elements correspond to GoogleTest test suites.
+* `<testcase>` elements correspond to GoogleTest test functions.
For instance, the following program
@@ -2311,15 +2126,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>
@@ -2328,7 +2143,7 @@ could generate this report:
Things to note:
* The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how
- many test functions the googletest program or test suite contains, while the
+ many test functions the GoogleTest program or test suite contains, while the
`failures` attribute tells how many of them failed.
* The `time` attribute expresses the duration of the test, test suite, or
@@ -2337,12 +2152,15 @@ Things to note:
* The `timestamp` attribute records the local date and time of the test
execution.
-* Each `<failure>` element corresponds to a single failed googletest
+* 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.
#### Generating a JSON Report
-googletest can also emit a JSON report as an alternative format to XML. To
+GoogleTest can also emit a JSON report as an alternative format to XML. To
generate the JSON report, set the `GTEST_OUTPUT` environment variable or the
`--gtest_output` flag to the string `"json:path_to_output_file"`, which will
create the file at the given location. You can also just use the string
@@ -2376,6 +2194,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"]
@@ -2453,6 +2273,8 @@ message TestCase {
message TestInfo {
string name = 1;
+ string file = 6;
+ int32 line = 7;
enum Status {
RUN = 0;
NOTRUN = 1;
@@ -2496,6 +2318,8 @@ could generate this report:
"testsuite": [
{
"name": "Addition",
+ "file": "test.cpp",
+ "line": 1,
"status": "RUN",
"time": "0.007s",
"classname": "",
@@ -2512,6 +2336,8 @@ could generate this report:
},
{
"name": "Subtraction",
+ "file": "test.cpp",
+ "line": 2,
"status": "RUN",
"time": "0.005s",
"classname": ""
@@ -2527,6 +2353,8 @@ could generate this report:
"testsuite": [
{
"name": "NonContradiction",
+ "file": "test.cpp",
+ "line": 3,
"status": "RUN",
"time": "0.005s",
"classname": ""
@@ -2537,15 +2365,27 @@ could generate this report:
}
```
+{: .callout .important}
IMPORTANT: The exact format of the JSON document is subject to change.
### Controlling How Failures Are Reported
+#### 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.
+
+This feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment
+variable has been set.
+
#### Turning Assertion Failures into Break-Points
When running test programs under a debugger, it's very convenient if the
debugger can catch an assertion failure and automatically drop into interactive
-mode. googletest's *break-on-failure* mode supports this behavior.
+mode. GoogleTest's *break-on-failure* mode supports this behavior.
To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value
other than `0`. Alternatively, you can use the `--gtest_break_on_failure`
@@ -2553,9 +2393,9 @@ command line flag.
#### Disabling Catching Test-Thrown Exceptions
-googletest can be used either with or without exceptions enabled. If a test
+GoogleTest can be used either with or without exceptions enabled. If a test
throws a C++ exception or (on Windows) a structured exception (SEH), by default
-googletest catches it, reports it as a test failure, and continues with the next
+GoogleTest catches it, reports it as a test failure, and continues with the next
test method. This maximizes the coverage of a test run. Also, on Windows an
uncaught exception will cause a pop-up window, so catching the exceptions allows
you to run the tests automatically.
@@ -2565,3 +2405,32 @@ to be handled by the debugger, such that you can examine the call stack when an
exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS`
environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when
running the tests.
+
+### Sanitizer Integration
+
+The
+[Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html),
+[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer),
+and
+[Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual)
+all provide weak functions that you can override to trigger explicit failures
+when they detect sanitizer errors, such as creating a reference from `nullptr`.
+To override these functions, place definitions for them in a source file that
+you compile as part of your main binary:
+
+```
+extern "C" {
+void __ubsan_on_report() {
+ FAIL() << "Encountered an undefined behavior sanitizer error";
+}
+void __asan_on_error() {
+ FAIL() << "Encountered an address sanitizer error";
+}
+void __tsan_on_report() {
+ FAIL() << "Encountered a thread sanitizer error";
+}
+} // extern "C"
+```
+
+After compiling your project with one of the sanitizers enabled, if a particular
+test triggers a sanitizer error, GoogleTest will report that it failed.
diff --git a/docs/assets/css/style.scss b/docs/assets/css/style.scss
new file mode 100644
index 000000000000..bb30f418da7b
--- /dev/null
+++ b/docs/assets/css/style.scss
@@ -0,0 +1,5 @@
+---
+---
+
+@import "jekyll-theme-primer";
+@import "main";
diff --git a/docs/community_created_documentation.md b/docs/community_created_documentation.md
new file mode 100644
index 000000000000..4569075ff23b
--- /dev/null
+++ b/docs/community_created_documentation.md
@@ -0,0 +1,7 @@
+# Community-Created Documentation
+
+The following is a list, in no particular order, of links to documentation
+created by the Googletest community.
+
+* [Googlemock Insights](https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/googletest/insights.md),
+ by [ElectricRCAircraftGuy](https://github.com/ElectricRCAircraftGuy)
diff --git a/googletest/docs/faq.md b/docs/faq.md
index 960a827989c9..1928097292a2 100644
--- a/googletest/docs/faq.md
+++ b/docs/faq.md
@@ -1,9 +1,12 @@
-# Googletest FAQ
-
-<!-- GOOGLETEST_CM0014 DO NOT DELETE -->
+# 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
+[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition
+to the following rationale.
+
Underscore (`_`) is special, as C++ reserves the following to be used by the
compiler and the standard library:
@@ -47,42 +50,42 @@ 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 `EXPECT_NE(nullptr, ptr)` and `ASSERT_NE(nullptr,
-ptr)`. This is the preferred syntax in the style guide because nullptr does not
-have the type problems that NULL does. Which is why NULL does not work.
+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)`,
+`ASSERT_NE(ptr, nullptr)`. This is the preferred syntax in the style guide
+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).
-The `EXPECT_EQ()` macro takes the *expected* value as its first argument and the
-*actual* value as the second. It's reasonable that someone wants to write
-`EXPECT_EQ(NULL, some_expression)`, and this indeed was requested several times.
-Therefore we implemented it.
+Historically, the `EXPECT_EQ()` macro took the *expected* value as its first
+argument and the *actual* value as the second, though this argument order is now
+discouraged. It was reasonable that someone wanted
+to write `EXPECT_EQ(NULL, some_expression)`, and this indeed was requested
+several times. Therefore we implemented it.
-The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the assertion
+The need for `EXPECT_NE(NULL, ptr)` wasn't nearly as strong. When the assertion
fails, you already know that `ptr` must be `NULL`, so it doesn't add any
information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)`
works just as well.
-If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll have to
-support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, we don't have a
-convention on the order of the two arguments for `EXPECT_NE`. This means using
-the template meta programming tricks twice in the implementation, making it even
-harder to understand and maintain. We believe the benefit doesn't justify the
-cost.
+If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'd have to
+support `EXPECT_NE(ptr, NULL)` as well. This means using the template meta
+programming tricks twice in the implementation, making it even harder to
+understand and maintain. We believe the benefit doesn't justify the cost.
Finally, with the growth of the gMock matcher library, we are encouraging people
to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One
@@ -127,6 +130,7 @@ can much more easily decide which one to use the next time.
## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!
+{: .callout .note}
**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated*
now. Please use `EqualsProto`, etc instead.
@@ -158,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()`.
@@ -176,18 +180,6 @@ template argument, and thus doesn't compile in opt mode when `a` contains a call
to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as
the solution must work with different compilers on various platforms.
-`htonl()` has some other problems as described in `//util/endian/endian.h`,
-which defines `ghtonl()` to replace it. `ghtonl()` does the same thing `htonl()`
-does, only without its problems. We suggest you to use `ghtonl()` instead of
-`htonl()`, both in your tests and production code.
-
-`//util/endian/endian.h` also defines `ghtons()`, which solves similar problems
-in `htons()`.
-
-Don't forget to add `//util/endian` to the list of dependencies in the `BUILD`
-file wherever `ghtonl()` and `ghtons()` are used. The library consists of a
-single header file and will not bloat your binary.
-
## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong?
If your class has a static data member:
@@ -207,10 +199,22 @@ 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. :-)
+If the declaration of the static data member is `constexpr` then it is
+implicitly an `inline` definition, and a separate definition in `foo.cc` is not
+needed:
+
+```c++
+// foo.h
+class Foo {
+ ...
+ static constexpr int kBar = 100; // Defines kBar, no need to do it in foo.cc.
+};
+```
+
## Can I derive a test fixture from another?
Yes.
@@ -221,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.
@@ -260,10 +264,10 @@ 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](../samples/sample5_unittest.cc).
+[sample5_unittest.cc](https://github.com/google/googletest/blob/main/googletest/samples/sample5_unittest.cc).
## My compiler complains "void value not ignored as it ought to be." What does this mean?
@@ -274,9 +278,10 @@ 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
-delicate. To write death tests you really need to understand how they work.
-Please make sure you have read [this](advanced.md#how-it-works).
+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.
In particular, death tests don't like having multiple threads in the parent
process. So the first thing you can try is to eliminate creating threads outside
@@ -295,13 +300,13 @@ program from the beginning in the child process. Therefore make sure your
program can run side-by-side with itself and is deterministic.
In the end, this boils down to good concurrent programming. You have to make
-sure that there is no race conditions or dead locks in your program. No silver
+sure that there are no race conditions or deadlocks in your program. No silver
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.
@@ -323,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
@@ -332,89 +337,25 @@ You may still want to use `SetUp()/TearDown()` in the following cases:
* In the body of a constructor (or destructor), it's not possible to use the
`ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal
test failure that should prevent the test from running, it's necessary to
- use `abort` <!-- GOOGLETEST_CM0015 DO NOT DELETE --> and abort the whole test executable,
- or to use `SetUp()` instead of a constructor.
+ use `abort` and abort the whole test
+ executable, or to use `SetUp()` instead of a constructor.
* If the tear-down operation could throw an exception, you must use
`TearDown()` as opposed to the destructor, as throwing in a destructor leads
to undefined behavior and usually will kill your program right away. Note
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?
-If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
-overloaded or a template, the compiler will have trouble figuring out which
-overloaded version it should use. `ASSERT_PRED_FORMAT*` and
-`EXPECT_PRED_FORMAT*` don't have this problem.
-
-If you see this error, you might want to switch to
-`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
-message. If, however, that is not an option, you can resolve the problem by
-explicitly telling the compiler which version to pick.
-
-For example, suppose you have
-
-```c++
-bool IsPositive(int n) {
- return n > 0;
-}
-
-bool IsPositive(double x) {
- return x > 0;
-}
-```
-
-you will get a compiler error if you write
-
-```c++
-EXPECT_PRED1(IsPositive, 5);
-```
-
-However, this will work:
-
-```c++
-EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
-```
-
-(The stuff inside the angled brackets for the `static_cast` operator is the type
-of the function pointer for the `int`-version of `IsPositive()`.)
-
-As another example, when you have a template function
-
-```c++
-template <typename T>
-bool IsNegative(T x) {
- return x < 0;
-}
-```
-
-you can use it in a predicate assertion like this:
-
-```c++
-ASSERT_PRED1(IsNegative<int>, -5);
-```
-
-Things are more interesting if your template has more than one parameters. The
-following won't compile:
-
-```c++
-ASSERT_PRED2(GreaterThan<int, int>, 5, 0);
-```
-
-as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which
-is one more than expected. The workaround is to wrap the predicate function in
-parentheses:
-
-```c++
-ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
-```
+See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the
+Assertions Reference.
## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why?
@@ -434,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
@@ -469,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
@@ -500,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:
@@ -531,8 +471,8 @@ There are several good reasons:
## What can the statement argument in ASSERT_DEATH() be?
-`ASSERT_DEATH(*statement*, *regex*)` (or any death assertion macro) can be used
-wherever `*statement*` is valid. So basically `*statement*` can be any C++
+`ASSERT_DEATH(statement, matcher)` (or any death assertion macro) can be used
+wherever *`statement`* is valid. So basically *`statement`* can be any C++
statement that makes sense in the current context. In particular, it can
reference global and/or local variables, and can be:
@@ -555,7 +495,7 @@ TEST(MyDeathTest, ComplexExpression) {
"(Func1|Method) failed");
}
-// Death assertions can be used any where in a function. In
+// Death assertions can be used anywhere in a function. In
// particular, they can be inside a loop.
TEST(MyDeathTest, InsideLoop) {
// Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
@@ -578,11 +518,9 @@ TEST(MyDeathTest, CompoundStatement) {
}
```
-gtest-death-test_test.cc contains more examples if you are interested.
-
## 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:
@@ -597,7 +535,7 @@ However, there are cases where you have to define your own:
## Why does ASSERT_DEATH complain about previous threads that were already joined?
With the Linux pthread library, there is no turning back once you cross the line
-from single thread to multiple threads. The first time you create a thread, a
+from a single thread to multiple threads. The first time you create a thread, a
manager thread is created in addition, so you get 3, not 2, threads. Later when
the thread you create joins the main thread, the thread count decrements by 1,
but the manager thread will never be killed, so you still have 2 threads, which
@@ -607,12 +545,12 @@ 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
-before the first test in it is run, and tear it down afterwords. Splitting up
+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.
@@ -650,29 +588,30 @@ 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
match). Admittedly, this is a hack. We'll consider a more permanent solution
after the fork-and-exec-style death tests are implemented.
-## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives?
+## The compiler complains about `no match for 'operator<<'` when I use an assertion. What gives?
If you use a user-defined type `FooType` in an assertion, you must make sure
there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
defined such that we can print a value of `FooType`.
In addition, if `FooType` is declared in a name space, the `<<` operator also
-needs to be defined in the *same* name space. See https://abseil.io/tips/49 for details.
+needs to be defined in the *same* name space. See
+[Tip of the Week #49](http://abseil.io/tips/49) for details.
## 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
@@ -686,13 +625,13 @@ 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](https://en.wikipedia.org/wiki/Dependency_injection). You can inject
+test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject
different functionality from the test and from the production code. Since your
production code doesn't link in the for-test logic at all (the
-[`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure
+[`testonly`](http://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure
that), there is no danger in accidentally running it.
However, if you *really*, *really*, *really* have no choice, and if you follow
@@ -703,12 +642,12 @@ whether the code is under test.
## How do I temporarily disable a test?
If you have a broken test that you cannot fix right away, you can add the
-DISABLED_ prefix to its name. This will exclude it from execution. This is
-better than commenting out the code or using #if 0, as disabled tests are still
-compiled (and thus won't rot).
+`DISABLED_` prefix to its name. This will exclude it from execution. This is
+better than commenting out the code or using `#if 0`, as disabled tests are
+still compiled (and thus won't rot).
To include disabled tests in test execution, just invoke the test program with
-the --gtest_also_run_disabled_tests flag.
+the `--gtest_also_run_disabled_tests` flag.
## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces?
@@ -733,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++
diff --git a/docs/gmock_cheat_sheet.md b/docs/gmock_cheat_sheet.md
new file mode 100644
index 000000000000..ddafaaa2206c
--- /dev/null
+++ b/docs/gmock_cheat_sheet.md
@@ -0,0 +1,241 @@
+# gMock Cheat Sheet
+
+## Defining a Mock Class
+
+### Mocking a Normal Class {#MockClass}
+
+Given
+
+```cpp
+class Foo {
+ public:
+ virtual ~Foo();
+ virtual int GetSize() const = 0;
+ virtual string Describe(const char* name) = 0;
+ virtual string Describe(int type) = 0;
+ virtual bool Process(Bar elem, int count) = 0;
+};
+```
+
+(note that `~Foo()` **must** be virtual) we can define its mock as
+
+```cpp
+#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));
+ MOCK_METHOD(bool, Process, (Bar elem, int count), (override));
+};
+```
+
+To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock,
+which warns on all uninteresting calls, or a "strict" mock, which treats them as
+failures:
+
+```cpp
+using ::testing::NiceMock;
+using ::testing::NaggyMock;
+using ::testing::StrictMock;
+
+NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo.
+NaggyMock<MockFoo> naggy_foo; // The type is a subclass of MockFoo.
+StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
+```
+
+{: .callout .note}
+**Note:** A mock object is currently naggy by default. We may make it nice by
+default in the future.
+
+### Mocking a Class Template {#MockTemplate}
+
+Class templates can be mocked just like any class.
+
+To mock
+
+```cpp
+template <typename Elem>
+class StackInterface {
+ public:
+ virtual ~StackInterface();
+ virtual int GetSize() const = 0;
+ virtual void Push(const Elem& x) = 0;
+};
+```
+
+(note that all member functions that are mocked, including `~StackInterface()`
+**must** be virtual).
+
+```cpp
+template <typename Elem>
+class MockStack : public StackInterface<Elem> {
+ public:
+ MOCK_METHOD(int, GetSize, (), (const, override));
+ MOCK_METHOD(void, Push, (const Elem& x), (override));
+};
+```
+
+### Specifying Calling Conventions for Mock Functions
+
+If your mock function doesn't use the default calling convention, you can
+specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter.
+For example,
+
+```cpp
+ MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE)));
+ MOCK_METHOD(int, Bar, (double x, double y),
+ (const, Calltype(STDMETHODCALLTYPE)));
+```
+
+where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
+
+## Using Mocks in Tests {#UsingMocks}
+
+The typical work flow is:
+
+1. Import the gMock names you need to use. All gMock symbols are in the
+ `testing` namespace unless they are macros or otherwise noted.
+2. Create the mock objects.
+3. Optionally, set the default actions of the mock objects.
+4. Set your expectations on the mock objects (How will they be called? What
+ will they do?).
+5. Exercise code that uses the mock objects; if necessary, check the result
+ using googletest assertions.
+6. When a mock object is destructed, gMock automatically verifies that all
+ expectations on it have been satisfied.
+
+Here's an example:
+
+```cpp
+using ::testing::Return; // #1
+
+TEST(BarTest, DoesThis) {
+ MockFoo foo; // #2
+
+ ON_CALL(foo, GetSize()) // #3
+ .WillByDefault(Return(1));
+ // ... other default actions ...
+
+ EXPECT_CALL(foo, Describe(5)) // #4
+ .Times(3)
+ .WillRepeatedly(Return("Category 5"));
+ // ... other expectations ...
+
+ EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5
+} // #6
+```
+
+## Setting Default Actions {#OnCall}
+
+gMock has a **built-in default action** for any function that returns `void`,
+`bool`, a numeric value, or a pointer. In C++11, it will additionally returns
+the default-constructed value, if one exists for the given type.
+
+To customize the default action for functions with return type `T`, use
+[`DefaultValue<T>`](reference/mocking.md#DefaultValue). For example:
+
+```cpp
+ // Sets the default action for return type std::unique_ptr<Buzz> to
+ // creating a new Buzz every time.
+ DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
+ [] { return std::make_unique<Buzz>(AccessLevel::kInternal); });
+
+ // When this fires, the default action of MakeBuzz() will run, which
+ // will return a new Buzz object.
+ EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
+
+ auto buzz1 = mock_buzzer_.MakeBuzz("hello");
+ auto buzz2 = mock_buzzer_.MakeBuzz("hello");
+ EXPECT_NE(buzz1, nullptr);
+ EXPECT_NE(buzz2, nullptr);
+ EXPECT_NE(buzz1, buzz2);
+
+ // Resets the default action for return type std::unique_ptr<Buzz>,
+ // to avoid interfere with other tests.
+ DefaultValue<std::unique_ptr<Buzz>>::Clear();
+```
+
+To customize the default action for a particular method of a specific mock
+object, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar
+syntax to `EXPECT_CALL`, but it is used for setting default behaviors when you
+do not require that the mock method is called. See
+[Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed
+discussion.
+
+## Setting Expectations {#ExpectCall}
+
+See [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference.
+
+## Matchers {#MatcherList}
+
+See the [Matchers Reference](reference/matchers.md).
+
+## Actions {#ActionList}
+
+See the [Actions Reference](reference/actions.md).
+
+## Cardinalities {#CardinalityList}
+
+See the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of
+`EXPECT_CALL` in the Mocking Reference.
+
+## Expectation Order
+
+By default, expectations can be matched in *any* order. If some or all
+expectations must be matched in a given order, you can use the
+[`After` clause](reference/mocking.md#EXPECT_CALL.After) or
+[`InSequence` clause](reference/mocking.md#EXPECT_CALL.InSequence) of
+`EXPECT_CALL`, or use an [`InSequence` object](reference/mocking.md#InSequence).
+
+## Verifying and Resetting a Mock
+
+gMock will verify the expectations on a mock object when it is destructed, or
+you can do it earlier:
+
+```cpp
+using ::testing::Mock;
+...
+// Verifies and removes the expectations on mock_obj;
+// returns true if and only if successful.
+Mock::VerifyAndClearExpectations(&mock_obj);
+...
+// Verifies and removes the expectations on mock_obj;
+// also removes the default actions set by ON_CALL();
+// returns true if and only if successful.
+Mock::VerifyAndClear(&mock_obj);
+```
+
+Do not set new expectations after verifying and clearing a mock after its use.
+Setting expectations after code that exercises the mock has undefined behavior.
+See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more
+information.
+
+You can also tell gMock that a mock object can be leaked and doesn't need to be
+verified:
+
+```cpp
+Mock::AllowLeak(&mock_obj);
+```
+
+## Mock Classes
+
+gMock defines a convenient mock class template
+
+```cpp
+class MockFunction<R(A1, ..., An)> {
+ public:
+ MOCK_METHOD(R, Call, (A1, ..., An));
+};
+```
+
+See this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of
+it.
+
+## Flags
+
+| Flag | Description |
+| :----------------------------- | :---------------------------------------- |
+| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
+| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
diff --git a/googlemock/docs/cook_book.md b/docs/gmock_cook_book.md
index ea55ab3583b5..da10918c9659 100644
--- a/googlemock/docs/cook_book.md
+++ b/docs/gmock_cook_book.md
@@ -1,10 +1,10 @@
# gMock Cookbook
-<!-- GOOGLETEST_CM0012 DO NOT DELETE -->
-
You can find recipes for using gMock here. If you haven't yet, please read
-[this](for_dummies.md) first to make sure you understand the basics.
+[the dummy guide](gmock_for_dummies.md) first to make sure you understand the
+basics.
+{: .callout .note}
**Note:** gMock lives in the `testing` name space. For readability, it is
recommended to write `using ::testing::Foo;` once in your file before using the
name `Foo` defined by gMock. We omit such `using` statements in this section for
@@ -35,13 +35,17 @@ generated method:
`noexcept` method.
* **`Calltype(...)`** - Sets the call type for the method (e.g. to
`STDMETHODCALLTYPE`), useful in Windows.
+* **`ref(...)`** - Marks the method with the reference qualification
+ specified. Required if overriding a method that has reference
+ qualifications. Eg `ref(&)` or `ref(&&)`.
### Dealing with unprotected commas
Unprotected commas, i.e. commas which are not surrounded by parentheses, prevent
`MOCK_METHOD` from parsing its arguments correctly:
-```cpp {.bad}
+{: .bad}
+```cpp
class MockFoo {
public:
MOCK_METHOD(std::pair<bool, int>, GetPair, ()); // Won't compile!
@@ -51,7 +55,8 @@ class MockFoo {
Solution 1 - wrap with parentheses:
-```cpp {.good}
+{: .good}
+```cpp
class MockFoo {
public:
MOCK_METHOD((std::pair<bool, int>), GetPair, ());
@@ -64,7 +69,8 @@ invalid C++. `MOCK_METHOD` removes the parentheses.
Solution 2 - define an alias:
-```cpp {.good}
+{: .good}
+```cpp
class MockFoo {
public:
using BoolAndInt = std::pair<bool, int>;
@@ -138,6 +144,7 @@ class MockFoo : public Foo {
};
```
+{: .callout .note}
**Note:** if you don't mock all versions of the overloaded method, the compiler
will give you a warning about some methods in the base class being hidden. To
fix that, use `using` to bring them in scope:
@@ -177,8 +184,7 @@ class MockStack : public StackInterface<Elem> {
### Mocking Non-virtual Methods {#MockingNonVirtualMethods}
-gMock can mock non-virtual functions to be used in Hi-perf dependency
-injection.<!-- GOOGLETEST_CM0017 DO NOT DELETE -->
+gMock can mock non-virtual functions to be used in Hi-perf dependency injection.
In this case, instead of sharing a common base class with the real class, your
mock class will be *unrelated* to the real class, but contain methods with the
@@ -245,9 +251,9 @@ tests.
### Mocking Free Functions
-It's possible to use gMock to mock a free function (i.e. a C-style function or a
-static method). You just need to rewrite your code to use an interface (abstract
-class).
+It is not possible to directly mock a free function (i.e. a C-style function or
+a static method). If you need to, you can rewrite your code to use an interface
+(abstract class).
Instead of calling a free function (say, `OpenFile`) directly, introduce an
interface for it and have a concrete subclass that calls the free function:
@@ -262,7 +268,7 @@ class FileInterface {
class File : public FileInterface {
public:
...
- virtual bool Open(const char* path, const char* mode) {
+ bool Open(const char* path, const char* mode) override {
return OpenFile(path, mode);
}
};
@@ -279,11 +285,17 @@ If you are concerned about the performance overhead incurred by virtual
functions, and profiling confirms your concern, you can combine this with the
recipe for [mocking non-virtual methods](#MockingNonVirtualMethods).
+Alternatively, instead of introducing a new interface, you can rewrite your code
+to accept a std::function instead of the free function, and then use
+[MockFunction](#MockFunction) to mock the std::function.
+
### Old-Style `MOCK_METHODn` Macros
-Before the generic `MOCK_METHOD` macro was introduced, mocks where created using
-a family of macros collectively called `MOCK_METHODn`. These macros are still
-supported, though migration to the new `MOCK_METHOD` is recommended.
+Before the generic `MOCK_METHOD` macro
+[was introduced in 2018](https://github.com/google/googletest/commit/c5f08bf91944ce1b19bcf414fa1760e69d20afc2),
+mocks where created using a family of macros collectively called `MOCK_METHODn`.
+These macros are still supported, though migration to the new `MOCK_METHOD` is
+recommended.
The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`:
@@ -297,44 +309,86 @@ The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`:
Old macros and their new equivalents:
-<a name="table99"></a>
-<table border="1" cellspacing="0" cellpadding="1">
-<tr> <th colspan=2> Simple </th></tr>
-<tr> <td> Old </td> <td> `MOCK_METHOD1(Foo, bool(int))` </td> </tr>
-<tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int))` </td> </tr>
-
-<tr> <th colspan=2> Const Method </th></tr> <tr> <td> Old </td> <td>
-`MOCK_CONST_METHOD1(Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td>
-`MOCK_METHOD(bool, Foo, (int), (const))` </td> </tr>
-
-<tr> <th colspan=2> Method in a Class Template </th></tr> <tr> <td> Old </td>
-<td> `MOCK_METHOD1_T(Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td>
-`MOCK_METHOD(bool, Foo, (int))` </td> </tr>
-
-<tr> <th colspan=2> Const Method in a Class Template </th></tr> <tr> <td> Old
-</td> <td> `MOCK_CONST_METHOD1_T(Foo, bool(int))` </td> </tr> <tr> <td> New
-</td> <td> `MOCK_METHOD(bool, Foo, (int), (const))` </td> </tr>
-
-<tr> <th colspan=2> Method with Call Type </th></tr> <tr> <td> Old </td> <td>
-`MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))` </td> </tr> <tr>
-<td> New </td> <td> `MOCK_METHOD(bool, Foo, (int),
-(Calltype(STDMETHODCALLTYPE)))` </td> </tr>
-
-<tr> <th colspan=2> Const Method with Call Type </th></tr> <tr> <td> Old</td>
-<td> `MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))` </td>
-</tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int), (const,
-Calltype(STDMETHODCALLTYPE)))` </td> </tr>
-
-<tr> <th colspan=2> Method with Call Type in a Class Template </th></tr> <tr>
-<td> Old </td> <td> `MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo,
-bool(int))` </td> </tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int),
-(Calltype(STDMETHODCALLTYPE)))` </td> </tr>
-
-<tr> <th colspan=2> Const Method with Call Type in a Class Template </th></tr>
-<tr> <td> Old </td> <td> `MOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE,
-Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo,
-(int), (const, Calltype(STDMETHODCALLTYPE)))` </td> </tr>
-
+<table>
+ <tr><th colspan=2>Simple</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_METHOD1(Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Const Method</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_CONST_METHOD1(Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (const))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Method in a Class Template</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_METHOD1_T(Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Const Method in a Class Template</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_CONST_METHOD1_T(Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (const))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Method with Call Type</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Const Method with Call Type</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Method with Call Type in a Class Template</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Const Method with Call Type in a Class Template</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))</code></td>
+ </tr>
</table>
### The Nice, the Strict, and the Naggy {#NiceStrictNaggy}
@@ -342,8 +396,7 @@ Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo,
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
@@ -405,13 +458,14 @@ TEST(...) {
}
```
+{: .callout .note}
NOTE: `NiceMock` and `StrictMock` only affects *uninteresting* calls (calls of
*methods* with no expectations); they do not affect *unexpected* calls (calls of
methods with expectations, but they don't match). See
[Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected).
-There are some caveats though (I dislike them just as much as the next guy, but
-sadly they are side effects of C++'s limitations):
+There are some caveats though (sadly they are side effects of C++'s
+limitations):
1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods
defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class.
@@ -421,17 +475,7 @@ sadly they are side effects of C++'s limitations):
`NiceMock<StrictMock<MockFoo> >`) is **not** supported.
2. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` may not work correctly if the
destructor of `MockFoo` is not virtual. We would like to fix this, but it
- requires cleaning up existing tests. http://b/28934720 tracks the issue.
-3. During the constructor or destructor of `MockFoo`, the mock object is *not*
- nice or strict. This may cause surprises if the constructor or destructor
- calls a mock method on `this` object. (This behavior, however, is consistent
- with C++'s general rule: if a constructor or destructor calls a virtual
- method of `this` object, that method is treated as non-virtual. In other
- words, to the base class's constructor or destructor, `this` object behaves
- like an instance of the base class, not the derived class. This rule is
- required for safety. Otherwise a base constructor may use members of a
- derived class before they are initialized, or a base destructor may use
- members of a derived class after they have been destroyed.)
+ requires cleaning up existing tests.
Finally, you should be **very cautious** about when to use naggy or strict
mocks, as they tend to make tests more brittle and harder to maintain. When you
@@ -471,9 +515,9 @@ The trick is to redispatch the method in the mock class:
class ScopedMockLog : public LogSink {
public:
...
- virtual void send(LogSeverity severity, const char* full_filename,
+ void send(LogSeverity severity, const char* full_filename,
const char* base_filename, int line, const tm* tm_time,
- const char* message, size_t message_len) {
+ const char* message, size_t message_len) override {
// We are only interested in the log severity, full file name, and
// log message.
Log(severity, full_filename, std::string(message, message_len));
@@ -513,7 +557,7 @@ argument matchers:
```cpp
ON_CALL(factory, DoMakeTurtle)
- .WillByDefault(MakeMockTurtle());
+ .WillByDefault(Return(MakeMockTurtle()));
```
### Alternative to Mocking Concrete Classes
@@ -653,9 +697,9 @@ TEST(AbcTest, Xyz) {
EXPECT_CALL(foo, DoThat(_, _));
int n = 0;
- EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked.
+ EXPECT_EQ(foo.DoThis(5), '+'); // FakeFoo::DoThis() is invoked.
foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked.
- EXPECT_EQ(2, n);
+ EXPECT_EQ(n, 2);
}
```
@@ -777,28 +821,12 @@ perhaps your test doesn't need to mock `Concrete()` at all (but it would be
oh-so painful to have to define a new mock class whenever you don't need to mock
one of its methods).
-The trick is to leave a back door in your mock class for accessing the real
-methods in the base class:
-
-```cpp
-class MockFoo : public Foo {
- public:
- // Mocking a pure method.
- MOCK_METHOD(void, Pure, (int n), (override));
- // Mocking a concrete method. Foo::Concrete() is shadowed.
- MOCK_METHOD(int, Concrete, (const char* str), (override));
-
- // Use this to call Concrete() defined in Foo.
- int FooConcrete(const char* str) { return Foo::Concrete(str); }
-};
-```
-
-Now, you can call `Foo::Concrete()` inside an action by:
+You can call `Foo::Concrete()` inside an action by:
```cpp
...
EXPECT_CALL(foo, Concrete).WillOnce([&foo](const char* str) {
- return foo.FooConcrete(str);
+ return foo.Foo::Concrete(str);
});
```
@@ -807,7 +835,7 @@ or tell the mock object that you don't want to mock `Concrete()`:
```cpp
...
ON_CALL(foo, Concrete).WillByDefault([&foo](const char* str) {
- return foo.FooConcrete(str);
+ return foo.Foo::Concrete(str);
});
```
@@ -848,7 +876,6 @@ A frequently used matcher is `_`, which matches anything:
```cpp
EXPECT_CALL(foo, DoThat(_, NotNull()));
```
-<!-- GOOGLETEST_CM0022 DO NOT DELETE -->
### Combining Matchers {#CombiningMatchers}
@@ -871,6 +898,22 @@ using ::testing::Not;
NULL));
```
+Matchers are function objects, and parametrized matchers can be composed just
+like any other function. However because their types can be long and rarely
+provide meaningful information, it can be easier to express them with C++14
+generic lambdas to avoid specifying types. For example,
+
+```cpp
+using ::testing::Contains;
+using ::testing::Property;
+
+inline constexpr auto HasFoo = [](const auto& f) {
+ return Property("foo", &MyClass::foo, Contains(f));
+};
+...
+ EXPECT_THAT(x, HasFoo("blah"));
+```
+
### Casting Matchers {#SafeMatcherCast}
gMock matchers are statically typed, meaning that the compiler can catch your
@@ -1024,9 +1067,8 @@ using ::testing::Lt;
says that the first argument of `InRange()` must not be 0, and must be less than
the second argument.
-The expression inside `With()` must be a matcher of type
-`Matcher< ::std::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the types of
-the function arguments.
+The expression inside `With()` must be a matcher of type `Matcher<std::tuple<A1,
+..., An>>`, where `A1`, ..., `An` are the types of the function arguments.
You can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms
are equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`.
@@ -1045,17 +1087,18 @@ 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,
-including the `Lt()` matcher above. See [here](#MultiArgMatchers) for the
+including the `Lt()` matcher above. See
+[Multi-argument Matchers](reference/matchers.md#MultiArgMatchers) for the
complete list.
Note that if you want to pass the arguments to a predicate of your own (e.g.
`.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to
-take a `::std::tuple` as its argument; gMock will pass the `n` selected
-arguments as *one* single tuple to the predicate.
+take a `std::tuple` as its argument; gMock will pass the `n` selected arguments
+as *one* single tuple to the predicate.
### Using Matchers as Predicates
@@ -1086,69 +1129,28 @@ using STL's `<functional>` header is just painful). For example, here's a
predicate that's satisfied by any number that is >= 0, <= 100, and != 50:
```cpp
-using testing::AllOf;
-using testing::Ge;
-using testing::Le;
-using testing::Matches;
-using testing::Ne;
-...
-Matches(AllOf(Ge(0), Le(100), Ne(50)))
-```
-
-### Using Matchers in googletest Assertions
-
-Since matchers are basically predicates that also know how to describe
-themselves, there is a way to take advantage of them in googletest assertions.
-It's called `ASSERT_THAT` and `EXPECT_THAT`:
-
-```cpp
- ASSERT_THAT(value, matcher); // Asserts that value matches matcher.
- EXPECT_THAT(value, matcher); // The non-fatal version.
-```
-
-For example, in a googletest test you can write:
-
-```cpp
-#include "gmock/gmock.h"
-
using ::testing::AllOf;
using ::testing::Ge;
using ::testing::Le;
-using ::testing::MatchesRegex;
-using ::testing::StartsWith;
-
+using ::testing::Matches;
+using ::testing::Ne;
...
- EXPECT_THAT(Foo(), StartsWith("Hello"));
- EXPECT_THAT(Bar(), MatchesRegex("Line \\d+"));
- ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10)));
+Matches(AllOf(Ge(0), Le(100), Ne(50)))
```
-which (as you can probably guess) executes `Foo()`, `Bar()`, and `Baz()`, and
-verifies that:
-
-* `Foo()` returns a string that starts with `"Hello"`.
-* `Bar()` returns a string that matches regular expression `"Line \\d+"`.
-* `Baz()` returns a number in the range [5, 10].
-
-The nice thing about these macros is that *they read like English*. They
-generate informative messages too. For example, if the first `EXPECT_THAT()`
-above fails, the message will be something like:
-
-```cpp
-Value of: Foo()
- Actual: "Hi, world!"
-Expected: starts with "Hello"
-```
+### Using Matchers in googletest Assertions
-**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was borrowed from Joe Walnes'
-Hamcrest project, which adds `assertThat()` to JUnit.
+See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions
+Reference.
### Using Predicates as Matchers
-gMock provides a [built-in set](#MatcherList) of matchers. In case you find them
-lacking, you can use an arbitrary unary predicate function or functor as a
-matcher - as long as the predicate accepts a value of the type you want. You do
-this by wrapping the predicate inside the `Truly()` function, for example:
+gMock provides a set of built-in matchers for matching arguments with expected
+values—see the [Matchers Reference](reference/matchers.md) for more information.
+In case you find the built-in set lacking, you can use an arbitrary unary
+predicate function or functor as a matcher - as long as the predicate accepts a
+value of the type you want. You do this by wrapping the predicate inside the
+`Truly()` function, for example:
```cpp
using ::testing::Truly;
@@ -1160,11 +1162,9 @@ int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
```
Note that the predicate function / functor doesn't have to return `bool`. It
-works as long as the return value can be used as the condition in in statement
+works as long as the return value can be used as the condition in the statement
`if (condition) ...`.
-<!-- GOOGLETEST_CM0023 DO NOT DELETE -->
-
### Matching Arguments that Are Not Copyable
When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, gMock saves away a copy of
@@ -1181,15 +1181,14 @@ executed. Just tell gMock that it should save a reference to `bar`, instead of a
copy of it. Here's how:
```cpp
-using ::testing::ByRef;
using ::testing::Eq;
using ::testing::Lt;
...
// Expects that Foo()'s argument == bar.
- EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar))));
+ EXPECT_CALL(mock_obj, Foo(Eq(std::ref(bar))));
// Expects that Foo()'s argument < bar.
- EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar))));
+ EXPECT_CALL(mock_obj, Foo(Lt(std::ref(bar))));
```
Remember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the
@@ -1219,17 +1218,17 @@ that satisfies matcher `m`.
For example:
-<!-- mdformat off(github rendering does not support multiline tables) -->
| Expression | Description |
| :--------------------------- | :--------------------------------------- |
| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. |
| `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. |
-<!-- mdformat on -->
Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument
-and be declared as `const`.
+and be declared as `const`. Don't use `Property()` against member functions that
+you do not own, because taking addresses of functions is fragile and generally
+not part of the contract of the function.
-BTW, `Field()` and `Property()` can also match plain pointers to objects. For
+`Field()` and `Property()` can also match plain pointers to objects. For
instance,
```cpp
@@ -1304,50 +1303,53 @@ 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;
-using ::testing::MatcherInterface;
-using ::testing::MatchResultListener;
+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:
-class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
+```cpp
+class BarPlusBazEqMatcher {
public:
+ using is_gtest_matcher = void;
+
explicit BarPlusBazEqMatcher(int expected_sum)
: expected_sum_(expected_sum) {}
bool MatchAndExplain(const Foo& foo,
- MatchResultListener* /* listener */) const override {
+ std::ostream* /* listener */) const {
return (foo.bar() + foo.baz()) == expected_sum_;
}
- void DescribeTo(::std::ostream* os) const override {
+ void DescribeTo(std::ostream* os) const {
*os << "bar() + baz() equals " << expected_sum_;
}
- void DescribeNegationTo(::std::ostream* os) const override {
+ 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) {
- return MakeMatcher(new BarPlusBazEqMatcher(expected_sum));
+::testing::Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
+ return BarPlusBazEqMatcher(expected_sum);
}
...
- EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
+ Foo foo;
+ EXPECT_THAT(foo, BarPlusBazEq(5))...;
```
### Matching Containers
@@ -1423,14 +1425,19 @@ using ::testing::ElementsAreArray;
Use `Pair` when comparing maps or other associative containers.
+{% raw %}
+
```cpp
-using testing::ElementsAre;
-using testing::Pair;
+using ::testing::UnorderedElementsAre;
+using ::testing::Pair;
...
- std::map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};
- EXPECT_THAT(m, ElementsAre(Pair("a", 1), Pair("b", 2), Pair("c", 3)));
+ absl::flat_hash_map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};
+ EXPECT_THAT(m, UnorderedElementsAre(
+ Pair("a", 1), Pair("b", 2), Pair("c", 3)));
```
+{% endraw %}
+
**Tips:**
* `ElementsAre*()` can be used to match *any* container that implements the
@@ -1443,8 +1450,8 @@ using testing::Pair;
* If the container is passed by pointer instead of by reference, just write
`Pointee(ElementsAre*(...))`.
* The order of elements *matters* for `ElementsAre*()`. If you are using it
- with containers whose element order are undefined (e.g. `hash_map`) you
- should use `WhenSorted` around `ElementsAre`.
+ with containers whose element order are undefined (such as a
+ `std::unordered_map`) you should use `UnorderedElementsAre`.
### Sharing Matchers
@@ -1454,7 +1461,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
@@ -1469,6 +1476,7 @@ using ::testing::Matcher;
### Matchers must have no side-effects {#PureMatchers}
+{: .callout .warning}
WARNING: gMock does not guarantee when or how many times a matcher will be
invoked. Therefore, all matchers must be *purely functional*: they cannot have
any side effects, and the match result must not depend on anything other than
@@ -1483,8 +1491,6 @@ mock object and gMock.
### Knowing When to Expect {#UseOnCall}
-<!-- GOOGLETEST_CM0018 DO NOT DELETE -->
-
**`ON_CALL`** is likely the *single most under-utilized construct* in gMock.
There are basically two constructs for defining the behavior of a mock object:
@@ -1676,11 +1682,11 @@ times from calling it with the wrong arguments.
### Expecting Ordered Calls {#OrderedCalls}
-Although an `EXPECT_CALL()` statement defined earlier takes precedence when
-gMock tries to match a function call with an expectation, by default calls don't
-have to happen in the order `EXPECT_CALL()` statements are written. For example,
-if the arguments match the matchers in the third `EXPECT_CALL()`, but not those
-in the first two, then the third expectation will be used.
+Although an `EXPECT_CALL()` statement defined later takes precedence when gMock
+tries to match a function call with an expectation, by default calls don't have
+to happen in the order `EXPECT_CALL()` statements are written. For example, if
+the arguments match the matchers in the second `EXPECT_CALL()`, but not those in
+the first and third, then the second expectation will be used.
If you would rather have all calls occur in the order of the expectations, put
the `EXPECT_CALL()` statements in a block where you define a variable of type
@@ -1713,8 +1719,8 @@ brittle tests. For example, we may care about `A` occurring before both `B` and
the test should reflect our real intent, instead of being overly constraining.
gMock allows you to impose an arbitrary DAG (directed acyclic graph) on the
-calls. One way to express the DAG is to use the [After](#AfterClause) clause of
-`EXPECT_CALL`.
+calls. One way to express the DAG is to use the
+[`After` clause](reference/mocking.md#EXPECT_CALL.After) of `EXPECT_CALL`.
Another way is via the `InSequence()` clause (not the same as the `InSequence`
class), which we borrowed from jMock 2. It's less flexible than `After()`, but
@@ -1757,7 +1763,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
@@ -1852,11 +1858,10 @@ Methods"). However, gMock doesn't let you use `ReturnRef()` in a mock function
whose return type is not a reference, as doing that usually indicates a user
error. So, what shall you do?
-Though you may be tempted, DO NOT use `ByRef()`:
+Though you may be tempted, DO NOT use `std::ref()`:
```cpp
-using testing::ByRef;
-using testing::Return;
+using ::testing::Return;
class MockFoo : public Foo {
public:
@@ -1866,9 +1871,9 @@ class MockFoo : public Foo {
int x = 0;
MockFoo foo;
EXPECT_CALL(foo, GetValue())
- .WillRepeatedly(Return(ByRef(x))); // Wrong!
+ .WillRepeatedly(Return(std::ref(x))); // Wrong!
x = 42;
- EXPECT_EQ(42, foo.GetValue());
+ EXPECT_EQ(foo.GetValue(), 42);
```
Unfortunately, it doesn't work here. The above code will fail with error:
@@ -1882,28 +1887,28 @@ Expected: 42
The reason is that `Return(*value*)` converts `value` to the actual return type
of the mock function at the time when the action is *created*, not when it is
*executed*. (This behavior was chosen for the action to be safe when `value` is
-a proxy object that references some temporary objects.) As a result, `ByRef(x)`
-is converted to an `int` value (instead of a `const int&`) when the expectation
-is set, and `Return(ByRef(x))` will always return 0.
+a proxy object that references some temporary objects.) As a result,
+`std::ref(x)` is converted to an `int` value (instead of a `const int&`) when
+the expectation is set, and `Return(std::ref(x))` will always return 0.
`ReturnPointee(pointer)` was provided to solve this problem specifically. It
returns the value pointed to by `pointer` at the time the action is *executed*:
```cpp
-using testing::ReturnPointee;
+using ::testing::ReturnPointee;
...
int x = 0;
MockFoo foo;
EXPECT_CALL(foo, GetValue())
.WillRepeatedly(ReturnPointee(&x)); // Note the & here.
x = 42;
- EXPECT_EQ(42, foo.GetValue()); // This will succeed now.
+ EXPECT_EQ(foo.GetValue(), 42); // This will succeed now.
```
### Combining Actions
Want to do more than one thing when a function is called? That's fine. `DoAll()`
-allow you to do sequence of actions every time. Only the return value of the
+allows you to do a sequence of actions every time. Only the return value of the
last action in the sequence will be used.
```cpp
@@ -1984,6 +1989,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;
@@ -2037,10 +2043,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()));
```
@@ -2129,7 +2132,7 @@ class MockFoo : public Foo {
DefaultValue<Bar>::Clear();
```
-Please note that changing the default value for a type can make you tests hard
+Please note that changing the default value for a type can make your tests hard
to understand. We recommend you to use this feature judiciously. For example,
you may want to make sure the `Set()` and `Clear()` calls are right next to the
code that uses your mock.
@@ -2175,9 +2178,7 @@ own precedence order distinct from the `ON_CALL` precedence order.
### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions}
If the built-in actions don't suit you, you can use an existing callable
-(function, `std::function`, method, functor, lambda as an action.
-
-<!-- GOOGLETEST_CM0024 DO NOT DELETE -->
+(function, `std::function`, method, functor, lambda) as an action.
```cpp
using ::testing::_; using ::testing::Invoke;
@@ -2203,7 +2204,8 @@ class Helper {
.WillOnce(&CalculateSum)
.WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1)));
EXPECT_CALL(foo, ComplexJob(_))
- .WillOnce(Invoke(&helper, &Helper::ComplexJob));
+ .WillOnce(Invoke(&helper, &Helper::ComplexJob))
+ .WillOnce([] { return true; })
.WillRepeatedly([](int x) { return x > 0; });
foo.Sum(5, 6); // Invokes CalculateSum(5, 6).
@@ -2213,13 +2215,13 @@ class Helper {
```
The only requirement is that the type of the function, etc must be *compatible*
-with the signature of the mock function, meaning that the latter's arguments can
-be implicitly converted to the corresponding arguments of the former, and the
-former's return type can be implicitly converted to that of the latter. So, you
-can invoke something whose type is *not* exactly the same as the mock function,
-as long as it's safe to do so - nice, huh?
+with the signature of the mock function, meaning that the latter's arguments (if
+it takes any) can be implicitly converted to the corresponding arguments of the
+former, and the former's return type can be implicitly converted to that of the
+latter. So, you can invoke something whose type is *not* exactly the same as the
+mock function, as long as it's safe to do so - nice, huh?
-**`Note:`{.escaped}**
+Note that:
* The action takes ownership of the callback and will delete it when the
action itself is destructed.
@@ -2262,25 +2264,26 @@ TEST_F(FooTest, Test) {
EXPECT_CALL(foo, DoThis(2))
.WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5)));
- EXPECT_EQ('+', foo.DoThis(2)); // Invokes SignOfSum(5, 2).
+ EXPECT_EQ(foo.DoThis(2), '+'); // Invokes SignOfSum(5, 2).
}
```
### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments
-`Invoke()` is very useful for doing actions that are more complex. It passes the
-mock function's arguments to the function, etc being invoked such that the
-callee has the full context of the call to work with. If the invoked function is
-not interested in some or all of the arguments, it can simply ignore them.
+`Invoke()` passes the mock function's arguments to the function, etc being
+invoked such that the callee has the full context of the call to work with. If
+the invoked function is not interested in some or all of the arguments, it can
+simply ignore them.
Yet, a common pattern is that a test author wants to invoke a function without
-the arguments of the mock function. `Invoke()` allows her to do that using a
-wrapper function that throws away the arguments before invoking an underlining
-nullary function. Needless to say, this can be tedious and obscures the intent
-of the test.
+the arguments of the mock function. She could do that using a wrapper function
+that throws away the arguments before invoking an underlining nullary function.
+Needless to say, this can be tedious and obscures the intent of the test.
-`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except that it
-doesn't pass the mock function's arguments to the callee. Here's an example:
+There are two solutions to this problem. First, you can pass any callable of
+zero args as an action. Alternatively, use `InvokeWithoutArgs()`, which is like
+`Invoke()` except that it doesn't pass the mock function's arguments to the
+callee. Here's an example of each:
```cpp
using ::testing::_;
@@ -2297,14 +2300,14 @@ bool Job2(int n, char c) { ... }
...
MockFoo foo;
EXPECT_CALL(foo, ComplexJob(_))
- .WillOnce(InvokeWithoutArgs(Job1))
+ .WillOnce([] { Job1(); });
.WillOnce(InvokeWithoutArgs(NewPermanentCallback(Job2, 5, 'a')));
foo.ComplexJob(10); // Invokes Job1().
foo.ComplexJob(20); // Invokes Job2(5, 'a').
```
-**`Note:`{.escaped}**
+Note that:
* The action takes ownership of the callback and will delete it when the
action itself is destructed.
@@ -2347,6 +2350,7 @@ using ::testing::_;
// second argument DoThis() receives.
```
+{: .callout .note}
NOTE: The section below is legacy documentation from before C++ had lambdas:
Arghh, you need to refer to a mock function argument but C++ has no lambda
@@ -2375,7 +2379,7 @@ using ::testing::InvokeArgument;
```
What if the callable takes an argument by reference? No problem - just wrap it
-inside `ByRef()`:
+inside `std::ref()`:
```cpp
...
@@ -2384,20 +2388,19 @@ inside `ByRef()`:
(override));
...
using ::testing::_;
- using ::testing::ByRef;
using ::testing::InvokeArgument;
...
MockFoo foo;
Helper helper;
...
EXPECT_CALL(foo, Bar(_))
- .WillOnce(InvokeArgument<0>(5, ByRef(helper)));
- // ByRef(helper) guarantees that a reference to helper, not a copy of it,
- // will be passed to the callback.
+ .WillOnce(InvokeArgument<0>(5, std::ref(helper)));
+ // std::ref(helper) guarantees that a reference to helper, not a copy of
+ // it, will be passed to the callback.
```
What if the callable takes an argument by reference and we do **not** wrap the
-argument in `ByRef()`? Then `InvokeArgument()` will *make a copy* of the
+argument in `std::ref()`? Then `InvokeArgument()` will *make a copy* of the
argument, and pass a *reference to the copy*, instead of a reference to the
original value, to the callable. This is especially handy when the argument is a
temporary value:
@@ -2608,7 +2611,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:
@@ -2637,8 +2640,8 @@ action will exhibit different behaviors. Example:
.WillRepeatedly(IncrementCounter(0));
foo.DoThis(); // Returns 1.
foo.DoThis(); // Returns 2.
- foo.DoThat(); // Returns 1 - Blah() uses a different
- // counter than Bar()'s.
+ foo.DoThat(); // Returns 1 - DoThat() uses a different
+ // counter than DoThis()'s.
```
versus
@@ -2668,26 +2671,18 @@ behavior nondeterministic. A better way is to use gMock actions and
`Notification` objects to force your asynchronous test to behave synchronously.
```cpp
-using ::testing::DoAll;
-using ::testing::InvokeWithoutArgs;
-using ::testing::Return;
-
class MockEventDispatcher : public EventDispatcher {
MOCK_METHOD(bool, DispatchEvent, (int32), (override));
};
-ACTION_P(Notify, notification) {
- notification->Notify();
-}
-
TEST(EventQueueTest, EnqueueEventTest) {
MockEventDispatcher mock_event_dispatcher;
EventQueue event_queue(&mock_event_dispatcher);
const int32 kEventId = 321;
- Notification done;
+ absl::Notification done;
EXPECT_CALL(mock_event_dispatcher, DispatchEvent(kEventId))
- .WillOnce(Notify(&done));
+ .WillOnce([&done] { done.Notify(); });
event_queue.EnqueueEvent(kEventId);
done.WaitForNotification();
@@ -2700,6 +2695,7 @@ additional action to notify the `Notification` object. Now we can just call
asynchronous call to finish. After that, our test suite is complete and we can
safely exit.
+{: .callout .note}
Note: this example has a downside: namely, if the expectation is not satisfied,
our test will run forever. It will eventually time-out and fail, but it will
take longer and be slightly harder to debug. To alleviate this problem, you can
@@ -2775,36 +2771,33 @@ returns a null `unique_ptr`, that’s what you’ll get if you don’t specify a
action:
```cpp
+using ::testing::IsNull;
+...
// Use the default action.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"));
// Triggers the previous EXPECT_CALL.
- EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello"));
+ EXPECT_THAT(mock_buzzer_.MakeBuzz("hello"), IsNull());
```
If you are not happy with the default action, you can tweak it as usual; see
[Setting Default Actions](#OnCall).
-If you just need to return a pre-defined move-only value, you can use the
-`Return(ByMove(...))` action:
+If you just need to return a move-only value, you can use it in combination with
+`WillOnce`. For example:
```cpp
- // When this fires, the unique_ptr<> specified by ByMove(...) will
- // be returned.
- EXPECT_CALL(mock_buzzer_, MakeBuzz("world"))
- .WillOnce(Return(ByMove(MakeUnique<Buzz>(AccessLevel::kInternal))));
-
- EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world"));
+ EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"))
+ .WillOnce(Return(std::make_unique<Buzz>(AccessLevel::kInternal)));
+ EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("hello"));
```
-Note that `ByMove()` is essential here - if you drop it, the code won’t compile.
-
-Quiz time! What do you think will happen if a `Return(ByMove(...))` action is
-performed more than once (e.g. you write `...
-.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time
-the action runs, the source value will be consumed (since it’s a move-only
-value), so the next time around, there’s no value to move from -- you’ll get a
-run-time error that `Return(ByMove(...))` can only be run once.
+Quiz time! What do you think will happen if a `Return` action is performed more
+than once (e.g. you write `... .WillRepeatedly(Return(std::move(...)));`)? Come
+think of it, after the first time the action runs, the source value will be
+consumed (since it’s a move-only value), so the next time around, there’s no
+value to move from -- you’ll get a run-time error that `Return(std::move(...))`
+can only be run once.
If you need your mock method to do more than just moving a pre-defined value,
remember that you can always use a lambda or a callable object, which can do
@@ -2813,7 +2806,7 @@ pretty much anything you want:
```cpp
EXPECT_CALL(mock_buzzer_, MakeBuzz("x"))
.WillRepeatedly([](StringPiece text) {
- return MakeUnique<Buzz>(AccessLevel::kInternal);
+ return std::make_unique<Buzz>(AccessLevel::kInternal);
});
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
@@ -2821,7 +2814,7 @@ pretty much anything you want:
```
Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created
-and returned. You cannot do this with `Return(ByMove(...))`.
+and returned. You cannot do this with `Return(std::make_unique<...>(...))`.
That covers returning move-only values; but how do we work with methods
accepting move-only arguments? The answer is that they work normally, although
@@ -2832,7 +2825,7 @@ can always use `Return`, or a [lambda or functor](#FunctionsAsActions):
using ::testing::Unused;
EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true));
- EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal)),
+ EXPECT_TRUE(mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal)),
0);
EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce(
@@ -2850,8 +2843,8 @@ work with non-copyable objects; you'll have to use functors instead.
#### Legacy workarounds for move-only types {#LegacyMoveOnly}
Support for move-only function arguments was only introduced to gMock in April
-2017. In older code, you may encounter the following workaround for the lack of
-this feature (it is no longer necessary - we're including it just for
+of 2017. In older code, you may encounter the following workaround for the lack
+of this feature (it is no longer necessary - we're including it just for
reference):
```cpp
@@ -2876,7 +2869,7 @@ method:
// When one calls ShareBuzz() on the MockBuzzer like this, the call is
// forwarded to DoShareBuzz(), which is mocked. Therefore this statement
// will trigger the above EXPECT_CALL.
- mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), 0);
+ mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal), 0);
```
### Making the Compilation Faster
@@ -2979,36 +2972,27 @@ TEST(MyServerTest, ProcessesRequest) {
} // server is destroyed when it goes out of scope here.
```
+{: .callout .tip}
**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a `bool` to
indicate whether the verification was successful (`true` for yes), so you can
wrap that function call inside a `ASSERT_TRUE()` if there is no point going
further when the verification has failed.
-### Using Check Points {#UsingCheckPoints}
+Do not set new expectations after verifying and clearing a mock after its use.
+Setting expectations after code that exercises the mock has undefined behavior.
+See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more
+information.
-Sometimes you may want to "reset" a mock object at various check points in your
-test: at each check point, you verify that all existing expectations on the mock
-object have been satisfied, and then you set some new expectations on it as if
-it's newly created. This allows you to work with a mock object in "phases" whose
-sizes are each manageable.
+### Using Checkpoints {#UsingCheckPoints}
-One such scenario is that in your test's `SetUp()` function, you may want to put
-the object you are testing into a certain state, with the help from a mock
-object. Once in the desired state, you want to clear all expectations on the
-mock, such that in the `TEST_F` body you can set fresh expectations on it.
+Sometimes you might want to test a mock object's behavior in phases whose sizes
+are each manageable, or you might want to set more detailed expectations about
+which API calls invoke which mock functions.
-As you may have figured out, the `Mock::VerifyAndClearExpectations()` function
-we saw in the previous recipe can help you here. Or, if you are using
-`ON_CALL()` to set default actions on the mock object and want to clear the
-default actions as well, use `Mock::VerifyAndClear(&mock_object)` instead. This
-function does what `Mock::VerifyAndClearExpectations(&mock_object)` does and
-returns the same `bool`, **plus** it clears the `ON_CALL()` statements on
-`mock_object` too.
-
-Another trick you can use to achieve the same effect is to put the expectations
-in sequences and insert calls to a dummy "check-point" function at specific
-places. Then you can verify that the mock function calls do happen at the right
-time. For example, if you are exercising code:
+A technique you can use is to put the expectations in a sequence and insert
+calls to a dummy "checkpoint" function at specific places. Then you can verify
+that the mock function calls do happen at the right time. For example, if you
+are exercising the code:
```cpp
Foo(1);
@@ -3017,7 +3001,7 @@ time. For example, if you are exercising code:
```
and want to verify that `Foo(1)` and `Foo(3)` both invoke `mock.Bar("a")`, but
-`Foo(2)` doesn't invoke anything. You can write:
+`Foo(2)` doesn't invoke anything, you can write:
```cpp
using ::testing::MockFunction;
@@ -3043,10 +3027,10 @@ TEST(FooTest, InvokesBarCorrectly) {
}
```
-The expectation spec says that the first `Bar("a")` must happen before check
-point "1", the second `Bar("a")` must happen after check point "2", and nothing
-should happen between the two check points. The explicit check points make it
-easy to tell which `Bar("a")` is called by which call to `Foo()`.
+The expectation spec says that the first `Bar("a")` call must happen before
+checkpoint "1", the second `Bar("a")` call must happen after checkpoint "2", and
+nothing should happen between the two checkpoints. The explicit checkpoints make
+it clear which `Bar("a")` is called by which call to `Foo()`.
### Mocking Destructors
@@ -3072,7 +3056,7 @@ class MockFoo : public Foo {
...
// Add the following two lines to the mock class.
MOCK_METHOD(void, Die, ());
- virtual ~MockFoo() { Die(); }
+ ~MockFoo() override { Die(); }
};
```
@@ -3210,11 +3194,11 @@ You can unlock this power by running your test with the `--gmock_verbose=info`
flag. For example, given the test program:
```cpp
-#include "gmock/gmock.h"
+#include <gmock/gmock.h>
-using testing::_;
-using testing::HasSubstr;
-using testing::Return;
+using ::testing::_;
+using ::testing::HasSubstr;
+using ::testing::Return;
class MockFoo {
public:
@@ -3271,8 +3255,6 @@ If you are interested in the mock call trace but not the stack traces, you can
combine `--gmock_verbose=info` with `--gtest_stack_trace_depth=0` on the test
command line.
-<!-- GOOGLETEST_CM0025 DO NOT DELETE -->
-
### Running Tests in Emacs
If you build and run your tests in Emacs using the `M-x google-compile` command
@@ -3297,6 +3279,7 @@ after typing `M-m`), or `M-up`/`M-down` to move back and forth between errors.
### Writing New Matchers Quickly {#NewMatchers}
+{: .callout .warning}
WARNING: gMock does not guarantee when or how many times a matcher will be
invoked. Therefore, all matchers must be functionally pure. See
[this section](#PureMatchers) for more details.
@@ -3341,7 +3324,7 @@ or,
```cpp
using ::testing::Not;
...
- // Verifies that two values are divisible by 7.
+ // Verifies that a value is divisible by 7 and the other is not.
EXPECT_THAT(some_expression, IsDivisibleBy7());
EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7()));
```
@@ -3400,6 +3383,7 @@ match succeeds in case of a success (unless it's obvious) - this is useful when
the matcher is used inside `Not()`. There is no need to print the argument value
itself, as gMock already prints it for you.
+{: .callout .note}
NOTE: The type of the value being matched (`arg_type`) is determined by the
context in which you use the matcher and is supplied to you by the compiler, so
you don't need to worry about declaring it (nor can you). This allows the
@@ -3538,51 +3522,39 @@ MATCHER_P2(Blah, a, b, description_string_2) { ... }
```
While it's tempting to always use the `MATCHER*` macros when defining a new
-matcher, you should also consider implementing `MatcherInterface` or using
-`MakePolymorphicMatcher()` instead (see the recipes that follow), especially if
-you need to use the matcher a lot. While these approaches require more work,
-they give you more control on the types of the value being matched and the
-matcher parameters, which in general leads to better compiler error messages
-that pay off in the long run. They also allow overloading matchers based on
-parameter types (as opposed to just based on the number of parameters).
+matcher, you should also consider implementing the matcher interface directly
+instead (see the recipes that follow), especially if you need to use the matcher
+a lot. While these approaches require more work, they give you more control on
+the types of the value being matched and the matcher parameters, which in
+general leads to better compiler error messages that pay off in the long run.
+They also allow overloading matchers based on parameter types (as opposed to
+just based on the number of parameters).
### Writing New Monomorphic Matchers
-A matcher of argument type `T` implements `::testing::MatcherInterface<T>` and
-does two things: it tests whether a value of type `T` matches the matcher, and
-can describe what kind of values it matches. The latter ability is used for
+A matcher of argument type `T` implements the matcher interface for `T` and does
+two things: it tests whether a value of type `T` matches the matcher, and can
+describe what kind of values it matches. The latter ability is used for
generating readable error messages when expectations are violated.
-The interface looks like this:
+A matcher of `T` must declare a typedef like:
```cpp
-class MatchResultListener {
- public:
- ...
- // Streams x to the underlying ostream; does nothing if the ostream
- // is NULL.
- template <typename T>
- MatchResultListener& operator<<(const T& x);
-
- // Returns the underlying ostream.
- ::std::ostream* stream();
-};
-
-template <typename T>
-class MatcherInterface {
- public:
- virtual ~MatcherInterface();
+using is_gtest_matcher = void;
+```
- // Returns true if and only if the matcher matches x; also explains the match
- // result to 'listener'.
- virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
+and supports the following operations:
- // Describes this matcher to an ostream.
- virtual void DescribeTo(::std::ostream* os) const = 0;
+```cpp
+// Match a value and optionally explain into an ostream.
+bool matched = matcher.MatchAndExplain(value, maybe_os);
+// where `value` is of type `T` and
+// `maybe_os` is of type `std::ostream*`, where it can be null if the caller
+// is not interested in there textual explanation.
- // Describes the negation of this matcher to an ostream.
- virtual void DescribeNegationTo(::std::ostream* os) const;
-};
+matcher.DescribeTo(os);
+matcher.DescribeNegationTo(os);
+// where `os` is of type `std::ostream*`.
```
If you need a custom matcher but `Truly()` is not a good option (for example,
@@ -3597,29 +3569,27 @@ For example, you can define a matcher to test whether an `int` is divisible by 7
and then use it like this:
```cpp
-using ::testing::MakeMatcher;
using ::testing::Matcher;
-using ::testing::MatcherInterface;
-using ::testing::MatchResultListener;
-class DivisibleBy7Matcher : public MatcherInterface<int> {
+class DivisibleBy7Matcher {
public:
- bool MatchAndExplain(int n,
- MatchResultListener* /* listener */) const override {
+ using is_gtest_matcher = void;
+
+ bool MatchAndExplain(int n, std::ostream*) const {
return (n % 7) == 0;
}
- void DescribeTo(::std::ostream* os) const override {
+ void DescribeTo(std::ostream* os) const {
*os << "is divisible by 7";
}
- void DescribeNegationTo(::std::ostream* os) const override {
+ void DescribeNegationTo(std::ostream* os) const {
*os << "is not divisible by 7";
}
};
Matcher<int> DivisibleBy7() {
- return MakeMatcher(new DivisibleBy7Matcher);
+ return DivisibleBy7Matcher();
}
...
@@ -3627,16 +3597,15 @@ Matcher<int> DivisibleBy7() {
```
You may improve the matcher message by streaming additional information to the
-`listener` argument in `MatchAndExplain()`:
+`os` argument in `MatchAndExplain()`:
```cpp
-class DivisibleBy7Matcher : public MatcherInterface<int> {
+class DivisibleBy7Matcher {
public:
- bool MatchAndExplain(int n,
- MatchResultListener* listener) const override {
+ bool MatchAndExplain(int n, std::ostream* os) const {
const int remainder = n % 7;
- if (remainder != 0) {
- *listener << "the remainder is " << remainder;
+ if (remainder != 0 && os != nullptr) {
+ *os << "the remainder is " << remainder;
}
return remainder == 0;
}
@@ -3652,15 +3621,87 @@ Expected: is divisible by 7
Actual: 23 (the remainder is 2)
```
+{: .callout .tip}
+Tip: for convenience, `MatchAndExplain()` can take a `MatchResultListener*`
+instead of `std::ostream*`.
+
### Writing New Polymorphic Matchers
-You've learned how to write your own matchers in the previous recipe. Just one
-problem: a matcher created using `MakeMatcher()` only works for one particular
-type of arguments. If you want a *polymorphic* matcher that works with arguments
-of several types (for instance, `Eq(x)` can be used to match a *`value`* as long
-as `value == x` compiles -- *`value`* and `x` don't have to share the same
-type), you can learn the trick from `testing/base/public/gmock-matchers.h` but
-it's a bit involved.
+Expanding what we learned above to *polymorphic* matchers is now just as simple
+as adding templates in the right place.
+
+```cpp
+
+class NotNullMatcher {
+ public:
+ using is_gtest_matcher = void;
+
+ // To implement a polymorphic matcher, we just need to make MatchAndExplain a
+ // template on its first argument.
+
+ // In this example, we want to use NotNull() with any pointer, so
+ // MatchAndExplain() accepts a pointer of any type as its first argument.
+ // In general, you can define MatchAndExplain() as an ordinary method or
+ // a method template, or even overload it.
+ template <typename T>
+ bool MatchAndExplain(T* p, std::ostream*) const {
+ return p != nullptr;
+ }
+
+ // Describes the property of a value matching this matcher.
+ void DescribeTo(std::ostream* os) const { *os << "is not NULL"; }
+
+ // Describes the property of a value NOT matching this matcher.
+ void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; }
+};
+
+NotNullMatcher NotNull() {
+ return NotNullMatcher();
+}
+
+...
+
+ EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer.
+```
+
+### Legacy Matcher Implementation
+
+Defining matchers used to be somewhat more complicated, in which it required
+several supporting classes and virtual functions. To implement a matcher for
+type `T` using the legacy API you have to derive from `MatcherInterface<T>` and
+call `MakeMatcher` to construct the object.
+
+The interface looks like this:
+
+```cpp
+class MatchResultListener {
+ public:
+ ...
+ // Streams x to the underlying ostream; does nothing if the ostream
+ // is NULL.
+ template <typename T>
+ MatchResultListener& operator<<(const T& x);
+
+ // Returns the underlying ostream.
+ std::ostream* stream();
+};
+
+template <typename T>
+class MatcherInterface {
+ public:
+ virtual ~MatcherInterface();
+
+ // Returns true if and only if the matcher matches x; also explains the match
+ // result to 'listener'.
+ virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
+
+ // Describes this matcher to an ostream.
+ virtual void DescribeTo(std::ostream* os) const = 0;
+
+ // Describes the negation of this matcher to an ostream.
+ virtual void DescribeNegationTo(std::ostream* os) const;
+};
+```
Fortunately, most of the time you can define a polymorphic matcher easily with
the help of `MakePolymorphicMatcher()`. Here's how you can define `NotNull()` as
@@ -3705,6 +3746,7 @@ PolymorphicMatcher<NotNullMatcher> NotNull() {
EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer.
```
+{: .callout .note}
**Note:** Your polymorphic matcher class does **not** need to inherit from
`MatcherInterface` or any other class, and its methods do **not** need to be
virtual.
@@ -3718,8 +3760,8 @@ A cardinality is used in `Times()` to tell gMock how many times you expect a
call to occur. It doesn't have to be exact. For example, you can say
`AtLeast(5)` or `Between(2, 4)`.
-If the [built-in set](cheat_sheet.md#CardinalityList) of cardinalities doesn't
-suit you, you are free to define your own by implementing the following
+If the [built-in set](gmock_cheat_sheet.md#CardinalityList) of cardinalities
+doesn't suit you, you are free to define your own by implementing the following
interface (in namespace `testing`):
```cpp
@@ -3771,35 +3813,74 @@ 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(mock.AsStdFunction()(2), 14);
```
-The same approach works with stateful functors (or any callable, really):
+Or a struct with a call operator (even a templated one):
-```
+```cpp
struct MultiplyBy {
template <typename T>
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:
+
+```cpp
+MockFunction<int(int)> mock;
+EXPECT_CALL(mock, Call).WillOnce([] { return 17; });
+EXPECT_EQ(mock.AsStdFunction()(0), 17);
+```
+
+When used with `WillOnce`, the callable can assume it will be called at most
+once and is allowed to be a move-only type:
+
+```cpp
+// 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
@@ -3995,7 +4076,7 @@ ACTION_TEMPLATE(DuplicateArg,
// Note the comma between int and k:
HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
AND_1_VALUE_PARAMS(output)) {
- *output = T(::std::get<k>(args));
+ *output = T(std::get<k>(args));
}
```
@@ -4042,23 +4123,18 @@ If you are writing a function that returns an `ACTION` object, you'll need to
know its type. The type depends on the macro used to define the action and the
parameter types. The rule is relatively simple:
+
| Given Definition | Expression | Has Type |
| ----------------------------- | ------------------- | --------------------- |
| `ACTION(Foo)` | `Foo()` | `FooAction` |
-| `ACTION_TEMPLATE(Foo,` | `Foo<t1, ..., | `FooAction<t1, ..., |
-: `HAS_m_TEMPLATE_PARAMS(...),` : t_m>()` : t_m>` :
-: `AND_0_VALUE_PARAMS())` : : :
+| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` |
| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` |
-| `ACTION_TEMPLATE(Bar,` | `Bar<t1, ..., t_m>` | `FooActionP<t1, ..., |
-: `HAS_m_TEMPLATE_PARAMS(...),` : `(int_value)` : t_m, int>` :
-: `AND_1_VALUE_PARAMS(p1))` : : :
-| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value,` | `BazActionP2<bool, |
-: : `int_value)` : int>` :
-| `ACTION_TEMPLATE(Baz,` | `Baz<t1, ..., t_m>` | `FooActionP2<t1, ..., |
-: `HAS_m_TEMPLATE_PARAMS(...),` : `(bool_value,` : t_m,` `bool, int>` :
-: `AND_2_VALUE_PARAMS(p1, p2))` : `int_value)` : :
+| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `BarActionP<t1, ..., t_m, int>` |
+| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` |
+| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `BazActionP2<t1, ..., t_m, bool, int>` |
| ... | ... | ... |
+
Note that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`,
and etc) for actions with different numbers of value parameters, or the action
definitions cannot be overloaded on the number of them.
@@ -4087,7 +4163,7 @@ class ActionInterface {
//
// For example, if F is int(bool, const string&), then Result would
- // be int, and ArgumentTuple would be ::std::tuple<bool, const string&>.
+ // be int, and ArgumentTuple would be std::tuple<bool, const string&>.
virtual Result Perform(const ArgumentTuple& args) = 0;
};
```
@@ -4102,8 +4178,8 @@ typedef int IncrementMethod(int*);
class IncrementArgumentAction : public ActionInterface<IncrementMethod> {
public:
- int Perform(const ::std::tuple<int*>& args) override {
- int* p = ::std::get<0>(args); // Grabs the first argument.
+ int Perform(const std::tuple<int*>& args) override {
+ int* p = std::get<0>(args); // Grabs the first argument.
return *p++;
}
};
@@ -4148,8 +4224,8 @@ class ReturnSecondArgumentAction {
public:
template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple& args) const {
- // To get the i-th (0-based) argument, use ::std::get(args).
- return ::std::get<1>(args);
+ // To get the i-th (0-based) argument, use std::get(args).
+ return std::get<1>(args);
}
};
```
@@ -4158,7 +4234,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.
@@ -4207,7 +4283,7 @@ value printer.
This printer knows how to print built-in C++ types, native arrays, STL
containers, and any type that supports the `<<` operator. For other types, it
prints the raw bytes in the value and hopes that you the user can figure it out.
-[googletest's advanced guide](../../googletest/docs/advanced.md#teaching-googletest-how-to-print-your-values)
+[The GoogleTest advanced guide](advanced.md#teaching-googletest-how-to-print-your-values)
explains how to extend the printer to do a better job at printing your
particular type than to dump the bytes.
@@ -4219,7 +4295,7 @@ particular type than to dump the bytes.
### Mock std::function {#MockFunction}
`std::function` is a general function type introduced in C++11. It is a
-preferred way of passing callbacks to new interfaces. Functions are copiable,
+preferred way of passing callbacks to new interfaces. Functions are copyable,
and are not usually passed around by pointer, which makes them tricky to mock.
But fear not - `MockFunction` can help you with that.
@@ -4266,5 +4342,3 @@ expectations.
Although `std::function` supports unlimited number of arguments, `MockFunction`
implementation is limited to ten. If you ever hit that limit... well, your
callback has bigger problems than being mockable. :-)
-
-<!-- GOOGLETEST_CM0034 DO NOT DELETE -->
diff --git a/googlemock/docs/gmock_faq.md b/docs/gmock_faq.md
index 214aabf1218a..8f220bf7a8fe 100644
--- a/googlemock/docs/gmock_faq.md
+++ b/docs/gmock_faq.md
@@ -1,11 +1,9 @@
-## Legacy gMock FAQ {#GMockFaq}
-
-<!-- GOOGLETEST_CM0021 DO NOT DELETE -->
+# Legacy gMock FAQ
### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem?
In order for a method to be mocked, it must be *virtual*, unless you use the
-[high-perf dependency injection technique](#MockingNonVirtualMethods).
+[high-perf dependency injection technique](gmock_cook_book.md#MockingNonVirtualMethods).
### Can I mock a variadic function?
@@ -81,8 +79,6 @@ void Bar(int* p); // Neither p nor *p is const.
void Bar(const int* p); // p is not const, but *p is.
```
-<!-- GOOGLETEST_CM0030 DO NOT DELETE -->
-
### I can't figure out why gMock thinks my expectations are not satisfied. What should I do?
You might want to run your test with `--gmock_verbose=info`. This flag lets
@@ -91,7 +87,7 @@ trace, you'll gain insights on why the expectations you set are not met.
If you see the message "The mock function has no default action set, and its
return type has no default value set.", then try
-[adding a default action](for_dummies.md#DefaultValue). Due to a known issue,
+[adding a default action](gmock_cheat_sheet.md#OnCall). Due to a known issue,
unexpected calls on mocks without default actions don't print out a detailed
comparison between the actual arguments and the expected arguments.
@@ -126,8 +122,6 @@ using ::testing::_;
.Times(0);
```
-<!-- GOOGLETEST_CM0031 DO NOT DELETE -->
-
### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant?
When gMock detects a failure, it prints relevant information (the mock function
@@ -375,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?
@@ -386,8 +380,8 @@ doesn't say what the return value should be. You need `DoAll()` to chain a
`SetArgPointee()` with a `Return()` that provides a value appropriate to the API
being mocked.
-See this [recipe](cook_book.md#mocking-side-effects) for more details and an
-example.
+See this [recipe](gmock_cook_book.md#mocking-side-effects) for more details and
+an example.
### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do?
diff --git a/googlemock/docs/for_dummies.md b/docs/gmock_for_dummies.md
index e11c18d9bf02..43f907aaa5da 100644
--- a/googlemock/docs/for_dummies.md
+++ b/docs/gmock_for_dummies.md
@@ -1,8 +1,6 @@
-## gMock for Dummies {#GMockForDummies}
+# gMock for Dummies
-<!-- GOOGLETEST_CM0013 DO NOT DELETE -->
-
-### What Is gMock?
+## What Is gMock?
When you write a prototype or test, often it's not feasible or wise to rely on
real objects entirely. A **mock object** implements the same interface as a real
@@ -10,9 +8,9 @@ object (so it can be used as one), but lets you specify at run time how it will
be used and what it should do (which methods will be called? in which order? how
many times? with what arguments? what will they return? etc).
-**Note:** It is easy to confuse the term *fake objects* with mock objects. Fakes
-and mocks actually mean very different things in the Test-Driven Development
-(TDD) community:
+It is easy to confuse the term *fake objects* with mock objects. Fakes and mocks
+actually mean very different things in the Test-Driven Development (TDD)
+community:
* **Fake** objects have working implementations, but usually take some
shortcut (perhaps to make the operations less expensive), which makes them
@@ -39,7 +37,7 @@ When using gMock,
3. then you exercise code that uses the mock objects. gMock will catch any
violation to the expectations as soon as it arises.
-### Why gMock?
+## Why gMock?
While mock objects help you remove unnecessary dependencies in tests and make
them fast and reliable, using mocks manually in C++ is *hard*:
@@ -53,9 +51,9 @@ them fast and reliable, using mocks manually in C++ is *hard*:
one.
In contrast, Java and Python programmers have some fine mock frameworks (jMock,
-EasyMock, [Mox](http://wtf/mox), etc), which automate the creation of mocks. As
-a result, mocking is a proven effective technique and widely adopted practice in
-those communities. Having the right tool absolutely makes the difference.
+EasyMock, etc), which automate the creation of mocks. As a result, mocking is a
+proven effective technique and widely adopted practice in those communities.
+Having the right tool absolutely makes the difference.
gMock was built to help C++ programmers. It was inspired by jMock and EasyMock,
but designed with C++'s specifics in mind. It is your friend if any of the
@@ -85,11 +83,11 @@ We encourage you to use gMock as
* a *testing* tool to cut your tests' outbound dependencies and probe the
interaction between your module and its collaborators.
-### Getting Started
+## Getting Started
gMock is bundled with googletest.
-### A Case for Mock Turtles
+## A Case for Mock Turtles
Let's look at an example. Suppose you are developing a graphics program that
relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like
@@ -106,7 +104,7 @@ the API in an interface (say, `Turtle`) and code to that interface:
```cpp
class Turtle {
...
- virtual ~Turtle() {};
+ virtual ~Turtle() {}
virtual void PenUp() = 0;
virtual void PenDown() = 0;
virtual void Forward(int distance) = 0;
@@ -135,20 +133,20 @@ because your new machine does anti-aliasing differently), easier to read and
maintain (the intent of a test is expressed in the code, not in some binary
images), and run *much, much faster*.
-### Writing the Mock Class
+## Writing the Mock Class
If you are lucky, the mocks you need to use have already been implemented by
some nice people. If, however, you find yourself in the position to write a mock
class, relax - gMock turns this task into a fun game! (Well, almost.)
-#### How to Define It
+### How to Define It
Using the `Turtle` interface as example, here are the simple steps you need to
follow:
* Derive a class `MockTurtle` from `Turtle`.
* Take a *virtual* function of `Turtle` (while it's possible to
- [mock non-virtual methods using templates](cook_book.md#MockingNonVirtualMethods),
+ [mock non-virtual methods using templates](gmock_cook_book.md#MockingNonVirtualMethods),
it's much more involved).
* In the `public:` section of the child class, write `MOCK_METHOD();`
* Now comes the fun part: you take the function signature, cut-and-paste it
@@ -166,7 +164,7 @@ follow:
After the process, you should have something like:
```cpp
-#include "gmock/gmock.h" // Brings in gMock.
+#include <gmock/gmock.h> // Brings in gMock.
class MockTurtle : public Turtle {
public:
@@ -184,7 +182,7 @@ class MockTurtle : public Turtle {
You don't need to define these mock methods somewhere else - the `MOCK_METHOD`
macro will generate the definitions for you. It's that simple!
-#### Where to Put It
+### Where to Put It
When you define a mock class, you need to decide where to put its definition.
Some people put it in a `_test.cc`. This is fine when the interface being mocked
@@ -192,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.
@@ -206,14 +204,12 @@ choosing the adaptor interface can make your code easier to write and more
readable (a net win in the long run), as you can choose `FooAdaptor` to fit your
specific domain much better than `Foo` does.
-<!-- GOOGLETEST_CM0029 DO NOT DELETE -->
-
-### Using Mocks in Tests
+## Using Mocks in Tests
Once you have a mock class, using it is easy. The typical work flow is:
1. Import the gMock names from the `testing` namespace such that you can use
- them unqualified (You only have to do it once per file. Remember that
+ them unqualified (You only have to do it once per file). Remember that
namespaces are a good idea.
2. Create some mock objects.
3. Specify your expectations on them (How many times will a method be called?
@@ -228,8 +224,8 @@ Here's an example:
```cpp
#include "path/to/mock-turtle.h"
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
using ::testing::AtLeast; // #1
@@ -257,8 +253,8 @@ Stack trace:
...
```
-**Tip 1:** If you run the test from an Emacs buffer, you can hit <Enter> on the
-line number to jump right to the failed expectation.
+**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on
+the line number to jump right to the failed expectation.
**Tip 2:** If your mock objects are never deleted, the final verification won't
happen. Therefore it's a good idea to turn on the heap checker in your tests
@@ -266,8 +262,9 @@ when you allocate mocks on the heap. You get that automatically if you use the
`gtest_main` library already.
**Important note:** gMock requires expectations to be set **before** the mock
-functions are called, otherwise the behavior is **undefined**. In particular,
-you mustn't interleave `EXPECT_CALL()s` and calls to the mock functions.
+functions are called, otherwise the behavior is **undefined**. Do not alternate
+between calls to `EXPECT_CALL()` and calls to the mock functions, and do not set
+any expectations on a mock after passing the mock to an API.
This means `EXPECT_CALL()` should be read as expecting that a call will occur
*in the future*, not that a call has occurred. Why does gMock work like that?
@@ -279,7 +276,7 @@ Admittedly, this test is contrived and doesn't do much. You can easily achieve
the same effect without using gMock. However, as we shall reveal soon, gMock
allows you to do *so much more* with the mocks.
-### Setting Expectations
+## Setting Expectations
The key to using a mock object successfully is to set the *right expectations*
on it. If you set the expectations too strict, your test will fail as the result
@@ -288,7 +285,7 @@ to do it just right such that your test can catch exactly the kind of bugs you
intend it to catch. gMock provides the necessary means for you to do it "just
right."
-#### General Syntax
+### General Syntax
In gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock
method. The general syntax is:
@@ -314,8 +311,8 @@ EXPECT_CALL(mock_object, non-overloaded-method)
This syntax allows the test writer to specify "called with any arguments"
without explicitly specifying the number or types of arguments. To avoid
-unintended ambiguity, this syntax may only be used for methods which are not
-overloaded
+unintended ambiguity, this syntax may only be used for methods that are not
+overloaded.
Either form of the macro can be followed by some optional *clauses* that provide
more information about the expectation. We'll discuss how each clause works in
@@ -338,12 +335,13 @@ says that the `turtle` object's `GetX()` method will be called five times, it
will return 100 the first time, 150 the second time, and then 200 every time.
Some people like to call this style of syntax a Domain-Specific Language (DSL).
+{: .callout .note}
**Note:** Why do we use a macro to do this? Well it serves two purposes: first
-it makes expectations easily identifiable (either by `gsearch` or by a human
+it makes expectations easily identifiable (either by `grep` or by a human
reader), and second it allows gMock to include the source file location of a
failed expectation in messages, making debugging easier.
-#### Matchers: What Arguments Do We Expect?
+### Matchers: What Arguments Do We Expect?
When a mock function takes arguments, we may specify what arguments we are
expecting, for example:
@@ -374,8 +372,8 @@ convenient way of saying "any value".
In the above examples, `100` and `50` are also matchers; implicitly, they are
the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be
equal (using `operator==`) to the matcher argument. There are many
-[built-in matchers](#MatcherList) for common types (as well as
-[custom matchers](cook_book.md#NewMatchers)); for example:
+[built-in matchers](reference/matchers.md) for common types (as well as
+[custom matchers](gmock_cook_book.md#NewMatchers)); for example:
```cpp
using ::testing::Ge;
@@ -397,9 +395,9 @@ EXPECT_CALL(turtle, GoTo);
This works for all non-overloaded methods; if a method is overloaded, you need
to help gMock resolve which overload is expected by specifying the number of
arguments and possibly also the
-[types of the arguments](cook_book.md#SelectOverload).
+[types of the arguments](gmock_cook_book.md#SelectOverload).
-#### Cardinalities: How Many Times Will It Be Called?
+### Cardinalities: How Many Times Will It Be Called?
The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We
call its argument a **cardinality** as it tells *how many times* the call should
@@ -414,7 +412,7 @@ called.
We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the
list of built-in cardinalities you can use, see
-[here](cheat_sheet.md#CardinalityList).
+[here](gmock_cheat_sheet.md#CardinalityList).
The `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer
the cardinality for you.** The rules are easy to remember:
@@ -429,7 +427,7 @@ the cardinality for you.** The rules are easy to remember:
**Quick quiz:** what do you think will happen if a function is expected to be
called twice but actually called four times?
-#### Actions: What Should It Do?
+### Actions: What Should It Do?
Remember that a mock object doesn't really have a working implementation? We as
users have to tell it what to do when a method is invoked. This is easy in
@@ -482,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](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
@@ -503,7 +501,7 @@ always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)`
will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will
return the same pointer every time. If you want the side effect to happen every
time, you need to define a custom action, which we'll teach in the
-[cook book](http://<!-- GOOGLETEST_CM0012 DO NOT DELETE -->).
+[cook book](gmock_cook_book.md).
Time for another quiz! What do you think the following means?
@@ -522,7 +520,7 @@ will be taken afterwards. So the right answer is that `turtle.GetY()` will
return 100 the first time, but **return 0 from the second time on**, as
returning 0 is the default action for `int` functions.
-#### Using Multiple Expectations {#MultiExpectations}
+### Using Multiple Expectations {#MultiExpectations}
So far we've only shown examples where you have a single expectation. More
realistically, you'll specify expectations on multiple mock methods which may be
@@ -547,6 +545,7 @@ error, as the last matching expectation (#2) has been saturated. If, however,
the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK,
as now #1 will be the matching expectation.
+{: .callout .note}
**Note:** Why does gMock search for a match in the *reverse* order of the
expectations? The reason is that this allows a user to set up the default
expectations in a mock object's constructor or the test fixture's set-up phase
@@ -555,15 +554,16 @@ body. So, if you have two expectations on the same method, you want to put the
one with more specific matchers **after** the other, or the more specific rule
would be shadowed by the more general one that comes after it.
+{: .callout .tip}
**Tip:** It is very common to start with a catch-all expectation for a method
and `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if
overloaded). This makes any calls to the method expected. This is not necessary
for methods that are not mentioned at all (these are "uninteresting"), but is
useful for methods that have some expectations, but for which other calls are
ok. See
-[Understanding Uninteresting vs Unexpected Calls](cook_book.md#uninteresting-vs-unexpected).
+[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected).
-#### Ordered vs Unordered Calls {#OrderedCalls}
+### Ordered vs Unordered Calls {#OrderedCalls}
By default, an expectation can match a call even though an earlier expectation
hasn't been satisfied. In other words, the calls don't have to occur in the
@@ -598,9 +598,9 @@ order as written. If a call is made out-of-order, it will be an error.
(What if you care about the relative order of some of the calls, but not all of
them? Can you specify an arbitrary partial order? The answer is ... yes! The
-details can be found [here](cook_book.md#OrderedCalls).)
+details can be found [here](gmock_cook_book.md#OrderedCalls).)
-#### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations}
+### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations}
Now let's do a quick quiz to see how well you can use this mock stuff already.
How would you test that the turtle is asked to go to the origin *exactly twice*
@@ -688,7 +688,7 @@ it's in a sequence - as soon as another expectation that comes after it in the
sequence has been used, it automatically retires (and will never be used to
match any call).
-#### Uninteresting Calls
+### Uninteresting Calls
A mock object may have many methods, and not all of them are that interesting.
For example, in some tests we may not care about how many times `GetX()` and
@@ -697,4 +697,4 @@ For example, in some tests we may not care about how many times `GetX()` and
In gMock, if you are not interested in a method, just don't say anything about
it. If a call to this method occurs, you'll see a warning in the test output,
but it won't be a failure. This is called "naggy" behavior; to change, see
-[The Nice, the Strict, and the Naggy](cook_book.md#NiceStrictNaggy).
+[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy).
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 000000000000..b162c7401163
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,22 @@
+# GoogleTest User's Guide
+
+## Welcome to GoogleTest!
+
+GoogleTest is Google's C++ testing and mocking framework. This user's guide has
+the following contents:
+
+* [GoogleTest Primer](primer.md) - Teaches you how to write simple tests using
+ GoogleTest. Read this first if you are new to GoogleTest.
+* [GoogleTest Advanced](advanced.md) - Read this when you've finished the
+ Primer and want to utilize GoogleTest to its full potential.
+* [GoogleTest Samples](samples.md) - Describes some GoogleTest samples.
+* [GoogleTest FAQ](faq.md) - Have a question? Want some tips? Check here
+ first.
+* [Mocking for Dummies](gmock_for_dummies.md) - Teaches you how to create mock
+ objects and use them in tests.
+* [Mocking Cookbook](gmock_cook_book.md) - Includes tips and approaches to
+ common mocking use cases.
+* [Mocking Cheat Sheet](gmock_cheat_sheet.md) - A handy reference for
+ matchers, actions, invariants, and more.
+* [Mocking FAQ](gmock_faq.md) - Contains answers to some mocking-specific
+ questions.
diff --git a/docs/pkgconfig.md b/docs/pkgconfig.md
new file mode 100644
index 000000000000..bf05d5931659
--- /dev/null
+++ b/docs/pkgconfig.md
@@ -0,0 +1,144 @@
+## Using GoogleTest from various build systems
+
+GoogleTest comes with pkg-config files that can be used to determine all
+necessary flags for compiling and linking to GoogleTest (and GoogleMock).
+Pkg-config is a standardised plain-text format containing
+
+* the includedir (-I) path
+* necessary macro (-D) definitions
+* further required flags (-pthread)
+* the library (-L) path
+* the library (-l) to link to
+
+All current build systems support pkg-config in one way or another. For all
+examples here we assume you want to compile the sample
+`samples/sample3_unittest.cc`.
+
+### CMake
+
+Using `pkg-config` in CMake is fairly easy:
+
+```cmake
+find_package(PkgConfig)
+pkg_search_module(GTEST REQUIRED gtest_main)
+
+add_executable(testapp)
+target_sources(testapp PRIVATE samples/sample3_unittest.cc)
+target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS})
+target_compile_options(testapp PRIVATE ${GTEST_CFLAGS})
+
+enable_testing()
+add_test(first_and_only_test testapp)
+```
+
+It is generally recommended that you use `target_compile_options` + `_CFLAGS`
+over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not
+just -I flags (GoogleTest might require a macro indicating to internal headers
+that all libraries have been compiled with threading enabled. In addition,
+GoogleTest might also require `-pthread` in the compiling step, and as such
+splitting the pkg-config `Cflags` variable into include dirs and macros for
+`target_compile_definitions()` might still miss this). The same recommendation
+goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens
+to discard `-L` flags and `-pthread`.
+
+### Help! pkg-config can't find GoogleTest!
+
+Let's say you have a `CMakeLists.txt` along the lines of the one in this
+tutorial and you try to run `cmake`. It is very possible that you get a failure
+along the lines of:
+
+```
+-- Checking for one of the modules 'gtest_main'
+CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message):
+ None of the required 'gtest_main' found
+```
+
+These failures are common if you installed GoogleTest yourself and have not
+sourced it from a distro or other package manager. If so, you need to tell
+pkg-config where it can find the `.pc` files containing the information. Say you
+installed GoogleTest to `/usr/local`, then it might be that the `.pc` files are
+installed under `/usr/local/lib64/pkgconfig`. If you set
+
+```
+export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig
+```
+
+pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`.
+
+### Using pkg-config in a cross-compilation setting
+
+Pkg-config can be used in a cross-compilation setting too. To do this, let's
+assume the final prefix of the cross-compiled installation will be `/usr`, and
+your sysroot is `/home/MYUSER/sysroot`. Configure and install GTest using
+
+```
+mkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr ..
+```
+
+Install into the sysroot using `DESTDIR`:
+
+```
+make -j install DESTDIR=/home/MYUSER/sysroot
+```
+
+Before we continue, it is recommended to **always** define the following two
+variables for pkg-config in a cross-compilation setting:
+
+```
+export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes
+export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes
+```
+
+otherwise `pkg-config` will filter `-I` and `-L` flags against standard prefixes
+such as `/usr` (see https://bugs.freedesktop.org/show_bug.cgi?id=28264#c3 for
+reasons why this stripping needs to occur usually).
+
+If you look at the generated pkg-config file, it will look something like
+
+```
+libdir=/usr/lib64
+includedir=/usr/include
+
+Name: gtest
+Description: GoogleTest (without main() function)
+Version: 1.11.0
+URL: https://github.com/google/googletest
+Libs: -L${libdir} -lgtest -lpthread
+Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread
+```
+
+Notice that the sysroot is not included in `libdir` and `includedir`! If you try
+to run `pkg-config` with the correct
+`PKG_CONFIG_LIBDIR=/home/MYUSER/sysroot/usr/lib64/pkgconfig` against this `.pc`
+file, you will get
+
+```
+$ pkg-config --cflags gtest
+-DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include
+$ pkg-config --libs gtest
+-L/usr/lib64 -lgtest -lpthread
+```
+
+which is obviously wrong and points to the `CBUILD` and not `CHOST` root. In
+order to use this in a cross-compilation setting, we need to tell pkg-config to
+inject the actual sysroot into `-I` and `-L` variables. Let us now tell
+pkg-config about the actual sysroot
+
+```
+export PKG_CONFIG_DIR=
+export PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot
+export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig
+```
+
+and running `pkg-config` again we get
+
+```
+$ pkg-config --cflags gtest
+-DGTEST_HAS_PTHREAD=1 -lpthread -I/home/MYUSER/sysroot/usr/include
+$ pkg-config --libs gtest
+-L/home/MYUSER/sysroot/usr/lib64 -lgtest -lpthread
+```
+
+which contains the correct sysroot now. For a more comprehensive guide to also
+including `${CHOST}` in build system calls, see the excellent tutorial by Diego
+Elio Pettenò: <https://autotools.io/pkgconfig/cross-compiling.html>
diff --git a/docs/platforms.md b/docs/platforms.md
new file mode 100644
index 000000000000..d35a7be054e8
--- /dev/null
+++ b/docs/platforms.md
@@ -0,0 +1,8 @@
+# Supported Platforms
+
+GoogleTest follows Google's
+[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
+See
+[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
+for a list of currently supported versions compilers, platforms, and build
+tools.
diff --git a/googletest/docs/primer.md b/docs/primer.md
index 0317692bbb0f..f2a97a7269b7 100644
--- a/googletest/docs/primer.md
+++ b/docs/primer.md
@@ -1,85 +1,84 @@
-# Googletest Primer
+# GoogleTest Primer
-## Introduction: Why googletest?
+## Introduction: Why GoogleTest?
-*googletest* helps you write better C++ tests.
+*GoogleTest* helps you write better C++ tests.
-googletest is a testing framework developed by the Testing Technology team with
+GoogleTest is a testing framework developed by the Testing Technology team with
Google's specific requirements and constraints in mind. Whether you work on
-Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it
+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.
-So what makes a good test, and how does googletest fit in? We believe:
+So what makes a good test, and how does GoogleTest fit in? We believe:
1. Tests should be *independent* and *repeatable*. It's a pain to debug a test
- that succeeds or fails as a result of other tests. googletest isolates the
+ that succeeds or fails as a result of other tests. GoogleTest isolates the
tests by running each of them on a different object. When a test fails,
- googletest allows you to run it in isolation for quick debugging.
+ GoogleTest allows you to run it in isolation for quick debugging.
2. Tests should be well *organized* and reflect the structure of the tested
- code. googletest groups related tests into test suites that can share data
+ code. GoogleTest groups related tests into test suites that can share data
and subroutines. This common pattern is easy to recognize and makes tests
easy to maintain. Such consistency is especially helpful when people switch
projects and start to work on a new code base.
3. Tests should be *portable* and *reusable*. Google has a lot of code that is
- platform-neutral; its tests should also be platform-neutral. googletest
+ platform-neutral; its tests should also be platform-neutral. GoogleTest
works on different OSes, with different compilers, with or without
- exceptions, so googletest tests can work with a variety of configurations.
+ exceptions, so GoogleTest tests can work with a variety of configurations.
4. When tests fail, they should provide as much *information* about the problem
- as possible. googletest doesn't stop at the first test failure. Instead, it
+ as possible. GoogleTest doesn't stop at the first test failure. Instead, it
only stops the current test and continues with the next. You can also set up
tests that report non-fatal failures after which the current test continues.
Thus, you can detect and fix multiple bugs in a single run-edit-compile
cycle.
5. The testing framework should liberate test writers from housekeeping chores
- and let them focus on the test *content*. googletest automatically keeps
+ and let them focus on the test *content*. GoogleTest automatically keeps
track of all tests defined, and doesn't require the user to enumerate them
in order to run them.
-6. Tests should be *fast*. With googletest, you can reuse shared resources
+6. Tests should be *fast*. With GoogleTest, you can reuse shared resources
across tests and pay for the set-up/tear-down only once, without making
tests depend on each other.
-Since googletest is based on the popular xUnit architecture, you'll feel right
+Since GoogleTest is based on the popular xUnit architecture, you'll feel right
at home if you've used JUnit or PyUnit before. If not, it will take you about 10
minutes to learn the basics and get started. So let's go!
-## Beware of the nomenclature
+## Beware of the Nomenclature
-_Note:_ There might be some confusion arising from different definitions of the
-terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these.
+{: .callout .note}
+*Note:* There might be some confusion arising from different definitions of the
+terms *Test*, *Test Case* and *Test Suite*, so beware of misunderstanding these.
-Historically, googletest started to use the term _Test Case_ for grouping
+Historically, GoogleTest started to use the term *Test Case* for grouping
related tests, whereas current publications, including International Software
Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and
various textbooks on software quality, use the term
-_[Test Suite][istqb test suite]_ for this.
+*[Test Suite][istqb test suite]* for this.
-The related term _Test_, as it is used in googletest, corresponds to the term
-_[Test Case][istqb test case]_ of ISTQB and others.
+The related term *Test*, as it is used in GoogleTest, corresponds to the term
+*[Test Case][istqb test case]* of ISTQB and others.
-The term _Test_ is commonly of broad enough sense, including ISTQB's definition
-of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as
+The term *Test* is commonly of broad enough sense, including ISTQB's definition
+of *Test Case*, so it's not much of a problem here. But the term *Test Case* as
was used in Google Test is of contradictory sense and thus confusing.
-googletest recently started replacing the term _Test Case_ with _Test Suite_.
+GoogleTest recently started replacing the term *Test Case* with *Test Suite*.
The preferred API is *TestSuite*. The older TestCase API is being slowly
deprecated and refactored away.
So please be aware of the different definitions of the terms:
-<!-- mdformat off(github rendering does not support multiline tables) -->
-Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term
+Meaning | GoogleTest Term | [ISTQB](http://www.istqb.org/) Term
:----------------------------------------------------------------------------------- | :---------------------- | :----------------------------------
Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
-<!-- mdformat on -->
[istqb test case]: http://glossary.istqb.org/en/search/test%20case
[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite
## Basic Concepts
-When using googletest, you start by writing *assertions*, which are statements
+When using GoogleTest, you start by writing *assertions*, which are statements
that check whether a condition is true. An assertion's result can be *success*,
*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
current function; otherwise the program continues normally.
@@ -99,11 +98,11 @@ assertion level and building up to tests and test suites.
## Assertions
-googletest assertions are macros that resemble function calls. You test a class
+GoogleTest assertions are macros that resemble function calls. You test a class
or function by making assertions about its behavior. When an assertion fails,
-googletest prints the assertion's source file and line number location, along
+GoogleTest prints the assertion's source file and line number location, along
with a failure message. You may also supply a custom failure message which will
-be appended to googletest's message.
+be appended to GoogleTest's message.
The assertions come in pairs that test the same thing but have different effects
on the current function. `ASSERT_*` versions generate fatal failures when they
@@ -119,7 +118,9 @@ Depending on the nature of the leak, it may or may not be worth fixing - so keep
this in mind if you get a heap checker error in addition to assertion errors.
To provide a custom failure message, simply stream it into the macro using the
-`<<` operator or a sequence of such operators. An example:
+`<<` operator or a sequence of such operators. See the following example, using
+the [`ASSERT_EQ` and `EXPECT_EQ`](reference/assertions.md#EXPECT_EQ) macros to
+verify value equality:
```c++
ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
@@ -134,112 +135,12 @@ macro--in particular, C strings and `string` objects. If a wide string
(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
streamed to an assertion, it will be translated to UTF-8 when printed.
-### Basic Assertions
-
-These assertions do basic true/false condition testing.
-
-Fatal assertion | Nonfatal assertion | Verifies
--------------------------- | -------------------------- | --------------------
-`ASSERT_TRUE(condition);` | `EXPECT_TRUE(condition);` | `condition` is true
-`ASSERT_FALSE(condition);` | `EXPECT_FALSE(condition);` | `condition` is false
-
-Remember, when they fail, `ASSERT_*` yields a fatal failure and returns from the
-current function, while `EXPECT_*` yields a nonfatal failure, allowing the
-function to continue running. In either case, an assertion failure means its
-containing test fails.
-
-**Availability**: Linux, Windows, Mac.
-
-### Binary Comparison
-
-This section describes assertions that compare two values.
-
-Fatal assertion | Nonfatal assertion | Verifies
------------------------- | ------------------------ | --------------
-`ASSERT_EQ(val1, val2);` | `EXPECT_EQ(val1, val2);` | `val1 == val2`
-`ASSERT_NE(val1, val2);` | `EXPECT_NE(val1, val2);` | `val1 != val2`
-`ASSERT_LT(val1, val2);` | `EXPECT_LT(val1, val2);` | `val1 < val2`
-`ASSERT_LE(val1, val2);` | `EXPECT_LE(val1, val2);` | `val1 <= val2`
-`ASSERT_GT(val1, val2);` | `EXPECT_GT(val1, val2);` | `val1 > val2`
-`ASSERT_GE(val1, val2);` | `EXPECT_GE(val1, val2);` | `val1 >= val2`
-
-Value arguments must be comparable by the assertion's comparison operator or
-you'll get a compiler error. We used to require the arguments to support the
-`<<` operator for streaming to an `ostream`, but this is no longer necessary. If
-`<<` is supported, it will be called to print the arguments when the assertion
-fails; otherwise googletest will attempt to print them in the best way it can.
-For more details and how to customize the printing of the arguments, see the
-[documentation](../../googlemock/docs/cook_book.md#teaching-gmock-how-to-print-your-values).
-
-These assertions can work with a user-defined type, but only if you define the
-corresponding comparison operator (e.g., `==` or `<`). Since this is discouraged
-by the Google
-[C++ Style Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading),
-you may need to use `ASSERT_TRUE()` or `EXPECT_TRUE()` to assert the equality of
-two objects of a user-defined type.
-
-However, when possible, `ASSERT_EQ(actual, expected)` is preferred to
-`ASSERT_TRUE(actual == expected)`, since it tells you `actual` and `expected`'s
-values on failure.
-
-Arguments are always evaluated exactly once. Therefore, it's OK for the
-arguments to have side effects. However, as with any ordinary C/C++ function,
-the arguments' evaluation order is undefined (i.e., the compiler is free to
-choose any order), and your code should not depend on any particular argument
-evaluation order.
-
-`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
-tests if they are in the same memory location, not if they have the same value.
-Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
-`ASSERT_STREQ()`, which will be described later on. In particular, to assert
-that a C string is `NULL`, use `ASSERT_STREQ(c_string, NULL)`. Consider using
-`ASSERT_EQ(c_string, nullptr)` if c++11 is supported. To compare two `string`
-objects, you should use `ASSERT_EQ`.
-
-When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)`
-instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is
-typed, while `NULL` is not. See the [FAQ](faq.md) for more details.
-
-If you're working with floating point numbers, you may want to use the floating
-point variations of some of these macros in order to avoid problems caused by
-rounding. See [Advanced googletest Topics](advanced.md) for details.
-
-Macros in this section work with both narrow and wide string objects (`string`
-and `wstring`).
-
-**Availability**: Linux, Windows, Mac.
-
-**Historical note**: Before February 2016 `*_EQ` had a convention of calling it
-as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now
-`*_EQ` treats both parameters in the same way.
-
-### String Comparison
-
-The assertions in this group compare two **C strings**. If you want to compare
-two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
-
-<!-- mdformat off(github rendering does not support multiline tables) -->
-
-| Fatal assertion | Nonfatal assertion | Verifies |
-| -------------------------- | ------------------------------ | -------------------------------------------------------- |
-| `ASSERT_STREQ(str1,str2);` | `EXPECT_STREQ(str1,str2);` | the two C strings have the same content |
-| `ASSERT_STRNE(str1,str2);` | `EXPECT_STRNE(str1,str2);` | the two C strings have different contents |
-| `ASSERT_STRCASEEQ(str1,str2);` | `EXPECT_STRCASEEQ(str1,str2);` | the two C strings have the same content, ignoring case |
-| `ASSERT_STRCASENE(str1,str2);` | `EXPECT_STRCASENE(str1,str2);` | the two C strings have different contents, ignoring case |
-
-<!-- mdformat on-->
-
-Note that "CASE" in an assertion name means that case is ignored. A `NULL`
-pointer and an empty string are considered *different*.
-
-`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a comparison
-of two wide strings fails, their values will be printed as UTF-8 narrow strings.
-
-**Availability**: Linux, Windows, Mac.
-
-**See also**: For more string comparison tricks (substring, prefix, suffix, and
-regular expression matching, for example), see [this](advanced.md) in the
-Advanced googletest Guide.
+GoogleTest provides a collection of assertions for verifying the behavior of
+your code in various ways. You can check Boolean conditions, compare values
+based on relational operators, verify string values, floating-point values, and
+much more. There are even assertions that enable you to verify more complex
+states by providing custom predicates. For the complete list of assertions
+provided by GoogleTest, see the [Assertions Reference](reference/assertions.md).
## Simple Tests
@@ -248,7 +149,7 @@ To create a test:
1. Use the `TEST()` macro to define and name a test function. These are
ordinary C++ functions that don't return a value.
2. In this function, along with any valid C++ statements you want to include,
- use the various googletest assertions to check values.
+ use the various GoogleTest assertions to check values.
3. The test's result is determined by the assertions; if any assertion in the
test fails (either fatally or non-fatally), or if the test crashes, the
entire test fails. Otherwise, it succeeds.
@@ -261,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
-case. 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:
@@ -289,7 +190,7 @@ TEST(FactorialTest, HandlesPositiveInput) {
}
```
-googletest groups the test results by test suites, so logically related tests
+GoogleTest groups the test results by test suites, so logically related tests
should be in the same test suite; in other words, the first argument to their
`TEST()` should be the same. In the above example, we have two tests,
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
@@ -326,14 +227,14 @@ When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
access objects and subroutines in the test fixture:
```c++
-TEST_F(TestFixtureName, TestName) {
+TEST_F(TestFixtureClassName, TestName) {
... test body ...
}
```
-Like `TEST()`, the first argument is the test suite name, but for `TEST_F()`
-this must be the name of the test fixture class. You've probably guessed: `_F`
-is for fixture.
+Unlike `TEST()`, in `TEST_F()` the first argument must be the name of the test
+fixture class. (`_F` stands for "Fixture"). No test suite name is specified for
+this macro.
Unfortunately, the C++ macro system does not allow us to create a single macro
that can handle both types of tests. Using the wrong macro causes a compiler
@@ -343,12 +244,12 @@ Also, you must first define a test fixture class before using it in a
`TEST_F()`, or you'll get the compiler error "`virtual outside class
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
+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
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
+GoogleTest always deletes a test fixture before it creates the next one.
+GoogleTest does **not** reuse the same test fixture for multiple tests. Any
changes one test makes to the fixture do not affect other tests.
As an example, let's write tests for a FIFO queue class named `Queue`, which has
@@ -373,6 +274,7 @@ First, define a fixture class. By convention, you should give it the name
class QueueTest : public ::testing::Test {
protected:
void SetUp() override {
+ // q0_ remains empty
q1_.Enqueue(1);
q2_.Enqueue(2);
q2_.Enqueue(3);
@@ -418,12 +320,12 @@ The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
to use `EXPECT_*` when you want the test to continue to reveal more errors after
the assertion failure, and use `ASSERT_*` when continuing after failure doesn't
make sense. For example, the second assertion in the `Dequeue` test is
-`ASSERT_NE(nullptr, n)`, as we need to dereference the pointer `n` later, which
+`ASSERT_NE(n, nullptr)`, as we need to dereference the pointer `n` later, which
would lead to a segfault when `n` is `NULL`.
When these tests run, the following happens:
-1. googletest constructs a `QueueTest` object (let's call it `t1`).
+1. GoogleTest constructs a `QueueTest` object (let's call it `t1`).
2. `t1.SetUp()` initializes `t1`.
3. The first test (`IsEmptyInitially`) runs on `t1`.
4. `t1.TearDown()` cleans up after the test finishes.
@@ -435,18 +337,18 @@ When these tests run, the following happens:
## Invoking the Tests
-`TEST()` and `TEST_F()` implicitly register their tests with googletest. So,
+`TEST()` and `TEST_F()` implicitly register their tests with GoogleTest. So,
unlike with many other C++ testing frameworks, you don't have to re-list all
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:
-* Saves the state of all googletest flags.
+* Saves the state of all GoogleTest flags.
* Creates a test fixture object for the first test.
@@ -458,12 +360,13 @@ When invoked, the `RUN_ALL_TESTS()` macro:
* Deletes the fixture.
-* Restores the state of all googletest flags.
+* Restores the state of all GoogleTest flags.
* Repeats the above steps for the next test, until all tests have run.
If a fatal failure happens the subsequent steps will be skipped.
+{: .callout .important}
> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or
> you will get a compiler error. The rationale for this design is that the
> automated testing service determines whether a test has passed based on its
@@ -471,29 +374,38 @@ If a fatal failure happens the subsequent steps will be skipped.
> return the value of `RUN_ALL_TESTS()`.
>
> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than
-> once conflicts with some advanced googletest features (e.g., thread-safe
+> once conflicts with some advanced GoogleTest features (e.g., thread-safe
> [death tests](advanced.md#death-tests)) and thus is not supported.
**Availability**: Linux, Windows, Mac.
## Writing the main() Function
-Write your own main() function, which should return the value of
+Most users should *not* need to write their own `main` function and instead link
+with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry
+point. See the end of this section for details. The remainder of this section
+should only apply when you need to do something custom before the tests run that
+cannot be expressed within the framework of fixtures and test suites.
+
+If you write your own `main` function, it should return the value of
`RUN_ALL_TESTS()`.
You can start from this boilerplate:
```c++
#include "this/package/foo.h"
-#include "gtest/gtest.h"
+#include <gtest/gtest.h>
+
+namespace my {
+namespace project {
namespace {
// The fixture for testing class Foo.
class FooTest : public ::testing::Test {
protected:
- // You can remove any or all of the following functions if its body
- // is empty.
+ // You can remove any or all of the following functions if their bodies would
+ // be empty.
FooTest() {
// You can do set-up work for each test here.
@@ -516,7 +428,8 @@ class FooTest : public ::testing::Test {
// before the destructor).
}
- // Objects declared here can be used by all tests in the test suite for Foo.
+ // Class members declared here can be used by all tests in the test suite
+ // for Foo.
};
// Tests that the Foo::Bar() method does Abc.
@@ -533,6 +446,8 @@ TEST_F(FooTest, DoesXyz) {
}
} // namespace
+} // namespace project
+} // namespace my
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
@@ -541,26 +456,27 @@ 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
+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
`RUN_ALL_TESTS()`, or the flags won't be properly initialized.
On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
in programs compiled in `UNICODE` mode as well.
-But maybe you think that writing all those main() functions is too much work? We
+But maybe you think that writing all those `main` functions is too much work? We
agree with you completely, and that's why Google Test provides a basic
implementation of main(). If it fits your needs, then just link your test with
-gtest\_main library and you are good to go.
+the `gtest_main` library and you are good to go.
+{: .callout .note}
NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
## Known Limitations
* Google Test is designed to be thread-safe. The implementation is thread-safe
on systems where the `pthreads` library is available. It is currently
- _unsafe_ to use Google Test assertions from two threads concurrently on
+ *unsafe* to use Google Test assertions from two threads concurrently on
other systems (e.g. Windows). In most tests this is not an issue as usually
the assertions are done in the main thread. If you want to help, you can
volunteer to implement the necessary synchronization primitives in
diff --git a/docs/quickstart-bazel.md b/docs/quickstart-bazel.md
new file mode 100644
index 000000000000..4f693dbe7fd4
--- /dev/null
+++ b/docs/quickstart-bazel.md
@@ -0,0 +1,153 @@
+# Quickstart: Building with Bazel
+
+This tutorial aims to get you up and running with GoogleTest using the Bazel
+build system. If you're using GoogleTest for the first time or need a refresher,
+we recommend this tutorial as a starting point.
+
+## Prerequisites
+
+To complete this tutorial, you'll need:
+
+* A compatible operating system (e.g. Linux, macOS, Windows).
+* A compatible C++ compiler that supports at least C++14.
+* [Bazel](https://bazel.build/), the preferred build system used by the
+ GoogleTest team.
+
+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://bazel.build/install).
+
+{: .callout .note} Note: The terminal commands in this tutorial show a Unix
+shell prompt, but the commands work on the Windows command line as well.
+
+## Set up a Bazel workspace
+
+A
+[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
+dependencies required to build the outputs.
+
+First, create a directory for your workspace:
+
+```
+$ 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/main/external.html)
+via the
+[`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:
+
+```
+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
+
+http_archive(
+ name = "com_google_googletest",
+ urls = ["https://github.com/google/googletest/archive/5ab508a01f9eb089207ee87fd547d290da39d015.zip"],
+ strip_prefix = "googletest-5ab508a01f9eb089207ee87fd547d290da39d015",
+)
+```
+
+The above configuration declares a dependency on GoogleTest which is downloaded
+as a ZIP archive from GitHub. In the above example,
+`5ab508a01f9eb089207ee87fd547d290da39d015` is the Git commit hash of the
+GoogleTest version to use; we recommend updating the hash often to point to the
+latest version. Use a recent hash on the `main` branch.
+
+Now you're ready to build C++ code that uses GoogleTest.
+
+## Create and run a binary
+
+With your Bazel workspace set up, you can now use GoogleTest code within your
+own project.
+
+As an example, create a file named `hello_test.cc` in your `my_workspace`
+directory with the following contents:
+
+```cpp
+#include <gtest/gtest.h>
+
+// Demonstrate some basic assertions.
+TEST(HelloTest, BasicAssertions) {
+ // Expect two strings not to be equal.
+ EXPECT_STRNE("hello", "world");
+ // Expect equality.
+ EXPECT_EQ(7 * 6, 42);
+}
+```
+
+GoogleTest provides [assertions](primer.md#assertions) that you use to test the
+behavior of your code. The above sample includes the main GoogleTest header file
+and demonstrates some basic assertions.
+
+To build the code, create a file named `BUILD` in the same directory with the
+following contents:
+
+```
+cc_test(
+ name = "hello_test",
+ size = "small",
+ srcs = ["hello_test.cc"],
+ deps = ["@com_google_googletest//:gtest_main"],
+)
+```
+
+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/main/tutorial/cpp.html).
+
+{: .callout .note}
+NOTE: In the example below, we assume Clang or GCC and set `--cxxopt=-std=c++14`
+to ensure that GoogleTest is compiled as C++14 instead of the compiler's default
+setting (which could be C++11). For MSVC, the equivalent would be
+`--cxxopt=/std:c++14`. See [Supported Platforms](platforms.md) for more details
+on supported language versions.
+
+Now you can build and run your test:
+
+<pre>
+<strong>my_workspace$ bazel test --cxxopt=-std=c++14 --test_output=all //:hello_test</strong>
+INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
+INFO: Found 1 test target...
+INFO: From Testing //:hello_test:
+==================== Test output for //:hello_test:
+Running main() from gmock_main.cc
+[==========] Running 1 test from 1 test suite.
+[----------] Global test environment set-up.
+[----------] 1 test from HelloTest
+[ RUN ] HelloTest.BasicAssertions
+[ OK ] HelloTest.BasicAssertions (0 ms)
+[----------] 1 test from HelloTest (0 ms total)
+
+[----------] Global test environment tear-down
+[==========] 1 test from 1 test suite ran. (0 ms total)
+[ PASSED ] 1 test.
+================================================================================
+Target //:hello_test up-to-date:
+ bazel-bin/hello_test
+INFO: Elapsed time: 4.190s, Critical Path: 3.05s
+INFO: 27 processes: 8 internal, 19 linux-sandbox.
+INFO: Build completed successfully, 27 total actions
+//:hello_test PASSED in 0.1s
+
+INFO: Build completed successfully, 27 total actions
+</pre>
+
+Congratulations! You've successfully built and run a test binary using
+GoogleTest.
+
+## Next steps
+
+* [Check out the Primer](primer.md) to start learning how to write simple
+ tests.
+* [See the code samples](samples.md) for more examples showing how to use a
+ variety of GoogleTest features.
diff --git a/docs/quickstart-cmake.md b/docs/quickstart-cmake.md
new file mode 100644
index 000000000000..4e422b74f830
--- /dev/null
+++ b/docs/quickstart-cmake.md
@@ -0,0 +1,157 @@
+# Quickstart: Building with CMake
+
+This tutorial aims to get you up and running with GoogleTest using CMake. If
+you're using GoogleTest for the first time or need a refresher, we recommend
+this tutorial as a starting point. If your project uses Bazel, see the
+[Quickstart for Bazel](quickstart-bazel.md) instead.
+
+## Prerequisites
+
+To complete this tutorial, you'll need:
+
+* A compatible operating system (e.g. Linux, macOS, Windows).
+* A compatible C++ compiler that supports at least C++14.
+* [CMake](https://cmake.org/) and a compatible build tool for building the
+ project.
+ * Compatible build tools include
+ [Make](https://www.gnu.org/software/make/),
+ [Ninja](https://ninja-build.org/), and others - see
+ [CMake Generators](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html)
+ for more information.
+
+See [Supported Platforms](platforms.md) for more information about platforms
+compatible with GoogleTest.
+
+If you don't already have CMake installed, see the
+[CMake installation guide](https://cmake.org/install).
+
+{: .callout .note}
+Note: The terminal commands in this tutorial show a Unix shell prompt, but the
+commands work on the Windows command line as well.
+
+## Set up a project
+
+CMake uses a file named `CMakeLists.txt` to configure the build system for a
+project. You'll use this file to set up your project and declare a dependency on
+GoogleTest.
+
+First, create a directory for your project:
+
+```
+$ mkdir my_project && cd my_project
+```
+
+Next, you'll create the `CMakeLists.txt` file and declare a dependency on
+GoogleTest. There are many ways to express dependencies in the CMake ecosystem;
+in this quickstart, you'll use the
+[`FetchContent` CMake module](https://cmake.org/cmake/help/latest/module/FetchContent.html).
+To do this, in your project directory (`my_project`), create a file named
+`CMakeLists.txt` with the following contents:
+
+```cmake
+cmake_minimum_required(VERSION 3.14)
+project(my_project)
+
+# GoogleTest requires at least C++14
+set(CMAKE_CXX_STANDARD 14)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+include(FetchContent)
+FetchContent_Declare(
+ googletest
+ URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
+)
+# For Windows: Prevent overriding the parent project's compiler/linker settings
+set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
+FetchContent_MakeAvailable(googletest)
+```
+
+The above configuration declares a dependency on GoogleTest which is downloaded
+from GitHub. In the above example, `03597a01ee50ed33e9dfd640b249b4be3799d395` is
+the Git commit hash of the GoogleTest version to use; we recommend updating the
+hash often to point to the latest version.
+
+For more information about how to create `CMakeLists.txt` files, see the
+[CMake Tutorial](https://cmake.org/cmake/help/latest/guide/tutorial/index.html).
+
+## Create and run a binary
+
+With GoogleTest declared as a dependency, you can use GoogleTest code within
+your own project.
+
+As an example, create a file named `hello_test.cc` in your `my_project`
+directory with the following contents:
+
+```cpp
+#include <gtest/gtest.h>
+
+// Demonstrate some basic assertions.
+TEST(HelloTest, BasicAssertions) {
+ // Expect two strings not to be equal.
+ EXPECT_STRNE("hello", "world");
+ // Expect equality.
+ EXPECT_EQ(7 * 6, 42);
+}
+```
+
+GoogleTest provides [assertions](primer.md#assertions) that you use to test the
+behavior of your code. The above sample includes the main GoogleTest header file
+and demonstrates some basic assertions.
+
+To build the code, add the following to the end of your `CMakeLists.txt` file:
+
+```cmake
+enable_testing()
+
+add_executable(
+ hello_test
+ hello_test.cc
+)
+target_link_libraries(
+ hello_test
+ GTest::gtest_main
+)
+
+include(GoogleTest)
+gtest_discover_tests(hello_test)
+```
+
+The above configuration enables testing in CMake, declares the C++ test binary
+you want to build (`hello_test`), and links it to GoogleTest (`gtest_main`). The
+last two lines enable CMake's test runner to discover the tests included in the
+binary, using the
+[`GoogleTest` CMake module](https://cmake.org/cmake/help/git-stage/module/GoogleTest.html).
+
+Now you can build and run your test:
+
+<pre>
+<strong>my_project$ cmake -S . -B build</strong>
+-- The C compiler identification is GNU 10.2.1
+-- The CXX compiler identification is GNU 10.2.1
+...
+-- Build files have been written to: .../my_project/build
+
+<strong>my_project$ cmake --build build</strong>
+Scanning dependencies of target gtest
+...
+[100%] Built target gmock_main
+
+<strong>my_project$ cd build && ctest</strong>
+Test project .../my_project/build
+ Start 1: HelloTest.BasicAssertions
+1/1 Test #1: HelloTest.BasicAssertions ........ Passed 0.00 sec
+
+100% tests passed, 0 tests failed out of 1
+
+Total Test time (real) = 0.01 sec
+</pre>
+
+Congratulations! You've successfully built and run a test binary using
+GoogleTest.
+
+## Next steps
+
+* [Check out the Primer](primer.md) to start learning how to write simple
+ tests.
+* [See the code samples](samples.md) for more examples showing how to use a
+ variety of GoogleTest features.
diff --git a/docs/reference/actions.md b/docs/reference/actions.md
new file mode 100644
index 000000000000..ab81a129eff6
--- /dev/null
+++ b/docs/reference/actions.md
@@ -0,0 +1,115 @@
+# Actions Reference
+
+[**Actions**](../gmock_for_dummies.md#actions-what-should-it-do) specify what a
+mock function should do when invoked. This page lists the built-in actions
+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. |
+| `ReturnArg<N>()` | Return the `N`-th (0-based) argument. |
+| `ReturnNew<T>(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. |
+| `ReturnNull()` | Return a null pointer. |
+| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. |
+| `ReturnRef(variable)` | Return a reference to `variable`. |
+| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. |
+| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. |
+
+## 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. |
+| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. |
+| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
+| `SetArgReferee<N>(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. |
+| `SetArgPointee<N>(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. |
+| `SetArgumentPointee<N>(value)` | Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0. |
+| `SetArrayArgument<N>(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. |
+| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. |
+| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. |
+
+## Using a Function, Functor, or Lambda as an Action
+
+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. |
+| `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. |
+| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. |
+| `InvokeArgument<N>(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. |
+
+The return value of the invoked function is used as the return value of the
+action.
+
+When defining a callable to be used with `Invoke*()`, you can declare any unused
+parameters as `Unused`:
+
+```cpp
+using ::testing::Invoke;
+double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
+...
+EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
+```
+
+`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of
+`callback`, which must be permanent. The type of `callback` must be a base
+callback type instead of a derived one, e.g.
+
+```cpp
+ BlockingClosure* done = new BlockingClosure;
+ ... Invoke(done) ...; // This won't compile!
+
+ Closure* done2 = new BlockingClosure;
+ ... Invoke(done2) ...; // This works.
+```
+
+In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference,
+wrap it inside `std::ref()`. For example,
+
+```cpp
+using ::testing::InvokeArgument;
+...
+InvokeArgument<2>(5, string("Hi"), std::ref(foo))
+```
+
+calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by
+value, and `foo` by reference.
+
+## Default Action
+
+| Action | Description |
+| :------------ | :----------------------------------------------------- |
+| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). |
+
+{: .callout .note}
+**Note:** due to technical reasons, `DoDefault()` cannot be used inside a
+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. |
+| `WithArg<N>(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. |
+| `WithArgs<N1, N2, ..., Nk>(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. |
+| `WithoutArgs(a)` | Perform action `a` without any arguments. |
+
+## 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`. |
+| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. |
+
+The `ACTION*` macros cannot be used inside a function or class.
diff --git a/docs/reference/assertions.md b/docs/reference/assertions.md
new file mode 100644
index 000000000000..aa1dbc04bd19
--- /dev/null
+++ b/docs/reference/assertions.md
@@ -0,0 +1,633 @@
+# Assertions Reference
+
+This page lists the assertion macros provided by GoogleTest for verifying code
+behavior. To use them, include the header `gtest/gtest.h`.
+
+The majority of the macros listed below come as a pair with an `EXPECT_` variant
+and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal
+failures and allow the current function to continue running, while `ASSERT_`
+macros generate fatal failures and abort the current function.
+
+All assertion macros support streaming a custom failure message into them with
+the `<<` operator, for example:
+
+```cpp
+EXPECT_TRUE(my_condition) << "My condition is not true";
+```
+
+Anything that can be streamed to an `ostream` can be streamed to an assertion
+macro—in particular, C strings and string objects. If a wide string (`wchar_t*`,
+`TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is streamed to an
+assertion, it will be translated to UTF-8 when printed.
+
+## Explicit Success and Failure {#success-failure}
+
+The assertions in this section generate a success or failure directly instead of
+testing a value or expression. These are useful when control flow, rather than a
+Boolean expression, determines the test's success or failure, as shown by the
+following example:
+
+```c++
+switch(expression) {
+ case 1:
+ ... some checks ...
+ case 2:
+ ... some other checks ...
+ default:
+ FAIL() << "We shouldn't get here.";
+}
+```
+
+### SUCCEED {#SUCCEED}
+
+`SUCCEED()`
+
+Generates a success. This *does not* make the overall test succeed. A test is
+considered successful only if none of its assertions fail during its execution.
+
+The `SUCCEED` assertion is purely documentary and currently doesn't generate any
+user-visible output. However, we may add `SUCCEED` messages to GoogleTest output
+in the future.
+
+### FAIL {#FAIL}
+
+`FAIL()`
+
+Generates a fatal failure, which returns from the current function.
+
+Can only be used in functions that return `void`. See
+[Assertion Placement](../advanced.md#assertion-placement) for more information.
+
+### ADD_FAILURE {#ADD_FAILURE}
+
+`ADD_FAILURE()`
+
+Generates a nonfatal failure, which allows the current function to continue
+running.
+
+### ADD_FAILURE_AT {#ADD_FAILURE_AT}
+
+`ADD_FAILURE_AT(`*`file_path`*`,`*`line_number`*`)`
+
+Generates a nonfatal failure at the file and line number specified.
+
+## Generalized Assertion {#generalized}
+
+The following assertion allows [matchers](matchers.md) to be used to verify
+values.
+
+### EXPECT_THAT {#EXPECT_THAT}
+
+`EXPECT_THAT(`*`value`*`,`*`matcher`*`)` \
+`ASSERT_THAT(`*`value`*`,`*`matcher`*`)`
+
+Verifies that *`value`* matches the [matcher](matchers.md) *`matcher`*.
+
+For example, the following code verifies that the string `value1` starts with
+`"Hello"`, `value2` matches a regular expression, and `value3` is between 5 and
+10:
+
+```cpp
+#include <gmock/gmock.h>
+
+using ::testing::AllOf;
+using ::testing::Gt;
+using ::testing::Lt;
+using ::testing::MatchesRegex;
+using ::testing::StartsWith;
+
+...
+EXPECT_THAT(value1, StartsWith("Hello"));
+EXPECT_THAT(value2, MatchesRegex("Line \\d+"));
+ASSERT_THAT(value3, AllOf(Gt(5), Lt(10)));
+```
+
+Matchers enable assertions of this form to read like English and generate
+informative failure messages. For example, if the above assertion on `value1`
+fails, the resulting message will be similar to the following:
+
+```
+Value of: value1
+ Actual: "Hi, world!"
+Expected: starts with "Hello"
+```
+
+GoogleTest provides a built-in library of matchers—see the
+[Matchers Reference](matchers.md). It is also possible to write your own
+matchers—see [Writing New Matchers Quickly](../gmock_cook_book.md#NewMatchers).
+The use of matchers makes `EXPECT_THAT` a powerful, extensible assertion.
+
+*The idea for this assertion was borrowed from Joe Walnes' Hamcrest project,
+which adds `assertThat()` to JUnit.*
+
+## Boolean Conditions {#boolean}
+
+The following assertions test Boolean conditions.
+
+### EXPECT_TRUE {#EXPECT_TRUE}
+
+`EXPECT_TRUE(`*`condition`*`)` \
+`ASSERT_TRUE(`*`condition`*`)`
+
+Verifies that *`condition`* is true.
+
+### EXPECT_FALSE {#EXPECT_FALSE}
+
+`EXPECT_FALSE(`*`condition`*`)` \
+`ASSERT_FALSE(`*`condition`*`)`
+
+Verifies that *`condition`* is false.
+
+## Binary Comparison {#binary-comparison}
+
+The following assertions compare two values. The value arguments must be
+comparable by the assertion's comparison operator, otherwise a compiler error
+will result.
+
+If an argument supports the `<<` operator, it will be called to print the
+argument when the assertion fails. Otherwise, GoogleTest will attempt to print
+them in the best way it can—see
+[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values).
+
+Arguments are always evaluated exactly once, so it's OK for the arguments to
+have side effects. However, the argument evaluation order is undefined and
+programs should not depend on any particular argument evaluation order.
+
+These assertions work with both narrow and wide string objects (`string` and
+`wstring`).
+
+See also the [Floating-Point Comparison](#floating-point) assertions to compare
+floating-point numbers and avoid problems caused by rounding.
+
+### EXPECT_EQ {#EXPECT_EQ}
+
+`EXPECT_EQ(`*`val1`*`,`*`val2`*`)` \
+`ASSERT_EQ(`*`val1`*`,`*`val2`*`)`
+
+Verifies that *`val1`*`==`*`val2`*.
+
+Does pointer equality on pointers. If used on two C strings, it tests if they
+are in the same memory location, not if they have the same value. Use
+[`EXPECT_STREQ`](#EXPECT_STREQ) to compare C strings (e.g. `const char*`) by
+value.
+
+When comparing a pointer to `NULL`, use `EXPECT_EQ(`*`ptr`*`, nullptr)` instead
+of `EXPECT_EQ(`*`ptr`*`, NULL)`.
+
+### EXPECT_NE {#EXPECT_NE}
+
+`EXPECT_NE(`*`val1`*`,`*`val2`*`)` \
+`ASSERT_NE(`*`val1`*`,`*`val2`*`)`
+
+Verifies that *`val1`*`!=`*`val2`*.
+
+Does pointer equality on pointers. If used on two C strings, it tests if they
+are in different memory locations, not if they have different values. Use
+[`EXPECT_STRNE`](#EXPECT_STRNE) to compare C strings (e.g. `const char*`) by
+value.
+
+When comparing a pointer to `NULL`, use `EXPECT_NE(`*`ptr`*`, nullptr)` instead
+of `EXPECT_NE(`*`ptr`*`, NULL)`.
+
+### EXPECT_LT {#EXPECT_LT}
+
+`EXPECT_LT(`*`val1`*`,`*`val2`*`)` \
+`ASSERT_LT(`*`val1`*`,`*`val2`*`)`
+
+Verifies that *`val1`*`<`*`val2`*.
+
+### EXPECT_LE {#EXPECT_LE}
+
+`EXPECT_LE(`*`val1`*`,`*`val2`*`)` \
+`ASSERT_LE(`*`val1`*`,`*`val2`*`)`
+
+Verifies that *`val1`*`<=`*`val2`*.
+
+### EXPECT_GT {#EXPECT_GT}
+
+`EXPECT_GT(`*`val1`*`,`*`val2`*`)` \
+`ASSERT_GT(`*`val1`*`,`*`val2`*`)`
+
+Verifies that *`val1`*`>`*`val2`*.
+
+### EXPECT_GE {#EXPECT_GE}
+
+`EXPECT_GE(`*`val1`*`,`*`val2`*`)` \
+`ASSERT_GE(`*`val1`*`,`*`val2`*`)`
+
+Verifies that *`val1`*`>=`*`val2`*.
+
+## String Comparison {#c-strings}
+
+The following assertions compare two **C strings**. To compare two `string`
+objects, use [`EXPECT_EQ`](#EXPECT_EQ) or [`EXPECT_NE`](#EXPECT_NE) instead.
+
+These assertions also accept wide C strings (`wchar_t*`). If a comparison of two
+wide strings fails, their values will be printed as UTF-8 narrow strings.
+
+To compare a C string with `NULL`, use `EXPECT_EQ(`*`c_string`*`, nullptr)` or
+`EXPECT_NE(`*`c_string`*`, nullptr)`.
+
+### EXPECT_STREQ {#EXPECT_STREQ}
+
+`EXPECT_STREQ(`*`str1`*`,`*`str2`*`)` \
+`ASSERT_STREQ(`*`str1`*`,`*`str2`*`)`
+
+Verifies that the two C strings *`str1`* and *`str2`* have the same contents.
+
+### EXPECT_STRNE {#EXPECT_STRNE}
+
+`EXPECT_STRNE(`*`str1`*`,`*`str2`*`)` \
+`ASSERT_STRNE(`*`str1`*`,`*`str2`*`)`
+
+Verifies that the two C strings *`str1`* and *`str2`* have different contents.
+
+### EXPECT_STRCASEEQ {#EXPECT_STRCASEEQ}
+
+`EXPECT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` \
+`ASSERT_STRCASEEQ(`*`str1`*`,`*`str2`*`)`
+
+Verifies that the two C strings *`str1`* and *`str2`* have the same contents,
+ignoring case.
+
+### EXPECT_STRCASENE {#EXPECT_STRCASENE}
+
+`EXPECT_STRCASENE(`*`str1`*`,`*`str2`*`)` \
+`ASSERT_STRCASENE(`*`str1`*`,`*`str2`*`)`
+
+Verifies that the two C strings *`str1`* and *`str2`* have different contents,
+ignoring case.
+
+## Floating-Point Comparison {#floating-point}
+
+The following assertions compare two floating-point values.
+
+Due to rounding errors, it is very unlikely that two floating-point values will
+match exactly, so `EXPECT_EQ` is not suitable. In general, for floating-point
+comparison to make sense, the user needs to carefully choose the error bound.
+
+GoogleTest also provides assertions that use a default error bound based on
+Units in the Last Place (ULPs). To learn more about ULPs, see the article
+[Comparing Floating Point Numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
+
+### EXPECT_FLOAT_EQ {#EXPECT_FLOAT_EQ}
+
+`EXPECT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` \
+`ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)`
+
+Verifies that the two `float` values *`val1`* and *`val2`* are approximately
+equal, to within 4 ULPs from each other.
+
+### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ}
+
+`EXPECT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` \
+`ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)`
+
+Verifies that the two `double` values *`val1`* and *`val2`* are approximately
+equal, to within 4 ULPs from each other.
+
+### EXPECT_NEAR {#EXPECT_NEAR}
+
+`EXPECT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` \
+`ASSERT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)`
+
+Verifies that the difference between *`val1`* and *`val2`* does not exceed the
+absolute error bound *`abs_error`*.
+
+## Exception Assertions {#exceptions}
+
+The following assertions verify that a piece of code throws, or does not throw,
+an exception. Usage requires exceptions to be enabled in the build environment.
+
+Note that the piece of code under test can be a compound statement, for example:
+
+```cpp
+EXPECT_NO_THROW({
+ int n = 5;
+ DoSomething(&n);
+});
+```
+
+### EXPECT_THROW {#EXPECT_THROW}
+
+`EXPECT_THROW(`*`statement`*`,`*`exception_type`*`)` \
+`ASSERT_THROW(`*`statement`*`,`*`exception_type`*`)`
+
+Verifies that *`statement`* throws an exception of type *`exception_type`*.
+
+### EXPECT_ANY_THROW {#EXPECT_ANY_THROW}
+
+`EXPECT_ANY_THROW(`*`statement`*`)` \
+`ASSERT_ANY_THROW(`*`statement`*`)`
+
+Verifies that *`statement`* throws an exception of any type.
+
+### EXPECT_NO_THROW {#EXPECT_NO_THROW}
+
+`EXPECT_NO_THROW(`*`statement`*`)` \
+`ASSERT_NO_THROW(`*`statement`*`)`
+
+Verifies that *`statement`* does not throw any exception.
+
+## Predicate Assertions {#predicates}
+
+The following assertions enable more complex predicates to be verified while
+printing a more clear failure message than if `EXPECT_TRUE` were used alone.
+
+### EXPECT_PRED* {#EXPECT_PRED}
+
+`EXPECT_PRED1(`*`pred`*`,`*`val1`*`)` \
+`EXPECT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \
+`EXPECT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
+`EXPECT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \
+`EXPECT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
+
+`ASSERT_PRED1(`*`pred`*`,`*`val1`*`)` \
+`ASSERT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \
+`ASSERT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
+`ASSERT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \
+`ASSERT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
+
+Verifies that the predicate *`pred`* returns `true` when passed the given values
+as arguments.
+
+The parameter *`pred`* is a function or functor that accepts as many arguments
+as the corresponding macro accepts values. If *`pred`* returns `true` for the
+given arguments, the assertion succeeds, otherwise the assertion fails.
+
+When the assertion fails, it prints the value of each argument. Arguments are
+always evaluated exactly once.
+
+As an example, see the following code:
+
+```cpp
+// Returns true if m and n have no common divisors except 1.
+bool MutuallyPrime(int m, int n) { ... }
+...
+const int a = 3;
+const int b = 4;
+const int c = 10;
+...
+EXPECT_PRED2(MutuallyPrime, a, b); // Succeeds
+EXPECT_PRED2(MutuallyPrime, b, c); // Fails
+```
+
+In the above example, the first assertion succeeds, and the second fails with
+the following message:
+
+```
+MutuallyPrime(b, c) is false, where
+b is 4
+c is 10
+```
+
+Note that if the given predicate is an overloaded function or a function
+template, the assertion macro might not be able to determine which version to
+use, and it might be necessary to explicitly specify the type of the function.
+For example, for a Boolean function `IsPositive()` overloaded to take either a
+single `int` or `double` argument, it would be necessary to write one of the
+following:
+
+```cpp
+EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
+EXPECT_PRED1(static_cast<bool (*)(double)>(IsPositive), 3.14);
+```
+
+Writing simply `EXPECT_PRED1(IsPositive, 5);` would result in a compiler error.
+Similarly, to use a template function, specify the template arguments:
+
+```cpp
+template <typename T>
+bool IsNegative(T x) {
+ return x < 0;
+}
+...
+EXPECT_PRED1(IsNegative<int>, -5); // Must specify type for IsNegative
+```
+
+If a template has multiple parameters, wrap the predicate in parentheses so the
+macro arguments are parsed correctly:
+
+```cpp
+ASSERT_PRED2((MyPredicate<int, int>), 5, 0);
+```
+
+### EXPECT_PRED_FORMAT* {#EXPECT_PRED_FORMAT}
+
+`EXPECT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \
+`EXPECT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \
+`EXPECT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
+`EXPECT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)`
+\
+`EXPECT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
+
+`ASSERT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \
+`ASSERT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \
+`ASSERT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
+`ASSERT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)`
+\
+`ASSERT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
+
+Verifies that the predicate *`pred_formatter`* succeeds when passed the given
+values as arguments.
+
+The parameter *`pred_formatter`* is a *predicate-formatter*, which is a function
+or functor with the signature:
+
+```cpp
+testing::AssertionResult PredicateFormatter(const char* expr1,
+ const char* expr2,
+ ...
+ const char* exprn,
+ T1 val1,
+ T2 val2,
+ ...
+ Tn valn);
+```
+
+where *`val1`*, *`val2`*, ..., *`valn`* are the values of the predicate
+arguments, and *`expr1`*, *`expr2`*, ..., *`exprn`* are the corresponding
+expressions as they appear in the source code. The types `T1`, `T2`, ..., `Tn`
+can be either value types or reference types; if an argument has type `T`, it
+can be declared as either `T` or `const T&`, whichever is appropriate. For more
+about the return type `testing::AssertionResult`, see
+[Using a Function That Returns an AssertionResult](../advanced.md#using-a-function-that-returns-an-assertionresult).
+
+As an example, see the following code:
+
+```cpp
+// Returns the smallest prime common divisor of m and n,
+// or 1 when m and n are mutually prime.
+int SmallestPrimeCommonDivisor(int m, int n) { ... }
+
+// Returns true if m and n have no common divisors except 1.
+bool MutuallyPrime(int m, int n) { ... }
+
+// A predicate-formatter for asserting that two integers are mutually prime.
+testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
+ const char* n_expr,
+ int m,
+ int n) {
+ if (MutuallyPrime(m, n)) return testing::AssertionSuccess();
+
+ return testing::AssertionFailure() << m_expr << " and " << n_expr
+ << " (" << m << " and " << n << ") are not mutually prime, "
+ << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n);
+}
+
+...
+const int a = 3;
+const int b = 4;
+const int c = 10;
+...
+EXPECT_PRED_FORMAT2(AssertMutuallyPrime, a, b); // Succeeds
+EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); // Fails
+```
+
+In the above example, the final assertion fails and the predicate-formatter
+produces the following failure message:
+
+```
+b and c (4 and 10) are not mutually prime, as they have a common divisor 2
+```
+
+## Windows HRESULT Assertions {#HRESULT}
+
+The following assertions test for `HRESULT` success or failure. For example:
+
+```cpp
+CComPtr<IShellDispatch2> shell;
+ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application"));
+CComVariant empty;
+ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));
+```
+
+The generated output contains the human-readable error message associated with
+the returned `HRESULT` code.
+
+### EXPECT_HRESULT_SUCCEEDED {#EXPECT_HRESULT_SUCCEEDED}
+
+`EXPECT_HRESULT_SUCCEEDED(`*`expression`*`)` \
+`ASSERT_HRESULT_SUCCEEDED(`*`expression`*`)`
+
+Verifies that *`expression`* is a success `HRESULT`.
+
+### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED}
+
+`EXPECT_HRESULT_FAILED(`*`expression`*`)` \
+`ASSERT_HRESULT_FAILED(`*`expression`*`)`
+
+Verifies that *`expression`* is a failure `HRESULT`.
+
+## Death Assertions {#death}
+
+The following assertions verify that a piece of code causes the process to
+terminate. For context, see [Death Tests](../advanced.md#death-tests).
+
+These assertions spawn a new process and execute the code under test in that
+process. How that happens depends on the platform and the variable
+`::testing::GTEST_FLAG(death_test_style)`, which is initialized from the
+command-line flag `--gtest_death_test_style`.
+
+* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the
+ child, after which:
+ * If the variable's value is `"fast"`, the death test statement is
+ immediately executed.
+ * If the variable's value is `"threadsafe"`, the child process re-executes
+ the unit test binary just as it was originally invoked, but with some
+ extra flags to cause just the single death test under consideration to
+ be run.
+* On Windows, the child is spawned using the `CreateProcess()` API, and
+ re-executes the binary to cause just the single death test under
+ consideration to be run - much like the `"threadsafe"` mode on POSIX.
+
+Other values for the variable are illegal and will cause the death test to fail.
+Currently, the flag's default value is
+**`"fast"`**.
+
+If the death test statement runs to completion without dying, the child process
+will nonetheless terminate, and the assertion fails.
+
+Note that the piece of code under test can be a compound statement, for example:
+
+```cpp
+EXPECT_DEATH({
+ int n = 5;
+ DoSomething(&n);
+}, "Error on line .* of DoSomething()");
+```
+
+### EXPECT_DEATH {#EXPECT_DEATH}
+
+`EXPECT_DEATH(`*`statement`*`,`*`matcher`*`)` \
+`ASSERT_DEATH(`*`statement`*`,`*`matcher`*`)`
+
+Verifies that *`statement`* causes the process to terminate with a nonzero exit
+status and produces `stderr` output that matches *`matcher`*.
+
+The parameter *`matcher`* is either a [matcher](matchers.md) for a `const
+std::string&`, or a regular expression (see
+[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare
+string *`s`* (with no matcher) is treated as
+[`ContainsRegex(s)`](matchers.md#string-matchers), **not**
+[`Eq(s)`](matchers.md#generic-comparison).
+
+For example, the following code verifies that calling `DoSomething(42)` causes
+the process to die with an error message that contains the text `My error`:
+
+```cpp
+EXPECT_DEATH(DoSomething(42), "My error");
+```
+
+### EXPECT_DEATH_IF_SUPPORTED {#EXPECT_DEATH_IF_SUPPORTED}
+
+`EXPECT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` \
+`ASSERT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)`
+
+If death tests are supported, behaves the same as
+[`EXPECT_DEATH`](#EXPECT_DEATH). Otherwise, verifies nothing.
+
+### EXPECT_DEBUG_DEATH {#EXPECT_DEBUG_DEATH}
+
+`EXPECT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` \
+`ASSERT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)`
+
+In debug mode, behaves the same as [`EXPECT_DEATH`](#EXPECT_DEATH). When not in
+debug mode (i.e. `NDEBUG` is defined), just executes *`statement`*.
+
+### EXPECT_EXIT {#EXPECT_EXIT}
+
+`EXPECT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` \
+`ASSERT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)`
+
+Verifies that *`statement`* causes the process to terminate with an exit status
+that satisfies *`predicate`*, and produces `stderr` output that matches
+*`matcher`*.
+
+The parameter *`predicate`* is a function or functor that accepts an `int` exit
+status and returns a `bool`. GoogleTest provides two predicates to handle common
+cases:
+
+```cpp
+// Returns true if the program exited normally with the given exit status code.
+::testing::ExitedWithCode(exit_code);
+
+// Returns true if the program was killed by the given signal.
+// Not available on Windows.
+::testing::KilledBySignal(signal_number);
+```
+
+The parameter *`matcher`* is either a [matcher](matchers.md) for a `const
+std::string&`, or a regular expression (see
+[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare
+string *`s`* (with no matcher) is treated as
+[`ContainsRegex(s)`](matchers.md#string-matchers), **not**
+[`Eq(s)`](matchers.md#generic-comparison).
+
+For example, the following code verifies that calling `NormalExit()` causes the
+process to print a message containing the text `Success` to `stderr` and exit
+with exit status code 0:
+
+```cpp
+EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success");
+```
diff --git a/docs/reference/matchers.md b/docs/reference/matchers.md
new file mode 100644
index 000000000000..243e3f95164d
--- /dev/null
+++ b/docs/reference/matchers.md
@@ -0,0 +1,302 @@
+# Matchers Reference
+
+A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or
+`EXPECT_CALL()`, or use it to validate a value directly using two macros:
+
+| Macro | Description |
+| :----------------------------------- | :------------------------------------ |
+| `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 .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)`.
+
+Built-in matchers (where `argument` is the function argument, e.g.
+`actual_value` in the example above, or when used in the context of
+`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are
+divided into several categories. All matchers are defined in the `::testing`
+namespace unless otherwise noted.
+
+## Wildcard
+
+Matcher | Description
+:-------------------------- | :-----------------------------------------------
+`_` | `argument` can be any value of the correct type.
+`A<type>()` or `An<type>()` | `argument` can be any value of type `type`.
+
+## Generic Comparison
+
+| Matcher | Description |
+| :--------------------- | :-------------------------------------------------- |
+| `Eq(value)` or `value` | `argument == value` |
+| `Ge(value)` | `argument >= value` |
+| `Gt(value)` | `argument > value` |
+| `Le(value)` | `argument <= value` |
+| `Lt(value)` | `argument < value` |
+| `Ne(value)` | `argument != value` |
+| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. |
+| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. |
+| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). |
+| `NotNull()` | `argument` is a non-null pointer (raw or smart). |
+| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)|
+| `VariantWith<T>(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. |
+| `Ref(variable)` | `argument` is a reference to `variable`. |
+| `TypedEq<type>(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. |
+
+Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or
+destructed later. If the compiler complains that `value` doesn't have a public
+copy constructor, try wrap it in `std::ref()`, e.g.
+`Eq(std::ref(non_copyable_value))`. If you do that, make sure
+`non_copyable_value` is not changed afterwards, or the meaning of your matcher
+will be changed.
+
+`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types
+that can be explicitly converted to Boolean, but are not implicitly converted to
+Boolean. In other cases, you can use the basic
+[`EXPECT_TRUE` and `EXPECT_FALSE`](assertions.md#boolean) assertions.
+
+## Floating-Point Matchers {#FpMatchers}
+
+| Matcher | Description |
+| :------------------------------- | :--------------------------------- |
+| `DoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. |
+| `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. |
+| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. |
+| `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. |
+| `IsNan()` | `argument` is any floating-point type with a NaN value. |
+
+The above matchers use ULP-based comparison (the same as used in googletest).
+They automatically pick a reasonable error bound based on the absolute value of
+the expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard,
+which requires comparing two NaNs for equality to return false. The
+`NanSensitive*` version instead treats two NaNs as equal, which is often what a
+user wants.
+
+| Matcher | Description |
+| :------------------------------------------------ | :----------------------- |
+| `DoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |
+| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |
+| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. |
+| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. |
+
+## String Matchers
+
+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`. |
+| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. The web-safe format from [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648#section-5) is supported. |
+
+`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
+use the regular expression syntax defined
+[here](../advanced.md#regular-expression-syntax). All of these matchers, except
+`ContainsRegex()` and `MatchesRegex()` work for wide strings as well.
+
+## Container Matchers
+
+Most STL-style containers support `==`, so you can use `Eq(expected_container)`
+or simply `expected_container` to match a container exactly. If you want to
+write the elements in-line, match them more flexibly, or get more informative
+messages, you can use:
+
+| Matcher | Description |
+| :---------------------------------------- | :------------------------------- |
+| `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. |
+| `IsEmpty()` | `argument` is an empty container (`container.empty()`). |
+| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. |
+| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. |
+| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. |
+| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. |
+| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. |
+| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
+| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. |
+| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. |
+| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. |
+
+**Notes:**
+
+* These matchers can also match:
+ 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`),
+ and
+ 2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer,
+ int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)).
+* The array being matched may be multi-dimensional (i.e. its elements can be
+ arrays).
+* `m` in `Pointwise(m, ...)` and `UnorderedPointwise(m, ...)` should be a
+ matcher for `::std::tuple<T, U>` where `T` and `U` are the element type of
+ the actual container and the expected container, respectively. For example,
+ to compare two `Foo` containers where `Foo` doesn't support `operator==`,
+ one might write:
+
+ ```cpp
+ MATCHER(FooEq, "") {
+ return std::get<0>(arg).Equals(std::get<1>(arg));
+ }
+ ...
+ EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));
+ ```
+
+## Member Matchers
+
+| Matcher | Description |
+| :------------------------------ | :----------------------------------------- |
+| `Field(&class::field, m)` | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. |
+| `Field(field_name, &class::field, m)` | The same as the two-parameter version, but provides a better error message. |
+| `Key(e)` | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. |
+| `Pair(m1, m2)` | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. |
+| `FieldsAre(m...)` | `argument` is a compatible object where each field matches piecewise with the matchers `m...`. A compatible object is any that supports the `std::tuple_size<Obj>`+`get<I>(obj)` protocol. In C++17 and up this also supports types compatible with structured bindings, like aggregates. |
+| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. |
+| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message.
+
+**Notes:**
+
+* You can use `FieldsAre()` to match any type that supports structured
+ bindings, such as `std::tuple`, `std::pair`, `std::array`, and aggregate
+ types. For example:
+
+ ```cpp
+ std::tuple<int, std::string> my_tuple{7, "hello world"};
+ EXPECT_THAT(my_tuple, FieldsAre(Ge(0), HasSubstr("hello")));
+
+ struct MyStruct {
+ int value = 42;
+ std::string greeting = "aloha";
+ };
+ MyStruct s;
+ EXPECT_THAT(s, FieldsAre(42, "aloha"));
+ ```
+
+* Don't use `Property()` against member functions that you do not own, because
+ taking addresses of functions is fragile and generally not part of the
+ contract of the function.
+
+## Matching the Result of a Function, Functor, or Callback
+
+| 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
+
+| Matcher | Description |
+| :------------------------ | :---------------------------------------------- |
+| `Address(m)` | the result of `std::addressof(argument)` matches `m`. |
+| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. |
+| `Pointer(m)` | `argument` (either a smart pointer or a raw pointer) contains a pointer that matches `m`. `m` will match against the raw pointer regardless of the type of `argument`. |
+| `WhenDynamicCastTo<T>(m)` | when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`. |
+
+## Multi-argument Matchers {#MultiArgMatchers}
+
+Technically, all matchers match a *single* value. A "multi-argument" matcher is
+just one that matches a *tuple*. The following matchers can be used to match a
+tuple `(x, y)`:
+
+Matcher | Description
+:------ | :----------
+`Eq()` | `x == y`
+`Ge()` | `x >= y`
+`Gt()` | `x > y`
+`Le()` | `x <= y`
+`Lt()` | `x < y`
+`Ne()` | `x != y`
+
+You can use the following selectors to pick a subset of the arguments (or
+reorder them) to participate in the matching:
+
+| Matcher | Description |
+| :------------------------- | :---------------------------------------------- |
+| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. |
+| `Args<N1, N2, ..., Nk>(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. |
+
+## Composite Matchers
+
+You can make a matcher from one or more other matchers:
+
+| Matcher | Description |
+| :------------------------------- | :-------------------------------------- |
+| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. |
+| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
+| `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
+
+| Matcher | Description |
+| :---------------------- | :------------------------------------ |
+| `MatcherCast<T>(m)` | casts matcher `m` to type `Matcher<T>`. |
+| `SafeMatcherCast<T>(m)` | [safely casts](../gmock_cook_book.md#SafeMatcherCast) matcher `m` to type `Matcher<T>`. |
+| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. |
+
+`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`,
+which must be a permanent callback.
+
+## Using Matchers as Predicates {#MatchersAsPredicatesCheat}
+
+| Matcher | Description |
+| :---------------------------- | :------------------------------------------ |
+| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. |
+| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. |
+| `Value(value, m)` | evaluates to `true` if `value` matches `m`. |
+
+## Defining Matchers
+
+| 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`. |
+| `MATCHER_P2(IsBetween, a, b, absl::StrCat(negation ? "isn't" : "is", " between ", PrintToString(a), " and ", PrintToString(b))) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |
+
+**Notes:**
+
+1. The `MATCHER*` macros cannot be used inside a function or class.
+2. The matcher body must be *purely functional* (i.e. it cannot have any side
+ effect, and the result must not depend on anything other than the value
+ being matched and the matcher parameters).
+3. You can use `PrintToString(x)` to convert a value `x` of any type to a
+ string.
+4. You can use `ExplainMatchResult()` in a custom matcher to wrap another
+ matcher, for example:
+
+ ```cpp
+ MATCHER_P(NestedPropertyMatches, matcher, "") {
+ return ExplainMatchResult(matcher, arg.nested().property(), result_listener);
+ }
+ ```
+
+5. You can use `DescribeMatcher<>` to describe another matcher. For example:
+
+ ```cpp
+ MATCHER_P(XAndYThat, matcher,
+ "X that " + DescribeMatcher<int>(matcher, negation) +
+ (negation ? " or" : " and") + " Y that " +
+ DescribeMatcher<double>(matcher, negation)) {
+ return ExplainMatchResult(matcher, arg.x(), result_listener) &&
+ ExplainMatchResult(matcher, arg.y(), result_listener);
+ }
+ ```
diff --git a/docs/reference/mocking.md b/docs/reference/mocking.md
new file mode 100644
index 000000000000..e414ffbd0dea
--- /dev/null
+++ b/docs/reference/mocking.md
@@ -0,0 +1,589 @@
+# Mocking Reference
+
+This page lists the facilities provided by GoogleTest for creating and working
+with mock objects. To use them, include the header
+`gmock/gmock.h`.
+
+## Macros {#macros}
+
+GoogleTest defines the following macros for working with mocks.
+
+### MOCK_METHOD {#MOCK_METHOD}
+
+`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`));` \
+`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`),
+(`*`specs...`*`));`
+
+Defines a mock method *`method_name`* with arguments `(`*`args...`*`)` and
+return type *`return_type`* within a mock class.
+
+The parameters of `MOCK_METHOD` mirror the method declaration. The optional
+fourth parameter *`specs...`* is a comma-separated list of qualifiers. The
+following qualifiers are accepted:
+
+| Qualifier | Meaning |
+| -------------------------- | -------------------------------------------- |
+| `const` | Makes the mocked method a `const` method. Required if overriding a `const` method. |
+| `override` | Marks the method with `override`. Recommended if overriding a `virtual` method. |
+| `noexcept` | Marks the method with `noexcept`. Required if overriding a `noexcept` method. |
+| `Calltype(`*`calltype`*`)` | Sets the call type for the method, for example `Calltype(STDMETHODCALLTYPE)`. Useful on Windows. |
+| `ref(`*`qualifier`*`)` | Marks the method with the given reference qualifier, for example `ref(&)` or `ref(&&)`. Required if overriding a method that has a reference qualifier. |
+
+Note that commas in arguments prevent `MOCK_METHOD` from parsing the arguments
+correctly if they are not appropriately surrounded by parentheses. See the
+following example:
+
+```cpp
+class MyMock {
+ public:
+ // The following 2 lines will not compile due to commas in the arguments:
+ MOCK_METHOD(std::pair<bool, int>, GetPair, ()); // Error!
+ MOCK_METHOD(bool, CheckMap, (std::map<int, double>, bool)); // Error!
+
+ // One solution - wrap arguments that contain commas in parentheses:
+ MOCK_METHOD((std::pair<bool, int>), GetPair, ());
+ MOCK_METHOD(bool, CheckMap, ((std::map<int, double>), bool));
+
+ // Another solution - use type aliases:
+ using BoolAndInt = std::pair<bool, int>;
+ MOCK_METHOD(BoolAndInt, GetPair, ());
+ using MapIntDouble = std::map<int, double>;
+ MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool));
+};
+```
+
+`MOCK_METHOD` must be used in the `public:` section of a mock class definition,
+regardless of whether the method being mocked is `public`, `protected`, or
+`private` in the base class.
+
+### EXPECT_CALL {#EXPECT_CALL}
+
+`EXPECT_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`
+
+Creates an [expectation](../gmock_for_dummies.md#setting-expectations) that the
+method *`method_name`* of the object *`mock_object`* is called with arguments
+that match the given matchers *`matchers...`*. `EXPECT_CALL` must precede any
+code that exercises the mock object.
+
+The parameter *`matchers...`* is a comma-separated list of
+[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that
+correspond to each argument of the method *`method_name`*. The expectation will
+apply only to calls of *`method_name`* whose arguments match all of the
+matchers. If `(`*`matchers...`*`)` is omitted, the expectation behaves as if
+each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).
+See the [Matchers Reference](matchers.md) for a list of all built-in matchers.
+
+The following chainable clauses can be used to modify the expectation, and they
+must be used in the following order:
+
+```cpp
+EXPECT_CALL(mock_object, method_name(matchers...))
+ .With(multi_argument_matcher) // Can be used at most once
+ .Times(cardinality) // Can be used at most once
+ .InSequence(sequences...) // Can be used any number of times
+ .After(expectations...) // Can be used any number of times
+ .WillOnce(action) // Can be used any number of times
+ .WillRepeatedly(action) // Can be used at most once
+ .RetiresOnSaturation(); // Can be used at most once
+```
+
+See details for each modifier clause below.
+
+#### With {#EXPECT_CALL.With}
+
+`.With(`*`multi_argument_matcher`*`)`
+
+Restricts the expectation to apply only to mock function calls whose arguments
+as a whole match the multi-argument matcher *`multi_argument_matcher`*.
+
+GoogleTest passes all of the arguments as one tuple into the matcher. The
+parameter *`multi_argument_matcher`* must thus be a matcher of type
+`Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the
+function arguments.
+
+For example, the following code sets the expectation that
+`my_mock.SetPosition()` is called with any two arguments, the first argument
+being less than the second:
+
+```cpp
+using ::testing::_;
+using ::testing::Lt;
+...
+EXPECT_CALL(my_mock, SetPosition(_, _))
+ .With(Lt());
+```
+
+GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`
+matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).
+
+The `With` clause can be used at most once on an expectation and must be the
+first clause.
+
+#### Times {#EXPECT_CALL.Times}
+
+`.Times(`*`cardinality`*`)`
+
+Specifies how many times the mock function call is expected.
+
+The parameter *`cardinality`* represents the number of expected calls and can be
+one of the following, all defined in the `::testing` namespace:
+
+| Cardinality | Meaning |
+| ------------------- | --------------------------------------------------- |
+| `AnyNumber()` | The function can be called any number of times. |
+| `AtLeast(n)` | The function call is expected at least *n* times. |
+| `AtMost(n)` | The function call is expected at most *n* times. |
+| `Between(m, n)` | The function call is expected between *m* and *n* times, inclusive. |
+| `Exactly(n)` or `n` | The function call is expected exactly *n* times. If *n* is 0, the call should never happen. |
+
+If the `Times` clause is omitted, GoogleTest infers the cardinality as follows:
+
+* If neither [`WillOnce`](#EXPECT_CALL.WillOnce) nor
+ [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) are specified, the inferred
+ cardinality is `Times(1)`.
+* If there are *n* `WillOnce` clauses and no `WillRepeatedly` clause, where
+ *n* >= 1, the inferred cardinality is `Times(n)`.
+* If there are *n* `WillOnce` clauses and one `WillRepeatedly` clause, where
+ *n* >= 0, the inferred cardinality is `Times(AtLeast(n))`.
+
+The `Times` clause can be used at most once on an expectation.
+
+#### InSequence {#EXPECT_CALL.InSequence}
+
+`.InSequence(`*`sequences...`*`)`
+
+Specifies that the mock function call is expected in a certain sequence.
+
+The parameter *`sequences...`* is any number of [`Sequence`](#Sequence) objects.
+Expected calls assigned to the same sequence are expected to occur in the order
+the expectations are declared.
+
+For example, the following code sets the expectation that the `Reset()` method
+of `my_mock` is called before both `GetSize()` and `Describe()`, and `GetSize()`
+and `Describe()` can occur in any order relative to each other:
+
+```cpp
+using ::testing::Sequence;
+Sequence s1, s2;
+...
+EXPECT_CALL(my_mock, Reset())
+ .InSequence(s1, s2);
+EXPECT_CALL(my_mock, GetSize())
+ .InSequence(s1);
+EXPECT_CALL(my_mock, Describe())
+ .InSequence(s2);
+```
+
+The `InSequence` clause can be used any number of times on an expectation.
+
+See also the [`InSequence` class](#InSequence).
+
+#### After {#EXPECT_CALL.After}
+
+`.After(`*`expectations...`*`)`
+
+Specifies that the mock function call is expected to occur after one or more
+other calls.
+
+The parameter *`expectations...`* can be up to five
+[`Expectation`](#Expectation) or [`ExpectationSet`](#ExpectationSet) objects.
+The mock function call is expected to occur after all of the given expectations.
+
+For example, the following code sets the expectation that the `Describe()`
+method of `my_mock` is called only after both `InitX()` and `InitY()` have been
+called.
+
+```cpp
+using ::testing::Expectation;
+...
+Expectation init_x = EXPECT_CALL(my_mock, InitX());
+Expectation init_y = EXPECT_CALL(my_mock, InitY());
+EXPECT_CALL(my_mock, Describe())
+ .After(init_x, init_y);
+```
+
+The `ExpectationSet` object is helpful when the number of prerequisites for an
+expectation is large or variable, for example:
+
+```cpp
+using ::testing::ExpectationSet;
+...
+ExpectationSet all_inits;
+// Collect all expectations of InitElement() calls
+for (int i = 0; i < element_count; i++) {
+ all_inits += EXPECT_CALL(my_mock, InitElement(i));
+}
+EXPECT_CALL(my_mock, Describe())
+ .After(all_inits); // Expect Describe() call after all InitElement() calls
+```
+
+The `After` clause can be used any number of times on an expectation.
+
+#### WillOnce {#EXPECT_CALL.WillOnce}
+
+`.WillOnce(`*`action`*`)`
+
+Specifies the mock function's actual behavior when invoked, for a single
+matching function call.
+
+The parameter *`action`* represents the
+[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
+call will perform. See the [Actions Reference](actions.md) for a list of
+built-in actions.
+
+The use of `WillOnce` implicitly sets a cardinality on the expectation when
+`Times` is not specified. See [`Times`](#EXPECT_CALL.Times).
+
+Each matching function call will perform the next action in the order declared.
+For example, the following code specifies that `my_mock.GetNumber()` is expected
+to be called exactly 3 times and will return `1`, `2`, and `3` respectively on
+the first, second, and third calls:
+
+```cpp
+using ::testing::Return;
+...
+EXPECT_CALL(my_mock, GetNumber())
+ .WillOnce(Return(1))
+ .WillOnce(Return(2))
+ .WillOnce(Return(3));
+```
+
+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}
+
+`.WillRepeatedly(`*`action`*`)`
+
+Specifies the mock function's actual behavior when invoked, for all subsequent
+matching function calls. Takes effect after the actions specified in the
+[`WillOnce`](#EXPECT_CALL.WillOnce) clauses, if any, have been performed.
+
+The parameter *`action`* represents the
+[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
+call will perform. See the [Actions Reference](actions.md) for a list of
+built-in actions.
+
+The use of `WillRepeatedly` implicitly sets a cardinality on the expectation
+when `Times` is not specified. See [`Times`](#EXPECT_CALL.Times).
+
+If any `WillOnce` clauses have been specified, matching function calls will
+perform those actions before the action specified by `WillRepeatedly`. See the
+following example:
+
+```cpp
+using ::testing::Return;
+...
+EXPECT_CALL(my_mock, GetName())
+ .WillRepeatedly(Return("John Doe")); // Return "John Doe" on all calls
+
+EXPECT_CALL(my_mock, GetNumber())
+ .WillOnce(Return(42)) // Return 42 on the first call
+ .WillRepeatedly(Return(7)); // Return 7 on all subsequent calls
+```
+
+The `WillRepeatedly` clause can be used at most once on an expectation.
+
+#### RetiresOnSaturation {#EXPECT_CALL.RetiresOnSaturation}
+
+`.RetiresOnSaturation()`
+
+Indicates that the expectation will no longer be active after the expected
+number of matching function calls has been reached.
+
+The `RetiresOnSaturation` clause is only meaningful for expectations with an
+upper-bounded cardinality. The expectation will *retire* (no longer match any
+function calls) after it has been *saturated* (the upper bound has been
+reached). See the following example:
+
+```cpp
+using ::testing::_;
+using ::testing::AnyNumber;
+...
+EXPECT_CALL(my_mock, SetNumber(_)) // Expectation 1
+ .Times(AnyNumber());
+EXPECT_CALL(my_mock, SetNumber(7)) // Expectation 2
+ .Times(2)
+ .RetiresOnSaturation();
+```
+
+In the above example, the first two calls to `my_mock.SetNumber(7)` match
+expectation 2, which then becomes inactive and no longer matches any calls. A
+third call to `my_mock.SetNumber(7)` would then match expectation 1. Without
+`RetiresOnSaturation()` on expectation 2, a third call to `my_mock.SetNumber(7)`
+would match expectation 2 again, producing a failure since the limit of 2 calls
+was exceeded.
+
+The `RetiresOnSaturation` clause can be used at most once on an expectation and
+must be the last clause.
+
+### ON_CALL {#ON_CALL}
+
+`ON_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`
+
+Defines what happens when the method *`method_name`* of the object
+*`mock_object`* is called with arguments that match the given matchers
+*`matchers...`*. Requires a modifier clause to specify the method's behavior.
+*Does not* set any expectations that the method will be called.
+
+The parameter *`matchers...`* is a comma-separated list of
+[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that
+correspond to each argument of the method *`method_name`*. The `ON_CALL`
+specification will apply only to calls of *`method_name`* whose arguments match
+all of the matchers. If `(`*`matchers...`*`)` is omitted, the behavior is as if
+each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).
+See the [Matchers Reference](matchers.md) for a list of all built-in matchers.
+
+The following chainable clauses can be used to set the method's behavior, and
+they must be used in the following order:
+
+```cpp
+ON_CALL(mock_object, method_name(matchers...))
+ .With(multi_argument_matcher) // Can be used at most once
+ .WillByDefault(action); // Required
+```
+
+See details for each modifier clause below.
+
+#### With {#ON_CALL.With}
+
+`.With(`*`multi_argument_matcher`*`)`
+
+Restricts the specification to only mock function calls whose arguments as a
+whole match the multi-argument matcher *`multi_argument_matcher`*.
+
+GoogleTest passes all of the arguments as one tuple into the matcher. The
+parameter *`multi_argument_matcher`* must thus be a matcher of type
+`Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the
+function arguments.
+
+For example, the following code sets the default behavior when
+`my_mock.SetPosition()` is called with any two arguments, the first argument
+being less than the second:
+
+```cpp
+using ::testing::_;
+using ::testing::Lt;
+using ::testing::Return;
+...
+ON_CALL(my_mock, SetPosition(_, _))
+ .With(Lt())
+ .WillByDefault(Return(true));
+```
+
+GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`
+matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).
+
+The `With` clause can be used at most once with each `ON_CALL` statement.
+
+#### WillByDefault {#ON_CALL.WillByDefault}
+
+`.WillByDefault(`*`action`*`)`
+
+Specifies the default behavior of a matching mock function call.
+
+The parameter *`action`* represents the
+[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
+call will perform. See the [Actions Reference](actions.md) for a list of
+built-in actions.
+
+For example, the following code specifies that by default, a call to
+`my_mock.Greet()` will return `"hello"`:
+
+```cpp
+using ::testing::Return;
+...
+ON_CALL(my_mock, Greet())
+ .WillByDefault(Return("hello"));
+```
+
+The action specified by `WillByDefault` is superseded by the actions specified
+on a matching `EXPECT_CALL` statement, if any. See the
+[`WillOnce`](#EXPECT_CALL.WillOnce) and
+[`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) clauses of `EXPECT_CALL`.
+
+The `WillByDefault` clause must be used exactly once with each `ON_CALL`
+statement.
+
+## Classes {#classes}
+
+GoogleTest defines the following classes for working with mocks.
+
+### DefaultValue {#DefaultValue}
+
+`::testing::DefaultValue<T>`
+
+Allows a user to specify the default value for a type `T` that is both copyable
+and publicly destructible (i.e. anything that can be used as a function return
+type). For mock functions with a return type of `T`, this default value is
+returned from function calls that do not specify an action.
+
+Provides the static methods `Set()`, `SetFactory()`, and `Clear()` to manage the
+default value:
+
+```cpp
+// Sets the default value to be returned. T must be copy constructible.
+DefaultValue<T>::Set(value);
+
+// Sets a factory. Will be invoked on demand. T must be move constructible.
+T MakeT();
+DefaultValue<T>::SetFactory(&MakeT);
+
+// Unsets the default value.
+DefaultValue<T>::Clear();
+```
+
+### NiceMock {#NiceMock}
+
+`::testing::NiceMock<T>`
+
+Represents a mock object that suppresses warnings on
+[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
+template parameter `T` is any mock class, except for another `NiceMock`,
+`NaggyMock`, or `StrictMock`.
+
+Usage of `NiceMock<T>` is analogous to usage of `T`. `NiceMock<T>` is a subclass
+of `T`, so it can be used wherever an object of type `T` is accepted. In
+addition, `NiceMock<T>` can be constructed with any arguments that a constructor
+of `T` accepts.
+
+For example, the following code suppresses warnings on the mock `my_mock` of
+type `MockClass` if a method other than `DoSomething()` is called:
+
+```cpp
+using ::testing::NiceMock;
+...
+NiceMock<MockClass> my_mock("some", "args");
+EXPECT_CALL(my_mock, DoSomething());
+... code that uses my_mock ...
+```
+
+`NiceMock<T>` only works for mock methods defined using the `MOCK_METHOD` macro
+directly in the definition of class `T`. If a mock method is defined in a base
+class of `T`, a warning might still be generated.
+
+`NiceMock<T>` might not work correctly if the destructor of `T` is not virtual.
+
+### NaggyMock {#NaggyMock}
+
+`::testing::NaggyMock<T>`
+
+Represents a mock object that generates warnings on
+[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
+template parameter `T` is any mock class, except for another `NiceMock`,
+`NaggyMock`, or `StrictMock`.
+
+Usage of `NaggyMock<T>` is analogous to usage of `T`. `NaggyMock<T>` is a
+subclass of `T`, so it can be used wherever an object of type `T` is accepted.
+In addition, `NaggyMock<T>` can be constructed with any arguments that a
+constructor of `T` accepts.
+
+For example, the following code generates warnings on the mock `my_mock` of type
+`MockClass` if a method other than `DoSomething()` is called:
+
+```cpp
+using ::testing::NaggyMock;
+...
+NaggyMock<MockClass> my_mock("some", "args");
+EXPECT_CALL(my_mock, DoSomething());
+... code that uses my_mock ...
+```
+
+Mock objects of type `T` by default behave the same way as `NaggyMock<T>`.
+
+### StrictMock {#StrictMock}
+
+`::testing::StrictMock<T>`
+
+Represents a mock object that generates test failures on
+[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
+template parameter `T` is any mock class, except for another `NiceMock`,
+`NaggyMock`, or `StrictMock`.
+
+Usage of `StrictMock<T>` is analogous to usage of `T`. `StrictMock<T>` is a
+subclass of `T`, so it can be used wherever an object of type `T` is accepted.
+In addition, `StrictMock<T>` can be constructed with any arguments that a
+constructor of `T` accepts.
+
+For example, the following code generates a test failure on the mock `my_mock`
+of type `MockClass` if a method other than `DoSomething()` is called:
+
+```cpp
+using ::testing::StrictMock;
+...
+StrictMock<MockClass> my_mock("some", "args");
+EXPECT_CALL(my_mock, DoSomething());
+... code that uses my_mock ...
+```
+
+`StrictMock<T>` only works for mock methods defined using the `MOCK_METHOD`
+macro directly in the definition of class `T`. If a mock method is defined in a
+base class of `T`, a failure might not be generated.
+
+`StrictMock<T>` might not work correctly if the destructor of `T` is not
+virtual.
+
+### Sequence {#Sequence}
+
+`::testing::Sequence`
+
+Represents a chronological sequence of expectations. See the
+[`InSequence`](#EXPECT_CALL.InSequence) clause of `EXPECT_CALL` for usage.
+
+### InSequence {#InSequence}
+
+`::testing::InSequence`
+
+An object of this type causes all expectations encountered in its scope to be
+put in an anonymous sequence.
+
+This allows more convenient expression of multiple expectations in a single
+sequence:
+
+```cpp
+using ::testing::InSequence;
+{
+ InSequence seq;
+
+ // The following are expected to occur in the order declared.
+ EXPECT_CALL(...);
+ EXPECT_CALL(...);
+ ...
+ EXPECT_CALL(...);
+}
+```
+
+The name of the `InSequence` object does not matter.
+
+### Expectation {#Expectation}
+
+`::testing::Expectation`
+
+Represents a mock function call expectation as created by
+[`EXPECT_CALL`](#EXPECT_CALL):
+
+```cpp
+using ::testing::Expectation;
+Expectation my_expectation = EXPECT_CALL(...);
+```
+
+Useful for specifying sequences of expectations; see the
+[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.
+
+### ExpectationSet {#ExpectationSet}
+
+`::testing::ExpectationSet`
+
+Represents a set of mock function call expectations.
+
+Use the `+=` operator to add [`Expectation`](#Expectation) objects to the set:
+
+```cpp
+using ::testing::ExpectationSet;
+ExpectationSet my_expectations;
+my_expectations += EXPECT_CALL(...);
+```
+
+Useful for specifying sequences of expectations; see the
+[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.
diff --git a/docs/reference/testing.md b/docs/reference/testing.md
new file mode 100644
index 000000000000..17225a682f51
--- /dev/null
+++ b/docs/reference/testing.md
@@ -0,0 +1,1432 @@
+# Testing Reference
+
+<!--* toc_depth: 3 *-->
+
+This page lists the facilities provided by GoogleTest for writing test programs.
+To use them, include the header `gtest/gtest.h`.
+
+## Macros
+
+GoogleTest defines the following macros for writing tests.
+
+### TEST {#TEST}
+
+<pre>
+TEST(<em>TestSuiteName</em>, <em>TestName</em>) {
+ ... <em>statements</em> ...
+}
+</pre>
+
+Defines an individual test named *`TestName`* in the test suite
+*`TestSuiteName`*, consisting of the given statements.
+
+Both arguments *`TestSuiteName`* and *`TestName`* must be valid C++ identifiers
+and must not contain underscores (`_`). Tests in different test suites can have
+the same individual name.
+
+The statements within the test body can be any code under test.
+[Assertions](assertions.md) used within the test body determine the outcome of
+the test.
+
+### TEST_F {#TEST_F}
+
+<pre>
+TEST_F(<em>TestFixtureName</em>, <em>TestName</em>) {
+ ... <em>statements</em> ...
+}
+</pre>
+
+Defines an individual test named *`TestName`* that uses the test fixture class
+*`TestFixtureName`*. The test suite name is *`TestFixtureName`*.
+
+Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++
+identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be
+the name of a test fixture class—see
+[Test Fixtures](../primer.md#same-data-multiple-tests).
+
+The statements within the test body can be any code under test.
+[Assertions](assertions.md) used within the test body determine the outcome of
+the test.
+
+### TEST_P {#TEST_P}
+
+<pre>
+TEST_P(<em>TestFixtureName</em>, <em>TestName</em>) {
+ ... <em>statements</em> ...
+}
+</pre>
+
+Defines an individual value-parameterized test named *`TestName`* that uses the
+test fixture class *`TestFixtureName`*. The test suite name is
+*`TestFixtureName`*.
+
+Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++
+identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be
+the name of a value-parameterized test fixture class—see
+[Value-Parameterized Tests](../advanced.md#value-parameterized-tests).
+
+The statements within the test body can be any code under test. Within the test
+body, the test parameter can be accessed with the `GetParam()` function (see
+[`WithParamInterface`](#WithParamInterface)). For example:
+
+```cpp
+TEST_P(MyTestSuite, DoesSomething) {
+ ...
+ EXPECT_TRUE(DoSomething(GetParam()));
+ ...
+}
+```
+
+[Assertions](assertions.md) used within the test body determine the outcome of
+the test.
+
+See also [`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P).
+
+### INSTANTIATE_TEST_SUITE_P {#INSTANTIATE_TEST_SUITE_P}
+
+`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`)`
+\
+`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`,`*`name_generator`*`)`
+
+Instantiates the value-parameterized test suite *`TestSuiteName`* (defined with
+[`TEST_P`](#TEST_P)).
+
+The argument *`InstantiationName`* is a unique name for the instantiation of the
+test suite, to distinguish between multiple instantiations. In test output, the
+instantiation name is added as a prefix to the test suite name
+*`TestSuiteName`*.
+
+The argument *`param_generator`* is one of the following GoogleTest-provided
+functions that generate the test parameters, all defined in the `::testing`
+namespace:
+
+<span id="param-generators"></span>
+
+| Parameter Generator | Behavior |
+| ------------------- | ---------------------------------------------------- |
+| `Range(begin, end [, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. |
+| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. |
+| `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. |
+| `Bool()` | Yields sequence `{false, true}`. |
+| `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. |
+| `ConvertGenerator<T>(g)` | Yields values generated by generator `g`, `static_cast` to `T`. |
+
+The optional last argument *`name_generator`* is a function or functor that
+generates custom test name suffixes based on the test parameters. The function
+must accept an argument of type
+[`TestParamInfo<class ParamType>`](#TestParamInfo) and return a `std::string`.
+The test name suffix can only contain alphanumeric characters and underscores.
+GoogleTest provides [`PrintToStringParamName`](#PrintToStringParamName), or a
+custom function can be used for more control:
+
+```cpp
+INSTANTIATE_TEST_SUITE_P(
+ MyInstantiation, MyTestSuite,
+ testing::Values(...),
+ [](const testing::TestParamInfo<MyTestSuite::ParamType>& info) {
+ // Can use info.param here to generate the test suffix
+ std::string name = ...
+ return name;
+ });
+```
+
+For more information, see
+[Value-Parameterized Tests](../advanced.md#value-parameterized-tests).
+
+See also
+[`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST`](#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST).
+
+### TYPED_TEST_SUITE {#TYPED_TEST_SUITE}
+
+`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)`
+
+Defines a typed test suite based on the test fixture *`TestFixtureName`*. The
+test suite name is *`TestFixtureName`*.
+
+The argument *`TestFixtureName`* is a fixture class template, parameterized by a
+type, for example:
+
+```cpp
+template <typename T>
+class MyFixture : public testing::Test {
+ public:
+ ...
+ using List = std::list<T>;
+ static T shared_;
+ T value_;
+};
+```
+
+The argument *`Types`* is a [`Types`](#Types) object representing the list of
+types to run the tests on, for example:
+
+```cpp
+using MyTypes = ::testing::Types<char, int, unsigned int>;
+TYPED_TEST_SUITE(MyFixture, MyTypes);
+```
+
+The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE`
+macro to parse correctly.
+
+See also [`TYPED_TEST`](#TYPED_TEST) and
+[Typed Tests](../advanced.md#typed-tests) for more information.
+
+### TYPED_TEST {#TYPED_TEST}
+
+<pre>
+TYPED_TEST(<em>TestSuiteName</em>, <em>TestName</em>) {
+ ... <em>statements</em> ...
+}
+</pre>
+
+Defines an individual typed test named *`TestName`* in the typed test suite
+*`TestSuiteName`*. The test suite must be defined with
+[`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE).
+
+Within the test body, the special name `TypeParam` refers to the type parameter,
+and `TestFixture` refers to the fixture class. See the following example:
+
+```cpp
+TYPED_TEST(MyFixture, Example) {
+ // Inside a test, refer to the special name TypeParam to get the type
+ // parameter. Since we are inside a derived class template, C++ requires
+ // us to visit the members of MyFixture via 'this'.
+ TypeParam n = this->value_;
+
+ // To visit static members of the fixture, add the 'TestFixture::'
+ // prefix.
+ n += TestFixture::shared_;
+
+ // To refer to typedefs in the fixture, add the 'typename TestFixture::'
+ // prefix. The 'typename' is required to satisfy the compiler.
+ typename TestFixture::List values;
+
+ values.push_back(n);
+ ...
+}
+```
+
+For more information, see [Typed Tests](../advanced.md#typed-tests).
+
+### TYPED_TEST_SUITE_P {#TYPED_TEST_SUITE_P}
+
+`TYPED_TEST_SUITE_P(`*`TestFixtureName`*`)`
+
+Defines a type-parameterized test suite based on the test fixture
+*`TestFixtureName`*. The test suite name is *`TestFixtureName`*.
+
+The argument *`TestFixtureName`* is a fixture class template, parameterized by a
+type. See [`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE) for an example.
+
+See also [`TYPED_TEST_P`](#TYPED_TEST_P) and
+[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more
+information.
+
+### TYPED_TEST_P {#TYPED_TEST_P}
+
+<pre>
+TYPED_TEST_P(<em>TestSuiteName</em>, <em>TestName</em>) {
+ ... <em>statements</em> ...
+}
+</pre>
+
+Defines an individual type-parameterized test named *`TestName`* in the
+type-parameterized test suite *`TestSuiteName`*. The test suite must be defined
+with [`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P).
+
+Within the test body, the special name `TypeParam` refers to the type parameter,
+and `TestFixture` refers to the fixture class. See [`TYPED_TEST`](#TYPED_TEST)
+for an example.
+
+See also [`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P) and
+[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more
+information.
+
+### REGISTER_TYPED_TEST_SUITE_P {#REGISTER_TYPED_TEST_SUITE_P}
+
+`REGISTER_TYPED_TEST_SUITE_P(`*`TestSuiteName`*`,`*`TestNames...`*`)`
+
+Registers the type-parameterized tests *`TestNames...`* of the test suite
+*`TestSuiteName`*. The test suite and tests must be defined with
+[`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P) and [`TYPED_TEST_P`](#TYPED_TEST_P).
+
+For example:
+
+```cpp
+// Define the test suite and tests.
+TYPED_TEST_SUITE_P(MyFixture);
+TYPED_TEST_P(MyFixture, HasPropertyA) { ... }
+TYPED_TEST_P(MyFixture, HasPropertyB) { ... }
+
+// Register the tests in the test suite.
+REGISTER_TYPED_TEST_SUITE_P(MyFixture, HasPropertyA, HasPropertyB);
+```
+
+See also [`INSTANTIATE_TYPED_TEST_SUITE_P`](#INSTANTIATE_TYPED_TEST_SUITE_P) and
+[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more
+information.
+
+### INSTANTIATE_TYPED_TEST_SUITE_P {#INSTANTIATE_TYPED_TEST_SUITE_P}
+
+`INSTANTIATE_TYPED_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`Types`*`)`
+
+Instantiates the type-parameterized test suite *`TestSuiteName`*. The test suite
+must be registered with
+[`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P).
+
+The argument *`InstantiationName`* is a unique name for the instantiation of the
+test suite, to distinguish between multiple instantiations. In test output, the
+instantiation name is added as a prefix to the test suite name
+*`TestSuiteName`*.
+
+The argument *`Types`* is a [`Types`](#Types) object representing the list of
+types to run the tests on, for example:
+
+```cpp
+using MyTypes = ::testing::Types<char, int, unsigned int>;
+INSTANTIATE_TYPED_TEST_SUITE_P(MyInstantiation, MyFixture, MyTypes);
+```
+
+The type alias (`using` or `typedef`) is necessary for the
+`INSTANTIATE_TYPED_TEST_SUITE_P` macro to parse correctly.
+
+For more information, see
+[Type-Parameterized Tests](../advanced.md#type-parameterized-tests).
+
+### FRIEND_TEST {#FRIEND_TEST}
+
+`FRIEND_TEST(`*`TestSuiteName`*`,`*`TestName`*`)`
+
+Within a class body, declares an individual test as a friend of the class,
+enabling the test to access private class members.
+
+If the class is defined in a namespace, then in order to be friends of the
+class, test fixtures and tests must be defined in the exact same namespace,
+without inline or anonymous namespaces.
+
+For example, if the class definition looks like the following:
+
+```cpp
+namespace my_namespace {
+
+class MyClass {
+ friend class MyClassTest;
+ FRIEND_TEST(MyClassTest, HasPropertyA);
+ FRIEND_TEST(MyClassTest, HasPropertyB);
+ ... definition of class MyClass ...
+};
+
+} // namespace my_namespace
+```
+
+Then the test code should look like:
+
+```cpp
+namespace my_namespace {
+
+class MyClassTest : public testing::Test {
+ ...
+};
+
+TEST_F(MyClassTest, HasPropertyA) { ... }
+TEST_F(MyClassTest, HasPropertyB) { ... }
+
+} // namespace my_namespace
+```
+
+See [Testing Private Code](../advanced.md#testing-private-code) for more
+information.
+
+### SCOPED_TRACE {#SCOPED_TRACE}
+
+`SCOPED_TRACE(`*`message`*`)`
+
+Causes the current file name, line number, and the given message *`message`* to
+be added to the failure message for each assertion failure that occurs in the
+scope.
+
+For more information, see
+[Adding Traces to Assertions](../advanced.md#adding-traces-to-assertions).
+
+See also the [`ScopedTrace` class](#ScopedTrace).
+
+### GTEST_SKIP {#GTEST_SKIP}
+
+`GTEST_SKIP()`
+
+Prevents further test execution at runtime.
+
+Can be used in individual test cases or in the `SetUp()` methods of test
+environments or test fixtures (classes derived from the
+[`Environment`](#Environment) or [`Test`](#Test) classes). If used in a global
+test environment `SetUp()` method, it skips all tests in the test program. If
+used in a test fixture `SetUp()` method, it skips all tests in the corresponding
+test suite.
+
+Similar to assertions, `GTEST_SKIP` allows streaming a custom message into it.
+
+See [Skipping Test Execution](../advanced.md#skipping-test-execution) for more
+information.
+
+### GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST {#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST}
+
+`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(`*`TestSuiteName`*`)`
+
+Allows the value-parameterized test suite *`TestSuiteName`* to be
+uninstantiated.
+
+By default, every [`TEST_P`](#TEST_P) call without a corresponding
+[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P) call causes a failing
+test in the test suite `GoogleTestVerification`.
+`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST` suppresses this failure for the
+given test suite.
+
+## Classes and types
+
+GoogleTest defines the following classes and types to help with writing tests.
+
+### AssertionResult {#AssertionResult}
+
+`testing::AssertionResult`
+
+A class for indicating whether an assertion was successful.
+
+When the assertion wasn't successful, the `AssertionResult` object stores a
+non-empty failure message that can be retrieved with the object's `message()`
+method.
+
+To create an instance of this class, use one of the factory functions
+[`AssertionSuccess()`](#AssertionSuccess) or
+[`AssertionFailure()`](#AssertionFailure).
+
+### AssertionException {#AssertionException}
+
+`testing::AssertionException`
+
+Exception which can be thrown from
+[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult).
+
+### EmptyTestEventListener {#EmptyTestEventListener}
+
+`testing::EmptyTestEventListener`
+
+Provides an empty implementation of all methods in the
+[`TestEventListener`](#TestEventListener) interface, such that a subclass only
+needs to override the methods it cares about.
+
+### Environment {#Environment}
+
+`testing::Environment`
+
+Represents a global test environment. See
+[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down).
+
+#### Protected Methods {#Environment-protected}
+
+##### SetUp {#Environment::SetUp}
+
+`virtual void Environment::SetUp()`
+
+Override this to define how to set up the environment.
+
+##### TearDown {#Environment::TearDown}
+
+`virtual void Environment::TearDown()`
+
+Override this to define how to tear down the environment.
+
+### ScopedTrace {#ScopedTrace}
+
+`testing::ScopedTrace`
+
+An instance of this class causes a trace to be included in every test failure
+message generated by code in the scope of the lifetime of the `ScopedTrace`
+instance. The effect is undone with the destruction of the instance.
+
+The `ScopedTrace` constructor has the following form:
+
+```cpp
+template <typename T>
+ScopedTrace(const char* file, int line, const T& message)
+```
+
+Example usage:
+
+```cpp
+testing::ScopedTrace trace("file.cc", 123, "message");
+```
+
+The resulting trace includes the given source file path and line number, and the
+given message. The `message` argument can be anything streamable to
+`std::ostream`.
+
+See also [`SCOPED_TRACE`](#SCOPED_TRACE).
+
+### Test {#Test}
+
+`testing::Test`
+
+The abstract class that all tests inherit from. `Test` is not copyable.
+
+#### Public Methods {#Test-public}
+
+##### SetUpTestSuite {#Test::SetUpTestSuite}
+
+`static void Test::SetUpTestSuite()`
+
+Performs shared setup for all tests in the test suite. GoogleTest calls
+`SetUpTestSuite()` before running the first test in the test suite.
+
+##### TearDownTestSuite {#Test::TearDownTestSuite}
+
+`static void Test::TearDownTestSuite()`
+
+Performs shared teardown for all tests in the test suite. GoogleTest calls
+`TearDownTestSuite()` after running the last test in the test suite.
+
+##### HasFatalFailure {#Test::HasFatalFailure}
+
+`static bool Test::HasFatalFailure()`
+
+Returns true if and only if the current test has a fatal failure.
+
+##### HasNonfatalFailure {#Test::HasNonfatalFailure}
+
+`static bool Test::HasNonfatalFailure()`
+
+Returns true if and only if the current test has a nonfatal failure.
+
+##### HasFailure {#Test::HasFailure}
+
+`static bool Test::HasFailure()`
+
+Returns true if and only if the current test has any failure, either fatal or
+nonfatal.
+
+##### IsSkipped {#Test::IsSkipped}
+
+`static bool Test::IsSkipped()`
+
+Returns true if and only if the current test was skipped.
+
+##### RecordProperty {#Test::RecordProperty}
+
+`static void Test::RecordProperty(const std::string& key, const std::string&
+value)` \
+`static void Test::RecordProperty(const std::string& key, int value)`
+
+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`, `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.
+
+Calls to `RecordProperty` made during the lifespan of the test (from the moment
+its constructor starts to the moment its destructor finishes) are output in XML
+as attributes of the `<testcase>` element. Properties recorded from a fixture's
+`SetUpTestSuite` or `TearDownTestSuite` methods are logged as attributes of the
+corresponding `<testsuite>` element. Calls to `RecordProperty` made in the
+global context (before or after invocation of `RUN_ALL_TESTS` or from the
+`SetUp`/`TearDown` methods of registered `Environment` objects) are output as
+attributes of the `<testsuites>` element.
+
+#### Protected Methods {#Test-protected}
+
+##### SetUp {#Test::SetUp}
+
+`virtual void Test::SetUp()`
+
+Override this to perform test fixture setup. GoogleTest calls `SetUp()` before
+running each individual test.
+
+##### TearDown {#Test::TearDown}
+
+`virtual void Test::TearDown()`
+
+Override this to perform test fixture teardown. GoogleTest calls `TearDown()`
+after running each individual test.
+
+### TestWithParam {#TestWithParam}
+
+`testing::TestWithParam<T>`
+
+A convenience class which inherits from both [`Test`](#Test) and
+[`WithParamInterface<T>`](#WithParamInterface).
+
+### TestSuite {#TestSuite}
+
+Represents a test suite. `TestSuite` is not copyable.
+
+#### Public Methods {#TestSuite-public}
+
+##### name {#TestSuite::name}
+
+`const char* TestSuite::name() const`
+
+Gets the name of the test suite.
+
+##### type_param {#TestSuite::type_param}
+
+`const char* TestSuite::type_param() const`
+
+Returns the name of the parameter type, or `NULL` if this is not a typed or
+type-parameterized test suite. See [Typed Tests](../advanced.md#typed-tests) and
+[Type-Parameterized Tests](../advanced.md#type-parameterized-tests).
+
+##### should_run {#TestSuite::should_run}
+
+`bool TestSuite::should_run() const`
+
+Returns true if any test in this test suite should run.
+
+##### successful_test_count {#TestSuite::successful_test_count}
+
+`int TestSuite::successful_test_count() const`
+
+Gets the number of successful tests in this test suite.
+
+##### skipped_test_count {#TestSuite::skipped_test_count}
+
+`int TestSuite::skipped_test_count() const`
+
+Gets the number of skipped tests in this test suite.
+
+##### failed_test_count {#TestSuite::failed_test_count}
+
+`int TestSuite::failed_test_count() const`
+
+Gets the number of failed tests in this test suite.
+
+##### reportable_disabled_test_count {#TestSuite::reportable_disabled_test_count}
+
+`int TestSuite::reportable_disabled_test_count() const`
+
+Gets the number of disabled tests that will be reported in the XML report.
+
+##### disabled_test_count {#TestSuite::disabled_test_count}
+
+`int TestSuite::disabled_test_count() const`
+
+Gets the number of disabled tests in this test suite.
+
+##### reportable_test_count {#TestSuite::reportable_test_count}
+
+`int TestSuite::reportable_test_count() const`
+
+Gets the number of tests to be printed in the XML report.
+
+##### test_to_run_count {#TestSuite::test_to_run_count}
+
+`int TestSuite::test_to_run_count() const`
+
+Get the number of tests in this test suite that should run.
+
+##### total_test_count {#TestSuite::total_test_count}
+
+`int TestSuite::total_test_count() const`
+
+Gets the number of all tests in this test suite.
+
+##### Passed {#TestSuite::Passed}
+
+`bool TestSuite::Passed() const`
+
+Returns true if and only if the test suite passed.
+
+##### Failed {#TestSuite::Failed}
+
+`bool TestSuite::Failed() const`
+
+Returns true if and only if the test suite failed.
+
+##### elapsed_time {#TestSuite::elapsed_time}
+
+`TimeInMillis TestSuite::elapsed_time() const`
+
+Returns the elapsed time, in milliseconds.
+
+##### start_timestamp {#TestSuite::start_timestamp}
+
+`TimeInMillis TestSuite::start_timestamp() const`
+
+Gets the time of the test suite start, in ms from the start of the UNIX epoch.
+
+##### GetTestInfo {#TestSuite::GetTestInfo}
+
+`const TestInfo* TestSuite::GetTestInfo(int i) const`
+
+Returns the [`TestInfo`](#TestInfo) for the `i`-th test among all the tests. `i`
+can range from 0 to `total_test_count() - 1`. If `i` is not in that range,
+returns `NULL`.
+
+##### ad_hoc_test_result {#TestSuite::ad_hoc_test_result}
+
+`const TestResult& TestSuite::ad_hoc_test_result() const`
+
+Returns the [`TestResult`](#TestResult) that holds test properties recorded
+during execution of `SetUpTestSuite` and `TearDownTestSuite`.
+
+### TestInfo {#TestInfo}
+
+`testing::TestInfo`
+
+Stores information about a test.
+
+#### Public Methods {#TestInfo-public}
+
+##### test_suite_name {#TestInfo::test_suite_name}
+
+`const char* TestInfo::test_suite_name() const`
+
+Returns the test suite name.
+
+##### name {#TestInfo::name}
+
+`const char* TestInfo::name() const`
+
+Returns the test name.
+
+##### type_param {#TestInfo::type_param}
+
+`const char* TestInfo::type_param() const`
+
+Returns the name of the parameter type, or `NULL` if this is not a typed or
+type-parameterized test. See [Typed Tests](../advanced.md#typed-tests) and
+[Type-Parameterized Tests](../advanced.md#type-parameterized-tests).
+
+##### value_param {#TestInfo::value_param}
+
+`const char* TestInfo::value_param() const`
+
+Returns the text representation of the value parameter, or `NULL` if this is not
+a value-parameterized test. See
+[Value-Parameterized Tests](../advanced.md#value-parameterized-tests).
+
+##### file {#TestInfo::file}
+
+`const char* TestInfo::file() const`
+
+Returns the file name where this test is defined.
+
+##### line {#TestInfo::line}
+
+`int TestInfo::line() const`
+
+Returns the line where this test is defined.
+
+##### is_in_another_shard {#TestInfo::is_in_another_shard}
+
+`bool TestInfo::is_in_another_shard() const`
+
+Returns true if this test should not be run because it's in another shard.
+
+##### should_run {#TestInfo::should_run}
+
+`bool TestInfo::should_run() const`
+
+Returns true if this test should run, that is if the test is not disabled (or it
+is disabled but the `also_run_disabled_tests` flag has been specified) and its
+full name matches the user-specified filter.
+
+GoogleTest allows the user to filter the tests by their full names. Only the
+tests that match the filter will run. See
+[Running a Subset of the Tests](../advanced.md#running-a-subset-of-the-tests)
+for more information.
+
+##### is_reportable {#TestInfo::is_reportable}
+
+`bool TestInfo::is_reportable() const`
+
+Returns true if and only if this test will appear in the XML report.
+
+##### result {#TestInfo::result}
+
+`const TestResult* TestInfo::result() const`
+
+Returns the result of the test. See [`TestResult`](#TestResult).
+
+### TestParamInfo {#TestParamInfo}
+
+`testing::TestParamInfo<T>`
+
+Describes a parameter to a value-parameterized test. The type `T` is the type of
+the parameter.
+
+Contains the fields `param` and `index` which hold the value of the parameter
+and its integer index respectively.
+
+### UnitTest {#UnitTest}
+
+`testing::UnitTest`
+
+This class contains information about the test program.
+
+`UnitTest` is a singleton class. The only instance is created when
+`UnitTest::GetInstance()` is first called. This instance is never deleted.
+
+`UnitTest` is not copyable.
+
+#### Public Methods {#UnitTest-public}
+
+##### GetInstance {#UnitTest::GetInstance}
+
+`static UnitTest* UnitTest::GetInstance()`
+
+Gets the singleton `UnitTest` object. The first time this method is called, a
+`UnitTest` object is constructed and returned. Consecutive calls will return the
+same object.
+
+##### original_working_dir {#UnitTest::original_working_dir}
+
+`const char* UnitTest::original_working_dir() const`
+
+Returns the working directory when the first [`TEST()`](#TEST) or
+[`TEST_F()`](#TEST_F) was executed. The `UnitTest` object owns the string.
+
+##### current_test_suite {#UnitTest::current_test_suite}
+
+`const TestSuite* UnitTest::current_test_suite() const`
+
+Returns the [`TestSuite`](#TestSuite) object for the test that's currently
+running, or `NULL` if no test is running.
+
+##### current_test_info {#UnitTest::current_test_info}
+
+`const TestInfo* UnitTest::current_test_info() const`
+
+Returns the [`TestInfo`](#TestInfo) object for the test that's currently
+running, or `NULL` if no test is running.
+
+##### random_seed {#UnitTest::random_seed}
+
+`int UnitTest::random_seed() const`
+
+Returns the random seed used at the start of the current test run.
+
+##### successful_test_suite_count {#UnitTest::successful_test_suite_count}
+
+`int UnitTest::successful_test_suite_count() const`
+
+Gets the number of successful test suites.
+
+##### failed_test_suite_count {#UnitTest::failed_test_suite_count}
+
+`int UnitTest::failed_test_suite_count() const`
+
+Gets the number of failed test suites.
+
+##### total_test_suite_count {#UnitTest::total_test_suite_count}
+
+`int UnitTest::total_test_suite_count() const`
+
+Gets the number of all test suites.
+
+##### test_suite_to_run_count {#UnitTest::test_suite_to_run_count}
+
+`int UnitTest::test_suite_to_run_count() const`
+
+Gets the number of all test suites that contain at least one test that should
+run.
+
+##### successful_test_count {#UnitTest::successful_test_count}
+
+`int UnitTest::successful_test_count() const`
+
+Gets the number of successful tests.
+
+##### skipped_test_count {#UnitTest::skipped_test_count}
+
+`int UnitTest::skipped_test_count() const`
+
+Gets the number of skipped tests.
+
+##### failed_test_count {#UnitTest::failed_test_count}
+
+`int UnitTest::failed_test_count() const`
+
+Gets the number of failed tests.
+
+##### reportable_disabled_test_count {#UnitTest::reportable_disabled_test_count}
+
+`int UnitTest::reportable_disabled_test_count() const`
+
+Gets the number of disabled tests that will be reported in the XML report.
+
+##### disabled_test_count {#UnitTest::disabled_test_count}
+
+`int UnitTest::disabled_test_count() const`
+
+Gets the number of disabled tests.
+
+##### reportable_test_count {#UnitTest::reportable_test_count}
+
+`int UnitTest::reportable_test_count() const`
+
+Gets the number of tests to be printed in the XML report.
+
+##### total_test_count {#UnitTest::total_test_count}
+
+`int UnitTest::total_test_count() const`
+
+Gets the number of all tests.
+
+##### test_to_run_count {#UnitTest::test_to_run_count}
+
+`int UnitTest::test_to_run_count() const`
+
+Gets the number of tests that should run.
+
+##### start_timestamp {#UnitTest::start_timestamp}
+
+`TimeInMillis UnitTest::start_timestamp() const`
+
+Gets the time of the test program start, in ms from the start of the UNIX epoch.
+
+##### elapsed_time {#UnitTest::elapsed_time}
+
+`TimeInMillis UnitTest::elapsed_time() const`
+
+Gets the elapsed time, in milliseconds.
+
+##### Passed {#UnitTest::Passed}
+
+`bool UnitTest::Passed() const`
+
+Returns true if and only if the unit test passed (i.e. all test suites passed).
+
+##### Failed {#UnitTest::Failed}
+
+`bool UnitTest::Failed() const`
+
+Returns true if and only if the unit test failed (i.e. some test suite failed or
+something outside of all tests failed).
+
+##### GetTestSuite {#UnitTest::GetTestSuite}
+
+`const TestSuite* UnitTest::GetTestSuite(int i) const`
+
+Gets the [`TestSuite`](#TestSuite) object for the `i`-th test suite among all
+the test suites. `i` can range from 0 to `total_test_suite_count() - 1`. If `i`
+is not in that range, returns `NULL`.
+
+##### ad_hoc_test_result {#UnitTest::ad_hoc_test_result}
+
+`const TestResult& UnitTest::ad_hoc_test_result() const`
+
+Returns the [`TestResult`](#TestResult) containing information on test failures
+and properties logged outside of individual test suites.
+
+##### listeners {#UnitTest::listeners}
+
+`TestEventListeners& UnitTest::listeners()`
+
+Returns the list of event listeners that can be used to track events inside
+GoogleTest. See [`TestEventListeners`](#TestEventListeners).
+
+### TestEventListener {#TestEventListener}
+
+`testing::TestEventListener`
+
+The interface for tracing execution of tests. The methods below are listed in
+the order the corresponding events are fired.
+
+#### Public Methods {#TestEventListener-public}
+
+##### OnTestProgramStart {#TestEventListener::OnTestProgramStart}
+
+`virtual void TestEventListener::OnTestProgramStart(const UnitTest& unit_test)`
+
+Fired before any test activity starts.
+
+##### OnTestIterationStart {#TestEventListener::OnTestIterationStart}
+
+`virtual void TestEventListener::OnTestIterationStart(const UnitTest& unit_test,
+int iteration)`
+
+Fired before each iteration of tests starts. There may be more than one
+iteration if `GTEST_FLAG(repeat)` is set. `iteration` is the iteration index,
+starting from 0.
+
+##### OnEnvironmentsSetUpStart {#TestEventListener::OnEnvironmentsSetUpStart}
+
+`virtual void TestEventListener::OnEnvironmentsSetUpStart(const UnitTest&
+unit_test)`
+
+Fired before environment set-up for each iteration of tests starts.
+
+##### OnEnvironmentsSetUpEnd {#TestEventListener::OnEnvironmentsSetUpEnd}
+
+`virtual void TestEventListener::OnEnvironmentsSetUpEnd(const UnitTest&
+unit_test)`
+
+Fired after environment set-up for each iteration of tests ends.
+
+##### OnTestSuiteStart {#TestEventListener::OnTestSuiteStart}
+
+`virtual void TestEventListener::OnTestSuiteStart(const TestSuite& test_suite)`
+
+Fired before the test suite starts.
+
+##### OnTestStart {#TestEventListener::OnTestStart}
+
+`virtual void TestEventListener::OnTestStart(const TestInfo& test_info)`
+
+Fired before the test starts.
+
+##### OnTestPartResult {#TestEventListener::OnTestPartResult}
+
+`virtual void TestEventListener::OnTestPartResult(const TestPartResult&
+test_part_result)`
+
+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 an
+[`AssertionException`](#AssertionException) or inherited from it.
+
+##### OnTestEnd {#TestEventListener::OnTestEnd}
+
+`virtual void TestEventListener::OnTestEnd(const TestInfo& test_info)`
+
+Fired after the test ends.
+
+##### OnTestSuiteEnd {#TestEventListener::OnTestSuiteEnd}
+
+`virtual void TestEventListener::OnTestSuiteEnd(const TestSuite& test_suite)`
+
+Fired after the test suite ends.
+
+##### OnEnvironmentsTearDownStart {#TestEventListener::OnEnvironmentsTearDownStart}
+
+`virtual void TestEventListener::OnEnvironmentsTearDownStart(const UnitTest&
+unit_test)`
+
+Fired before environment tear-down for each iteration of tests starts.
+
+##### OnEnvironmentsTearDownEnd {#TestEventListener::OnEnvironmentsTearDownEnd}
+
+`virtual void TestEventListener::OnEnvironmentsTearDownEnd(const UnitTest&
+unit_test)`
+
+Fired after environment tear-down for each iteration of tests ends.
+
+##### OnTestIterationEnd {#TestEventListener::OnTestIterationEnd}
+
+`virtual void TestEventListener::OnTestIterationEnd(const UnitTest& unit_test,
+int iteration)`
+
+Fired after each iteration of tests finishes.
+
+##### OnTestProgramEnd {#TestEventListener::OnTestProgramEnd}
+
+`virtual void TestEventListener::OnTestProgramEnd(const UnitTest& unit_test)`
+
+Fired after all test activities have ended.
+
+### TestEventListeners {#TestEventListeners}
+
+`testing::TestEventListeners`
+
+Lets users add listeners to track events in GoogleTest.
+
+#### Public Methods {#TestEventListeners-public}
+
+##### Append {#TestEventListeners::Append}
+
+`void TestEventListeners::Append(TestEventListener* listener)`
+
+Appends an event listener to the end of the list. GoogleTest assumes ownership
+of the listener (i.e. it will delete the listener when the test program
+finishes).
+
+##### Release {#TestEventListeners::Release}
+
+`TestEventListener* TestEventListeners::Release(TestEventListener* listener)`
+
+Removes the given event listener from the list and returns it. It then becomes
+the caller's responsibility to delete the listener. Returns `NULL` if the
+listener is not found in the list.
+
+##### default_result_printer {#TestEventListeners::default_result_printer}
+
+`TestEventListener* TestEventListeners::default_result_printer() const`
+
+Returns the standard listener responsible for the default console output. Can be
+removed from the listeners list to shut down default console output. Note that
+removing this object from the listener list with
+[`Release()`](#TestEventListeners::Release) transfers its ownership to the
+caller and makes this function return `NULL` the next time.
+
+##### default_xml_generator {#TestEventListeners::default_xml_generator}
+
+`TestEventListener* TestEventListeners::default_xml_generator() const`
+
+Returns the standard listener responsible for the default XML output controlled
+by the `--gtest_output=xml` flag. Can be removed from the listeners list by
+users who want to shut down the default XML output controlled by this flag and
+substitute it with custom one. Note that removing this object from the listener
+list with [`Release()`](#TestEventListeners::Release) transfers its ownership to
+the caller and makes this function return `NULL` the next time.
+
+### TestPartResult {#TestPartResult}
+
+`testing::TestPartResult`
+
+A copyable object representing the result of a test part (i.e. an assertion or
+an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`).
+
+#### Public Methods {#TestPartResult-public}
+
+##### type {#TestPartResult::type}
+
+`Type TestPartResult::type() const`
+
+Gets the outcome of the test part.
+
+The return type `Type` is an enum defined as follows:
+
+```cpp
+enum Type {
+ kSuccess, // Succeeded.
+ kNonFatalFailure, // Failed but the test can continue.
+ kFatalFailure, // Failed and the test should be terminated.
+ kSkip // Skipped.
+};
+```
+
+##### file_name {#TestPartResult::file_name}
+
+`const char* TestPartResult::file_name() const`
+
+Gets the name of the source file where the test part took place, or `NULL` if
+it's unknown.
+
+##### line_number {#TestPartResult::line_number}
+
+`int TestPartResult::line_number() const`
+
+Gets the line in the source file where the test part took place, or `-1` if it's
+unknown.
+
+##### summary {#TestPartResult::summary}
+
+`const char* TestPartResult::summary() const`
+
+Gets the summary of the failure message.
+
+##### message {#TestPartResult::message}
+
+`const char* TestPartResult::message() const`
+
+Gets the message associated with the test part.
+
+##### skipped {#TestPartResult::skipped}
+
+`bool TestPartResult::skipped() const`
+
+Returns true if and only if the test part was skipped.
+
+##### passed {#TestPartResult::passed}
+
+`bool TestPartResult::passed() const`
+
+Returns true if and only if the test part passed.
+
+##### nonfatally_failed {#TestPartResult::nonfatally_failed}
+
+`bool TestPartResult::nonfatally_failed() const`
+
+Returns true if and only if the test part non-fatally failed.
+
+##### fatally_failed {#TestPartResult::fatally_failed}
+
+`bool TestPartResult::fatally_failed() const`
+
+Returns true if and only if the test part fatally failed.
+
+##### failed {#TestPartResult::failed}
+
+`bool TestPartResult::failed() const`
+
+Returns true if and only if the test part failed.
+
+### TestProperty {#TestProperty}
+
+`testing::TestProperty`
+
+A copyable object representing a user-specified test property which can be
+output as a key/value string pair.
+
+#### Public Methods {#TestProperty-public}
+
+##### key {#key}
+
+`const char* key() const`
+
+Gets the user-supplied key.
+
+##### value {#value}
+
+`const char* value() const`
+
+Gets the user-supplied value.
+
+##### SetValue {#SetValue}
+
+`void SetValue(const std::string& new_value)`
+
+Sets a new value, overriding the previous one.
+
+### TestResult {#TestResult}
+
+`testing::TestResult`
+
+Contains information about the result of a single test.
+
+`TestResult` is not copyable.
+
+#### Public Methods {#TestResult-public}
+
+##### total_part_count {#TestResult::total_part_count}
+
+`int TestResult::total_part_count() const`
+
+Gets the number of all test parts. This is the sum of the number of successful
+test parts and the number of failed test parts.
+
+##### test_property_count {#TestResult::test_property_count}
+
+`int TestResult::test_property_count() const`
+
+Returns the number of test properties.
+
+##### Passed {#TestResult::Passed}
+
+`bool TestResult::Passed() const`
+
+Returns true if and only if the test passed (i.e. no test part failed).
+
+##### Skipped {#TestResult::Skipped}
+
+`bool TestResult::Skipped() const`
+
+Returns true if and only if the test was skipped.
+
+##### Failed {#TestResult::Failed}
+
+`bool TestResult::Failed() const`
+
+Returns true if and only if the test failed.
+
+##### HasFatalFailure {#TestResult::HasFatalFailure}
+
+`bool TestResult::HasFatalFailure() const`
+
+Returns true if and only if the test fatally failed.
+
+##### HasNonfatalFailure {#TestResult::HasNonfatalFailure}
+
+`bool TestResult::HasNonfatalFailure() const`
+
+Returns true if and only if the test has a non-fatal failure.
+
+##### elapsed_time {#TestResult::elapsed_time}
+
+`TimeInMillis TestResult::elapsed_time() const`
+
+Returns the elapsed time, in milliseconds.
+
+##### start_timestamp {#TestResult::start_timestamp}
+
+`TimeInMillis TestResult::start_timestamp() const`
+
+Gets the time of the test case start, in ms from the start of the UNIX epoch.
+
+##### GetTestPartResult {#TestResult::GetTestPartResult}
+
+`const TestPartResult& TestResult::GetTestPartResult(int i) const`
+
+Returns the [`TestPartResult`](#TestPartResult) for 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.
+
+##### GetTestProperty {#TestResult::GetTestProperty}
+
+`const TestProperty& TestResult::GetTestProperty(int i) const`
+
+Returns the [`TestProperty`](#TestProperty) object for the `i`-th test property.
+`i` can range from 0 to `test_property_count() - 1`. If `i` is not in that
+range, aborts the program.
+
+### TimeInMillis {#TimeInMillis}
+
+`testing::TimeInMillis`
+
+An integer type representing time in milliseconds.
+
+### Types {#Types}
+
+`testing::Types<T...>`
+
+Represents a list of types for use in typed tests and type-parameterized tests.
+
+The template argument `T...` can be any number of types, for example:
+
+```
+testing::Types<char, int, unsigned int>
+```
+
+See [Typed Tests](../advanced.md#typed-tests) and
+[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more
+information.
+
+### WithParamInterface {#WithParamInterface}
+
+`testing::WithParamInterface<T>`
+
+The pure interface class that all value-parameterized tests inherit from.
+
+A value-parameterized test fixture class must inherit from both [`Test`](#Test)
+and `WithParamInterface`. In most cases that just means inheriting from
+[`TestWithParam`](#TestWithParam), but more complicated test hierarchies may
+need to inherit from `Test` and `WithParamInterface` at different levels.
+
+This interface defines the type alias `ParamType` for the parameter type `T` and
+has support for accessing the test parameter value via the `GetParam()` method:
+
+```
+static const ParamType& GetParam()
+```
+
+For more information, see
+[Value-Parameterized Tests](../advanced.md#value-parameterized-tests).
+
+## Functions
+
+GoogleTest defines the following functions to help with writing and running
+tests.
+
+### InitGoogleTest {#InitGoogleTest}
+
+`void testing::InitGoogleTest(int* argc, char** argv)` \
+`void testing::InitGoogleTest(int* argc, wchar_t** argv)` \
+`void testing::InitGoogleTest()`
+
+Initializes GoogleTest. This must be called before calling
+[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line
+for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it
+is removed from `argv`, and `*argc` is decremented.
+
+No value is returned. Instead, the GoogleTest flag variables are updated.
+
+The `InitGoogleTest(int* argc, wchar_t** argv)` overload can be used in Windows
+programs compiled in `UNICODE` mode.
+
+The argument-less `InitGoogleTest()` overload can be used on Arduino/embedded
+platforms where there is no `argc`/`argv`.
+
+### AddGlobalTestEnvironment {#AddGlobalTestEnvironment}
+
+`Environment* testing::AddGlobalTestEnvironment(Environment* env)`
+
+Adds a test environment to the test program. Must be called before
+[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See
+[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down) for
+more information.
+
+See also [`Environment`](#Environment).
+
+### RegisterTest {#RegisterTest}
+
+```cpp
+template <typename Factory>
+TestInfo* testing::RegisterTest(const char* test_suite_name, const char* test_name,
+ const char* type_param, const char* value_param,
+ const char* file, int line, Factory factory)
+```
+
+Dynamically registers a test with the framework.
+
+The `factory` argument is a factory callable (move-constructible) object or
+function pointer that creates a new instance of the `Test` object. It handles
+ownership to the caller. The signature of the callable is `Fixture*()`, where
+`Fixture` is the test fixture class for the test. All tests registered with the
+same `test_suite_name` must return the same fixture type. This is checked at
+runtime.
+
+The framework will infer the fixture class from the factory and will call the
+`SetUpTestSuite` and `TearDownTestSuite` methods for it.
+
+Must be called before [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is invoked, otherwise
+behavior is undefined.
+
+See
+[Registering tests programmatically](../advanced.md#registering-tests-programmatically)
+for more information.
+
+### RUN_ALL_TESTS {#RUN_ALL_TESTS}
+
+`int RUN_ALL_TESTS()`
+
+Use this function in `main()` to run all tests. It returns `0` if all tests are
+successful, or `1` otherwise.
+
+`RUN_ALL_TESTS()` should be invoked after the command line has been parsed by
+[`InitGoogleTest()`](#InitGoogleTest).
+
+This function was formerly a macro; thus, it is in the global namespace and has
+an all-caps name.
+
+### AssertionSuccess {#AssertionSuccess}
+
+`AssertionResult testing::AssertionSuccess()`
+
+Creates a successful assertion result. See
+[`AssertionResult`](#AssertionResult).
+
+### AssertionFailure {#AssertionFailure}
+
+`AssertionResult testing::AssertionFailure()`
+
+Creates a failed assertion result. Use the `<<` operator to store a failure
+message:
+
+```cpp
+testing::AssertionFailure() << "My failure message";
+```
+
+See [`AssertionResult`](#AssertionResult).
+
+### StaticAssertTypeEq {#StaticAssertTypeEq}
+
+`testing::StaticAssertTypeEq<T1, T2>()`
+
+Compile-time assertion for type equality. Compiles if and only if `T1` and `T2`
+are the same type. The value it returns is irrelevant.
+
+See [Type Assertions](../advanced.md#type-assertions) for more information.
+
+### PrintToString {#PrintToString}
+
+`std::string testing::PrintToString(x)`
+
+Prints any value `x` using GoogleTest's value printer.
+
+See
+[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values)
+for more information.
+
+### PrintToStringParamName {#PrintToStringParamName}
+
+`std::string testing::PrintToStringParamName(TestParamInfo<T>& info)`
+
+A built-in parameterized test name generator which returns the result of
+[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the
+test parameter is a `std::string` or C string. See
+[Specifying Names for Value-Parameterized Test Parameters](../advanced.md#specifying-names-for-value-parameterized-test-parameters)
+for more information.
+
+See also [`TestParamInfo`](#TestParamInfo) and
+[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P).
diff --git a/googletest/docs/samples.md b/docs/samples.md
index aaa5883830b6..dedc59098df5 100644
--- a/googletest/docs/samples.md
+++ b/docs/samples.md
@@ -1,7 +1,7 @@
-# Googletest Samples {#samples}
+# Googletest Samples
If you're like us, you'd like to look at
-[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples)
+[googletest samples.](https://github.com/google/googletest/blob/main/googletest/samples)
The sample directory has a number of well-commented samples showing how to use a
variety of googletest features.
diff --git a/googlemock/CMakeLists.txt b/googlemock/CMakeLists.txt
index d32b70b5be0e..a9aa0723fbf1 100644
--- a/googlemock/CMakeLists.txt
+++ b/googlemock/CMakeLists.txt
@@ -36,13 +36,8 @@ 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.6.4)
+cmake_minimum_required(VERSION 3.13)
+project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
if (COMMAND set_up_hermetic_build)
set_up_hermetic_build()
@@ -100,21 +95,20 @@ if (MSVC)
else()
cxx_library(gmock "${cxx_strict}" src/gmock-all.cc)
target_link_libraries(gmock PUBLIC gtest)
+ set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION})
cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc)
target_link_libraries(gmock_main PUBLIC gmock)
-endif()
-# If the CMake version supports it, attach header directory information
-# 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")
- target_include_directories(gmock SYSTEM INTERFACE
- "$<BUILD_INTERFACE:${gmock_build_include_dirs}>"
- "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
- target_include_directories(gmock_main SYSTEM INTERFACE
- "$<BUILD_INTERFACE:${gmock_build_include_dirs}>"
- "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
+ set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
endif()
+string(REPLACE ";" "$<SEMICOLON>" dirs "${gmock_build_include_dirs}")
+target_include_directories(gmock SYSTEM INTERFACE
+ "$<BUILD_INTERFACE:${dirs}>"
+ "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
+target_include_directories(gmock_main SYSTEM INTERFACE
+ "$<BUILD_INTERFACE:${dirs}>"
+ "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
+
########################################################################
#
# Install rules
@@ -136,26 +130,8 @@ if (gmock_build_tests)
# 'make test' or ctest.
enable_testing()
- if (WIN32)
- file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1"
- CONTENT
-"$project_bin = \"${CMAKE_BINARY_DIR}/bin/$<CONFIG>\"
-$env:Path = \"$project_bin;$env:Path\"
-& $args")
- elseif (MINGW OR CYGWIN)
- file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1"
- CONTENT
-"$project_bin = (cygpath --windows ${CMAKE_BINARY_DIR}/bin)
-$env:Path = \"$project_bin;$env:Path\"
-& $args")
- endif()
-
if (MINGW OR CYGWIN)
- if (CMAKE_VERSION VERSION_LESS "2.8.12")
- add_compile_options("-Wa,-mbig-obj")
- else()
- add_definitions("-Wa,-mbig-obj")
- endif()
+ add_compile_options("-Wa,-mbig-obj")
endif()
############################################################
@@ -165,11 +141,11 @@ $env:Path = \"$project_bin;$env:Path\"
cxx_test(gmock-cardinalities_test gmock_main)
cxx_test(gmock_ex_test gmock_main)
cxx_test(gmock-function-mocker_test gmock_main)
- cxx_test(gmock-generated-actions_test gmock_main)
- cxx_test(gmock-generated-function-mockers_test gmock_main)
- cxx_test(gmock-generated-matchers_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)
diff --git a/googlemock/CONTRIBUTORS b/googlemock/CONTRIBUTORS
deleted file mode 100644
index 6e9ae362b60c..000000000000
--- a/googlemock/CONTRIBUTORS
+++ /dev/null
@@ -1,40 +0,0 @@
-# This file contains a list of people who've made non-trivial
-# contribution to the Google C++ Mocking Framework project. People
-# who commit code to the project are encouraged to add their names
-# here. Please keep the list sorted by first names.
-
-Benoit Sigoure <tsuna@google.com>
-Bogdan Piloca <boo@google.com>
-Chandler Carruth <chandlerc@google.com>
-Dave MacLachlan <dmaclach@gmail.com>
-David Anderson <danderson@google.com>
-Dean Sturtevant
-Gene Volovich <gv@cite.com>
-Hal Burch <gmock@hburch.com>
-Jeffrey Yasskin <jyasskin@google.com>
-Jim Keller <jimkeller@google.com>
-Joe Walnes <joe@truemesh.com>
-Jon Wray <jwray@google.com>
-Keir Mierle <mierle@gmail.com>
-Keith Ray <keith.ray@gmail.com>
-Kostya Serebryany <kcc@google.com>
-Lev Makhlis
-Manuel Klimek <klimek@google.com>
-Mario Tanev <radix@google.com>
-Mark Paskin
-Markus Heule <markus.heule@gmail.com>
-Matthew Simmons <simmonmt@acm.org>
-Mike Bland <mbland@google.com>
-Neal Norwitz <nnorwitz@gmail.com>
-Nermin Ozkiranartli <nermin@google.com>
-Owen Carlsen <ocarlsen@google.com>
-Paneendra Ba <paneendra@google.com>
-Paul Menage <menage@google.com>
-Piotr Kaminski <piotrk@google.com>
-Russ Rufer <russ@pentad.com>
-Sverre Sundsdal <sundsdal@gmail.com>
-Takeshi Yoshino <tyoshino@google.com>
-Vadim Berman <vadimb@google.com>
-Vlad Losev <vladl@google.com>
-Wolfgang Klier <wklier@google.com>
-Zhanyong Wan <wan@google.com>
diff --git a/googlemock/LICENSE b/googlemock/LICENSE
deleted file mode 100644
index 1941a11f8ce9..000000000000
--- a/googlemock/LICENSE
+++ /dev/null
@@ -1,28 +0,0 @@
-Copyright 2008, Google Inc.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/googlemock/README.md b/googlemock/README.md
index 183fdb81d9b6..7da60655dba8 100644
--- a/googlemock/README.md
+++ b/googlemock/README.md
@@ -7,38 +7,34 @@ derive better designs of your system and write better tests.
It is inspired by:
-* [jMock](http://www.jmock.org/),
-* [EasyMock](http://www.easymock.org/), and
-* [Hamcrest](http://code.google.com/p/hamcrest/),
+* [jMock](http://www.jmock.org/)
+* [EasyMock](http://www.easymock.org/)
+* [Hamcrest](http://code.google.com/p/hamcrest/)
-and designed with C++'s specifics in mind.
+It is designed with C++'s specifics in mind.
gMock:
-- provides a declarative syntax for defining mocks,
-- can define partial (hybrid) mocks, which are a cross of real and mock
- objects,
-- handles functions of arbitrary types and overloaded functions,
-- comes with a rich set of matchers for validating function arguments,
-- uses an intuitive syntax for controlling the behavior of a mock,
-- does automatic verification of expectations (no record-and-replay needed),
-- allows arbitrary (partial) ordering constraints on function calls to be
- expressed,
-- lets a user extend it by defining new matchers and actions.
-- does not use exceptions, and
-- is easy to learn and use.
+- Provides a declarative syntax for defining mocks.
+- Can define partial (hybrid) mocks, which are a cross of real and mock
+ objects.
+- Handles functions of arbitrary types and overloaded functions.
+- Comes with a rich set of matchers for validating function arguments.
+- Uses an intuitive syntax for controlling the behavior of a mock.
+- Does automatic verification of expectations (no record-and-replay needed).
+- Allows arbitrary (partial) ordering constraints on function calls to be
+ expressed.
+- Lets a user extend it by defining new matchers and actions.
+- Does not use exceptions.
+- Is easy to learn and use.
Details and examples can be found here:
-* [gMock for Dummies](docs/for_dummies.md)
-* [Legacy gMock FAQ](docs/gmock_faq.md)
-* [gMock Cookbook](docs/cook_book.md)
-* [gMock Cheat Sheet](docs/cheat_sheet.md)
+* [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html)
+* [Legacy gMock FAQ](https://google.github.io/googletest/gmock_faq.html)
+* [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 Google Mock's license.
-
-Google Mock is a part of
-[Google Test C++ testing framework](http://github.com/google/googletest/) and a
+GoogleMock is a part of
+[GoogleTest C++ testing framework](http://github.com/google/googletest/) and a
subject to the same requirements.
diff --git a/googlemock/cmake/gmock.pc.in b/googlemock/cmake/gmock.pc.in
index 08e0454749ba..23c67b5c88db 100644
--- a/googlemock/cmake/gmock.pc.in
+++ b/googlemock/cmake/gmock.pc.in
@@ -1,11 +1,10 @@
-prefix=${pcfiledir}/../..
-libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
-includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
+libdir=@CMAKE_INSTALL_FULL_LIBDIR@
+includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
Name: gmock
Description: GoogleMock (without main() function)
Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest
-Requires: gtest
+Requires: gtest = @PROJECT_VERSION@
Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@
-Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@
+Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
diff --git a/googlemock/cmake/gmock_main.pc.in b/googlemock/cmake/gmock_main.pc.in
index b22fe6148283..66ffea7f4431 100644
--- a/googlemock/cmake/gmock_main.pc.in
+++ b/googlemock/cmake/gmock_main.pc.in
@@ -1,11 +1,10 @@
-prefix=${pcfiledir}/../..
-libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
-includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
+libdir=@CMAKE_INSTALL_FULL_LIBDIR@
+includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
Name: gmock_main
Description: GoogleMock (with main() function)
Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest
-Requires: gmock
+Requires: gmock = @PROJECT_VERSION@
Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@
-Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@
+Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
diff --git a/googlemock/docs/README.md b/googlemock/docs/README.md
new file mode 100644
index 000000000000..1bc57b799cce
--- /dev/null
+++ b/googlemock/docs/README.md
@@ -0,0 +1,4 @@
+# Content Moved
+
+We are working on updates to the GoogleTest documentation, which has moved to
+the top-level [docs](../../docs) directory.
diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md
deleted file mode 100644
index 850963af2848..000000000000
--- a/googlemock/docs/cheat_sheet.md
+++ /dev/null
@@ -1,781 +0,0 @@
-## gMock Cheat Sheet
-
-<!-- GOOGLETEST_CM0019 DO NOT DELETE -->
-
-<!-- GOOGLETEST_CM0033 DO NOT DELETE -->
-
-### Defining a Mock Class
-
-#### Mocking a Normal Class {#MockClass}
-
-Given
-
-```cpp
-class Foo {
- ...
- virtual ~Foo();
- virtual int GetSize() const = 0;
- virtual string Describe(const char* name) = 0;
- virtual string Describe(int type) = 0;
- virtual bool Process(Bar elem, int count) = 0;
-};
-```
-
-(note that `~Foo()` **must** be virtual) we can define its mock as
-
-```cpp
-#include "gmock/gmock.h"
-
-class MockFoo : public Foo {
- ...
- MOCK_METHOD(int, GetSize, (), (const, override));
- MOCK_METHOD(string, Describe, (const char* name), (override));
- MOCK_METHOD(string, Describe, (int type), (override));
- MOCK_METHOD(bool, Process, (Bar elem, int count), (override));
-};
-```
-
-To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock,
-which warns on all uninteresting calls, or a "strict" mock, which treats them as
-failures:
-
-```cpp
-using ::testing::NiceMock;
-using ::testing::NaggyMock;
-using ::testing::StrictMock;
-
-NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo.
-NaggyMock<MockFoo> naggy_foo; // The type is a subclass of MockFoo.
-StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
-```
-
-**Note:** A mock object is currently naggy by default. We may make it nice by
-default in the future.
-
-#### Mocking a Class Template {#MockTemplate}
-
-Class templates can be mocked just like any class.
-
-To mock
-
-```cpp
-template <typename Elem>
-class StackInterface {
- ...
- virtual ~StackInterface();
- virtual int GetSize() const = 0;
- virtual void Push(const Elem& x) = 0;
-};
-```
-
-(note that all member functions that are mocked, including `~StackInterface()`
-**must** be virtual).
-
-```cpp
-template <typename Elem>
-class MockStack : public StackInterface<Elem> {
- ...
- MOCK_METHOD(int, GetSize, (), (const, override));
- MOCK_METHOD(void, Push, (const Elem& x), (override));
-};
-```
-
-#### Specifying Calling Conventions for Mock Functions
-
-If your mock function doesn't use the default calling convention, you can
-specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter.
-For example,
-
-```cpp
- MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE)));
- MOCK_METHOD(int, Bar, (double x, double y),
- (const, Calltype(STDMETHODCALLTYPE)));
-```
-
-where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
-
-### Using Mocks in Tests {#UsingMocks}
-
-The typical work flow is:
-
-1. Import the gMock names you need to use. All gMock symbols are in the
- `testing` namespace unless they are macros or otherwise noted.
-2. Create the mock objects.
-3. Optionally, set the default actions of the mock objects.
-4. Set your expectations on the mock objects (How will they be called? What
- will they do?).
-5. Exercise code that uses the mock objects; if necessary, check the result
- using googletest assertions.
-6. When a mock object is destructed, gMock automatically verifies that all
- expectations on it have been satisfied.
-
-Here's an example:
-
-```cpp
-using ::testing::Return; // #1
-
-TEST(BarTest, DoesThis) {
- MockFoo foo; // #2
-
- ON_CALL(foo, GetSize()) // #3
- .WillByDefault(Return(1));
- // ... other default actions ...
-
- EXPECT_CALL(foo, Describe(5)) // #4
- .Times(3)
- .WillRepeatedly(Return("Category 5"));
- // ... other expectations ...
-
- EXPECT_EQ("good", MyProductionFunction(&foo)); // #5
-} // #6
-```
-
-### Setting Default Actions {#OnCall}
-
-gMock has a **built-in default action** for any function that returns `void`,
-`bool`, a numeric value, or a pointer. In C++11, it will additionally returns
-the default-constructed value, if one exists for the given type.
-
-To customize the default action for functions with return type *`T`*:
-
-```cpp
-using ::testing::DefaultValue;
-
-// Sets the default value to be returned. T must be CopyConstructible.
-DefaultValue<T>::Set(value);
-// Sets a factory. Will be invoked on demand. T must be MoveConstructible.
-// T MakeT();
-DefaultValue<T>::SetFactory(&MakeT);
-// ... use the mocks ...
-// Resets the default value.
-DefaultValue<T>::Clear();
-```
-
-Example usage:
-
-```cpp
- // Sets the default action for return type std::unique_ptr<Buzz> to
- // creating a new Buzz every time.
- DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
- [] { return MakeUnique<Buzz>(AccessLevel::kInternal); });
-
- // When this fires, the default action of MakeBuzz() will run, which
- // will return a new Buzz object.
- EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
-
- auto buzz1 = mock_buzzer_.MakeBuzz("hello");
- auto buzz2 = mock_buzzer_.MakeBuzz("hello");
- EXPECT_NE(nullptr, buzz1);
- EXPECT_NE(nullptr, buzz2);
- EXPECT_NE(buzz1, buzz2);
-
- // Resets the default action for return type std::unique_ptr<Buzz>,
- // to avoid interfere with other tests.
- DefaultValue<std::unique_ptr<Buzz>>::Clear();
-```
-
-To customize the default action for a particular method of a specific mock
-object, use `ON_CALL()`. `ON_CALL()` has a similar syntax to `EXPECT_CALL()`,
-but it is used for setting default behaviors (when you do not require that the
-mock method is called). See [here](cook_book.md#UseOnCall) for a more detailed
-discussion.
-
-```cpp
-ON_CALL(mock-object, method(matchers))
- .With(multi-argument-matcher) ?
- .WillByDefault(action);
-```
-
-### Setting Expectations {#ExpectCall}
-
-`EXPECT_CALL()` sets **expectations** on a mock method (How will it be called?
-What will it do?):
-
-```cpp
-EXPECT_CALL(mock-object, method (matchers)?)
- .With(multi-argument-matcher) ?
- .Times(cardinality) ?
- .InSequence(sequences) *
- .After(expectations) *
- .WillOnce(action) *
- .WillRepeatedly(action) ?
- .RetiresOnSaturation(); ?
-```
-
-For each item above, `?` means it can be used at most once, while `*` means it
-can be used any number of times.
-
-In order to pass, `EXPECT_CALL` must be used before the calls are actually made.
-
-The `(matchers)` is a comma-separated list of matchers that correspond to each
-of the arguments of `method`, and sets the expectation only for calls of
-`method` that matches all of the matchers.
-
-If `(matchers)` is omitted, the expectation is the same as if the matchers were
-set to anything matchers (for example, `(_, _, _, _)` for a four-arg method).
-
-If `Times()` is omitted, the cardinality is assumed to be:
-
-* `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`;
-* `Times(n)` when there are `n` `WillOnce()`s but no `WillRepeatedly()`, where
- `n` >= 1; or
-* `Times(AtLeast(n))` when there are `n` `WillOnce()`s and a
- `WillRepeatedly()`, where `n` >= 0.
-
-A method with no `EXPECT_CALL()` is free to be invoked *any number of times*,
-and the default action will be taken each time.
-
-### Matchers {#MatcherList}
-
-<!-- GOOGLETEST_CM0020 DO NOT DELETE -->
-
-A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or
-`EXPECT_CALL()`, or use it to validate a value directly using two macros:
-
-<!-- mdformat off(github rendering does not support multiline tables) -->
-| Macro | Description |
-| :----------------------------------- | :------------------------------------ |
-| `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. |
-<!-- mdformat on -->
-
-Built-in matchers (where `argument` is the function argument, e.g.
-`actual_value` in the example above, or when used in the context of
-`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are
-divided into several categories:
-
-#### Wildcard
-
-Matcher | Description
-:-------------------------- | :-----------------------------------------------
-`_` | `argument` can be any value of the correct type.
-`A<type>()` or `An<type>()` | `argument` can be any value of type `type`.
-
-#### Generic Comparison
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :--------------------- | :-------------------------------------------------- |
-| `Eq(value)` or `value` | `argument == value` |
-| `Ge(value)` | `argument >= value` |
-| `Gt(value)` | `argument > value` |
-| `Le(value)` | `argument <= value` |
-| `Lt(value)` | `argument < value` |
-| `Ne(value)` | `argument != value` |
-| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. |
-| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. |
-| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). |
-| `NotNull()` | `argument` is a non-null pointer (raw or smart). |
-| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. |
-| `VariantWith<T>(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. |
-| `Ref(variable)` | `argument` is a reference to `variable`. |
-| `TypedEq<type>(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. |
-<!-- mdformat on -->
-
-Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or
-destructed later. If the compiler complains that `value` doesn't have a public
-copy constructor, try wrap it in `ByRef()`, e.g.
-`Eq(ByRef(non_copyable_value))`. If you do that, make sure `non_copyable_value`
-is not changed afterwards, or the meaning of your matcher will be changed.
-
-#### Floating-Point Matchers {#FpMatchers}
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :------------------------------- | :--------------------------------- |
-| `DoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. |
-| `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. |
-| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. |
-| `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. |
-<!-- mdformat on -->
-
-The above matchers use ULP-based comparison (the same as used in googletest).
-They automatically pick a reasonable error bound based on the absolute value of
-the expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard,
-which requires comparing two NaNs for equality to return false. The
-`NanSensitive*` version instead treats two NaNs as equal, which is often what a
-user wants.
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :------------------------------------------------ | :----------------------- |
-| `DoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |
-| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |
-| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. |
-| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. |
-<!-- mdformat on -->
-
-#### String Matchers
-
-The `argument` can be either a C string or a C++ string object:
-
-<!-- mdformat off(no multiline tables) -->
-| 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. |
-| `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`. |
-<!-- mdformat on -->
-
-`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
-use the regular expression syntax defined
-[here](../../googletest/docs/advanced.md#regular-expression-syntax).
-`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide strings as
-well.
-
-#### Container Matchers
-
-Most STL-style containers support `==`, so you can use `Eq(expected_container)`
-or simply `expected_container` to match a container exactly. If you want to
-write the elements in-line, match them more flexibly, or get more informative
-messages, you can use:
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :---------------------------------------- | :------------------------------- |
-| `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. |
-| `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. |
-| `IsEmpty()` | `argument` is an empty container (`container.empty()`). |
-| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. |
-| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. |
-| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. |
-| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. |
-| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. |
-| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
-| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. |
-| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. |
-| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. |
-<!-- mdformat on -->
-
-**Notes:**
-
-* These matchers can also match:
- 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`),
- and
- 2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer,
- int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)).
-* The array being matched may be multi-dimensional (i.e. its elements can be
- arrays).
-* `m` in `Pointwise(m, ...)` should be a matcher for `::std::tuple<T, U>`
- where `T` and `U` are the element type of the actual container and the
- expected container, respectively. For example, to compare two `Foo`
- containers where `Foo` doesn't support `operator==`, one might write:
-
- ```cpp
- using ::std::get;
- MATCHER(FooEq, "") {
- return std::get<0>(arg).Equals(std::get<1>(arg));
- }
- ...
- EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));
- ```
-
-#### Member Matchers
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :------------------------------ | :----------------------------------------- |
-| `Field(&class::field, m)` | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. |
-| `Key(e)` | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. |
-| `Pair(m1, m2)` | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. |
-| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. |
-<!-- mdformat on -->
-
-#### Matching the Result of a Function, Functor, or Callback
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :--------------- | :------------------------------------------------ |
-| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. |
-<!-- mdformat on -->
-
-#### Pointer Matchers
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :------------------------ | :---------------------------------------------- |
-| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. |
-| `WhenDynamicCastTo<T>(m)` | when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`. |
-<!-- mdformat on -->
-
-<!-- GOOGLETEST_CM0026 DO NOT DELETE -->
-
-<!-- GOOGLETEST_CM0027 DO NOT DELETE -->
-
-#### Multi-argument Matchers {#MultiArgMatchers}
-
-Technically, all matchers match a *single* value. A "multi-argument" matcher is
-just one that matches a *tuple*. The following matchers can be used to match a
-tuple `(x, y)`:
-
-Matcher | Description
-:------ | :----------
-`Eq()` | `x == y`
-`Ge()` | `x >= y`
-`Gt()` | `x > y`
-`Le()` | `x <= y`
-`Lt()` | `x < y`
-`Ne()` | `x != y`
-
-You can use the following selectors to pick a subset of the arguments (or
-reorder them) to participate in the matching:
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :------------------------- | :---------------------------------------------- |
-| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. |
-| `Args<N1, N2, ..., Nk>(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. |
-<!-- mdformat on -->
-
-#### Composite Matchers
-
-You can make a matcher from one or more other matchers:
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :------------------------------- | :-------------------------------------- |
-| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. |
-| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
-| `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`. |
-<!-- mdformat on -->
-
-<!-- GOOGLETEST_CM0028 DO NOT DELETE -->
-
-#### Adapters for Matchers
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :---------------------- | :------------------------------------ |
-| `MatcherCast<T>(m)` | casts matcher `m` to type `Matcher<T>`. |
-| `SafeMatcherCast<T>(m)` | [safely casts](cook_book.md#casting-matchers) matcher `m` to type `Matcher<T>`. |
-| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. |
-<!-- mdformat on -->
-
-`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`,
-which must be a permanent callback.
-
-#### Using Matchers as Predicates {#MatchersAsPredicatesCheat}
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :---------------------------- | :------------------------------------------ |
-| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. |
-| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. |
-| `Value(value, m)` | evaluates to `true` if `value` matches `m`. |
-<!-- mdformat on -->
-
-#### Defining Matchers
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | 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 macher `IsDivisibleBy(n)` to match a number divisible by `n`. |
-| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |
-<!-- mdformat on -->
-
-**Notes:**
-
-1. The `MATCHER*` macros cannot be used inside a function or class.
-2. The matcher body must be *purely functional* (i.e. it cannot have any side
- effect, and the result must not depend on anything other than the value
- being matched and the matcher parameters).
-3. You can use `PrintToString(x)` to convert a value `x` of any type to a
- string.
-
-### Actions {#ActionList}
-
-**Actions** specify what a mock function should do when invoked.
-
-#### Returning a Value
-
-<!-- mdformat off(no multiline tables) -->
-| | |
-| :-------------------------- | :-------------------------------------------- |
-| `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. |
-| `ReturnArg<N>()` | Return the `N`-th (0-based) argument. |
-| `ReturnNew<T>(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. |
-| `ReturnNull()` | Return a null pointer. |
-| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. |
-| `ReturnRef(variable)` | Return a reference to `variable`. |
-| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. |
-<!-- mdformat on -->
-
-#### Side Effects
-
-<!-- mdformat off(no multiline tables) -->
-| | |
-| :--------------------------------- | :-------------------------------------- |
-| `Assign(&variable, value)` | Assign `value` to variable. |
-| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. |
-| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. |
-| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
-| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. |
-| `SetArgPointee<N>(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. |
-| `SetArgumentPointee<N>(value)` | Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0. |
-| `SetArrayArgument<N>(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. |
-| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. |
-| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. |
-<!-- mdformat on -->
-
-#### Using a Function, Functor, or Lambda as an Action
-
-In the following, by "callable" we mean a free function, `std::function`,
-functor, or lambda.
-
-<!-- mdformat off(no multiline tables) -->
-| | |
-| :---------------------------------- | :------------------------------------- |
-| `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. |
-| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. |
-| `InvokeArgument<N>(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. |
-<!-- mdformat on -->
-
-The return value of the invoked function is used as the return value of the
-action.
-
-When defining a callable to be used with `Invoke*()`, you can declare any unused
-parameters as `Unused`:
-
-```cpp
-using ::testing::Invoke;
-double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
-...
-EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
-```
-
-`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of
-`callback`, which must be permanent. The type of `callback` must be a base
-callback type instead of a derived one, e.g.
-
-```cpp
- BlockingClosure* done = new BlockingClosure;
- ... Invoke(done) ...; // This won't compile!
-
- Closure* done2 = new BlockingClosure;
- ... Invoke(done2) ...; // This works.
-```
-
-In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference,
-wrap it inside `ByRef()`. For example,
-
-```cpp
-using ::testing::ByRef;
-using ::testing::InvokeArgument;
-...
-InvokeArgument<2>(5, string("Hi"), ByRef(foo))
-```
-
-calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by
-value, and `foo` by reference.
-
-#### Default Action
-
-<!-- mdformat off(no multiline tables) -->
-| Matcher | Description |
-| :------------ | :----------------------------------------------------- |
-| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). |
-<!-- mdformat on -->
-
-**Note:** due to technical reasons, `DoDefault()` cannot be used inside a
-composite action - trying to do so will result in a run-time error.
-
-<!-- GOOGLETEST_CM0032 DO NOT DELETE -->
-
-#### Composite Actions
-
-<!-- mdformat off(no multiline tables) -->
-| | |
-| :----------------------------- | :------------------------------------------ |
-| `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. |
-| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. |
-| `WithArg<N>(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. |
-| `WithArgs<N1, N2, ..., Nk>(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. |
-| `WithoutArgs(a)` | Perform action `a` without any arguments. |
-<!-- mdformat on -->
-
-#### Defining Actions
-
-<table border="1" cellspacing="0" cellpadding="1">
- <tr>
- <td>`struct SumAction {` <br>
- &emsp;`template <typename T>` <br>
- &emsp;`T operator()(T x, Ty) { return x + y; }` <br>
- `};`
- </td>
- <td> Defines a generic functor that can be used as an action summing its
- arguments. </td> </tr>
- <tr>
- </tr>
-</table>
-
-<!-- mdformat off(no multiline tables) -->
-| | |
-| :--------------------------------- | :-------------------------------------- |
-| `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`. |
-| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. |
-<!-- mdformat on -->
-
-The `ACTION*` macros cannot be used inside a function or class.
-
-### Cardinalities {#CardinalityList}
-
-These are used in `Times()` to specify how many times a mock function will be
-called:
-
-<!-- mdformat off(no multiline tables) -->
-| | |
-| :---------------- | :----------------------------------------------------- |
-| `AnyNumber()` | The function can be called any number of times. |
-| `AtLeast(n)` | The call is expected at least `n` times. |
-| `AtMost(n)` | The call is expected at most `n` times. |
-| `Between(m, n)` | The call is expected between `m` and `n` (inclusive) times. |
-| `Exactly(n) or n` | The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0. |
-<!-- mdformat on -->
-
-### Expectation Order
-
-By default, the expectations can be matched in *any* order. If some or all
-expectations must be matched in a given order, there are two ways to specify it.
-They can be used either independently or together.
-
-#### The After Clause {#AfterClause}
-
-```cpp
-using ::testing::Expectation;
-...
-Expectation init_x = EXPECT_CALL(foo, InitX());
-Expectation init_y = EXPECT_CALL(foo, InitY());
-EXPECT_CALL(foo, Bar())
- .After(init_x, init_y);
-```
-
-says that `Bar()` can be called only after both `InitX()` and `InitY()` have
-been called.
-
-If you don't know how many pre-requisites an expectation has when you write it,
-you can use an `ExpectationSet` to collect them:
-
-```cpp
-using ::testing::ExpectationSet;
-...
-ExpectationSet all_inits;
-for (int i = 0; i < element_count; i++) {
- all_inits += EXPECT_CALL(foo, InitElement(i));
-}
-EXPECT_CALL(foo, Bar())
- .After(all_inits);
-```
-
-says that `Bar()` can be called only after all elements have been initialized
-(but we don't care about which elements get initialized before the others).
-
-Modifying an `ExpectationSet` after using it in an `.After()` doesn't affect the
-meaning of the `.After()`.
-
-#### Sequences {#UsingSequences}
-
-When you have a long chain of sequential expectations, it's easier to specify
-the order using **sequences**, which don't require you to given each expectation
-in the chain a different name. *All expected calls* in the same sequence must
-occur in the order they are specified.
-
-```cpp
-using ::testing::Return;
-using ::testing::Sequence;
-Sequence s1, s2;
-...
-EXPECT_CALL(foo, Reset())
- .InSequence(s1, s2)
- .WillOnce(Return(true));
-EXPECT_CALL(foo, GetSize())
- .InSequence(s1)
- .WillOnce(Return(1));
-EXPECT_CALL(foo, Describe(A<const char*>()))
- .InSequence(s2)
- .WillOnce(Return("dummy"));
-```
-
-says that `Reset()` must be called before *both* `GetSize()` *and* `Describe()`,
-and the latter two can occur in any order.
-
-To put many expectations in a sequence conveniently:
-
-```cpp
-using ::testing::InSequence;
-{
- InSequence seq;
-
- EXPECT_CALL(...)...;
- EXPECT_CALL(...)...;
- ...
- EXPECT_CALL(...)...;
-}
-```
-
-says that all expected calls in the scope of `seq` must occur in strict order.
-The name `seq` is irrelevant.
-
-### Verifying and Resetting a Mock
-
-gMock will verify the expectations on a mock object when it is destructed, or
-you can do it earlier:
-
-```cpp
-using ::testing::Mock;
-...
-// Verifies and removes the expectations on mock_obj;
-// returns true if and only if successful.
-Mock::VerifyAndClearExpectations(&mock_obj);
-...
-// Verifies and removes the expectations on mock_obj;
-// also removes the default actions set by ON_CALL();
-// returns true if and only if successful.
-Mock::VerifyAndClear(&mock_obj);
-```
-
-You can also tell gMock that a mock object can be leaked and doesn't need to be
-verified:
-
-```cpp
-Mock::AllowLeak(&mock_obj);
-```
-
-### Mock Classes
-
-gMock defines a convenient mock class template
-
-```cpp
-class MockFunction<R(A1, ..., An)> {
- public:
- MOCK_METHOD(R, Call, (A1, ..., An));
-};
-```
-
-See this [recipe](cook_book.md#using-check-points) for one application of it.
-
-### Flags
-
-<!-- mdformat off(no multiline tables) -->
-| Flag | Description |
-| :----------------------------- | :---------------------------------------- |
-| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
-| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
-<!-- mdformat on -->
diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h
index f12d39be06a7..bd9ba73ee634 100644
--- a/googlemock/include/gmock/gmock-actions.h
+++ b/googlemock/include/gmock/gmock-actions.h
@@ -27,34 +27,126 @@
// (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 actions.
+// The ACTION* family of macros can be used in a namespace scope to
+// define custom actions easily. The syntax:
+//
+// ACTION(name) { statements; }
+//
+// will define an action with the given name that executes the
+// statements. The value returned by the statements will be used as
+// the return value of the action. Inside the statements, you can
+// refer to the K-th (0-based) argument of the mock function by
+// 'argK', and refer to its type by 'argK_type'. For example:
+//
+// ACTION(IncrementArg1) {
+// arg1_type temp = arg1;
+// return ++(*temp);
+// }
+//
+// allows you to write
+//
+// ...WillOnce(IncrementArg1());
+//
+// You can also refer to the entire argument tuple and its type by
+// 'args' and 'args_type', and refer to the mock function type and its
+// return type by 'function_type' and 'return_type'.
+//
+// Note that you don't need to specify the types of the mock function
+// arguments. However rest assured that your code is still type-safe:
+// you'll get a compiler error if *arg1 doesn't support the ++
+// operator, or if the type of ++(*arg1) isn't compatible with the
+// mock function's return type, for example.
+//
+// Sometimes you'll want to parameterize the action. For that you can use
+// another macro:
+//
+// ACTION_P(name, param_name) { statements; }
+//
+// For example:
+//
+// ACTION_P(Add, n) { return arg0 + n; }
+//
+// will allow you to write:
+//
+// ...WillOnce(Add(5));
+//
+// Note that you don't need to provide the type of the parameter
+// either. If you need to reference the type of a parameter named
+// 'foo', you can write 'foo_type'. For example, in the body of
+// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
+// of 'n'.
+//
+// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
+// multi-parameter actions.
+//
+// For the purpose of typing, you can view
+//
+// ACTION_Pk(Foo, p1, ..., pk) { ... }
+//
+// as shorthand for
+//
+// template <typename p1_type, ..., typename pk_type>
+// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
+//
+// In particular, you can provide the template type arguments
+// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
+// although usually you can rely on the compiler to infer the types
+// for you automatically. You can assign the result of expression
+// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
+// pk_type>. This can be useful when composing actions.
+//
+// You can also overload actions with different numbers of parameters:
+//
+// ACTION_P(Plus, a) { ... }
+// ACTION_P2(Plus, a, b) { ... }
+//
+// While it's tempting to always use the ACTION* macros when defining
+// a new action, you should also consider implementing ActionInterface
+// or using MakePolymorphicAction() instead, especially if you need to
+// use the action a lot. While these approaches require more work,
+// they give you more control on the types of the mock function
+// arguments and the action parameters, which in general leads to
+// better compiler error messages that pay off in the long run. They
+// also allow overloading actions based on parameter types (as opposed
+// to just based on the number of parameters).
+//
+// CAVEAT:
+//
+// ACTION*() can only be used in a namespace scope as templates cannot be
+// declared inside of a local class.
+// Users can, however, define any local functors (e.g. a lambda) that
+// can be used as actions.
+//
+// MORE INFORMATION:
+//
+// To learn more about using these macros, please search for 'ACTION' on
+// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
+#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 <functional>
#include <memory>
#include <string>
+#include <tuple>
#include <type_traits>
#include <utility>
#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h"
+#include "gmock/internal/gmock-pp.h"
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
namespace testing {
@@ -101,9 +193,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<
@@ -132,11 +222,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
@@ -160,17 +250,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_(UInt64, 0);
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 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 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_
+// 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;
@@ -229,7 +611,7 @@ class DefaultValue {
private:
class ValueProducer {
public:
- virtual ~ValueProducer() {}
+ virtual ~ValueProducer() = default;
virtual T Produce() = 0;
};
@@ -240,7 +622,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 {
@@ -251,7 +634,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_;
@@ -315,8 +699,8 @@ class ActionInterface {
typedef typename internal::Function<F>::Result Result;
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
- ActionInterface() {}
- virtual ~ActionInterface() {}
+ ActionInterface() = default;
+ virtual ~ActionInterface() = default;
// Performs the action. This method is not const, as in general an
// action can have side effects and be stateful. For example, a
@@ -325,46 +709,59 @@ 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)...));
}
};
+ template <typename G>
+ using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;
+
public:
typedef typename internal::Function<F>::Result Result;
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
// Constructs a null Action. Needed for storing Action objects in
// STL containers.
- Action() {}
+ Action() = default;
// Construct an Action from a specified callable.
// This cannot take std::function directly, because then Action would not be
// directly constructible from lambda (it would require two conversions).
- template <typename G,
- typename = typename ::std::enable_if<
- ::std::is_constructible<::std::function<F>, G>::value>::type>
- Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
+ template <
+ typename G,
+ typename = typename std::enable_if<internal::disjunction<
+ IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,
+ G>>::value>::type>
+ Action(G&& fun) { // NOLINT
+ Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());
+ }
// Constructs an Action from its implementation.
explicit Action(ActionInterface<F>* impl)
@@ -374,7 +771,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; }
@@ -392,10 +790,48 @@ 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;
+ template <typename G>
+ void Init(G&& g, ::std::true_type) {
+ fun_ = ::std::forward<G>(g);
+ }
+
+ template <typename G>
+ void Init(G&& g, ::std::false_type) {
+ fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};
+ }
+
+ template <typename FunctionImpl>
+ struct IgnoreArgs {
+ template <typename... InArgs>
+ Result operator()(const InArgs&...) const {
+ return function_impl();
+ }
+
+ FunctionImpl function_impl;
+ };
+
// fun_ is an empty function if and only if this is the DoDefault() action.
::std::function<F> fun_;
};
@@ -446,13 +882,9 @@ class PolymorphicAction {
private:
Impl impl_;
-
- GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
};
Impl impl_;
-
- GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
};
// Creates an Action from its implementation and returns it. The
@@ -484,122 +916,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_;
+};
- explicit Impl(const std::shared_ptr<R>& wrapper)
- : performed_(false), wrapper_(wrapper) {}
+// 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))) {}
- Result Perform(const ArgumentTuple&) override {
- GTEST_CHECK_(!performed_)
- << "A ByMove() action should only be performed once.";
- performed_ = true;
- return std::move(wrapper_->payload);
- }
+ T operator()() const {
+ GTEST_CHECK_(!state_->called)
+ << "A ByMove() action must be performed at most once.";
- private:
- bool performed_;
- const std::shared_ptr<R> wrapper_;
+ state_->called = true;
+ return std::move(state_->value);
+ }
- GTEST_DISALLOW_ASSIGN_(Impl);
- };
+ 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)) {}
- const std::shared_ptr<R> value_;
+ T value;
+ bool called = false;
+ };
- GTEST_DISALLOW_ASSIGN_(ReturnAction);
+ const std::shared_ptr<State> state_;
};
// Implements the ReturnNull() action.
@@ -641,8 +1149,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_));
}
@@ -660,13 +1168,9 @@ class ReturnRefAction {
private:
T& ref_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
T& ref_;
-
- GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
};
// Implements the polymorphic ReturnRefOfCopy(x) action, which can be
@@ -687,9 +1191,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_));
}
@@ -707,13 +1210,39 @@ class ReturnRefOfCopyAction {
private:
T value_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const T value_;
+};
- GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
+// Implements the polymorphic ReturnRoundRobin(v) action, which can be
+// used in any function that returns the element_type of v.
+template <typename T>
+class ReturnRoundRobinAction {
+ public:
+ explicit ReturnRoundRobinAction(std::vector<T> values) {
+ GTEST_CHECK_(!values.empty())
+ << "ReturnRoundRobin requires at least one element.";
+ state_->values = std::move(values);
+ }
+
+ template <typename... Args>
+ T operator()(Args&&...) const {
+ return state_->Next();
+ }
+
+ private:
+ struct State {
+ T Next() {
+ T ret_val = values[i++];
+ if (i == values.size()) i = 0;
+ return ret_val;
+ }
+
+ std::vector<T> values;
+ size_t i = 0;
+ };
+ std::shared_ptr<State> state_ = std::make_shared<State>();
};
// Implements the polymorphic DoDefault() action.
@@ -722,7 +1251,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
@@ -740,11 +1271,9 @@ class AssignAction {
private:
T1* const ptr_;
const T2 value_;
-
- GTEST_DISALLOW_ASSIGN_(AssignAction);
};
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
// Implements the SetErrnoAndReturn action to simulate return from
// various system calls and libc functions.
@@ -752,8 +1281,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_;
@@ -763,8 +1291,6 @@ class SetErrnoAndReturnAction {
private:
const int errno_;
const T result_;
-
- GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
};
#endif // !GTEST_OS_WINDOWS_MOBILE
@@ -816,7 +1342,8 @@ struct InvokeMethodWithoutArgsAction {
Class* const obj_ptr;
const MethodPtr method_ptr;
- using ReturnType = typename std::result_of<MethodPtr(Class*)>::type;
+ using ReturnType =
+ decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());
template <typename... Args>
ReturnType operator()(const Args&...) const {
@@ -865,66 +1392,356 @@ 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_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const A action_;
-
- GTEST_DISALLOW_ASSIGN_(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.
+ // TupleElement is also an MSVC workaround.
+ // See its definition for details.
+ OnceAction<R(internal::TupleElement<
+ I, std::tuple<Args...>>...)>>::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.
+ // TupleElement is also an MSVC workaround.
+ // See its definition for details.
+ Action<R(internal::TupleElement<
+ I, std::tuple<Args...>>...)>>::value,
+ int>::type = 0>
operator Action<R(Args...)>() const { // NOLINT
- Action<R(typename std::tuple_element<I, std::tuple<Args...>>::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:
- template <typename... Args, size_t... I>
- std::vector<Action<void(Args...)>> Convert(IndexSequence<I...>) const {
- return {std::get<I>(actions)...};
+class DoAllAction;
+
+// Base case: only a single action.
+template <typename FinalAction>
+class DoAllAction<FinalAction> {
+ public:
+ struct UserConstructorTag {};
+
+ template <typename T>
+ 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 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(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(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<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>
+struct ReturnNewAction {
+ T* operator()() const {
+ return internal::Apply(
+ [](const Params&... unpacked_params) {
+ return new T(unpacked_params...);
+ },
+ params);
+ }
+ std::tuple<Params...> params;
+};
+
+template <size_t k>
+struct ReturnArgAction {
+ 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)...));
+ }
+};
+
+template <size_t k, typename Ptr>
+struct SaveArgAction {
+ Ptr pointer;
+
+ template <typename... Args>
+ void operator()(const Args&... args) const {
+ *pointer = std::get<k>(std::tie(args...));
+ }
+};
+
+template <size_t k, typename Ptr>
+struct SaveArgPointeeAction {
+ Ptr pointer;
+
+ template <typename... Args>
+ void operator()(const Args&... args) const {
+ *pointer = *std::get<k>(std::tie(args...));
+ }
+};
+
+template <size_t k, typename T>
+struct SetArgRefereeAction {
+ T value;
+
+ template <typename... Args>
+ void operator()(Args&&... args) const {
+ using argk_type =
+ typename ::std::tuple_element<k, std::tuple<Args...>>::type;
+ static_assert(std::is_lvalue_reference<argk_type>::value,
+ "Argument must be a reference type.");
+ std::get<k>(std::tie(args...)) = value;
}
};
+template <size_t k, typename I1, typename I2>
+struct SetArrayArgumentAction {
+ I1 first;
+ I2 last;
+
+ template <typename... Args>
+ void operator()(const Args&... args) const {
+ auto value = std::get<k>(std::tie(args...));
+ for (auto it = first; it != last; ++it, (void)++value) {
+ *value = *it;
+ }
+ }
+};
+
+template <size_t k>
+struct DeleteArgAction {
+ template <typename... Args>
+ void operator()(const Args&... args) const {
+ delete std::get<k>(std::tie(args...));
+ }
+};
+
+template <typename Ptr>
+struct ReturnPointeeAction {
+ Ptr pointer;
+ template <typename... Args>
+ auto operator()(const Args&...) const -> decltype(*pointer) {
+ return *pointer;
+ }
+};
+
+#if GTEST_HAS_EXCEPTIONS
+template <typename T>
+struct ThrowAction {
+ T exception;
+ // We use a conversion operator to adapt to any return type.
+ template <typename R, typename... Args>
+ operator Action<R(Args...)>() const { // NOLINT
+ T copy = exception;
+ return [copy](Args...) -> R { throw copy; };
+ }
+};
+#endif // GTEST_HAS_EXCEPTIONS
+
} // namespace internal
// An Unused object can be implicitly constructed from ANY value.
@@ -960,11 +1777,13 @@ struct DoAllAction {
typedef internal::IgnoredValue Unused;
// Creates an action that does actions a1, a2, ..., sequentially in
-// each invocation.
+// each invocation. All but the last action will have a readonly view of the
+// arguments.
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
@@ -973,8 +1792,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)};
}
@@ -993,14 +1812,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));
@@ -1022,6 +1862,10 @@ inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
return internal::ReturnRefAction<R>(x);
}
+// Prevent using ReturnRef on reference to temporary.
+template <typename R, R* = nullptr>
+internal::ReturnRefAction<R> ReturnRef(R&&) = delete;
+
// Creates an action that returns the reference to a copy of the
// argument. The copy is created when the action is constructed and
// lives as long as the action.
@@ -1030,6 +1874,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
@@ -1039,6 +1885,23 @@ internal::ByMoveWrapper<R> ByMove(R x) {
return internal::ByMoveWrapper<R>(std::move(x));
}
+// Creates an action that returns an element of `vals`. Calling this action will
+// repeatedly return the next value from `vals` until it reaches the end and
+// will restart from the beginning.
+template <typename T>
+internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {
+ return internal::ReturnRoundRobinAction<T>(std::move(vals));
+}
+
+// Creates an action that returns an element of `vals`. Calling this action will
+// repeatedly return the next value from `vals` until it reaches the end and
+// will restart from the beginning.
+template <typename T>
+internal::ReturnRoundRobinAction<T> ReturnRoundRobin(
+ std::initializer_list<T> vals) {
+ return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));
+}
+
// Creates an action that does the default action for the give mock function.
inline internal::DoDefaultAction DoDefault() {
return internal::DoDefaultAction();
@@ -1047,28 +1910,28 @@ inline internal::DoDefaultAction DoDefault() {
// Creates an action that sets the variable pointed by the N-th
// (0-based) function argument to 'value'.
template <size_t N, typename T>
-internal::SetArgumentPointeeAction<N, T> SetArgPointee(T x) {
- return {std::move(x)};
+internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {
+ return {std::move(value)};
}
// The following version is DEPRECATED.
template <size_t N, typename T>
-internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T x) {
- return {std::move(x)};
+internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {
+ return {std::move(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));
}
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
// 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));
}
@@ -1132,11 +1995,303 @@ inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
return ::std::reference_wrapper<T>(l_value);
}
-} // namespace testing
+// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
+// instance of type T, constructed on the heap with constructor arguments
+// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
+template <typename T, typename... Params>
+internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
+ Params&&... params) {
+ return {std::forward_as_tuple(std::forward<Params>(params)...)};
+}
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
+// Action ReturnArg<k>() returns the k-th argument of the mock function.
+template <size_t k>
+internal::ReturnArgAction<k> ReturnArg() {
+ return {};
+}
+
+// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
+// mock function to *pointer.
+template <size_t k, typename Ptr>
+internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
+ return {pointer};
+}
+
+// Action SaveArgPointee<k>(pointer) saves the value pointed to
+// by the k-th (0-based) argument of the mock function to *pointer.
+template <size_t k, typename Ptr>
+internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {
+ return {pointer};
+}
+
+// Action SetArgReferee<k>(value) assigns 'value' to the variable
+// referenced by the k-th (0-based) argument of the mock function.
+template <size_t k, typename T>
+internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(
+ T&& value) {
+ return {std::forward<T>(value)};
+}
+
+// Action SetArrayArgument<k>(first, last) copies the elements in
+// source range [first, last) to the array pointed to by the k-th
+// (0-based) argument, which can be either a pointer or an
+// iterator. The action does not take ownership of the elements in the
+// source range.
+template <size_t k, typename I1, typename I2>
+internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,
+ I2 last) {
+ return {first, last};
+}
+
+// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
+// function.
+template <size_t k>
+internal::DeleteArgAction<k> DeleteArg() {
+ return {};
+}
+
+// This action returns the value pointed to by 'pointer'.
+template <typename Ptr>
+internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
+ return {pointer};
+}
+
+// Action Throw(exception) can be used in a mock function of any type
+// to throw the given exception. Any copyable value can be thrown.
+#if GTEST_HAS_EXCEPTIONS
+template <typename T>
+internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {
+ return {std::forward<T>(exception)};
+}
+#endif // GTEST_HAS_EXCEPTIONS
+
+namespace internal {
+
+// A macro from the ACTION* family (defined later in gmock-generated-actions.h)
+// defines an action that can be used in a mock function. Typically,
+// these actions only care about a subset of the arguments of the mock
+// function. For example, if such an action only uses the second
+// argument, it can be used in any mock function that takes >= 2
+// arguments where the type of the second argument is compatible.
+//
+// Therefore, the action implementation must be prepared to take more
+// arguments than it needs. The ExcessiveArg type is used to
+// represent those excessive arguments. In order to keep the compiler
+// error messages tractable, we define it in the testing namespace
+// instead of testing::internal. However, this is an INTERNAL TYPE
+// and subject to change without notice, so a user MUST NOT USE THIS
+// TYPE DIRECTLY.
+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 Impl>
+struct ImplBase {
+ struct Holder {
+ // Allows each copy of the Action<> to get to the Impl.
+ explicit operator const Impl&() const { return *ptr; }
+ std::shared_ptr<Impl> ptr;
+ };
+ using type = typename std::conditional<std::is_constructible<Impl>::value,
+ Impl, Holder>::type;
+};
+
+template <typename R, typename... Args, typename Impl>
+struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
+ using Base = typename ImplBase<Impl>::type;
+ using function_type = R(Args...);
+ 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)} {}
+
+ R operator()(Args&&... arg) const {
+ static constexpr size_t kMaxArgs =
+ sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
+ return Apply(MakeIndexSequence<kMaxArgs>{},
+ MakeIndexSequence<10 - kMaxArgs>{},
+ args_type{std::forward<Args>(arg)...});
+ }
+
+ template <std::size_t... arg_id, std::size_t... excess_id>
+ R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,
+ const args_type& args) const {
+ // Impl need not be specific to the signature of action being implemented;
+ // only the implementing function body needs to have all of the specific
+ // types instantiated. Up to 10 of the args that are provided by the
+ // 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)...);
+ }
+};
+
+// Stores a default-constructed Impl as part of the Action<>'s
+// std::function<>. The Impl should be trivial to copy.
+template <typename F, typename Impl>
+::testing::Action<F> MakeAction() {
+ return ::testing::Action<F>(ActionImpl<F, Impl>());
+}
+
+// Stores just the one given instance of Impl.
+template <typename F, typename Impl>
+::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {
+ return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(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_ \
+ const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
+ GMOCK_INTERNAL_ARG_UNUSED, , 10)
+
+#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
+#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
+ const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
+
+#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
+#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
+ GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
+
+#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
+#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
+
+#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
+#define GMOCK_ACTION_TYPE_PARAMS_(params) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
+
+#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
+ , param##_type gmock_p##i
+#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
+
+#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
+ , std::forward<param##_type>(gmock_p##i)
+#define GMOCK_ACTION_GVALUE_PARAMS_(params) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
+
+#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
+ , param(::std::forward<param##_type>(gmock_p##i))
+#define GMOCK_ACTION_INIT_PARAMS_(params) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
+
+#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
+#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)) 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
+
+// Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.
+#define ACTION(name) \
+ class name##Action { \
+ public: \
+ 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: \
+ 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; \
+ }; \
+ }; \
+ inline name##Action name() GTEST_MUST_USE_RESULT_; \
+ inline name##Action name() { return name##Action(); } \
+ template <typename function_type, typename return_type, typename args_type, \
+ GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
+ return_type name##Action::gmock_Impl::gmock_PerformImpl( \
+ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
+
+#define ACTION_P(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
+
+#define ACTION_P2(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
+
+#define ACTION_P3(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
+
+#define ACTION_P4(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
+
+#define ACTION_P5(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
+
+#define ACTION_P6(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
+
+#define ACTION_P7(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
+
+#define ACTION_P8(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
+
+#define ACTION_P9(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
+
+#define ACTION_P10(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
+
+} // namespace testing
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
diff --git a/googlemock/include/gmock/gmock-cardinalities.h b/googlemock/include/gmock/gmock-cardinalities.h
index 46e01e102d58..533e604f326c 100644
--- a/googlemock/include/gmock/gmock-cardinalities.h
+++ b/googlemock/include/gmock/gmock-cardinalities.h
@@ -27,21 +27,23 @@
// (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 GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
+#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"
@@ -63,7 +65,7 @@ namespace testing {
// The implementation of a cardinality.
class CardinalityInterface {
public:
- virtual ~CardinalityInterface() {}
+ virtual ~CardinalityInterface() = default;
// Conservative estimate on the lower/upper bound of the number of
// calls allowed.
@@ -90,7 +92,7 @@ class GTEST_API_ Cardinality {
public:
// Constructs a null cardinality. Needed for storing Cardinality
// objects in STL containers.
- Cardinality() {}
+ Cardinality() = default;
// Constructs a Cardinality from its implementation.
explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}
@@ -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
@@ -154,4 +156,4 @@ inline Cardinality MakeCardinality(const CardinalityInterface* c) {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
diff --git a/googlemock/include/gmock/gmock-function-mocker.h b/googlemock/include/gmock/gmock-function-mocker.h
index cc1535c806bf..1a1f126e492f 100644
--- a/googlemock/include/gmock/gmock-function-mocker.h
+++ b/googlemock/include/gmock/gmock-function-mocker.h
@@ -31,16 +31,88 @@
//
// This file implements MOCK_METHOD.
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
-#ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
-#define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
-#include "gmock/gmock-generated-function-mockers.h" // NOLINT
+#include <type_traits> // IWYU pragma: keep
+#include <utility> // IWYU pragma: keep
+
+#include "gmock/gmock-spec-builders.h"
+#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-pp.h"
-#define MOCK_METHOD(...) \
- GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__)
+namespace testing {
+namespace internal {
+template <typename T>
+using identity_t = T;
+
+template <typename Pattern>
+struct ThisRefAdjuster {
+ template <typename T>
+ using AdjustT = typename std::conditional<
+ std::is_const<typename std::remove_reference<Pattern>::type>::value,
+ typename std::conditional<std::is_lvalue_reference<Pattern>::value,
+ const T&, const T&&>::type,
+ typename std::conditional<std::is_lvalue_reference<Pattern>::value, T&,
+ T&&>::type>::type;
+
+ template <typename MockType>
+ static AdjustT<MockType> Adjust(const MockType& mock) {
+ return static_cast<AdjustT<MockType>>(const_cast<MockType&>(mock));
+ }
+};
+
+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
+// inside a header file. However, the FunctionMocker class template
+// is meant to be defined in the ::testing namespace. The following
+// line is just a trick for working around a bug in MSVC 8.0, which
+// cannot handle it if we define FunctionMocker in ::testing.
+using internal::FunctionMocker;
+} // namespace testing
+
+#define MOCK_METHOD(...) \
+ GMOCK_INTERNAL_WARNING_PUSH() \
+ GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \
+ GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) \
+ GMOCK_INTERNAL_WARNING_POP()
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
@@ -51,16 +123,18 @@
#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_HAS_NOEXCEPT(_Spec), GMOCK_INTERNAL_GET_CALLTYPE(_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(...) \
@@ -94,20 +168,20 @@
::testing::tuple_size<typename ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == _N, \
"This method does not take " GMOCK_PP_STRINGIZE( \
- _N) " arguments. Parenthesize all types with unproctected commas.")
+ _N) " arguments. Parenthesize all types with unprotected commas.")
#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec)
#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \
- _Override, _Final, _Noexcept, \
- _CallType, _Signature) \
+ _Override, _Final, _NoexceptSpec, \
+ _CallType, _RefSpec, _Signature) \
typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \
_Signature)>::Result \
GMOCK_INTERNAL_EXPAND(_CallType) \
_MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \
- GMOCK_PP_IF(_Constness, const, ) GMOCK_PP_IF(_Noexcept, noexcept, ) \
- GMOCK_PP_IF(_Override, override, ) \
+ GMOCK_PP_IF(_Constness, const, ) \
+ _RefSpec _NoexceptSpec GMOCK_PP_IF(_Override, override, ) \
GMOCK_PP_IF(_Final, final, ) { \
GMOCK_MOCKER_(_N, _Constness, _MethodName) \
.SetOwnerAndName(this, #_MethodName); \
@@ -116,7 +190,7 @@
} \
::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \
- GMOCK_PP_IF(_Constness, const, ) { \
+ GMOCK_PP_IF(_Constness, const, ) _RefSpec { \
GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \
return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
.With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \
@@ -124,19 +198,18 @@
::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
const ::testing::internal::WithoutMatchers&, \
GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \
- GMOCK_PP_REMOVE_PARENS(_Signature)>*) \
- const GMOCK_PP_IF(_Noexcept, noexcept, ) { \
- return GMOCK_PP_CAT(::testing::internal::AdjustConstness_, \
- GMOCK_PP_IF(_Constness, const, ))(this) \
- ->gmock_##_MethodName(GMOCK_PP_REPEAT( \
+ GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \
+ return ::testing::internal::ThisRefAdjuster<GMOCK_PP_IF( \
+ _Constness, const, ) int _RefSpec>::Adjust(*this) \
+ .gmock_##_MethodName(GMOCK_PP_REPEAT( \
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))
@@ -147,22 +220,48 @@
#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \
GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple))
-#define GMOCK_INTERNAL_HAS_NOEXCEPT(_Tuple) \
- GMOCK_PP_HAS_COMMA( \
- GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_NOEXCEPT, ~, _Tuple))
-
-#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_INTERNAL_IS_CALLTYPE(_elem)) == 1, \
- GMOCK_PP_STRINGIZE( \
+#define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \
+ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple)
+
+#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \
+ GMOCK_PP_IF( \
+ 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)
+
+#define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \
+ GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \
+ GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
+
+#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) \
@@ -180,37 +279,43 @@
#define GMOCK_INTERNAL_DETECT_FINAL_I_final ,
-// TODO(iserna): Maybe noexcept should accept an argument here as well.
#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem)
#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept ,
-#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_REF(_i, _, _elem) \
+ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem)
+
+#define GMOCK_INTERNAL_DETECT_REF_I_ref ,
-// 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_UNPACK_ref(x) x
-#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_CAT(GMOCK_PP_IDENTITY, _arg)
+#define GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem) \
+ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CALLTYPE_I_, _elem)
-#define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype
+#define GMOCK_INTERNAL_DETECT_CALLTYPE_I_Calltype ,
-#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \
- GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), GMOCK_PP_REMOVE_PARENS, \
- GMOCK_PP_IDENTITY) \
- (_Ret)(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args))
+#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
+// returning a function pointer must be written as
+//
+// fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...)
+//
+// But we only support placing the return type at the beginning. To handle this,
+// we wrap all calls in identity_t, so that a declaration will be expanded to
+//
+// identity_t<fn_ptr_return_t (*)(fn_ptr_args_t...)> method(method_args_t...)
+//
+// This allows us to work around the syntactic oddities of function/method
+// types.
+#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \
+ ::testing::internal::identity_t<GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), \
+ GMOCK_PP_REMOVE_PARENS, \
+ GMOCK_PP_IDENTITY)(_Ret)>( \
+ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args))
#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \
GMOCK_PP_COMMA_IF(_i) \
@@ -218,36 +323,196 @@
GMOCK_PP_IDENTITY) \
(_elem)
-#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
- GMOCK_PP_COMMA_IF(_i) \
- GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \
- GMOCK_PP_REMOVE_PARENS(_Signature)) \
+#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
+ GMOCK_PP_COMMA_IF(_i) \
+ GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
gmock_a##_i
-#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
- GMOCK_PP_COMMA_IF(_i) \
- ::std::forward<GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \
- GMOCK_PP_REMOVE_PARENS(_Signature))>( \
- gmock_a##_i)
+#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
+ GMOCK_PP_COMMA_IF(_i) \
+ ::std::forward<GMOCK_INTERNAL_ARG_O( \
+ _i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i)
-#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
- GMOCK_PP_COMMA_IF(_i) \
- GMOCK_INTERNAL_MATCHER_O(typename, GMOCK_PP_INC(_i), \
- GMOCK_PP_REMOVE_PARENS(_Signature)) \
+#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
+ GMOCK_PP_COMMA_IF(_i) \
+ GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
gmock_a##_i
#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \
GMOCK_PP_COMMA_IF(_i) \
gmock_a##_i
-#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
- GMOCK_PP_COMMA_IF(_i) \
- ::testing::A<GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \
- GMOCK_PP_REMOVE_PARENS(_Signature))>()
-
-#define GMOCK_INTERNAL_ARG_O(_tn, _i, ...) GMOCK_ARG_(_tn, _i, __VA_ARGS__)
-
-#define GMOCK_INTERNAL_MATCHER_O(_tn, _i, ...) \
- GMOCK_MATCHER_(_tn, _i, __VA_ARGS__)
-
-#endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_
+#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
+ GMOCK_PP_COMMA_IF(_i) \
+ ::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>()
+
+#define GMOCK_INTERNAL_ARG_O(_i, ...) \
+ typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type
+
+#define GMOCK_INTERNAL_MATCHER_O(_i, ...) \
+ const ::testing::Matcher<typename ::testing::internal::Function< \
+ __VA_ARGS__>::template Arg<_i>::type>&
+
+#define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__)
+#define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__)
+#define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__)
+#define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__)
+#define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__)
+#define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__)
+#define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__)
+#define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__)
+#define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__)
+#define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__)
+#define MOCK_METHOD10(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__)
+
+#define MOCK_CONST_METHOD0(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__)
+#define MOCK_CONST_METHOD1(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__)
+#define MOCK_CONST_METHOD2(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__)
+#define MOCK_CONST_METHOD3(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__)
+#define MOCK_CONST_METHOD4(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__)
+#define MOCK_CONST_METHOD5(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__)
+#define MOCK_CONST_METHOD6(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__)
+#define MOCK_CONST_METHOD7(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__)
+#define MOCK_CONST_METHOD8(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__)
+#define MOCK_CONST_METHOD9(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__)
+#define MOCK_CONST_METHOD10(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__)
+
+#define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__)
+#define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__)
+#define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__)
+#define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__)
+#define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__)
+#define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__)
+#define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__)
+#define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__)
+#define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__)
+#define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__)
+#define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__)
+
+#define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__)
+
+#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__)
+#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__)
+#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__)
+#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__)
+#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__)
+#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__)
+#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__)
+#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__)
+#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__)
+#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__)
+#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__)
+
+#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__)
+#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__)
+#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__)
+#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__)
+#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__)
+#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__)
+#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__)
+#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__)
+#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__)
+#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__)
+#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__)
+
+#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+
+#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+
+#define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \
+ GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
+ args_num, ::testing::internal::identity_t<__VA_ARGS__>); \
+ GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
+ args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \
+ (::testing::internal::identity_t<__VA_ARGS__>))
+
+#define GMOCK_MOCKER_(arity, constness, Method) \
+ GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
+
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h
deleted file mode 100644
index 981af78ff9a1..000000000000
--- a/googlemock/include/gmock/gmock-generated-actions.h
+++ /dev/null
@@ -1,1884 +0,0 @@
-// This file was GENERATED by command:
-// pump.py gmock-generated-actions.h.pump
-// DO NOT EDIT BY HAND!!!
-
-// 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 implements some commonly used variadic actions.
-
-// GOOGLETEST_CM0002 DO NOT DELETE
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
-
-#include <memory>
-#include <utility>
-
-#include "gmock/gmock-actions.h"
-#include "gmock/internal/gmock-port.h"
-
-namespace testing {
-namespace internal {
-
-// A macro from the ACTION* family (defined later in this file)
-// defines an action that can be used in a mock function. Typically,
-// these actions only care about a subset of the arguments of the mock
-// function. For example, if such an action only uses the second
-// argument, it can be used in any mock function that takes >= 2
-// arguments where the type of the second argument is compatible.
-//
-// Therefore, the action implementation must be prepared to take more
-// arguments than it needs. The ExcessiveArg type is used to
-// represent those excessive arguments. In order to keep the compiler
-// error messages tractable, we define it in the testing namespace
-// instead of testing::internal. However, this is an INTERNAL TYPE
-// and subject to change without notice, so a user MUST NOT USE THIS
-// TYPE DIRECTLY.
-struct ExcessiveArg {};
-
-// A helper class needed for implementing the ACTION* macros.
-template <typename Result, class Impl>
-class ActionHelper {
- public:
- static Result Perform(Impl* impl, const ::std::tuple<>& args) {
- return impl->template gmock_PerformImpl<>(args, ExcessiveArg(),
- ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
- ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
- ExcessiveArg());
- }
-
- template <typename A0>
- static Result Perform(Impl* impl, const ::std::tuple<A0>& args) {
- return impl->template gmock_PerformImpl<A0>(args, std::get<0>(args),
- ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
- ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
- ExcessiveArg());
- }
-
- template <typename A0, typename A1>
- static Result Perform(Impl* impl, const ::std::tuple<A0, A1>& args) {
- return impl->template gmock_PerformImpl<A0, A1>(args, std::get<0>(args),
- std::get<1>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
- ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
- ExcessiveArg());
- }
-
- template <typename A0, typename A1, typename A2>
- static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2>& args) {
- return impl->template gmock_PerformImpl<A0, A1, A2>(args,
- std::get<0>(args), std::get<1>(args), std::get<2>(args),
- ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
- ExcessiveArg(), ExcessiveArg(), ExcessiveArg());
- }
-
- template <typename A0, typename A1, typename A2, typename A3>
- static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3>& args) {
- return impl->template gmock_PerformImpl<A0, A1, A2, A3>(args,
- std::get<0>(args), std::get<1>(args), std::get<2>(args),
- std::get<3>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
- ExcessiveArg(), ExcessiveArg(), ExcessiveArg());
- }
-
- template <typename A0, typename A1, typename A2, typename A3, typename A4>
- static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3,
- A4>& args) {
- return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4>(args,
- std::get<0>(args), std::get<1>(args), std::get<2>(args),
- std::get<3>(args), std::get<4>(args), ExcessiveArg(), ExcessiveArg(),
- ExcessiveArg(), ExcessiveArg(), ExcessiveArg());
- }
-
- template <typename A0, typename A1, typename A2, typename A3, typename A4,
- typename A5>
- static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3, A4,
- A5>& args) {
- return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5>(args,
- std::get<0>(args), std::get<1>(args), std::get<2>(args),
- std::get<3>(args), std::get<4>(args), std::get<5>(args),
- ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg());
- }
-
- template <typename A0, typename A1, typename A2, typename A3, typename A4,
- typename A5, typename A6>
- static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3, A4, A5,
- A6>& args) {
- return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6>(args,
- std::get<0>(args), std::get<1>(args), std::get<2>(args),
- std::get<3>(args), std::get<4>(args), std::get<5>(args),
- std::get<6>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg());
- }
-
- template <typename A0, typename A1, typename A2, typename A3, typename A4,
- typename A5, typename A6, typename A7>
- static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3, A4, A5,
- A6, A7>& args) {
- return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6,
- A7>(args, std::get<0>(args), std::get<1>(args), std::get<2>(args),
- std::get<3>(args), std::get<4>(args), std::get<5>(args),
- std::get<6>(args), std::get<7>(args), ExcessiveArg(), ExcessiveArg());
- }
-
- template <typename A0, typename A1, typename A2, typename A3, typename A4,
- typename A5, typename A6, typename A7, typename A8>
- static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3, A4, A5,
- A6, A7, A8>& args) {
- return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7,
- A8>(args, std::get<0>(args), std::get<1>(args), std::get<2>(args),
- std::get<3>(args), std::get<4>(args), std::get<5>(args),
- std::get<6>(args), std::get<7>(args), std::get<8>(args),
- ExcessiveArg());
- }
-
- template <typename A0, typename A1, typename A2, typename A3, typename A4,
- typename A5, typename A6, typename A7, typename A8, typename A9>
- static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3, A4, A5,
- A6, A7, A8, A9>& args) {
- return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7, A8,
- A9>(args, std::get<0>(args), std::get<1>(args), std::get<2>(args),
- std::get<3>(args), std::get<4>(args), std::get<5>(args),
- std::get<6>(args), std::get<7>(args), std::get<8>(args),
- std::get<9>(args));
- }
-};
-
-} // namespace internal
-} // namespace testing
-
-// The ACTION* family of macros can be used in a namespace scope to
-// define custom actions easily. The syntax:
-//
-// ACTION(name) { statements; }
-//
-// will define an action with the given name that executes the
-// statements. The value returned by the statements will be used as
-// the return value of the action. Inside the statements, you can
-// refer to the K-th (0-based) argument of the mock function by
-// 'argK', and refer to its type by 'argK_type'. For example:
-//
-// ACTION(IncrementArg1) {
-// arg1_type temp = arg1;
-// return ++(*temp);
-// }
-//
-// allows you to write
-//
-// ...WillOnce(IncrementArg1());
-//
-// You can also refer to the entire argument tuple and its type by
-// 'args' and 'args_type', and refer to the mock function type and its
-// return type by 'function_type' and 'return_type'.
-//
-// Note that you don't need to specify the types of the mock function
-// arguments. However rest assured that your code is still type-safe:
-// you'll get a compiler error if *arg1 doesn't support the ++
-// operator, or if the type of ++(*arg1) isn't compatible with the
-// mock function's return type, for example.
-//
-// Sometimes you'll want to parameterize the action. For that you can use
-// another macro:
-//
-// ACTION_P(name, param_name) { statements; }
-//
-// For example:
-//
-// ACTION_P(Add, n) { return arg0 + n; }
-//
-// will allow you to write:
-//
-// ...WillOnce(Add(5));
-//
-// Note that you don't need to provide the type of the parameter
-// either. If you need to reference the type of a parameter named
-// 'foo', you can write 'foo_type'. For example, in the body of
-// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
-// of 'n'.
-//
-// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
-// multi-parameter actions.
-//
-// For the purpose of typing, you can view
-//
-// ACTION_Pk(Foo, p1, ..., pk) { ... }
-//
-// as shorthand for
-//
-// template <typename p1_type, ..., typename pk_type>
-// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
-//
-// In particular, you can provide the template type arguments
-// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
-// although usually you can rely on the compiler to infer the types
-// for you automatically. You can assign the result of expression
-// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
-// pk_type>. This can be useful when composing actions.
-//
-// You can also overload actions with different numbers of parameters:
-//
-// ACTION_P(Plus, a) { ... }
-// ACTION_P2(Plus, a, b) { ... }
-//
-// While it's tempting to always use the ACTION* macros when defining
-// a new action, you should also consider implementing ActionInterface
-// or using MakePolymorphicAction() instead, especially if you need to
-// use the action a lot. While these approaches require more work,
-// they give you more control on the types of the mock function
-// arguments and the action parameters, which in general leads to
-// better compiler error messages that pay off in the long run. They
-// also allow overloading actions based on parameter types (as opposed
-// to just based on the number of parameters).
-//
-// CAVEAT:
-//
-// ACTION*() can only be used in a namespace scope as templates cannot be
-// declared inside of a local class.
-// Users can, however, define any local functors (e.g. a lambda) that
-// can be used as actions.
-//
-// MORE INFORMATION:
-//
-// To learn more about using these macros, please search for 'ACTION' on
-// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
-
-// An internal macro needed for implementing ACTION*().
-#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\
- const args_type& args GTEST_ATTRIBUTE_UNUSED_, \
- const arg0_type& arg0 GTEST_ATTRIBUTE_UNUSED_, \
- const arg1_type& arg1 GTEST_ATTRIBUTE_UNUSED_, \
- const arg2_type& arg2 GTEST_ATTRIBUTE_UNUSED_, \
- const arg3_type& arg3 GTEST_ATTRIBUTE_UNUSED_, \
- const arg4_type& arg4 GTEST_ATTRIBUTE_UNUSED_, \
- const arg5_type& arg5 GTEST_ATTRIBUTE_UNUSED_, \
- const arg6_type& arg6 GTEST_ATTRIBUTE_UNUSED_, \
- const arg7_type& arg7 GTEST_ATTRIBUTE_UNUSED_, \
- const arg8_type& arg8 GTEST_ATTRIBUTE_UNUSED_, \
- const arg9_type& arg9 GTEST_ATTRIBUTE_UNUSED_
-
-// Sometimes you want to give an action explicit template parameters
-// that cannot be inferred from its value parameters. ACTION() and
-// ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that
-// and can be viewed as an extension to ACTION() and ACTION_P*().
-//
-// The syntax:
-//
-// ACTION_TEMPLATE(ActionName,
-// HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
-// AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
-//
-// defines an action template that takes m explicit template
-// parameters and n value parameters. name_i is the name of the i-th
-// template parameter, and kind_i specifies whether it's a typename,
-// an integral constant, or a template. p_i is the name of the i-th
-// value parameter.
-//
-// Example:
-//
-// // DuplicateArg<k, T>(output) converts the k-th argument of the mock
-// // function to type T and copies it to *output.
-// ACTION_TEMPLATE(DuplicateArg,
-// HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
-// AND_1_VALUE_PARAMS(output)) {
-// *output = T(::std::get<k>(args));
-// }
-// ...
-// int n;
-// EXPECT_CALL(mock, Foo(_, _))
-// .WillOnce(DuplicateArg<1, unsigned char>(&n));
-//
-// To create an instance of an action template, write:
-//
-// ActionName<t1, ..., t_m>(v1, ..., v_n)
-//
-// where the ts are the template arguments and the vs are the value
-// arguments. The value argument types are inferred by the compiler.
-// If you want to explicitly specify the value argument types, you can
-// provide additional template arguments:
-//
-// ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
-//
-// where u_i is the desired type of v_i.
-//
-// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
-// number of value parameters, but not on the number of template
-// parameters. Without the restriction, the meaning of the following
-// is unclear:
-//
-// OverloadedAction<int, bool>(x);
-//
-// Are we using a single-template-parameter action where 'bool' refers
-// to the type of x, or are we using a two-template-parameter action
-// where the compiler is asked to infer the type of x?
-//
-// Implementation notes:
-//
-// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
-// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
-// implementing ACTION_TEMPLATE. The main trick we use is to create
-// new macro invocations when expanding a macro. For example, we have
-//
-// #define ACTION_TEMPLATE(name, template_params, value_params)
-// ... GMOCK_INTERNAL_DECL_##template_params ...
-//
-// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
-// to expand to
-//
-// ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
-//
-// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
-// preprocessor will continue to expand it to
-//
-// ... typename T ...
-//
-// This technique conforms to the C++ standard and is portable. It
-// allows us to implement action templates using O(N) code, where N is
-// the maximum number of template/value parameters supported. Without
-// using it, we'd have to devote O(N^2) amount of code to implement all
-// combinations of m and n.
-
-// 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_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- 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
-#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
-
-// 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_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- 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
-#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
-
-// 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_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
-#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
-#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
-#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
-
-// 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)), \
- 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)), \
- 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)), \
- 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_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)), \
- p9(::std::move(gmock_p9))
-
-// 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_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;
-
-// Lists the value parameters.
-#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0
-#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_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- 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_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- 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
-#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
-#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
-
-// 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_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
-
-// The suffix of the class template implementing the action template.
-#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P
-#define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2
-#define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3
-#define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4
-#define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5
-#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
-#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7, p8) P9
-#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- 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 ACTION_TEMPLATE(name, template_params, value_params)\
- template <GMOCK_INTERNAL_DECL_##template_params\
- GMOCK_INTERNAL_DECL_TYPE_##value_params>\
- class GMOCK_ACTION_CLASS_(name, value_params) {\
- public:\
- explicit GMOCK_ACTION_CLASS_(name, value_params)\
- GMOCK_INTERNAL_INIT_##value_params {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- GMOCK_INTERNAL_DEFN_##value_params\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(\
- new gmock_Impl<F>(GMOCK_INTERNAL_LIST_##value_params));\
- }\
- GMOCK_INTERNAL_DEFN_##value_params\
- private:\
- GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\
- };\
- 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);\
- }\
- template <GMOCK_INTERNAL_DECL_##template_params\
- GMOCK_INTERNAL_DECL_TYPE_##value_params>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- GMOCK_ACTION_CLASS_(name, value_params)<\
- GMOCK_INTERNAL_LIST_##template_params\
- GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl<F>::\
- gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION(name)\
- class name##Action {\
- public:\
- name##Action() {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- gmock_Impl() {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>());\
- }\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##Action);\
- };\
- inline name##Action name() {\
- return name##Action();\
- }\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- name##Action::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P(name, p0)\
- template <typename p0##_type>\
- class name##ActionP {\
- public:\
- explicit name##ActionP(p0##_type gmock_p0) : \
- p0(::std::forward<p0##_type>(gmock_p0)) {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- explicit gmock_Impl(p0##_type gmock_p0) : \
- p0(::std::forward<p0##_type>(gmock_p0)) {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0));\
- }\
- p0##_type p0;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP);\
- };\
- template <typename p0##_type>\
- inline name##ActionP<p0##_type> name(p0##_type p0) {\
- return name##ActionP<p0##_type>(p0);\
- }\
- template <typename p0##_type>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- name##ActionP<p0##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P2(name, p0, p1)\
- template <typename p0##_type, typename p1##_type>\
- class name##ActionP2 {\
- public:\
- name##ActionP2(p0##_type gmock_p0, \
- p1##_type gmock_p1) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)) {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- gmock_Impl(p0##_type gmock_p0, \
- p1##_type gmock_p1) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)) {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP2);\
- };\
- template <typename p0##_type, typename p1##_type>\
- inline name##ActionP2<p0##_type, p1##_type> name(p0##_type p0, \
- p1##_type p1) {\
- return name##ActionP2<p0##_type, p1##_type>(p0, p1);\
- }\
- template <typename p0##_type, typename p1##_type>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- name##ActionP2<p0##_type, p1##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P3(name, p0, p1, p2)\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- class name##ActionP3 {\
- public:\
- name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)) {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)) {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP3);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- inline name##ActionP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \
- p1##_type p1, p2##_type p2) {\
- return name##ActionP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- name##ActionP3<p0##_type, p1##_type, \
- p2##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P4(name, p0, p1, p2, p3)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- class name##ActionP4 {\
- public:\
- name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, \
- p3##_type gmock_p3) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)) {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)) {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP4);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- inline name##ActionP4<p0##_type, p1##_type, p2##_type, \
- p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
- p3##_type p3) {\
- return name##ActionP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, p1, \
- p2, p3);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- name##ActionP4<p0##_type, p1##_type, p2##_type, \
- p3##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P5(name, p0, p1, p2, p3, p4)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- class name##ActionP5 {\
- public:\
- name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, \
- p4##_type gmock_p4) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)) {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, \
- p4##_type gmock_p4) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)) {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP5);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- inline name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
- p4##_type p4) {\
- return name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type>(p0, p1, p2, p3, p4);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P6(name, p0, p1, p2, p3, p4, p5)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- class name##ActionP6 {\
- public:\
- name##ActionP6(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::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)) {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- gmock_Impl(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::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)) {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP6);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- inline name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
- p3##_type p3, p4##_type p4, p5##_type p5) {\
- return name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P7(name, p0, p1, p2, p3, p4, p5, p6)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- class name##ActionP7 {\
- public:\
- name##ActionP7(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::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)) {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- gmock_Impl(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::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)) {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- p6##_type p6;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(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;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP7);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- inline name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \
- p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
- p6##_type p6) {\
- return name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P8(name, p0, p1, p2, p3, p4, p5, p6, p7)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- class name##ActionP8 {\
- public:\
- name##ActionP8(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::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)) {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- gmock_Impl(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::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)) {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- p6##_type p6;\
- p7##_type p7;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(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;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP8);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- inline name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \
- p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
- p6##_type p6, p7##_type p7) {\
- return name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \
- p6, p7);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, \
- p7##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8)\
- template <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>\
- class name##ActionP9 {\
- public:\
- name##ActionP9(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::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)), \
- p8(::std::forward<p8##_type>(gmock_p8)) {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- gmock_Impl(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::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)), \
- p8(::std::forward<p8##_type>(gmock_p8)) {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- 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;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(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;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP9);\
- };\
- template <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>\
- inline name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, \
- p8##_type> name(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) {\
- return name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \
- p3, p4, p5, p6, p7, p8);\
- }\
- template <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>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, p7##_type, \
- p8##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)\
- template <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>\
- class name##ActionP10 {\
- public:\
- name##ActionP10(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::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)), \
- p8(::std::forward<p8##_type>(gmock_p8)), \
- p9(::std::forward<p9##_type>(gmock_p9)) {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- gmock_Impl(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::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)), \
- p8(::std::forward<p8##_type>(gmock_p8)), \
- p9(::std::forward<p9##_type>(gmock_p9)) {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- 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;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(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;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP10);\
- };\
- template <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>\
- inline name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
- p9##_type> name(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) {\
- return name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \
- p1, p2, p3, p4, p5, p6, p7, p8, p9);\
- }\
- template <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>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, p7##_type, p8##_type, \
- p9##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-namespace testing {
-
-
-// The ACTION*() macros trigger warning C4100 (unreferenced formal
-// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
-// the macro definition, as the warnings are generated when the macro
-// is expanded and macro expansion cannot contain #pragma. Therefore
-// we suppress them here.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#endif
-
-// Various overloads for InvokeArgument<N>().
-//
-// The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
-// (0-based) argument, which must be a k-ary callable, of the mock
-// function, with arguments a1, a2, ..., a_k.
-//
-// Notes:
-//
-// 1. The arguments are passed by value by default. If you need to
-// pass an argument by reference, wrap it inside ByRef(). For
-// example,
-//
-// InvokeArgument<1>(5, string("Hello"), ByRef(foo))
-//
-// passes 5 and string("Hello") by value, and passes foo by
-// reference.
-//
-// 2. If the callable takes an argument by reference but ByRef() is
-// not used, it will receive the reference to a copy of the value,
-// instead of the original value. For example, when the 0-th
-// argument of the mock function takes a const string&, the action
-//
-// InvokeArgument<0>(string("Hello"))
-//
-// makes a copy of the temporary string("Hello") object and passes a
-// reference of the copy, instead of the original temporary object,
-// to the callable. This makes it easy for a user to define an
-// InvokeArgument action from temporary values and have it performed
-// later.
-
-namespace internal {
-namespace invoke_argument {
-
-// Appears in InvokeArgumentAdl's argument list to help avoid
-// accidental calls to user functions of the same name.
-struct AdlTag {};
-
-// InvokeArgumentAdl - a helper for InvokeArgument.
-// The basic overloads are provided here for generic functors.
-// Overloads for other custom-callables are provided in the
-// internal/custom/callback-actions.h header.
-
-template <typename R, typename F>
-R InvokeArgumentAdl(AdlTag, F f) {
- return f();
-}
-template <typename R, typename F, typename A1>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1) {
- return f(a1);
-}
-template <typename R, typename F, typename A1, typename A2>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2) {
- return f(a1, a2);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) {
- return f(a1, a2, a3);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) {
- return f(a1, a2, a3, a4);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) {
- return f(a1, a2, a3, a4, a5);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5, typename A6>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) {
- return f(a1, a2, a3, a4, a5, a6);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5, typename A6, typename A7>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
- A7 a7) {
- return f(a1, a2, a3, a4, a5, a6, a7);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5, typename A6, typename A7, typename A8>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
- A7 a7, A8 a8) {
- return f(a1, a2, a3, a4, a5, a6, a7, a8);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5, typename A6, typename A7, typename A8,
- typename A9>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
- A7 a7, A8 a8, A9 a9) {
- return f(a1, a2, a3, a4, a5, a6, a7, a8, a9);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5, typename A6, typename A7, typename A8,
- typename A9, typename A10>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
- A7 a7, A8 a8, A9 a9, A10 a10) {
- return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
-}
-} // namespace invoke_argument
-} // namespace internal
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_0_VALUE_PARAMS()) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args));
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_1_VALUE_PARAMS(p0)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_2_VALUE_PARAMS(p0, p1)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_3_VALUE_PARAMS(p0, p1, p2)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_4_VALUE_PARAMS(p0, p1, p2, p3)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4, p5);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
-}
-
-// Various overloads for ReturnNew<T>().
-//
-// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
-// instance of type T, constructed on the heap with constructor arguments
-// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_0_VALUE_PARAMS()) {
- return new T();
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_1_VALUE_PARAMS(p0)) {
- return new T(p0);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_2_VALUE_PARAMS(p0, p1)) {
- return new T(p0, p1);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_3_VALUE_PARAMS(p0, p1, p2)) {
- return new T(p0, p1, p2);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_4_VALUE_PARAMS(p0, p1, p2, p3)) {
- return new T(p0, p1, p2, p3);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) {
- return new T(p0, p1, p2, p3, p4);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) {
- return new T(p0, p1, p2, p3, p4, p5);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) {
- return new T(p0, p1, p2, p3, p4, p5, p6);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) {
- return new T(p0, p1, p2, p3, p4, p5, p6, p7);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) {
- return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) {
- return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
-}
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-
-} // namespace testing
-
-// Include any custom callback actions added by the local installation.
-// We must include this header at the end to make sure it can use the
-// declarations from this file.
-#include "gmock/internal/custom/gmock-generated-actions.h"
-
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump
deleted file mode 100644
index 209603c5a901..000000000000
--- a/googlemock/include/gmock/gmock-generated-actions.h.pump
+++ /dev/null
@@ -1,627 +0,0 @@
-$$ -*- mode: c++; -*-
-$$ This is a Pump source file. Please use Pump to convert it to
-$$ gmock-generated-actions.h.
-$$
-$var n = 10 $$ The maximum arity we support.
-$$}} This meta comment fixes auto-indentation in editors.
-// 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 implements some commonly used variadic actions.
-
-// GOOGLETEST_CM0002 DO NOT DELETE
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
-
-#include <memory>
-#include <utility>
-
-#include "gmock/gmock-actions.h"
-#include "gmock/internal/gmock-port.h"
-
-namespace testing {
-namespace internal {
-
-// A macro from the ACTION* family (defined later in this file)
-// defines an action that can be used in a mock function. Typically,
-// these actions only care about a subset of the arguments of the mock
-// function. For example, if such an action only uses the second
-// argument, it can be used in any mock function that takes >= 2
-// arguments where the type of the second argument is compatible.
-//
-// Therefore, the action implementation must be prepared to take more
-// arguments than it needs. The ExcessiveArg type is used to
-// represent those excessive arguments. In order to keep the compiler
-// error messages tractable, we define it in the testing namespace
-// instead of testing::internal. However, this is an INTERNAL TYPE
-// and subject to change without notice, so a user MUST NOT USE THIS
-// TYPE DIRECTLY.
-struct ExcessiveArg {};
-
-// A helper class needed for implementing the ACTION* macros.
-template <typename Result, class Impl>
-class ActionHelper {
- public:
-$range i 0..n
-$for i
-
-[[
-$var template = [[$if i==0 [[]] $else [[
-$range j 0..i-1
- template <$for j, [[typename A$j]]>
-]]]]
-$range j 0..i-1
-$var As = [[$for j, [[A$j]]]]
-$var as = [[$for j, [[std::get<$j>(args)]]]]
-$range k 1..n-i
-$var eas = [[$for k, [[ExcessiveArg()]]]]
-$var arg_list = [[$if (i==0) | (i==n) [[$as$eas]] $else [[$as, $eas]]]]
-$template
- static Result Perform(Impl* impl, const ::std::tuple<$As>& args) {
- return impl->template gmock_PerformImpl<$As>(args, $arg_list);
- }
-
-]]
-};
-
-} // namespace internal
-} // namespace testing
-
-// The ACTION* family of macros can be used in a namespace scope to
-// define custom actions easily. The syntax:
-//
-// ACTION(name) { statements; }
-//
-// will define an action with the given name that executes the
-// statements. The value returned by the statements will be used as
-// the return value of the action. Inside the statements, you can
-// refer to the K-th (0-based) argument of the mock function by
-// 'argK', and refer to its type by 'argK_type'. For example:
-//
-// ACTION(IncrementArg1) {
-// arg1_type temp = arg1;
-// return ++(*temp);
-// }
-//
-// allows you to write
-//
-// ...WillOnce(IncrementArg1());
-//
-// You can also refer to the entire argument tuple and its type by
-// 'args' and 'args_type', and refer to the mock function type and its
-// return type by 'function_type' and 'return_type'.
-//
-// Note that you don't need to specify the types of the mock function
-// arguments. However rest assured that your code is still type-safe:
-// you'll get a compiler error if *arg1 doesn't support the ++
-// operator, or if the type of ++(*arg1) isn't compatible with the
-// mock function's return type, for example.
-//
-// Sometimes you'll want to parameterize the action. For that you can use
-// another macro:
-//
-// ACTION_P(name, param_name) { statements; }
-//
-// For example:
-//
-// ACTION_P(Add, n) { return arg0 + n; }
-//
-// will allow you to write:
-//
-// ...WillOnce(Add(5));
-//
-// Note that you don't need to provide the type of the parameter
-// either. If you need to reference the type of a parameter named
-// 'foo', you can write 'foo_type'. For example, in the body of
-// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
-// of 'n'.
-//
-// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P$n to support
-// multi-parameter actions.
-//
-// For the purpose of typing, you can view
-//
-// ACTION_Pk(Foo, p1, ..., pk) { ... }
-//
-// as shorthand for
-//
-// template <typename p1_type, ..., typename pk_type>
-// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
-//
-// In particular, you can provide the template type arguments
-// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
-// although usually you can rely on the compiler to infer the types
-// for you automatically. You can assign the result of expression
-// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
-// pk_type>. This can be useful when composing actions.
-//
-// You can also overload actions with different numbers of parameters:
-//
-// ACTION_P(Plus, a) { ... }
-// ACTION_P2(Plus, a, b) { ... }
-//
-// While it's tempting to always use the ACTION* macros when defining
-// a new action, you should also consider implementing ActionInterface
-// or using MakePolymorphicAction() instead, especially if you need to
-// use the action a lot. While these approaches require more work,
-// they give you more control on the types of the mock function
-// arguments and the action parameters, which in general leads to
-// better compiler error messages that pay off in the long run. They
-// also allow overloading actions based on parameter types (as opposed
-// to just based on the number of parameters).
-//
-// CAVEAT:
-//
-// ACTION*() can only be used in a namespace scope as templates cannot be
-// declared inside of a local class.
-// Users can, however, define any local functors (e.g. a lambda) that
-// can be used as actions.
-//
-// MORE INFORMATION:
-//
-// To learn more about using these macros, please search for 'ACTION' on
-// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
-
-$range i 0..n
-$range k 0..n-1
-
-// An internal macro needed for implementing ACTION*().
-#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\
- const args_type& args GTEST_ATTRIBUTE_UNUSED_
-$for k [[, \
- const arg$k[[]]_type& arg$k GTEST_ATTRIBUTE_UNUSED_]]
-
-
-// Sometimes you want to give an action explicit template parameters
-// that cannot be inferred from its value parameters. ACTION() and
-// ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that
-// and can be viewed as an extension to ACTION() and ACTION_P*().
-//
-// The syntax:
-//
-// ACTION_TEMPLATE(ActionName,
-// HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
-// AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
-//
-// defines an action template that takes m explicit template
-// parameters and n value parameters. name_i is the name of the i-th
-// template parameter, and kind_i specifies whether it's a typename,
-// an integral constant, or a template. p_i is the name of the i-th
-// value parameter.
-//
-// Example:
-//
-// // DuplicateArg<k, T>(output) converts the k-th argument of the mock
-// // function to type T and copies it to *output.
-// ACTION_TEMPLATE(DuplicateArg,
-// HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
-// AND_1_VALUE_PARAMS(output)) {
-// *output = T(::std::get<k>(args));
-// }
-// ...
-// int n;
-// EXPECT_CALL(mock, Foo(_, _))
-// .WillOnce(DuplicateArg<1, unsigned char>(&n));
-//
-// To create an instance of an action template, write:
-//
-// ActionName<t1, ..., t_m>(v1, ..., v_n)
-//
-// where the ts are the template arguments and the vs are the value
-// arguments. The value argument types are inferred by the compiler.
-// If you want to explicitly specify the value argument types, you can
-// provide additional template arguments:
-//
-// ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
-//
-// where u_i is the desired type of v_i.
-//
-// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
-// number of value parameters, but not on the number of template
-// parameters. Without the restriction, the meaning of the following
-// is unclear:
-//
-// OverloadedAction<int, bool>(x);
-//
-// Are we using a single-template-parameter action where 'bool' refers
-// to the type of x, or are we using a two-template-parameter action
-// where the compiler is asked to infer the type of x?
-//
-// Implementation notes:
-//
-// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
-// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
-// implementing ACTION_TEMPLATE. The main trick we use is to create
-// new macro invocations when expanding a macro. For example, we have
-//
-// #define ACTION_TEMPLATE(name, template_params, value_params)
-// ... GMOCK_INTERNAL_DECL_##template_params ...
-//
-// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
-// to expand to
-//
-// ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
-//
-// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
-// preprocessor will continue to expand it to
-//
-// ... typename T ...
-//
-// This technique conforms to the C++ standard and is portable. It
-// allows us to implement action templates using O(N) code, where N is
-// the maximum number of template/value parameters supported. Without
-// using it, we'd have to devote O(N^2) amount of code to implement all
-// combinations of m and n.
-
-// Declares the template parameters.
-
-$range j 1..n
-$for j [[
-$range m 0..j-1
-#define GMOCK_INTERNAL_DECL_HAS_$j[[]]
-_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[kind$m name$m]]
-
-
-]]
-
-// Lists the template parameters.
-
-$for j [[
-$range m 0..j-1
-#define GMOCK_INTERNAL_LIST_HAS_$j[[]]
-_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[name$m]]
-
-
-]]
-
-// Declares the types of value parameters.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_DECL_TYPE_AND_$i[[]]
-_VALUE_PARAMS($for j, [[p$j]]) $for j [[, typename p$j##_type]]
-
-
-]]
-
-// Initializes the value parameters.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_INIT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])\
- ($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(::std::move(gmock_p$j))]]
-
-
-]]
-
-// Declares the fields for storing the value parameters.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_DEFN_AND_$i[[]]
-_VALUE_PARAMS($for j, [[p$j]]) $for j [[p$j##_type p$j; ]]
-
-
-]]
-
-// Lists the value parameters.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_LIST_AND_$i[[]]
-_VALUE_PARAMS($for j, [[p$j]]) $for j, [[p$j]]
-
-
-]]
-
-// Lists the value parameter types.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_LIST_TYPE_AND_$i[[]]
-_VALUE_PARAMS($for j, [[p$j]]) $for j [[, p$j##_type]]
-
-
-]]
-
-// Declares the value parameters.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_DECL_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]]
-$for j, [[p$j##_type p$j]]
-
-
-]]
-
-// The suffix of the class template implementing the action template.
-$for i [[
-
-
-$range j 0..i-1
-#define GMOCK_INTERNAL_COUNT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]]
-$if i==1 [[P]] $elif i>=2 [[P$i]]
-]]
-
-
-// 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)
-
-$range k 0..n-1
-
-#define ACTION_TEMPLATE(name, template_params, value_params)\
- template <GMOCK_INTERNAL_DECL_##template_params\
- GMOCK_INTERNAL_DECL_TYPE_##value_params>\
- class GMOCK_ACTION_CLASS_(name, value_params) {\
- public:\
- explicit GMOCK_ACTION_CLASS_(name, value_params)\
- GMOCK_INTERNAL_INIT_##value_params {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <$for k, [[typename arg$k[[]]_type]]>\
- return_type gmock_PerformImpl(const args_type& args[[]]
-$for k [[, const arg$k[[]]_type& arg$k]]) const;\
- GMOCK_INTERNAL_DEFN_##value_params\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(\
- new gmock_Impl<F>(GMOCK_INTERNAL_LIST_##value_params));\
- }\
- GMOCK_INTERNAL_DEFN_##value_params\
- private:\
- GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\
- };\
- 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);\
- }\
- template <GMOCK_INTERNAL_DECL_##template_params\
- GMOCK_INTERNAL_DECL_TYPE_##value_params>\
- template <typename F>\
- template <typename arg0_type, typename arg1_type, typename arg2_type, \
- typename arg3_type, typename arg4_type, typename arg5_type, \
- typename arg6_type, typename arg7_type, typename arg8_type, \
- typename arg9_type>\
- typename ::testing::internal::Function<F>::Result\
- GMOCK_ACTION_CLASS_(name, value_params)<\
- GMOCK_INTERNAL_LIST_##template_params\
- GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl<F>::\
- gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-$for i
-
-[[
-$var template = [[$if i==0 [[]] $else [[
-$range j 0..i-1
-
- template <$for j, [[typename p$j##_type]]>\
-]]]]
-$var class_name = [[name##Action[[$if i==0 [[]] $elif i==1 [[P]]
- $else [[P$i]]]]]]
-$range j 0..i-1
-$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
-$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
-$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::forward<p$j##_type>(gmock_p$j))]]]]]]
-$var param_field_decls = [[$for j
-[[
-
- p$j##_type p$j;\
-]]]]
-$var param_field_decls2 = [[$for j
-[[
-
- p$j##_type p$j;\
-]]]]
-$var params = [[$for j, [[p$j]]]]
-$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
-$var typename_arg_types = [[$for k, [[typename arg$k[[]]_type]]]]
-$var arg_types_and_names = [[$for k, [[const arg$k[[]]_type& arg$k]]]]
-$var macro_name = [[$if i==0 [[ACTION]] $elif i==1 [[ACTION_P]]
- $else [[ACTION_P$i]]]]
-
-#define $macro_name(name$for j [[, p$j]])\$template
- class $class_name {\
- public:\
- [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {}\
- template <typename F>\
- class gmock_Impl : public ::testing::ActionInterface<F> {\
- public:\
- typedef F function_type;\
- typedef typename ::testing::internal::Function<F>::Result return_type;\
- typedef typename ::testing::internal::Function<F>::ArgumentTuple\
- args_type;\
- [[$if i==1 [[explicit ]]]]gmock_Impl($ctor_param_list)$inits {}\
- virtual return_type Perform(const args_type& args) {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- template <$typename_arg_types>\
- return_type gmock_PerformImpl(const args_type& args, [[]]
-$arg_types_and_names) const;\$param_field_decls
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>($params));\
- }\$param_field_decls2
- private:\
- GTEST_DISALLOW_ASSIGN_($class_name);\
- };\$template
- inline $class_name$param_types name($param_types_and_names) {\
- return $class_name$param_types($params);\
- }\$template
- template <typename F>\
- template <$typename_arg_types>\
- typename ::testing::internal::Function<F>::Result\
- $class_name$param_types::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-]]
-$$ } // This meta comment fixes auto-indentation in Emacs. It won't
-$$ // show up in the generated code.
-
-
-namespace testing {
-
-
-// The ACTION*() macros trigger warning C4100 (unreferenced formal
-// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
-// the macro definition, as the warnings are generated when the macro
-// is expanded and macro expansion cannot contain #pragma. Therefore
-// we suppress them here.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#endif
-
-// Various overloads for InvokeArgument<N>().
-//
-// The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
-// (0-based) argument, which must be a k-ary callable, of the mock
-// function, with arguments a1, a2, ..., a_k.
-//
-// Notes:
-//
-// 1. The arguments are passed by value by default. If you need to
-// pass an argument by reference, wrap it inside ByRef(). For
-// example,
-//
-// InvokeArgument<1>(5, string("Hello"), ByRef(foo))
-//
-// passes 5 and string("Hello") by value, and passes foo by
-// reference.
-//
-// 2. If the callable takes an argument by reference but ByRef() is
-// not used, it will receive the reference to a copy of the value,
-// instead of the original value. For example, when the 0-th
-// argument of the mock function takes a const string&, the action
-//
-// InvokeArgument<0>(string("Hello"))
-//
-// makes a copy of the temporary string("Hello") object and passes a
-// reference of the copy, instead of the original temporary object,
-// to the callable. This makes it easy for a user to define an
-// InvokeArgument action from temporary values and have it performed
-// later.
-
-namespace internal {
-namespace invoke_argument {
-
-// Appears in InvokeArgumentAdl's argument list to help avoid
-// accidental calls to user functions of the same name.
-struct AdlTag {};
-
-// InvokeArgumentAdl - a helper for InvokeArgument.
-// The basic overloads are provided here for generic functors.
-// Overloads for other custom-callables are provided in the
-// internal/custom/callback-actions.h header.
-
-$range i 0..n
-$for i
-[[
-$range j 1..i
-
-template <typename R, typename F[[$for j [[, typename A$j]]]]>
-R InvokeArgumentAdl(AdlTag, F f[[$for j [[, A$j a$j]]]]) {
- return f([[$for j, [[a$j]]]]);
-}
-]]
-
-} // namespace invoke_argument
-} // namespace internal
-
-$range i 0..n
-$for i [[
-$range j 0..i-1
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args)$for j [[, p$j]]);
-}
-
-]]
-
-// Various overloads for ReturnNew<T>().
-//
-// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
-// instance of type T, constructed on the heap with constructor arguments
-// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
-$range i 0..n
-$for i [[
-$range j 0..i-1
-$var ps = [[$for j, [[p$j]]]]
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_$i[[]]_VALUE_PARAMS($ps)) {
- return new T($ps);
-}
-
-]]
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-
-} // namespace testing
-
-// Include any custom callback actions added by the local installation.
-// We must include this header at the end to make sure it can use the
-// declarations from this file.
-#include "gmock/internal/custom/gmock-generated-actions.h"
-
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h b/googlemock/include/gmock/gmock-generated-function-mockers.h
deleted file mode 100644
index cd9578178c00..000000000000
--- a/googlemock/include/gmock/gmock-generated-function-mockers.h
+++ /dev/null
@@ -1,752 +0,0 @@
-// This file was GENERATED by command:
-// pump.py gmock-generated-function-mockers.h.pump
-// DO NOT EDIT BY HAND!!!
-
-// 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 implements function mockers of various arities.
-
-// GOOGLETEST_CM0002 DO NOT DELETE
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
-
-#include <functional>
-#include <utility>
-
-#include "gmock/gmock-spec-builders.h"
-#include "gmock/internal/gmock-internal-utils.h"
-
-namespace testing {
-namespace internal {
-// Removes the given pointer; this is a helper for the expectation setter method
-// for parameterless matchers.
-//
-// We want to make sure that the user cannot set a parameterless expectation on
-// overloaded methods, including methods which are overloaded on const. Example:
-//
-// class MockClass {
-// MOCK_METHOD0(GetName, string&());
-// MOCK_CONST_METHOD0(GetName, const string&());
-// };
-//
-// TEST() {
-// // This should be an error, as it's not clear which overload is expected.
-// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value));
-// }
-//
-// Here are the generated expectation-setter methods:
-//
-// class MockClass {
-// // Overload 1
-// MockSpec<string&()> gmock_GetName() { ... }
-// // Overload 2. Declared const so that the compiler will generate an
-// // error when trying to resolve between this and overload 4 in
-// // 'gmock_GetName(WithoutMatchers(), nullptr)'.
-// MockSpec<string&()> gmock_GetName(
-// const WithoutMatchers&, const Function<string&()>*) const {
-// // Removes const from this, calls overload 1
-// return AdjustConstness_(this)->gmock_GetName();
-// }
-//
-// // Overload 3
-// const string& gmock_GetName() const { ... }
-// // Overload 4
-// MockSpec<const string&()> gmock_GetName(
-// const WithoutMatchers&, const Function<const string&()>*) const {
-// // Does not remove const, calls overload 3
-// return AdjustConstness_const(this)->gmock_GetName();
-// }
-// }
-//
-template <typename MockType>
-const MockType* AdjustConstness_const(const MockType* mock) {
- return mock;
-}
-
-// Removes const from and returns the given pointer; this is a helper for the
-// expectation setter method for parameterless matchers.
-template <typename MockType>
-MockType* AdjustConstness_(const MockType* mock) {
- return const_cast<MockType*>(mock);
-}
-
-} // namespace internal
-
-// The style guide prohibits "using" statements in a namespace scope
-// inside a header file. However, the FunctionMocker class template
-// is meant to be defined in the ::testing namespace. The following
-// line is just a trick for working around a bug in MSVC 8.0, which
-// cannot handle it if we define FunctionMocker in ::testing.
-using internal::FunctionMocker;
-
-// GMOCK_RESULT_(tn, F) expands to the result type of function type F.
-// We define this as a variadic macro in case F contains unprotected
-// commas (the same reason that we use variadic macros in other places
-// in this file).
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_RESULT_(tn, ...) \
- tn ::testing::internal::Function<__VA_ARGS__>::Result
-
-// The type of argument N of the given function type.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_ARG_(tn, N, ...) \
- tn ::testing::internal::Function<__VA_ARGS__>::template Arg<N-1>::type
-
-// The matcher type for argument N of the given function type.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_MATCHER_(tn, N, ...) \
- const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>&
-
-// The variable for mocking the given method.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_MOCKER_(arity, constness, Method) \
- GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \
- static_assert(0 == \
- ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
- "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- ) constness { \
- GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_(0, constness, Method).Invoke(); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method() constness { \
- GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_(0, constness, Method).With(); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method(); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \
- Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \
- static_assert(1 == \
- ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
- "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
- GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_(1, constness, \
- Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
- __VA_ARGS__)>(gmock_a1)); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
- GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>()); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \
- Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \
- static_assert(2 == \
- ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
- "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
- __VA_ARGS__) gmock_a2) constness { \
- GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_(2, constness, \
- Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
- __VA_ARGS__)>(gmock_a1), \
- ::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2)); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
- GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \
- GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>()); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \
- Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \
- static_assert(3 == \
- ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
- "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
- __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, \
- __VA_ARGS__) gmock_a3) constness { \
- GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_(3, constness, \
- Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
- __VA_ARGS__)>(gmock_a1), \
- ::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
- ::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3)); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
- GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
- GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \
- GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \
- gmock_a3); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>()); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \
- Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \
- static_assert(4 == \
- ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
- "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
- __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
- GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_(4, constness, \
- Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
- __VA_ARGS__)>(gmock_a1), \
- ::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
- ::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
- ::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4)); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
- GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
- GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
- GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \
- gmock_a3, gmock_a4); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>()); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \
- Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \
- static_assert(5 == \
- ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
- "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
- __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
- __VA_ARGS__) gmock_a5) constness { \
- GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_(5, constness, \
- Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
- __VA_ARGS__)>(gmock_a1), \
- ::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
- ::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
- ::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
- ::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5)); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
- GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
- GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
- GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \
- GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \
- gmock_a3, gmock_a4, gmock_a5); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>()); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \
- Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \
- static_assert(6 == \
- ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
- "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
- __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
- __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, \
- __VA_ARGS__) gmock_a6) constness { \
- GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_(6, constness, \
- Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
- __VA_ARGS__)>(gmock_a1), \
- ::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
- ::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
- ::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
- ::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
- ::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6)); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
- GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
- GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
- GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
- GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \
- GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \
- gmock_a3, gmock_a4, gmock_a5, gmock_a6); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>()); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \
- Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \
- static_assert(7 == \
- ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
- "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
- __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
- __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
- GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
- GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_(7, constness, \
- Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
- __VA_ARGS__)>(gmock_a1), \
- ::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
- ::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
- ::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
- ::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
- ::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
- ::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7)); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
- GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
- GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
- GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
- GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
- GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
- GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \
- gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>()); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \
- Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \
- static_assert(8 == \
- ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
- "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
- __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
- __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
- GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
- __VA_ARGS__) gmock_a8) constness { \
- GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_(8, constness, \
- Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
- __VA_ARGS__)>(gmock_a1), \
- ::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
- ::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
- ::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
- ::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
- ::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
- ::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
- ::std::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8)); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
- GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
- GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
- GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
- GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
- GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
- GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \
- GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \
- gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>()); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \
- Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \
- static_assert(9 == \
- ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
- "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
- __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
- __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
- GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
- __VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, \
- __VA_ARGS__) gmock_a9) constness { \
- GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_(9, constness, \
- Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
- __VA_ARGS__)>(gmock_a1), \
- ::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
- ::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
- ::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
- ::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
- ::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
- ::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
- ::std::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8), \
- ::std::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(gmock_a9)); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
- GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
- GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
- GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
- GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
- GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
- GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
- GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \
- GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_(9, constness, Method).With(gmock_a1, gmock_a2, \
- gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \
- gmock_a9); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 9, __VA_ARGS__)>()); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \
- Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \
- static_assert(10 == \
- ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
- "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
- __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
- __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
- GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
- __VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \
- GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \
- GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_(10, constness, \
- Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
- __VA_ARGS__)>(gmock_a1), \
- ::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
- ::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
- ::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
- ::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
- ::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
- ::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
- ::std::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8), \
- ::std::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(gmock_a9), \
- ::std::forward<GMOCK_ARG_(tn, 10, __VA_ARGS__)>(gmock_a10)); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
- GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
- GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
- GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
- GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
- GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
- GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
- GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
- GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, \
- GMOCK_MATCHER_(tn, 10, \
- __VA_ARGS__) gmock_a10) constness { \
- GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_(10, constness, Method).With(gmock_a1, gmock_a2, \
- gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \
- gmock_a10); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(), \
- ::testing::A<GMOCK_ARG_(tn, 10, __VA_ARGS__)>()); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \
- Method)
-
-#define MOCK_METHOD0(m, ...) GMOCK_METHOD0_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD1(m, ...) GMOCK_METHOD1_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD2(m, ...) GMOCK_METHOD2_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD3(m, ...) GMOCK_METHOD3_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD4(m, ...) GMOCK_METHOD4_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD5(m, ...) GMOCK_METHOD5_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD6(m, ...) GMOCK_METHOD6_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD7(m, ...) GMOCK_METHOD7_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD8(m, ...) GMOCK_METHOD8_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD9(m, ...) GMOCK_METHOD9_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD10(m, ...) GMOCK_METHOD10_(, , , m, __VA_ARGS__)
-
-#define MOCK_CONST_METHOD0(m, ...) GMOCK_METHOD0_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD1(m, ...) GMOCK_METHOD1_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD2(m, ...) GMOCK_METHOD2_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD3(m, ...) GMOCK_METHOD3_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD4(m, ...) GMOCK_METHOD4_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD5(m, ...) GMOCK_METHOD5_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD6(m, ...) GMOCK_METHOD6_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD7(m, ...) GMOCK_METHOD7_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD8(m, ...) GMOCK_METHOD8_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD9(m, ...) GMOCK_METHOD9_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD10(m, ...) GMOCK_METHOD10_(, const, , m, __VA_ARGS__)
-
-#define MOCK_METHOD0_T(m, ...) GMOCK_METHOD0_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD1_T(m, ...) GMOCK_METHOD1_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD2_T(m, ...) GMOCK_METHOD2_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD3_T(m, ...) GMOCK_METHOD3_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD4_T(m, ...) GMOCK_METHOD4_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD5_T(m, ...) GMOCK_METHOD5_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD6_T(m, ...) GMOCK_METHOD6_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD7_T(m, ...) GMOCK_METHOD7_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD8_T(m, ...) GMOCK_METHOD8_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD9_T(m, ...) GMOCK_METHOD9_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD10_T(m, ...) GMOCK_METHOD10_(typename, , , m, __VA_ARGS__)
-
-#define MOCK_CONST_METHOD0_T(m, ...) \
- GMOCK_METHOD0_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD1_T(m, ...) \
- GMOCK_METHOD1_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD2_T(m, ...) \
- GMOCK_METHOD2_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD3_T(m, ...) \
- GMOCK_METHOD3_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD4_T(m, ...) \
- GMOCK_METHOD4_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD5_T(m, ...) \
- GMOCK_METHOD5_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD6_T(m, ...) \
- GMOCK_METHOD6_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD7_T(m, ...) \
- GMOCK_METHOD7_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD8_T(m, ...) \
- GMOCK_METHOD8_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD9_T(m, ...) \
- GMOCK_METHOD9_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD10_T(m, ...) \
- GMOCK_METHOD10_(typename, const, , m, __VA_ARGS__)
-
-#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD0_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD1_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD2_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD3_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD4_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD5_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD6_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD7_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD8_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD9_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD10_(, , ct, m, __VA_ARGS__)
-
-#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD0_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD1_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD2_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD3_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD4_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD5_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD6_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD7_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD8_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD9_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD10_(, const, ct, m, __VA_ARGS__)
-
-#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD0_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD1_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD2_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD3_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD4_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD5_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD6_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD7_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD8_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD9_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD10_(typename, , ct, m, __VA_ARGS__)
-
-#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD0_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD1_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD2_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD3_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD4_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD5_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD6_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD7_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD8_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD9_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD10_(typename, const, ct, m, __VA_ARGS__)
-
-} // namespace testing
-
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump
deleted file mode 100644
index a56e132f3487..000000000000
--- a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump
+++ /dev/null
@@ -1,227 +0,0 @@
-$$ -*- mode: c++; -*-
-$$ This is a Pump source file. Please use Pump to convert
-$$ it to gmock-generated-function-mockers.h.
-$$
-$var n = 10 $$ The maximum arity we support.
-// 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 implements function mockers of various arities.
-
-// GOOGLETEST_CM0002 DO NOT DELETE
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
-
-#include <functional>
-#include <utility>
-
-#include "gmock/gmock-spec-builders.h"
-#include "gmock/internal/gmock-internal-utils.h"
-
-namespace testing {
-namespace internal {
-
-$range i 0..n
-// Removes the given pointer; this is a helper for the expectation setter method
-// for parameterless matchers.
-//
-// We want to make sure that the user cannot set a parameterless expectation on
-// overloaded methods, including methods which are overloaded on const. Example:
-//
-// class MockClass {
-// MOCK_METHOD0(GetName, string&());
-// MOCK_CONST_METHOD0(GetName, const string&());
-// };
-//
-// TEST() {
-// // This should be an error, as it's not clear which overload is expected.
-// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value));
-// }
-//
-// Here are the generated expectation-setter methods:
-//
-// class MockClass {
-// // Overload 1
-// MockSpec<string&()> gmock_GetName() { ... }
-// // Overload 2. Declared const so that the compiler will generate an
-// // error when trying to resolve between this and overload 4 in
-// // 'gmock_GetName(WithoutMatchers(), nullptr)'.
-// MockSpec<string&()> gmock_GetName(
-// const WithoutMatchers&, const Function<string&()>*) const {
-// // Removes const from this, calls overload 1
-// return AdjustConstness_(this)->gmock_GetName();
-// }
-//
-// // Overload 3
-// const string& gmock_GetName() const { ... }
-// // Overload 4
-// MockSpec<const string&()> gmock_GetName(
-// const WithoutMatchers&, const Function<const string&()>*) const {
-// // Does not remove const, calls overload 3
-// return AdjustConstness_const(this)->gmock_GetName();
-// }
-// }
-//
-template <typename MockType>
-const MockType* AdjustConstness_const(const MockType* mock) {
- return mock;
-}
-
-// Removes const from and returns the given pointer; this is a helper for the
-// expectation setter method for parameterless matchers.
-template <typename MockType>
-MockType* AdjustConstness_(const MockType* mock) {
- return const_cast<MockType*>(mock);
-}
-
-} // namespace internal
-
-// The style guide prohibits "using" statements in a namespace scope
-// inside a header file. However, the FunctionMocker class template
-// is meant to be defined in the ::testing namespace. The following
-// line is just a trick for working around a bug in MSVC 8.0, which
-// cannot handle it if we define FunctionMocker in ::testing.
-using internal::FunctionMocker;
-
-// GMOCK_RESULT_(tn, F) expands to the result type of function type F.
-// We define this as a variadic macro in case F contains unprotected
-// commas (the same reason that we use variadic macros in other places
-// in this file).
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_RESULT_(tn, ...) \
- tn ::testing::internal::Function<__VA_ARGS__>::Result
-
-// The type of argument N of the given function type.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_ARG_(tn, N, ...) \
- tn ::testing::internal::Function<__VA_ARGS__>::template Arg<N-1>::type
-
-// The matcher type for argument N of the given function type.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_MATCHER_(tn, N, ...) \
- const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>&
-
-// The variable for mocking the given method.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_MOCKER_(arity, constness, Method) \
- GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
-
-
-$for i [[
-$range j 1..i
-$var arg_as = [[$for j, [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
-$var as = [[$for j, \
- [[::std::forward<GMOCK_ARG_(tn, $j, __VA_ARGS__)>(gmock_a$j)]]]]
-$var matcher_arg_as = [[$for j, \
- [[GMOCK_MATCHER_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
-$var matcher_as = [[$for j, [[gmock_a$j]]]]
-$var anything_matchers = [[$for j, \
- [[::testing::A<GMOCK_ARG_(tn, $j, __VA_ARGS__)>()]]]]
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, ...) \
- static_assert($i == ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, "MOCK_METHOD<N> must match argument count.");\
- GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
- $arg_as) constness { \
- GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \
- return GMOCK_MOCKER_($i, constness, Method).Invoke($as); \
- } \
- ::testing::MockSpec<__VA_ARGS__> \
- gmock_##Method($matcher_arg_as) constness { \
- GMOCK_MOCKER_($i, constness, Method).RegisterOwner(this); \
- return GMOCK_MOCKER_($i, constness, Method).With($matcher_as); \
- } \
- ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
- const ::testing::internal::WithoutMatchers&, \
- constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
- return ::testing::internal::AdjustConstness_##constness(this)-> \
- gmock_##Method($anything_matchers); \
- } \
- mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_($i, constness, Method)
-
-
-]]
-$for i [[
-#define MOCK_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, , , m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_CONST_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, const, , m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_METHOD$i[[]]_T(m, ...) GMOCK_METHOD$i[[]]_(typename, , , m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_CONST_METHOD$i[[]]_T(m, ...) \
- GMOCK_METHOD$i[[]]_(typename, const, , m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD$i[[]]_(, , ct, m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_CONST_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD$i[[]]_(, const, ct, m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD$i[[]]_(typename, , ct, m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_CONST_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
- GMOCK_METHOD$i[[]]_(typename, const, ct, m, __VA_ARGS__)
-
-]]
-
-} // namespace testing
-
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
diff --git a/googlemock/include/gmock/gmock-generated-matchers.h b/googlemock/include/gmock/gmock-generated-matchers.h
deleted file mode 100644
index 690a57f1c9fd..000000000000
--- a/googlemock/include/gmock/gmock-generated-matchers.h
+++ /dev/null
@@ -1,1097 +0,0 @@
-// This file was GENERATED by command:
-// pump.py gmock-generated-matchers.h.pump
-// DO NOT EDIT BY HAND!!!
-
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements some commonly used variadic matchers.
-
-// GOOGLETEST_CM0002 DO NOT DELETE
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
-
-#include <iterator>
-#include <sstream>
-#include <string>
-#include <utility>
-#include <vector>
-#include "gmock/gmock-matchers.h"
-
-// The MATCHER* family of macros can be used in a namespace scope to
-// define custom matchers easily.
-//
-// Basic Usage
-// ===========
-//
-// The syntax
-//
-// MATCHER(name, description_string) { statements; }
-//
-// defines a matcher with the given name that executes the statements,
-// which must return a bool to indicate if the match succeeds. Inside
-// the statements, you can refer to the value being matched by 'arg',
-// and refer to its type by 'arg_type'.
-//
-// The description string documents what the matcher does, and is used
-// to generate the failure message when the match fails. Since a
-// MATCHER() is usually defined in a header file shared by multiple
-// C++ source files, we require the description to be a C-string
-// literal to avoid possible side effects. It can be empty, in which
-// case we'll use the sequence of words in the matcher name as the
-// description.
-//
-// For example:
-//
-// MATCHER(IsEven, "") { return (arg % 2) == 0; }
-//
-// allows you to write
-//
-// // Expects mock_foo.Bar(n) to be called where n is even.
-// EXPECT_CALL(mock_foo, Bar(IsEven()));
-//
-// or,
-//
-// // Verifies that the value of some_expression is even.
-// EXPECT_THAT(some_expression, IsEven());
-//
-// If the above assertion fails, it will print something like:
-//
-// Value of: some_expression
-// Expected: is even
-// Actual: 7
-//
-// where the description "is even" is automatically calculated from the
-// matcher name IsEven.
-//
-// Argument Type
-// =============
-//
-// Note that the type of the value being matched (arg_type) is
-// determined by the context in which you use the matcher and is
-// supplied to you by the compiler, so you don't need to worry about
-// declaring it (nor can you). This allows the matcher to be
-// polymorphic. For example, IsEven() can be used to match any type
-// where the value of "(arg % 2) == 0" can be implicitly converted to
-// a bool. In the "Bar(IsEven())" example above, if method Bar()
-// takes an int, 'arg_type' will be int; if it takes an unsigned long,
-// 'arg_type' will be unsigned long; and so on.
-//
-// Parameterizing Matchers
-// =======================
-//
-// Sometimes you'll want to parameterize the matcher. For that you
-// can use another macro:
-//
-// MATCHER_P(name, param_name, description_string) { statements; }
-//
-// For example:
-//
-// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
-//
-// will allow you to write:
-//
-// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
-//
-// which may lead to this message (assuming n is 10):
-//
-// Value of: Blah("a")
-// Expected: has absolute value 10
-// Actual: -9
-//
-// Note that both the matcher description and its parameter are
-// printed, making the message human-friendly.
-//
-// In the matcher definition body, you can write 'foo_type' to
-// reference the type of a parameter named 'foo'. For example, in the
-// body of MATCHER_P(HasAbsoluteValue, value) above, you can write
-// 'value_type' to refer to the type of 'value'.
-//
-// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P10 to
-// support multi-parameter matchers.
-//
-// Describing Parameterized Matchers
-// =================================
-//
-// The last argument to MATCHER*() is a string-typed expression. The
-// expression can reference all of the matcher's parameters and a
-// special bool-typed variable named 'negation'. When 'negation' is
-// false, the expression should evaluate to the matcher's description;
-// otherwise it should evaluate to the description of the negation of
-// the matcher. For example,
-//
-// using testing::PrintToString;
-//
-// MATCHER_P2(InClosedRange, low, hi,
-// std::string(negation ? "is not" : "is") + " in range [" +
-// PrintToString(low) + ", " + PrintToString(hi) + "]") {
-// return low <= arg && arg <= hi;
-// }
-// ...
-// EXPECT_THAT(3, InClosedRange(4, 6));
-// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
-//
-// would generate two failures that contain the text:
-//
-// Expected: is in range [4, 6]
-// ...
-// Expected: is not in range [2, 4]
-//
-// If you specify "" as the description, the failure message will
-// contain the sequence of words in the matcher name followed by the
-// parameter values printed as a tuple. For example,
-//
-// MATCHER_P2(InClosedRange, low, hi, "") { ... }
-// ...
-// EXPECT_THAT(3, InClosedRange(4, 6));
-// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
-//
-// would generate two failures that contain the text:
-//
-// Expected: in closed range (4, 6)
-// ...
-// Expected: not (in closed range (2, 4))
-//
-// Types of Matcher Parameters
-// ===========================
-//
-// For the purpose of typing, you can view
-//
-// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
-//
-// as shorthand for
-//
-// template <typename p1_type, ..., typename pk_type>
-// FooMatcherPk<p1_type, ..., pk_type>
-// Foo(p1_type p1, ..., pk_type pk) { ... }
-//
-// When you write Foo(v1, ..., vk), the compiler infers the types of
-// the parameters v1, ..., and vk for you. If you are not happy with
-// the result of the type inference, you can specify the types by
-// explicitly instantiating the template, as in Foo<long, bool>(5,
-// false). As said earlier, you don't get to (or need to) specify
-// 'arg_type' as that's determined by the context in which the matcher
-// is used. You can assign the result of expression Foo(p1, ..., pk)
-// to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
-// can be useful when composing matchers.
-//
-// While you can instantiate a matcher template with reference types,
-// passing the parameters by pointer usually makes your code more
-// readable. If, however, you still want to pass a parameter by
-// reference, be aware that in the failure message generated by the
-// matcher you will see the value of the referenced object but not its
-// address.
-//
-// Explaining Match Results
-// ========================
-//
-// Sometimes the matcher description alone isn't enough to explain why
-// the match has failed or succeeded. For example, when expecting a
-// long string, it can be very helpful to also print the diff between
-// the expected string and the actual one. To achieve that, you can
-// optionally stream additional information to a special variable
-// named result_listener, whose type is a pointer to class
-// MatchResultListener:
-//
-// MATCHER_P(EqualsLongString, str, "") {
-// if (arg == str) return true;
-//
-// *result_listener << "the difference: "
-/// << DiffStrings(str, arg);
-// return false;
-// }
-//
-// Overloading Matchers
-// ====================
-//
-// You can overload matchers with different numbers of parameters:
-//
-// MATCHER_P(Blah, a, description_string1) { ... }
-// MATCHER_P2(Blah, a, b, description_string2) { ... }
-//
-// Caveats
-// =======
-//
-// When defining a new matcher, you should also consider implementing
-// MatcherInterface or using MakePolymorphicMatcher(). These
-// approaches require more work than the MATCHER* macros, but also
-// give you more control on the types of the value being matched and
-// the matcher parameters, which may leads to better compiler error
-// messages when the matcher is used wrong. They also allow
-// overloading matchers based on parameter types (as opposed to just
-// based on the number of parameters).
-//
-// MATCHER*() can only be used in a namespace scope as templates cannot be
-// declared inside of a local class.
-//
-// More Information
-// ================
-//
-// To learn more about using these macros, please search for 'MATCHER'
-// on
-// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
-
-#define MATCHER(name, description)\
- class name##Matcher {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl()\
- {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<>()));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>());\
- }\
- name##Matcher() {\
- }\
- private:\
- };\
- inline name##Matcher name() {\
- return name##Matcher();\
- }\
- template <typename arg_type>\
- bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P(name, p0, description)\
- template <typename p0##_type>\
- class name##MatcherP {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- explicit gmock_Impl(p0##_type gmock_p0)\
- : p0(::std::move(gmock_p0)) {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<p0##_type>(p0)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0));\
- }\
- explicit name##MatcherP(p0##_type gmock_p0) : p0(::std::move(gmock_p0)) {\
- }\
- p0##_type const p0;\
- private:\
- };\
- template <typename p0##_type>\
- inline name##MatcherP<p0##_type> name(p0##_type p0) {\
- return name##MatcherP<p0##_type>(p0);\
- }\
- template <typename p0##_type>\
- template <typename arg_type>\
- bool name##MatcherP<p0##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P2(name, p0, p1, description)\
- template <typename p0##_type, typename p1##_type>\
- class name##MatcherP2 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\
- : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)) {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<p0##_type, p1##_type>(p0, p1)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1));\
- }\
- name##MatcherP2(p0##_type gmock_p0, \
- p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type>\
- inline name##MatcherP2<p0##_type, p1##_type> name(p0##_type p0, \
- p1##_type p1) {\
- return name##MatcherP2<p0##_type, p1##_type>(p0, p1);\
- }\
- template <typename p0##_type, typename p1##_type>\
- template <typename arg_type>\
- bool name##MatcherP2<p0##_type, \
- p1##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P3(name, p0, p1, p2, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- class name##MatcherP3 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(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)) {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<p0##_type, p1##_type, p2##_type>(p0, p1, p2)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2));\
- }\
- name##MatcherP3(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)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- inline name##MatcherP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \
- p1##_type p1, p2##_type p2) {\
- return name##MatcherP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- template <typename arg_type>\
- bool name##MatcherP3<p0##_type, p1##_type, \
- p2##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P4(name, p0, p1, p2, p3, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- class name##MatcherP4 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(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)) {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type>(p0, \
- p1, p2, p3)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3));\
- }\
- name##MatcherP4(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)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- inline name##MatcherP4<p0##_type, p1##_type, p2##_type, \
- p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
- p3##_type p3) {\
- return name##MatcherP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, \
- p1, p2, p3);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- template <typename arg_type>\
- bool name##MatcherP4<p0##_type, p1##_type, p2##_type, \
- p3##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P5(name, p0, p1, p2, p3, p4, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- class name##MatcherP5 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(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)) {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type>(p0, p1, p2, p3, p4)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4));\
- }\
- name##MatcherP5(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)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- inline name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
- p4##_type p4) {\
- return name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type>(p0, p1, p2, p3, p4);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- template <typename arg_type>\
- bool name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- class name##MatcherP6 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(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)) {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5));\
- }\
- name##MatcherP6(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)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- inline name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
- p3##_type p3, p4##_type p4, p5##_type p5) {\
- return name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- template <typename arg_type>\
- bool name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- class name##MatcherP7 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(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)) {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, \
- p6)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6));\
- }\
- name##MatcherP7(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)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- inline name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \
- p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
- p6##_type p6) {\
- return name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- template <typename arg_type>\
- bool name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- class name##MatcherP8 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(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)) {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, \
- p3, p4, p5, p6, p7)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7));\
- }\
- name##MatcherP8(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)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- inline name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \
- p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
- p6##_type p6, p7##_type p7) {\
- return name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \
- p6, p7);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- template <typename arg_type>\
- bool name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, \
- p7##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description)\
- template <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>\
- class name##MatcherP9 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(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)) {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- p8##_type const p8;\
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, \
- p8##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8));\
- }\
- name##MatcherP9(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)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- p8##_type const p8;\
- private:\
- };\
- template <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>\
- inline name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, \
- p8##_type> name(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) {\
- return name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \
- p3, p4, p5, p6, p7, p8);\
- }\
- template <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>\
- template <typename arg_type>\
- bool name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, p7##_type, \
- p8##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description)\
- template <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>\
- class name##MatcherP10 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(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)) {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- p8##_type const p8;\
- p9##_type const p9;\
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
- p9##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9));\
- }\
- name##MatcherP10(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)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- p8##_type const p8;\
- p9##_type const p9;\
- private:\
- };\
- template <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>\
- inline name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
- p9##_type> name(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) {\
- return name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \
- p1, p2, p3, p4, p5, p6, p7, p8, p9);\
- }\
- template <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>\
- template <typename arg_type>\
- bool name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
- p9##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
diff --git a/googlemock/include/gmock/gmock-generated-matchers.h.pump b/googlemock/include/gmock/gmock-generated-matchers.h.pump
deleted file mode 100644
index ae90917cc38e..000000000000
--- a/googlemock/include/gmock/gmock-generated-matchers.h.pump
+++ /dev/null
@@ -1,346 +0,0 @@
-$$ -*- mode: c++; -*-
-$$ This is a Pump source file. Please use Pump to convert
-$$ it to gmock-generated-matchers.h.
-$$
-$var n = 10 $$ The maximum arity we support.
-$$ }} This line fixes auto-indentation of the following code in Emacs.
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements some commonly used variadic matchers.
-
-// GOOGLETEST_CM0002 DO NOT DELETE
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
-
-#include <iterator>
-#include <sstream>
-#include <string>
-#include <utility>
-#include <vector>
-#include "gmock/gmock-matchers.h"
-
-// The MATCHER* family of macros can be used in a namespace scope to
-// define custom matchers easily.
-//
-// Basic Usage
-// ===========
-//
-// The syntax
-//
-// MATCHER(name, description_string) { statements; }
-//
-// defines a matcher with the given name that executes the statements,
-// which must return a bool to indicate if the match succeeds. Inside
-// the statements, you can refer to the value being matched by 'arg',
-// and refer to its type by 'arg_type'.
-//
-// The description string documents what the matcher does, and is used
-// to generate the failure message when the match fails. Since a
-// MATCHER() is usually defined in a header file shared by multiple
-// C++ source files, we require the description to be a C-string
-// literal to avoid possible side effects. It can be empty, in which
-// case we'll use the sequence of words in the matcher name as the
-// description.
-//
-// For example:
-//
-// MATCHER(IsEven, "") { return (arg % 2) == 0; }
-//
-// allows you to write
-//
-// // Expects mock_foo.Bar(n) to be called where n is even.
-// EXPECT_CALL(mock_foo, Bar(IsEven()));
-//
-// or,
-//
-// // Verifies that the value of some_expression is even.
-// EXPECT_THAT(some_expression, IsEven());
-//
-// If the above assertion fails, it will print something like:
-//
-// Value of: some_expression
-// Expected: is even
-// Actual: 7
-//
-// where the description "is even" is automatically calculated from the
-// matcher name IsEven.
-//
-// Argument Type
-// =============
-//
-// Note that the type of the value being matched (arg_type) is
-// determined by the context in which you use the matcher and is
-// supplied to you by the compiler, so you don't need to worry about
-// declaring it (nor can you). This allows the matcher to be
-// polymorphic. For example, IsEven() can be used to match any type
-// where the value of "(arg % 2) == 0" can be implicitly converted to
-// a bool. In the "Bar(IsEven())" example above, if method Bar()
-// takes an int, 'arg_type' will be int; if it takes an unsigned long,
-// 'arg_type' will be unsigned long; and so on.
-//
-// Parameterizing Matchers
-// =======================
-//
-// Sometimes you'll want to parameterize the matcher. For that you
-// can use another macro:
-//
-// MATCHER_P(name, param_name, description_string) { statements; }
-//
-// For example:
-//
-// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
-//
-// will allow you to write:
-//
-// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
-//
-// which may lead to this message (assuming n is 10):
-//
-// Value of: Blah("a")
-// Expected: has absolute value 10
-// Actual: -9
-//
-// Note that both the matcher description and its parameter are
-// printed, making the message human-friendly.
-//
-// In the matcher definition body, you can write 'foo_type' to
-// reference the type of a parameter named 'foo'. For example, in the
-// body of MATCHER_P(HasAbsoluteValue, value) above, you can write
-// 'value_type' to refer to the type of 'value'.
-//
-// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
-// support multi-parameter matchers.
-//
-// Describing Parameterized Matchers
-// =================================
-//
-// The last argument to MATCHER*() is a string-typed expression. The
-// expression can reference all of the matcher's parameters and a
-// special bool-typed variable named 'negation'. When 'negation' is
-// false, the expression should evaluate to the matcher's description;
-// otherwise it should evaluate to the description of the negation of
-// the matcher. For example,
-//
-// using testing::PrintToString;
-//
-// MATCHER_P2(InClosedRange, low, hi,
-// std::string(negation ? "is not" : "is") + " in range [" +
-// PrintToString(low) + ", " + PrintToString(hi) + "]") {
-// return low <= arg && arg <= hi;
-// }
-// ...
-// EXPECT_THAT(3, InClosedRange(4, 6));
-// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
-//
-// would generate two failures that contain the text:
-//
-// Expected: is in range [4, 6]
-// ...
-// Expected: is not in range [2, 4]
-//
-// If you specify "" as the description, the failure message will
-// contain the sequence of words in the matcher name followed by the
-// parameter values printed as a tuple. For example,
-//
-// MATCHER_P2(InClosedRange, low, hi, "") { ... }
-// ...
-// EXPECT_THAT(3, InClosedRange(4, 6));
-// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
-//
-// would generate two failures that contain the text:
-//
-// Expected: in closed range (4, 6)
-// ...
-// Expected: not (in closed range (2, 4))
-//
-// Types of Matcher Parameters
-// ===========================
-//
-// For the purpose of typing, you can view
-//
-// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
-//
-// as shorthand for
-//
-// template <typename p1_type, ..., typename pk_type>
-// FooMatcherPk<p1_type, ..., pk_type>
-// Foo(p1_type p1, ..., pk_type pk) { ... }
-//
-// When you write Foo(v1, ..., vk), the compiler infers the types of
-// the parameters v1, ..., and vk for you. If you are not happy with
-// the result of the type inference, you can specify the types by
-// explicitly instantiating the template, as in Foo<long, bool>(5,
-// false). As said earlier, you don't get to (or need to) specify
-// 'arg_type' as that's determined by the context in which the matcher
-// is used. You can assign the result of expression Foo(p1, ..., pk)
-// to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
-// can be useful when composing matchers.
-//
-// While you can instantiate a matcher template with reference types,
-// passing the parameters by pointer usually makes your code more
-// readable. If, however, you still want to pass a parameter by
-// reference, be aware that in the failure message generated by the
-// matcher you will see the value of the referenced object but not its
-// address.
-//
-// Explaining Match Results
-// ========================
-//
-// Sometimes the matcher description alone isn't enough to explain why
-// the match has failed or succeeded. For example, when expecting a
-// long string, it can be very helpful to also print the diff between
-// the expected string and the actual one. To achieve that, you can
-// optionally stream additional information to a special variable
-// named result_listener, whose type is a pointer to class
-// MatchResultListener:
-//
-// MATCHER_P(EqualsLongString, str, "") {
-// if (arg == str) return true;
-//
-// *result_listener << "the difference: "
-/// << DiffStrings(str, arg);
-// return false;
-// }
-//
-// Overloading Matchers
-// ====================
-//
-// You can overload matchers with different numbers of parameters:
-//
-// MATCHER_P(Blah, a, description_string1) { ... }
-// MATCHER_P2(Blah, a, b, description_string2) { ... }
-//
-// Caveats
-// =======
-//
-// When defining a new matcher, you should also consider implementing
-// MatcherInterface or using MakePolymorphicMatcher(). These
-// approaches require more work than the MATCHER* macros, but also
-// give you more control on the types of the value being matched and
-// the matcher parameters, which may leads to better compiler error
-// messages when the matcher is used wrong. They also allow
-// overloading matchers based on parameter types (as opposed to just
-// based on the number of parameters).
-//
-// MATCHER*() can only be used in a namespace scope as templates cannot be
-// declared inside of a local class.
-//
-// More Information
-// ================
-//
-// To learn more about using these macros, please search for 'MATCHER'
-// on
-// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
-
-$range i 0..n
-$for i
-
-[[
-$var macro_name = [[$if i==0 [[MATCHER]] $elif i==1 [[MATCHER_P]]
- $else [[MATCHER_P$i]]]]
-$var class_name = [[name##Matcher[[$if i==0 [[]] $elif i==1 [[P]]
- $else [[P$i]]]]]]
-$range j 0..i-1
-$var template = [[$if i==0 [[]] $else [[
-
- template <$for j, [[typename p$j##_type]]>\
-]]]]
-$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
-$var impl_ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
-$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::move(gmock_p$j))]]]]]]
-$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::move(gmock_p$j))]]]]]]
-$var params = [[$for j, [[p$j]]]]
-$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
-$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
-$var param_field_decls = [[$for j
-[[
-
- p$j##_type const p$j;\
-]]]]
-$var param_field_decls2 = [[$for j
-[[
-
- p$j##_type const p$j;\
-]]]]
-
-#define $macro_name(name$for j [[, p$j]], description)\$template
- class $class_name {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- [[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\
- $impl_inits {}\
- virtual bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const;\
- virtual void DescribeTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(false);\
- }\
- virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
- *gmock_os << FormatDescription(true);\
- }\$param_field_decls
- private:\
- ::std::string FormatDescription(bool negation) const {\
- ::std::string gmock_description = (description);\
- if (!gmock_description.empty()) {\
- return gmock_description;\
- }\
- return ::testing::internal::FormatMatcherDescription(\
- negation, #name, \
- ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
- ::std::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>($params));\
- }\
- [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {\
- }\$param_field_decls2
- private:\
- };\$template
- inline $class_name$param_types name($param_types_and_names) {\
- return $class_name$param_types($params);\
- }\$template
- template <typename arg_type>\
- bool $class_name$param_types::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-]]
-
-
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h
index 28e188bb8130..0f67713776a6 100644
--- a/googlemock/include/gmock/gmock-matchers.h
+++ b/googlemock/include/gmock/gmock-matchers.h
@@ -27,24 +27,240 @@
// (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 argument matchers. More
+// The MATCHER* family of macros can be used in a namespace scope to
+// define custom matchers easily.
+//
+// Basic Usage
+// ===========
+//
+// The syntax
+//
+// MATCHER(name, description_string) { statements; }
+//
+// defines a matcher with the given name that executes the statements,
+// which must return a bool to indicate if the match succeeds. Inside
+// the statements, you can refer to the value being matched by 'arg',
+// and refer to its type by 'arg_type'.
+//
+// The description string documents what the matcher does, and is used
+// to generate the failure message when the match fails. Since a
+// MATCHER() is usually defined in a header file shared by multiple
+// C++ source files, we require the description to be a C-string
+// literal to avoid possible side effects. It can be empty, in which
+// case we'll use the sequence of words in the matcher name as the
+// description.
+//
+// For example:
+//
+// MATCHER(IsEven, "") { return (arg % 2) == 0; }
+//
+// allows you to write
+//
+// // Expects mock_foo.Bar(n) to be called where n is even.
+// EXPECT_CALL(mock_foo, Bar(IsEven()));
+//
+// or,
+//
+// // Verifies that the value of some_expression is even.
+// EXPECT_THAT(some_expression, IsEven());
+//
+// If the above assertion fails, it will print something like:
+//
+// Value of: some_expression
+// Expected: is even
+// Actual: 7
+//
+// where the description "is even" is automatically calculated from the
+// matcher name IsEven.
+//
+// Argument Type
+// =============
+//
+// Note that the type of the value being matched (arg_type) is
+// determined by the context in which you use the matcher and is
+// supplied to you by the compiler, so you don't need to worry about
+// declaring it (nor can you). This allows the matcher to be
+// polymorphic. For example, IsEven() can be used to match any type
+// where the value of "(arg % 2) == 0" can be implicitly converted to
+// a bool. In the "Bar(IsEven())" example above, if method Bar()
+// takes an int, 'arg_type' will be int; if it takes an unsigned long,
+// 'arg_type' will be unsigned long; and so on.
+//
+// Parameterizing Matchers
+// =======================
+//
+// Sometimes you'll want to parameterize the matcher. For that you
+// can use another macro:
+//
+// MATCHER_P(name, param_name, description_string) { statements; }
+//
+// For example:
+//
+// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
+//
+// will allow you to write:
+//
+// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
+//
+// which may lead to this message (assuming n is 10):
+//
+// Value of: Blah("a")
+// Expected: has absolute value 10
+// Actual: -9
+//
+// Note that both the matcher description and its parameter are
+// printed, making the message human-friendly.
+//
+// In the matcher definition body, you can write 'foo_type' to
+// reference the type of a parameter named 'foo'. For example, in the
+// body of MATCHER_P(HasAbsoluteValue, value) above, you can write
+// 'value_type' to refer to the type of 'value'.
+//
+// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
+// support multi-parameter matchers.
+//
+// Describing Parameterized Matchers
+// =================================
+//
+// The last argument to MATCHER*() is a string-typed expression. The
+// expression can reference all of the matcher's parameters and a
+// special bool-typed variable named 'negation'. When 'negation' is
+// false, the expression should evaluate to the matcher's description;
+// otherwise it should evaluate to the description of the negation of
+// the matcher. For example,
+//
+// using testing::PrintToString;
+//
+// MATCHER_P2(InClosedRange, low, hi,
+// std::string(negation ? "is not" : "is") + " in range [" +
+// PrintToString(low) + ", " + PrintToString(hi) + "]") {
+// return low <= arg && arg <= hi;
+// }
+// ...
+// EXPECT_THAT(3, InClosedRange(4, 6));
+// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
+//
+// would generate two failures that contain the text:
+//
+// Expected: is in range [4, 6]
+// ...
+// Expected: is not in range [2, 4]
+//
+// If you specify "" as the description, the failure message will
+// contain the sequence of words in the matcher name followed by the
+// parameter values printed as a tuple. For example,
+//
+// MATCHER_P2(InClosedRange, low, hi, "") { ... }
+// ...
+// EXPECT_THAT(3, InClosedRange(4, 6));
+// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
+//
+// would generate two failures that contain the text:
+//
+// Expected: in closed range (4, 6)
+// ...
+// Expected: not (in closed range (2, 4))
+//
+// Types of Matcher Parameters
+// ===========================
+//
+// For the purpose of typing, you can view
+//
+// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
+//
+// as shorthand for
+//
+// template <typename p1_type, ..., typename pk_type>
+// FooMatcherPk<p1_type, ..., pk_type>
+// Foo(p1_type p1, ..., pk_type pk) { ... }
+//
+// When you write Foo(v1, ..., vk), the compiler infers the types of
+// the parameters v1, ..., and vk for you. If you are not happy with
+// the result of the type inference, you can specify the types by
+// explicitly instantiating the template, as in Foo<long, bool>(5,
+// false). As said earlier, you don't get to (or need to) specify
+// 'arg_type' as that's determined by the context in which the matcher
+// is used. You can assign the result of expression Foo(p1, ..., pk)
+// to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
+// can be useful when composing matchers.
+//
+// While you can instantiate a matcher template with reference types,
+// passing the parameters by pointer usually makes your code more
+// readable. If, however, you still want to pass a parameter by
+// reference, be aware that in the failure message generated by the
+// matcher you will see the value of the referenced object but not its
+// address.
+//
+// Explaining Match Results
+// ========================
+//
+// Sometimes the matcher description alone isn't enough to explain why
+// the match has failed or succeeded. For example, when expecting a
+// long string, it can be very helpful to also print the diff between
+// the expected string and the actual one. To achieve that, you can
+// optionally stream additional information to a special variable
+// named result_listener, whose type is a pointer to class
+// MatchResultListener:
+//
+// MATCHER_P(EqualsLongString, str, "") {
+// if (arg == str) return true;
+//
+// *result_listener << "the difference: "
+/// << DiffStrings(str, arg);
+// return false;
+// }
+//
+// Overloading Matchers
+// ====================
+//
+// You can overload matchers with different numbers of parameters:
+//
+// MATCHER_P(Blah, a, description_string1) { ... }
+// MATCHER_P2(Blah, a, b, description_string2) { ... }
+//
+// Caveats
+// =======
+//
+// When defining a new matcher, you should also consider implementing
+// MatcherInterface or using MakePolymorphicMatcher(). These
+// approaches require more work than the MATCHER* macros, but also
+// give you more control on the types of the value being matched and
+// the matcher parameters, which may leads to better compiler error
+// messages when the matcher is used wrong. They also allow
+// overloading matchers based on parameter types (as opposed to just
+// based on the number of parameters).
+//
+// MATCHER*() can only be used in a namespace scope as templates cannot be
+// declared inside of a local class.
+//
+// More Information
+// ================
+//
+// To learn more about using these macros, please search for 'MATCHER'
+// on
+// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md
+//
+// This file also implements some commonly used argument matchers. More
// matchers can be defined by the user implementing the
// MatcherInterface<T> interface if necessary.
//
// 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 GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
-#include <math.h>
#include <algorithm>
+#include <cmath>
+#include <exception>
+#include <functional>
#include <initializer_list>
+#include <ios>
#include <iterator>
#include <limits>
#include <memory>
@@ -54,8 +270,10 @@
#include <type_traits>
#include <utility>
#include <vector>
+
#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h"
+#include "gmock/internal/gmock-pp.h"
#include "gtest/gtest.h"
// MSVC warning C5046 is new as of VS2017 version 15.8.
@@ -98,7 +316,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
@@ -128,7 +348,7 @@ class MatcherCastImpl {
// constructor from M (this usually happens when T has an implicit
// constructor from any type).
//
- // It won't work to unconditionally implict_cast
+ // It won't work to unconditionally implicit_cast
// polymorphic_matcher_or_value to Matcher<T> because it won't trigger
// a user-defined conversion from M to T if one exists (assuming M is
// a value).
@@ -141,7 +361,7 @@ class MatcherCastImpl {
template <bool Ignore>
static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
std::true_type /* convertible_to_matcher */,
- bool_constant<Ignore>) {
+ std::integral_constant<bool, Ignore>) {
// M is implicitly convertible to Matcher<T>, which means that either
// M is a polymorphic matcher or Matcher<T> has an implicit constructor
// from M. In both cases using the implicit conversion will produce a
@@ -181,7 +401,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));
@@ -209,7 +429,14 @@ class MatcherCastImpl<T, Matcher<U> > {
!std::is_base_of<FromType, ToType>::value,
"Can't implicitly convert from <base> to <derived>");
- return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
+ // Do the cast to `U` explicitly if necessary.
+ // Otherwise, let implicit conversions do the trick.
+ using CastType =
+ typename std::conditional<std::is_convertible<T&, const U&>::value,
+ T&, U>::type;
+
+ return source_matcher_.MatchAndExplain(static_cast<CastType>(x),
+ listener);
}
void DescribeTo(::std::ostream* os) const override {
@@ -222,19 +449,61 @@ class MatcherCastImpl<T, Matcher<U> > {
private:
const Matcher<U> source_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
};
// 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; }
};
+// Template specialization for parameterless Matcher.
+template <typename Derived>
+class MatcherBaseImpl {
+ public:
+ MatcherBaseImpl() = default;
+
+ template <typename T>
+ operator ::testing::Matcher<T>() const { // NOLINT(runtime/explicit)
+ return ::testing::Matcher<T>(new
+ typename Derived::template gmock_Impl<T>());
+ }
+};
+
+// Template specialization for Matcher with parameters.
+template <template <typename...> class Derived, typename... Ts>
+class MatcherBaseImpl<Derived<Ts...>> {
+ public:
+ // Mark the constructor explicit for single argument T to avoid implicit
+ // conversions.
+ template <typename E = std::enable_if<sizeof...(Ts) == 1>,
+ typename E::type* = nullptr>
+ explicit MatcherBaseImpl(Ts... params)
+ : params_(std::forward<Ts>(params)...) {}
+ template <typename E = std::enable_if<sizeof...(Ts) != 1>,
+ typename = typename E::type>
+ MatcherBaseImpl(Ts... params) // NOLINT
+ : params_(std::forward<Ts>(params)...) {}
+
+ template <typename F>
+ operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit)
+ return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{});
+ }
+
+ private:
+ template <typename F, std::size_t... tuple_ids>
+ ::testing::Matcher<F> Apply(IndexSequence<tuple_ids...>) const {
+ return ::testing::Matcher<F>(
+ new typename Derived<Ts...>::template gmock_Impl<F>(
+ std::get<tuple_ids>(params_)...));
+ }
+
+ const std::tuple<Ts...> params_;
+};
+
} // namespace internal
// In order to be safe and clear, casting between different matcher
@@ -246,56 +515,42 @@ inline Matcher<T> MatcherCast(const M& matcher) {
return internal::MatcherCastImpl<T, M>::Cast(matcher);
}
-// Implements SafeMatcherCast().
-//
-// FIXME: The intermediate SafeMatcherCastImpl class was introduced as a
-// workaround for a compiler bug, and can now be removed.
-template <typename T>
-class SafeMatcherCastImpl {
- public:
- // This overload handles polymorphic matchers and values only since
- // monomorphic matchers are handled by the next one.
- template <typename M>
- static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
- return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
- }
-
- // This overload handles monomorphic matchers.
- //
- // In general, if type T can be implicitly converted to type U, we can
- // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
- // contravariant): just keep a copy of the original Matcher<U>, convert the
- // argument from type T to U, and then pass it to the underlying Matcher<U>.
- // The only exception is when U is a reference and T is not, as the
- // underlying Matcher<U> may be interested in the argument's address, which
- // is not preserved in the conversion from T to U.
- template <typename U>
- static inline Matcher<T> Cast(const Matcher<U>& matcher) {
- // Enforce that T can be implicitly converted to U.
- GTEST_COMPILE_ASSERT_((std::is_convertible<T, U>::value),
- "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);
- // 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;
- const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
- const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
- GTEST_COMPILE_ASSERT_(
- kTIsOther || kUIsOther ||
- (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
- conversion_of_arithmetic_types_must_be_lossless);
- return MatcherCast<T>(matcher);
- }
-};
-
+// This overload handles polymorphic matchers and values only since
+// monomorphic matchers are handled by the next one.
template <typename T, typename M>
-inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
- return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
+inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {
+ return MatcherCast<T>(polymorphic_matcher_or_value);
+}
+
+// This overload handles monomorphic matchers.
+//
+// In general, if type T can be implicitly converted to type U, we can
+// safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
+// contravariant): just keep a copy of the original Matcher<U>, convert the
+// argument from type T to U, and then pass it to the underlying Matcher<U>.
+// The only exception is when U is a reference and T is not, as the
+// underlying Matcher<U> may be interested in the argument's address, which
+// is not preserved in the conversion from T to U.
+template <typename T, typename U>
+inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
+ // Enforce that T can be implicitly converted to U.
+ static_assert(std::is_convertible<const T&, const U&>::value,
+ "T must be implicitly convertible to U");
+ // Enforce that we are not converting a non-reference type T to a reference
+ // type U.
+ 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;
+ static_assert(
+ kTIsOther || kUIsOther ||
+ (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
+ "conversion of arithmetic types must be lossless");
+ return MatcherCast<T>(matcher);
}
// A<T>() returns a matcher that matches any value of type T.
@@ -309,7 +564,7 @@ namespace internal {
// If the explanation is not empty, prints it to the ostream.
inline void PrintIfNotEmpty(const std::string& explanation,
::std::ostream* os) {
- if (explanation != "" && os != nullptr) {
+ if (!explanation.empty() && os != nullptr) {
*os << ", " << explanation;
}
}
@@ -427,9 +682,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);
}
@@ -438,8 +693,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);
}
@@ -463,14 +717,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;
}
};
@@ -484,31 +738,25 @@ OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
}
-// Implements A<T>().
-template <typename T>
-class AnyMatcherImpl : public MatcherInterface<const T&> {
- public:
- bool MatchAndExplain(const T& /* x */,
- MatchResultListener* /* listener */) const override {
- return true;
- }
- void DescribeTo(::std::ostream* os) const override { *os << "is anything"; }
- void DescribeNegationTo(::std::ostream* os) const override {
- // This is mostly for completeness' safe, as it's not very useful
- // to write Not(A<bool>()). However we cannot completely rule out
- // such a possibility, and it doesn't hurt to be prepared.
- *os << "never matches";
- }
-};
-
// Implements _, a matcher that matches any value of any
// type. This is a polymorphic matcher, so we need a template type
// conversion operator to make it appearing as a Matcher<T> for any
// type T.
class AnythingMatcher {
public:
+ using is_gtest_matcher = void;
+
template <typename T>
- operator Matcher<T>() const { return A<T>(); }
+ bool MatchAndExplain(const T& /* x */, std::ostream* /* listener */) const {
+ return true;
+ }
+ void DescribeTo(std::ostream* os) const { *os << "is anything"; }
+ void DescribeNegationTo(::std::ostream* os) const {
+ // This is mostly for completeness' sake, as it's not very useful
+ // to write Not(A<bool>()). However we cannot completely rule out
+ // such a possibility, and it doesn't hurt to be prepared.
+ *os << "never matches";
+ }
};
// Implements the polymorphic IsNull() matcher, which matches any raw or smart
@@ -522,9 +770,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
@@ -538,9 +784,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
@@ -608,13 +852,9 @@ class RefMatcher<T&> {
private:
const Super& object_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
T& object_;
-
- GTEST_DISALLOW_ASSIGN_(RefMatcher);
};
// Polymorphic helper functions for narrow and wide string matchers.
@@ -630,8 +870,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;
@@ -656,19 +895,20 @@ bool CaseInsensitiveStringEquals(const StringType& s1,
template <typename StringType>
class StrEqualityMatcher {
public:
- StrEqualityMatcher(const StringType& str, bool expect_eq,
- bool case_sensitive)
- : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
+ StrEqualityMatcher(StringType str, bool expect_eq, bool case_sensitive)
+ : string_(std::move(str)),
+ expect_eq_(expect_eq),
+ case_sensitive_(case_sensitive) {}
-#if GTEST_HAS_ABSL
- bool MatchAndExplain(const absl::string_view& s,
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const {
- // This should fail to compile if absl::string_view is used with wide
+ // This should fail to compile if StringView is used with wide
// strings.
const StringType& str = std::string(s);
return MatchAndExplain(str, listener);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly:
// const char*
@@ -686,13 +926,13 @@ class StrEqualityMatcher {
// Matches anything that can convert to StringType.
//
// This is a template, not just a plain function with const StringType&,
- // because absl::string_view has some interfering non-explicit constructors.
+ // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const {
- const StringType& s2(s);
- const bool eq = case_sensitive_ ? s2 == string_ :
- CaseInsensitiveStringEquals(s2, string_);
+ const StringType s2(s);
+ const bool eq = case_sensitive_ ? s2 == string_
+ : CaseInsensitiveStringEquals(s2, string_);
return expect_eq_ == eq;
}
@@ -717,8 +957,6 @@ class StrEqualityMatcher {
const StringType string_;
const bool expect_eq_;
const bool case_sensitive_;
-
- GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
};
// Implements the polymorphic HasSubstr(substring) matcher, which
@@ -730,15 +968,15 @@ class HasSubstrMatcher {
explicit HasSubstrMatcher(const StringType& substring)
: substring_(substring) {}
-#if GTEST_HAS_ABSL
- bool MatchAndExplain(const absl::string_view& s,
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const {
- // This should fail to compile if absl::string_view is used with wide
+ // This should fail to compile if StringView is used with wide
// strings.
const StringType& str = std::string(s);
return MatchAndExplain(str, listener);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly:
// const char*
@@ -753,12 +991,11 @@ class HasSubstrMatcher {
// Matches anything that can convert to StringType.
//
// This is a template, not just a plain function with const StringType&,
- // because absl::string_view has some interfering non-explicit constructors.
+ // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const {
- const StringType& s2(s);
- return s2.find(substring_) != StringType::npos;
+ return StringType(s).find(substring_) != StringType::npos;
}
// Describes what this matcher matches.
@@ -774,8 +1011,6 @@ class HasSubstrMatcher {
private:
const StringType substring_;
-
- GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
};
// Implements the polymorphic StartsWith(substring) matcher, which
@@ -784,18 +1019,17 @@ class HasSubstrMatcher {
template <typename StringType>
class StartsWithMatcher {
public:
- explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
- }
+ explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {}
-#if GTEST_HAS_ABSL
- bool MatchAndExplain(const absl::string_view& s,
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const {
- // This should fail to compile if absl::string_view is used with wide
+ // This should fail to compile if StringView is used with wide
// strings.
const StringType& str = std::string(s);
return MatchAndExplain(str, listener);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly:
// const char*
@@ -810,13 +1044,13 @@ class StartsWithMatcher {
// Matches anything that can convert to StringType.
//
// This is a template, not just a plain function with const StringType&,
- // because absl::string_view has some interfering non-explicit constructors.
+ // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
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 {
@@ -831,8 +1065,6 @@ class StartsWithMatcher {
private:
const StringType prefix_;
-
- GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
};
// Implements the polymorphic EndsWith(substring) matcher, which
@@ -843,15 +1075,15 @@ class EndsWithMatcher {
public:
explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
-#if GTEST_HAS_ABSL
- bool MatchAndExplain(const absl::string_view& s,
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const {
- // This should fail to compile if absl::string_view is used with wide
+ // This should fail to compile if StringView is used with wide
// strings.
const StringType& str = std::string(s);
return MatchAndExplain(str, listener);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly:
// const char*
@@ -866,13 +1098,13 @@ class EndsWithMatcher {
// Matches anything that can convert to StringType.
//
// This is a template, not just a plain function with const StringType&,
- // because absl::string_view has some interfering non-explicit constructors.
+ // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
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 {
@@ -887,8 +1119,45 @@ class EndsWithMatcher {
private:
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);
+ }
- GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
+ 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
@@ -932,27 +1201,27 @@ class PairMatchBase {
};
};
-class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
+class Eq2Matcher : public PairMatchBase<Eq2Matcher, std::equal_to<>> {
public:
static const char* Desc() { return "an equal pair"; }
};
-class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
+class Ne2Matcher : public PairMatchBase<Ne2Matcher, std::not_equal_to<>> {
public:
static const char* Desc() { return "an unequal pair"; }
};
-class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
+class Lt2Matcher : public PairMatchBase<Lt2Matcher, std::less<>> {
public:
static const char* Desc() { return "a pair where the first < the second"; }
};
-class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
+class Gt2Matcher : public PairMatchBase<Gt2Matcher, std::greater<>> {
public:
static const char* Desc() { return "a pair where the first > the second"; }
};
-class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
+class Le2Matcher : public PairMatchBase<Le2Matcher, std::less_equal<>> {
public:
static const char* Desc() { return "a pair where the first <= the second"; }
};
-class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
+class Ge2Matcher : public PairMatchBase<Ge2Matcher, std::greater_equal<>> {
public:
static const char* Desc() { return "a pair where the first >= the second"; }
};
@@ -964,8 +1233,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 {
@@ -982,8 +1250,6 @@ class NotMatcherImpl : public MatcherInterface<const T&> {
private:
const Matcher<T> matcher_;
-
- GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
};
// Implements the Not(m) matcher, which matches a value that doesn't
@@ -1002,8 +1268,6 @@ class NotMatcher {
private:
InnerMatcher matcher_;
-
- GTEST_DISALLOW_ASSIGN_(NotMatcher);
};
// Implements the AllOf(m1, m2) matcher for a particular argument type
@@ -1013,7 +1277,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 {
@@ -1064,9 +1328,7 @@ class AllOfMatcherImpl : public MatcherInterface<const T&> {
}
private:
- const std::vector<Matcher<T> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl);
+ const std::vector<Matcher<T>> matchers_;
};
// VariadicMatcher is used for the variadic implementation of
@@ -1081,19 +1343,22 @@ class VariadicMatcher {
static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
}
+ VariadicMatcher(const VariadicMatcher&) = default;
+ VariadicMatcher& operator=(const VariadicMatcher&) = delete;
+
// This template type conversion operator allows an
// VariadicMatcher<Matcher1, Matcher2...> object to match any type that
// 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>());
@@ -1101,12 +1366,10 @@ 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_;
-
- GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
};
template <typename... Args>
@@ -1119,7 +1382,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 {
@@ -1170,15 +1433,35 @@ class AnyOfMatcherImpl : public MatcherInterface<const T&> {
}
private:
- const std::vector<Matcher<T> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl);
+ 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 {
@@ -1192,6 +1475,7 @@ class SomeOfArrayMatcher {
operator Matcher<U>() const { // NOLINT
using RawU = typename std::decay<U>::type;
std::vector<Matcher<RawU>> matchers;
+ matchers.reserve(matchers_.size());
for (const auto& matcher : matchers_) {
matchers.push_back(MatcherCast<RawU>(matcher));
}
@@ -1200,8 +1484,6 @@ class SomeOfArrayMatcher {
private:
const ::std::vector<T> matchers_;
-
- GTEST_DISALLOW_ASSIGN_(SomeOfArrayMatcher);
};
template <typename T>
@@ -1223,15 +1505,15 @@ class TrulyMatcher {
// interested in the address of the argument.
template <typename T>
bool MatchAndExplain(T& x, // NOLINT
- MatchResultListener* /* listener */) const {
+ MatchResultListener* listener) const {
// Without the if-statement, MSVC sometimes warns about converting
// a value to bool (warning 4800).
//
// 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;
}
@@ -1245,8 +1527,6 @@ class TrulyMatcher {
private:
Predicate predicate_;
-
- GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
};
// Used for implementing Matches(matcher), which turns a matcher into
@@ -1283,8 +1563,6 @@ class MatcherAsPredicate {
private:
M matcher_;
-
- GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
};
// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
@@ -1323,7 +1601,7 @@ class PredicateFormatterFromMatcher {
<< "Expected: ";
matcher.DescribeTo(&ss);
- // Rerun the matcher to "PrintAndExain" the failure.
+ // Rerun the matcher to "PrintAndExplain" the failure.
StringMatchResultListener listener;
if (MatchPrintAndExplain(x, matcher, &listener)) {
ss << "\n The matcher failed on the initial attempt; but passed when "
@@ -1335,8 +1613,6 @@ class PredicateFormatterFromMatcher {
private:
const M matcher_;
-
- GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
};
// A helper function for converting a matcher to a predicate-formatter
@@ -1344,11 +1620,25 @@ 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));
}
+// Implements the polymorphic IsNan() matcher, which matches any floating type
+// value that is Nan.
+class IsNanMatcher {
+ public:
+ template <typename FloatType>
+ bool MatchAndExplain(const FloatType& f,
+ MatchResultListener* /* listener */) const {
+ return (::std::isnan)(f);
+ }
+
+ void DescribeTo(::std::ostream* os) const { *os << "is NaN"; }
+ void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NaN"; }
+};
+
// Implements the polymorphic floating point equality matcher, which matches
// two float values using ULP-based approximation or, optionally, a
// user-specified epsilon. The template is meant to be instantiated with
@@ -1362,9 +1652,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
@@ -1409,7 +1698,7 @@ class FloatingEqMatcher {
}
const FloatType diff = value - expected_;
- if (fabs(diff) <= max_abs_error_) {
+ if (::std::fabs(diff) <= max_abs_error_) {
return true;
}
@@ -1426,8 +1715,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";
@@ -1445,8 +1734,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";
@@ -1464,24 +1753,17 @@ 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_;
// max_abs_error will be used for value comparison when >= 0.
const FloatType max_abs_error_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
// The following 3 type conversion operators allow FloatEq(expected) and
// NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
// Matcher<const float&>, or a Matcher<float&>, but nothing else.
- // (While Google's C++ coding style doesn't allow arguments passed
- // by non-const reference, we may see them in code not conforming to
- // the style. Therefore Google Mock needs to support them.)
operator Matcher<FloatType>() const {
return MakeMatcher(
new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
@@ -1502,8 +1784,6 @@ class FloatingEqMatcher {
const bool nan_eq_nan_;
// max_abs_error will be used for value comparison when >= 0.
const FloatType max_abs_error_;
-
- GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
};
// A 2-tuple ("binary") wrapper around FloatingEqMatcher:
@@ -1545,9 +1825,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 {
@@ -1607,8 +1886,9 @@ class PointeeMatcher {
template <typename Pointer>
class Impl : public MatcherInterface<Pointer> {
public:
- typedef typename PointeeOf<typename std::remove_const<
- typename std::remove_reference<Pointer>::type>::type>::type Pointee;
+ using Pointee =
+ typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
+ Pointer)>::element_type;
explicit Impl(const InnerMatcher& matcher)
: matcher_(MatcherCast<const Pointee&>(matcher)) {}
@@ -1633,13 +1913,67 @@ class PointeeMatcher {
private:
const Matcher<const Pointee&> matcher_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const InnerMatcher matcher_;
+};
+
+// Implements the Pointer(m) matcher
+// Implements the Pointer(m) matcher for matching a pointer that matches matcher
+// m. The pointer can be either raw or smart, and will match `m` against the
+// raw pointer.
+template <typename InnerMatcher>
+class PointerMatcher {
+ public:
+ explicit PointerMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
+
+ // This type conversion operator template allows Pointer(m) to be
+ // used as a matcher for any pointer type whose pointer type is
+ // compatible with the inner matcher, where type PointerType can be
+ // either a raw pointer or a smart pointer.
+ //
+ // The reason we do this instead of relying on
+ // MakePolymorphicMatcher() is that the latter is not flexible
+ // enough for implementing the DescribeTo() method of Pointer().
+ template <typename PointerType>
+ operator Matcher<PointerType>() const { // NOLINT
+ return Matcher<PointerType>(new Impl<const PointerType&>(matcher_));
+ }
+
+ private:
+ // The monomorphic implementation that works for a particular pointer type.
+ template <typename PointerType>
+ class Impl : public MatcherInterface<PointerType> {
+ public:
+ using Pointer =
+ const typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
+ PointerType)>::element_type*;
+
+ explicit Impl(const InnerMatcher& matcher)
+ : matcher_(MatcherCast<Pointer>(matcher)) {}
+
+ void DescribeTo(::std::ostream* os) const override {
+ *os << "is a pointer that ";
+ matcher_.DescribeTo(os);
+ }
+
+ void DescribeNegationTo(::std::ostream* os) const override {
+ *os << "is not a pointer that ";
+ matcher_.DescribeTo(os);
+ }
+
+ bool MatchAndExplain(PointerType pointer,
+ MatchResultListener* listener) const override {
+ *listener << "which is a pointer that ";
+ Pointer p = GetRawPointer(pointer);
+ return MatchPrintAndExplain(p, matcher_, listener);
+ }
+
+ private:
+ Matcher<Pointer> matcher_;
+ };
- GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
+ const InnerMatcher matcher_;
};
#if GTEST_HAS_RTTI
@@ -1668,16 +2002,12 @@ 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) {
*os << "when dynamic_cast to " << GetToName() << ", ";
}
-
- GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
};
// Primary template.
@@ -1775,8 +2105,6 @@ class FieldMatcher {
// Contains either "whose given field " if the name of the field is unknown
// or "whose field `name_of_field` " if the name is known.
const std::string whose_field_;
-
- GTEST_DISALLOW_ASSIGN_(FieldMatcher);
};
// Implements the Property() matcher for matching a property
@@ -1811,7 +2139,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);
@@ -1845,8 +2173,6 @@ class PropertyMatcher {
// Contains either "whose given property " if the name of the property is
// unknown or "whose property `name_of_property` " if the name is known.
const std::string whose_property_;
-
- GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
};
// Type traits specifying various features of different functors for ResultOf.
@@ -1865,16 +2191,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);
}
};
@@ -1885,13 +2211,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:
@@ -1904,21 +2238,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
@@ -1929,6 +2278,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
@@ -1936,14 +2286,11 @@ class ResultOfMatcher {
// how many times the callable will be invoked.
mutable CallableStorageType callable_;
const Matcher<ResultType> matcher_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
}; // class Impl
+ const std::string result_description_;
const CallableStorageType callable_;
const InnerMatcher matcher_;
-
- GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
};
// Implements a matcher that checks the size of an STL-style container.
@@ -1951,8 +2298,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 {
@@ -1967,11 +2313,11 @@ class SizeIsMatcher {
: size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
void DescribeTo(::std::ostream* os) const override {
- *os << "size ";
+ *os << "has a size that ";
size_matcher_.DescribeTo(os);
}
void DescribeNegationTo(::std::ostream* os) const override {
- *os << "size ";
+ *os << "has a size that ";
size_matcher_.DescribeNegationTo(os);
}
@@ -1980,20 +2326,18 @@ 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;
}
private:
const Matcher<SizeType> size_matcher_;
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const SizeMatcher size_matcher_;
- GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
};
// Implements a matcher that checks the begin()..end() distance of an STL-style
@@ -2012,8 +2356,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;
@@ -2045,12 +2390,10 @@ class BeginEndDistanceIsMatcher {
private:
const Matcher<DistanceType> distance_matcher_;
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const DistanceMatcher distance_matcher_;
- GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
};
// Implements an equality matcher for any STL-style container whose elements
@@ -2095,18 +2438,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) {
@@ -2121,11 +2461,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 {
@@ -2143,14 +2482,14 @@ class ContainerEqMatcher {
private:
const StlContainer expected_;
-
- GTEST_DISALLOW_ASSIGN_(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).
@@ -2169,14 +2508,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) {}
@@ -2196,8 +2537,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
@@ -2210,8 +2551,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;
}
@@ -2220,14 +2561,13 @@ 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:
const Comparator comparator_;
const ContainerMatcher matcher_;
-
- GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
};
// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
@@ -2236,9 +2576,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;
@@ -2257,9 +2597,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_));
@@ -2268,8 +2608,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;
@@ -2309,14 +2650,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)),
@@ -2343,15 +2684,11 @@ class PointwiseMatcher {
private:
const Matcher<InnerMatcherArg> mono_tuple_matcher_;
const RhsStlContainer rhs_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const TupleMatcher tuple_matcher_;
const RhsStlContainer rhs_;
-
- GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
};
// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
@@ -2367,18 +2704,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);
@@ -2392,10 +2728,56 @@ 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_;
-
- GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
};
// Implements Contains(element_matcher) for the given argument type Container.
@@ -2422,9 +2804,6 @@ class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
MatchResultListener* listener) const override {
return this->MatchAndExplainImpl(false, container, listener);
}
-
- private:
- GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
};
// Implements Each(element_matcher) for the given argument type Container.
@@ -2451,9 +2830,58 @@ class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
MatchResultListener* listener) const override {
return this->MatchAndExplainImpl(true, container, listener);
}
+};
+
+// 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:
- GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
+ 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).
@@ -2463,15 +2891,17 @@ 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_;
-
- GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
};
// Implements polymorphic Each(element_matcher).
@@ -2481,15 +2911,13 @@ 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_));
}
private:
const M inner_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(EachMatcher);
};
struct Rank1 {};
@@ -2529,8 +2957,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.
@@ -2540,7 +2967,7 @@ class KeyMatcherImpl : public MatcherInterface<PairType> {
const bool match = inner_matcher_.MatchAndExplain(
pair_getters::First(key_value, Rank0()), &inner_listener);
const std::string explanation = inner_listener.str();
- if (explanation != "") {
+ if (!explanation.empty()) {
*listener << "whose first field is a value " << explanation;
}
return match;
@@ -2560,8 +2987,6 @@ class KeyMatcherImpl : public MatcherInterface<PairType> {
private:
const Matcher<const KeyType&> inner_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
};
// Implements polymorphic Key(matcher_for_key).
@@ -2578,8 +3003,49 @@ class KeyMatcher {
private:
const M matcher_for_key_;
+};
+
+// Implements polymorphic Address(matcher_for_address).
+template <typename InnerMatcher>
+class AddressMatcher {
+ public:
+ explicit AddressMatcher(InnerMatcher m) : matcher_(m) {}
+
+ template <typename Type>
+ operator Matcher<Type>() const { // NOLINT
+ return Matcher<Type>(new Impl<const Type&>(matcher_));
+ }
+
+ private:
+ // The monomorphic implementation that works for a particular object type.
+ template <typename Type>
+ class Impl : public MatcherInterface<Type> {
+ public:
+ using Address = const GTEST_REMOVE_REFERENCE_AND_CONST_(Type) *;
+ explicit Impl(const InnerMatcher& matcher)
+ : matcher_(MatcherCast<Address>(matcher)) {}
+
+ void DescribeTo(::std::ostream* os) const override {
+ *os << "has address that ";
+ matcher_.DescribeTo(os);
+ }
+
+ void DescribeNegationTo(::std::ostream* os) const override {
+ *os << "does not have address that ";
+ matcher_.DescribeTo(os);
+ }
- GTEST_DISALLOW_ASSIGN_(KeyMatcher);
+ bool MatchAndExplain(Type object,
+ MatchResultListener* listener) const override {
+ *listener << "which has address ";
+ Address address = std::addressof(object);
+ return MatchPrintAndExplain(address, matcher_, listener);
+ }
+
+ private:
+ const Matcher<Address> matcher_;
+ };
+ const InnerMatcher matcher_;
};
// Implements Pair(first_matcher, second_matcher) for the given argument pair
@@ -2596,8 +3062,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 {
@@ -2649,12 +3114,12 @@ class PairMatcherImpl : public MatcherInterface<PairType> {
const std::string& second_explanation,
MatchResultListener* listener) const {
*listener << "whose both fields match";
- if (first_explanation != "") {
+ if (!first_explanation.empty()) {
*listener << ", where the first field is a value " << first_explanation;
}
- if (second_explanation != "") {
+ if (!second_explanation.empty()) {
*listener << ", ";
- if (first_explanation != "") {
+ if (!first_explanation.empty()) {
*listener << "and ";
} else {
*listener << "where ";
@@ -2665,8 +3130,6 @@ class PairMatcherImpl : public MatcherInterface<PairType> {
const Matcher<const FirstType&> first_matcher_;
const Matcher<const SecondType&> second_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
};
// Implements polymorphic Pair(first_matcher, second_matcher).
@@ -2677,7 +3140,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_));
}
@@ -2685,8 +3148,218 @@ class PairMatcher {
private:
const FirstMatcher first_matcher_;
const SecondMatcher second_matcher_;
+};
+
+template <typename T, size_t... I>
+auto UnpackStructImpl(const T& t, IndexSequence<I...>, int)
+ -> decltype(std::tie(get<I>(t)...)) {
+ static_assert(std::tuple_size<T>::value == sizeof...(I),
+ "Number of arguments doesn't match the number of fields.");
+ return std::tie(get<I>(t)...);
+}
- GTEST_DISALLOW_ASSIGN_(PairMatcher);
+#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<1>, char) {
+ const auto& [a] = t;
+ return std::tie(a);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<2>, char) {
+ const auto& [a, b] = t;
+ return std::tie(a, b);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<3>, char) {
+ const auto& [a, b, c] = t;
+ return std::tie(a, b, c);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<4>, char) {
+ const auto& [a, b, c, d] = t;
+ return std::tie(a, b, c, d);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<5>, char) {
+ const auto& [a, b, c, d, e] = t;
+ return std::tie(a, b, c, d, e);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<6>, char) {
+ const auto& [a, b, c, d, e, f] = t;
+ return std::tie(a, b, c, d, e, f);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<7>, char) {
+ const auto& [a, b, c, d, e, f, g] = t;
+ return std::tie(a, b, c, d, e, f, g);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<8>, char) {
+ const auto& [a, b, c, d, e, f, g, h] = t;
+ return std::tie(a, b, c, d, e, f, g, h);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<9>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<10>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<11>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<12>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<13>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<14>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<15>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<17>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<18>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<19>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s);
+}
+#endif // defined(__cpp_structured_bindings)
+
+template <size_t I, typename T>
+auto UnpackStruct(const T& t)
+ -> decltype((UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0)) {
+ return (UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0);
+}
+
+// Helper function to do comma folding in C++11.
+// The array ensures left-to-right order of evaluation.
+// Usage: VariadicExpand({expr...});
+template <typename T, size_t N>
+void VariadicExpand(const T (&)[N]) {}
+
+template <typename Struct, typename StructSize>
+class FieldsAreMatcherImpl;
+
+template <typename Struct, size_t... I>
+class FieldsAreMatcherImpl<Struct, IndexSequence<I...>>
+ : public MatcherInterface<Struct> {
+ using UnpackedType =
+ decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>()));
+ using MatchersType = std::tuple<
+ Matcher<const typename std::tuple_element<I, UnpackedType>::type&>...>;
+
+ public:
+ template <typename Inner>
+ explicit FieldsAreMatcherImpl(const Inner& matchers)
+ : matchers_(testing::SafeMatcherCast<
+ const typename std::tuple_element<I, UnpackedType>::type&>(
+ std::get<I>(matchers))...) {}
+
+ void DescribeTo(::std::ostream* os) const override {
+ const char* separator = "";
+ VariadicExpand(
+ {(*os << separator << "has field #" << I << " that ",
+ std::get<I>(matchers_).DescribeTo(os), separator = ", and ")...});
+ }
+
+ void DescribeNegationTo(::std::ostream* os) const override {
+ const char* separator = "";
+ VariadicExpand({(*os << separator << "has field #" << I << " that ",
+ std::get<I>(matchers_).DescribeNegationTo(os),
+ separator = ", or ")...});
+ }
+
+ bool MatchAndExplain(Struct t, MatchResultListener* listener) const override {
+ return MatchInternal((UnpackStruct<sizeof...(I)>)(t), listener);
+ }
+
+ private:
+ bool MatchInternal(UnpackedType tuple, MatchResultListener* listener) const {
+ if (!listener->IsInterested()) {
+ // If the listener is not interested, we don't need to construct the
+ // explanation.
+ bool good = true;
+ VariadicExpand({good = good && std::get<I>(matchers_).Matches(
+ std::get<I>(tuple))...});
+ return good;
+ }
+
+ size_t failed_pos = ~size_t{};
+
+ std::vector<StringMatchResultListener> inner_listener(sizeof...(I));
+
+ VariadicExpand(
+ {failed_pos == ~size_t{} && !std::get<I>(matchers_).MatchAndExplain(
+ std::get<I>(tuple), &inner_listener[I])
+ ? failed_pos = I
+ : 0 ...});
+ if (failed_pos != ~size_t{}) {
+ *listener << "whose field #" << failed_pos << " does not match";
+ PrintIfNotEmpty(inner_listener[failed_pos].str(), listener->stream());
+ return false;
+ }
+
+ *listener << "whose all elements match";
+ const char* separator = ", where";
+ for (size_t index = 0; index < sizeof...(I); ++index) {
+ const std::string str = inner_listener[index].str();
+ if (!str.empty()) {
+ *listener << separator << " field #" << index << " is a value " << str;
+ separator = ", and";
+ }
+ }
+
+ return true;
+ }
+
+ MatchersType matchers_;
+};
+
+template <typename... Inner>
+class FieldsAreMatcher {
+ public:
+ explicit FieldsAreMatcher(Inner... inner) : matchers_(std::move(inner)...) {}
+
+ template <typename Struct>
+ operator Matcher<Struct>() const { // NOLINT
+ return Matcher<Struct>(
+ new FieldsAreMatcherImpl<const Struct&, IndexSequenceFor<Inner...>>(
+ matchers_));
+ }
+
+ private:
+ std::tuple<Inner...> matchers_;
};
// Implements ElementsAre() and ElementsAreArray().
@@ -2754,7 +3427,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?
@@ -2831,9 +3504,7 @@ class ElementsAreMatcherImpl : public MatcherInterface<Container> {
size_t count() const { return matchers_.size(); }
- ::std::vector<Matcher<const Element&> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
+ ::std::vector<Matcher<const Element&>> matchers_;
};
// Connectivity matrix of (elements X matchers), in element-major order.
@@ -2845,8 +3516,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_; }
@@ -2885,8 +3555,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 {
@@ -2923,9 +3592,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");
@@ -2936,8 +3603,6 @@ class GTEST_API_ UnorderedElementsAreMatcherImplBase {
private:
UnorderedMatcherRequire::Flags match_flags_;
MatcherDescriberVec matcher_describers_;
-
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
};
// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
@@ -2951,7 +3616,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>
@@ -2960,7 +3624,9 @@ class UnorderedElementsAreMatcherImpl
: UnorderedElementsAreMatcherImplBase(matcher_flags) {
for (; first != last; ++first) {
matchers_.push_back(MatcherCast<const Element&>(*first));
- matcher_describers().push_back(matchers_.back().GetDescriber());
+ }
+ for (const auto& m : matchers_) {
+ matcher_describers().push_back(m.GetDescriber());
}
}
@@ -2982,23 +3648,6 @@ class UnorderedElementsAreMatcherImpl
AnalyzeElements(stl_container.begin(), stl_container.end(),
&element_printouts, listener);
- if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
- return true;
- }
-
- if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
- if (matrix.LhsSize() != matrix.RhsSize()) {
- // The element count doesn't match. If the container is empty,
- // there's no need to explain anything as Google Mock already
- // prints the empty container. Otherwise we just need to show
- // how many elements there actually are.
- if (matrix.LhsSize() != 0 && listener->IsInterested()) {
- *listener << "which has " << Elements(matrix.LhsSize());
- }
- return false;
- }
- }
-
return VerifyMatchMatrix(element_printouts, matrix, listener) &&
FindPairing(matrix, listener);
}
@@ -3011,12 +3660,14 @@ class UnorderedElementsAreMatcherImpl
element_printouts->clear();
::std::vector<char> did_match;
size_t num_elements = 0;
+ DummyMatchResultListener dummy;
for (; elem_first != elem_last; ++num_elements, ++elem_first) {
if (listener->IsInterested()) {
element_printouts->push_back(PrintToString(*elem_first));
}
for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
- did_match.push_back(Matches(matchers_[irhs])(*elem_first));
+ did_match.push_back(
+ matchers_[irhs].MatchAndExplain(*elem_first, &dummy));
}
}
@@ -3030,9 +3681,7 @@ class UnorderedElementsAreMatcherImpl
return matrix;
}
- ::std::vector<Matcher<const Element&> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
+ ::std::vector<Matcher<const Element&>> matchers_;
};
// Functor for use in TransformTuple.
@@ -3057,7 +3706,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_,
@@ -3070,7 +3719,6 @@ class UnorderedElementsAreMatcher {
private:
const MatcherTuple matchers_;
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
};
// Implements ElementsAre.
@@ -3081,15 +3729,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_,
@@ -3100,7 +3748,6 @@ class ElementsAreMatcher {
private:
const MatcherTuple matchers_;
- GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
};
// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
@@ -3122,8 +3769,6 @@ class UnorderedElementsAreArrayMatcher {
private:
UnorderedMatcherRequire::Flags match_flags_;
::std::vector<T> matchers_;
-
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
};
// Implements ElementsAreArray().
@@ -3135,9 +3780,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()));
@@ -3145,8 +3790,6 @@ class ElementsAreArrayMatcher {
private:
const ::std::vector<T> matchers_;
-
- GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
};
// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
@@ -3164,6 +3807,8 @@ class BoundSecondMatcher {
BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
: tuple2_matcher_(tm), second_value_(second) {}
+ BoundSecondMatcher(const BoundSecondMatcher& other) = default;
+
template <typename T>
operator Matcher<T>() const {
return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
@@ -3206,8 +3851,6 @@ class BoundSecondMatcher {
private:
const Matcher<const ArgTuple&> mono_tuple2_matcher_;
const Second second_value_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const Tuple2Matcher tuple2_matcher_;
@@ -3229,9 +3872,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>
@@ -3280,12 +3923,10 @@ class OptionalMatcher {
private:
const Matcher<ValueType> value_matcher_;
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const ValueMatcher value_matcher_;
- GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
};
namespace variant_matcher {
@@ -3461,7 +4102,12 @@ class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
const char* sep = "";
// Workaround spurious C4189 on MSVC<=15.7 when k is empty.
(void)sep;
- const char* dummy[] = {"", (*os << sep << "#" << k, sep = ", ")...};
+ // The static_cast to void is needed to silence Clang's -Wcomma warning.
+ // This pattern looks suspiciously like we may have mismatched parentheses
+ // and may have been trying to use the first operation of the comma operator
+ // as a member of the array, so Clang warns that we may have made a mistake.
+ const char* dummy[] = {
+ "", (static_cast<void>(*os << sep << "#" << k), sep = ", ")...};
(void)dummy;
*os << ") ";
}
@@ -3510,26 +4156,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());
}
@@ -3556,14 +4202,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);
}
@@ -3575,8 +4221,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());
}
@@ -3593,12 +4239,14 @@ const internal::AnythingMatcher _ = {};
// Creates a matcher that matches any value of the given type T.
template <typename T>
inline Matcher<T> A() {
- return Matcher<T>(new internal::AnyMatcherImpl<T>());
+ return _;
}
// Creates a matcher that matches any value of the given type T.
template <typename T>
-inline Matcher<T> An() { return A<T>(); }
+inline Matcher<T> An() {
+ return _;
+}
template <typename T, typename M>
Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
@@ -3608,14 +4256,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());
}
@@ -3626,6 +4274,11 @@ inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
return internal::RefMatcher<T&>(x);
}
+// Creates a polymorphic matcher that matches any NaN floating point.
+inline PolymorphicMatcher<internal::IsNanMatcher> IsNan() {
+ return MakePolymorphicMatcher(internal::IsNanMatcher());
+}
+
// Creates a matcher that matches any double argument approximately
// equal to rhs, where two NANs are considered unequal.
inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
@@ -3641,8 +4294,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);
}
@@ -3669,8 +4322,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);
}
@@ -3698,7 +4351,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));
@@ -3710,12 +4363,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)
@@ -3725,7 +4376,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>(
@@ -3738,7 +4389,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(
@@ -3755,7 +4406,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) {
@@ -3768,8 +4419,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,
@@ -3780,9 +4431,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,
@@ -3801,109 +4452,127 @@ 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.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
- const std::string& str) {
+template <typename T = std::string>
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrEq(
+ const internal::StringLike<T>& str) {
return MakePolymorphicMatcher(
- internal::StrEqualityMatcher<std::string>(str, true, true));
+ internal::StrEqualityMatcher<std::string>(std::string(str), true, true));
}
// Matches a string not equal to str.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
- const std::string& str) {
+template <typename T = std::string>
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrNe(
+ const internal::StringLike<T>& str) {
return MakePolymorphicMatcher(
- internal::StrEqualityMatcher<std::string>(str, false, true));
+ internal::StrEqualityMatcher<std::string>(std::string(str), false, true));
}
// Matches a string equal to str, ignoring case.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
- const std::string& str) {
+template <typename T = std::string>
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseEq(
+ const internal::StringLike<T>& str) {
return MakePolymorphicMatcher(
- internal::StrEqualityMatcher<std::string>(str, true, false));
+ internal::StrEqualityMatcher<std::string>(std::string(str), true, false));
}
// Matches a string not equal to str, ignoring case.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
- const std::string& str) {
- return MakePolymorphicMatcher(
- internal::StrEqualityMatcher<std::string>(str, false, false));
+template <typename T = std::string>
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseNe(
+ const internal::StringLike<T>& str) {
+ return MakePolymorphicMatcher(internal::StrEqualityMatcher<std::string>(
+ std::string(str), false, false));
}
// Creates a matcher that matches any string, std::string, or C string
// that contains the given substring.
-inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
- const std::string& substring) {
+template <typename T = std::string>
+PolymorphicMatcher<internal::HasSubstrMatcher<std::string>> HasSubstr(
+ const internal::StringLike<T>& substring) {
return MakePolymorphicMatcher(
- internal::HasSubstrMatcher<std::string>(substring));
+ internal::HasSubstrMatcher<std::string>(std::string(substring)));
}
// Matches a string that starts with 'prefix' (case-sensitive).
-inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
- const std::string& prefix) {
+template <typename T = std::string>
+PolymorphicMatcher<internal::StartsWithMatcher<std::string>> StartsWith(
+ const internal::StringLike<T>& prefix) {
return MakePolymorphicMatcher(
- internal::StartsWithMatcher<std::string>(prefix));
+ internal::StartsWithMatcher<std::string>(std::string(prefix)));
}
// Matches a string that ends with 'suffix' (case-sensitive).
-inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
- const std::string& suffix) {
- return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
+template <typename T = std::string>
+PolymorphicMatcher<internal::EndsWithMatcher<std::string>> EndsWith(
+ const internal::StringLike<T>& suffix) {
+ return MakePolymorphicMatcher(
+ internal::EndsWithMatcher<std::string>(std::string(suffix)));
}
#if GTEST_HAS_STD_WSTRING
// 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));
@@ -3998,8 +4667,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));
}
@@ -4010,8 +4679,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);
}
@@ -4021,8 +4690,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);
}
@@ -4031,22 +4700,17 @@ 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) {
- // This following line is for working around a bug in MSVC 8.0,
- // which causes Container to be a const type sometimes.
- typedef typename std::remove_const<Container>::type RawContainer;
- return MakePolymorphicMatcher(
- internal::ContainerEqMatcher<RawContainer>(rhs));
+ return MakePolymorphicMatcher(internal::ContainerEqMatcher<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);
}
@@ -4056,9 +4720,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
@@ -4071,23 +4735,17 @@ template <typename TupleMatcher, typename Container>
inline internal::PointwiseMatcher<TupleMatcher,
typename std::remove_const<Container>::type>
Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
- // This following line is for working around a bug in MSVC 8.0,
- // which causes Container to be a const type sometimes (e.g. when
- // rhs is a const int[])..
- typedef typename std::remove_const<Container>::type RawContainer;
- return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
- tuple_matcher, rhs);
+ return internal::PointwiseMatcher<TupleMatcher, Container>(tuple_matcher,
+ 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
@@ -4107,42 +4765,34 @@ inline internal::UnorderedElementsAreArrayMatcher<
typename std::remove_const<RhsContainer>::type>::type::value_type>>
UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
const RhsContainer& rhs_container) {
- // This following line is for working around a bug in MSVC 8.0,
- // which causes RhsContainer to be a const type sometimes (e.g. when
- // rhs_container is a const int[]).
- typedef typename std::remove_const<RhsContainer>::type RawRhsContainer;
-
// RhsView allows the same code to handle RhsContainer being a
// STL-style container and it being a native C-style array.
- typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
+ typedef typename internal::StlContainerView<RhsContainer> RhsView;
typedef typename RhsView::type RhsStlContainer;
typedef typename RhsStlContainer::value_type Second;
const RhsStlContainer& rhs_stl_container =
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.
//
@@ -4152,7 +4802,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;
@@ -4161,6 +4811,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);
@@ -4287,7 +4950,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:
@@ -4330,12 +4993,61 @@ 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.
+// In particular, `std::tuple`, `std::pair`, `std::array` and aggregate types.
+template <typename... M>
+internal::FieldsAreMatcher<typename std::decay<M>::type...> FieldsAre(
+ M&&... matchers) {
+ return internal::FieldsAreMatcher<typename std::decay<M>::type...>(
+ std::forward<M>(matchers)...);
}
+// Creates a matcher that matches a pointer (raw or smart) that matches
+// inner_matcher.
+template <typename InnerMatcher>
+inline internal::PointerMatcher<InnerMatcher> Pointer(
+ const InnerMatcher& inner_matcher) {
+ return internal::PointerMatcher<InnerMatcher>(inner_matcher);
+}
+
+// Creates a matcher that matches an object that has an address that matches
+// inner_matcher.
+template <typename InnerMatcher>
+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
// given matcher.
template <typename M>
@@ -4352,8 +5064,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);
}
@@ -4363,7 +5075,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);
// }
@@ -4512,7 +5225,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<>
@@ -4520,7 +5235,7 @@ inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
// and is printable using 'PrintToString'. It is compatible with
// std::optional/std::experimental::optional.
// Note that to compare an optional type variable against nullopt you should
-// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
+// use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the
// optional value contains an optional itself.
template <typename ValueMatcher>
inline internal::OptionalMatcher<ValueMatcher> Optional(
@@ -4530,7 +5245,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));
@@ -4541,20 +5256,360 @@ 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));
}
+#if GTEST_HAS_EXCEPTIONS
+
+// Anything inside the `internal` namespace is internal to the implementation
+// and must not be used in user code!
+namespace internal {
+
+class WithWhatMatcherImpl {
+ public:
+ WithWhatMatcherImpl(Matcher<std::string> matcher)
+ : matcher_(std::move(matcher)) {}
+
+ void DescribeTo(std::ostream* os) const {
+ *os << "contains .what() that ";
+ matcher_.DescribeTo(os);
+ }
+
+ void DescribeNegationTo(std::ostream* os) const {
+ *os << "contains .what() that does not ";
+ matcher_.DescribeTo(os);
+ }
+
+ template <typename Err>
+ bool MatchAndExplain(const Err& err, MatchResultListener* listener) const {
+ *listener << "which contains .what() (of value = " << err.what()
+ << ") that ";
+ return matcher_.MatchAndExplain(err.what(), listener);
+ }
+
+ private:
+ const Matcher<std::string> matcher_;
+};
+
+inline PolymorphicMatcher<WithWhatMatcherImpl> WithWhat(
+ Matcher<std::string> m) {
+ return MakePolymorphicMatcher(WithWhatMatcherImpl(std::move(m)));
+}
+
+template <typename Err>
+class ExceptionMatcherImpl {
+ class NeverThrown {
+ public:
+ const char* what() const noexcept {
+ return "this exception should never be thrown";
+ }
+ };
+
+ // If the matchee raises an exception of a wrong type, we'd like to
+ // catch it and print its message and type. To do that, we add an additional
+ // catch clause:
+ //
+ // try { ... }
+ // catch (const Err&) { /* an expected exception */ }
+ // catch (const std::exception&) { /* exception of a wrong type */ }
+ //
+ // However, if the `Err` itself is `std::exception`, we'd end up with two
+ // identical `catch` clauses:
+ //
+ // try { ... }
+ // catch (const std::exception&) { /* an expected exception */ }
+ // catch (const std::exception&) { /* exception of a wrong type */ }
+ //
+ // This can cause a warning or an error in some compilers. To resolve
+ // the issue, we use a fake error type whenever `Err` is `std::exception`:
+ //
+ // try { ... }
+ // catch (const std::exception&) { /* an expected exception */ }
+ // catch (const NeverThrown&) { /* exception of a wrong type */ }
+ using DefaultExceptionType = typename std::conditional<
+ std::is_same<typename std::remove_cv<
+ typename std::remove_reference<Err>::type>::type,
+ std::exception>::value,
+ const NeverThrown&, const std::exception&>::type;
+
+ public:
+ ExceptionMatcherImpl(Matcher<const Err&> matcher)
+ : matcher_(std::move(matcher)) {}
+
+ void DescribeTo(std::ostream* os) const {
+ *os << "throws an exception which is a " << GetTypeName<Err>();
+ *os << " which ";
+ matcher_.DescribeTo(os);
+ }
+
+ void DescribeNegationTo(std::ostream* os) const {
+ *os << "throws an exception which is not a " << GetTypeName<Err>();
+ *os << " which ";
+ matcher_.DescribeNegationTo(os);
+ }
+
+ template <typename T>
+ bool MatchAndExplain(T&& x, MatchResultListener* listener) const {
+ try {
+ (void)(std::forward<T>(x)());
+ } catch (const Err& err) {
+ *listener << "throws an exception which is a " << GetTypeName<Err>();
+ *listener << " ";
+ return matcher_.MatchAndExplain(err, listener);
+ } catch (DefaultExceptionType err) {
+#if GTEST_HAS_RTTI
+ *listener << "throws an exception of type " << GetTypeName(typeid(err));
+ *listener << " ";
+#else
+ *listener << "throws an std::exception-derived type ";
+#endif
+ *listener << "with description \"" << err.what() << "\"";
+ return false;
+ } catch (...) {
+ *listener << "throws an exception of an unknown type";
+ return false;
+ }
+
+ *listener << "does not throw any exception";
+ return false;
+ }
+
+ private:
+ const Matcher<const Err&> matcher_;
+};
+
+} // namespace internal
+
+// Throws()
+// Throws(exceptionMatcher)
+// ThrowsMessage(messageMatcher)
+//
+// This matcher accepts a callable and verifies that when invoked, it throws
+// an exception with the given type and properties.
+//
+// Examples:
+//
+// EXPECT_THAT(
+// []() { throw std::runtime_error("message"); },
+// Throws<std::runtime_error>());
+//
+// EXPECT_THAT(
+// []() { throw std::runtime_error("message"); },
+// ThrowsMessage<std::runtime_error>(HasSubstr("message")));
+//
+// EXPECT_THAT(
+// []() { throw std::runtime_error("message"); },
+// Throws<std::runtime_error>(
+// Property(&std::runtime_error::what, HasSubstr("message"))));
+
+template <typename Err>
+PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws() {
+ return MakePolymorphicMatcher(
+ internal::ExceptionMatcherImpl<Err>(A<const Err&>()));
+}
+
+template <typename Err, typename ExceptionMatcher>
+PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws(
+ const ExceptionMatcher& exception_matcher) {
+ // Using matcher cast allows users to pass a matcher of a more broad type.
+ // For example user may want to pass Matcher<std::exception>
+ // to Throws<std::runtime_error>, or Matcher<int64> to Throws<int32>.
+ return MakePolymorphicMatcher(internal::ExceptionMatcherImpl<Err>(
+ SafeMatcherCast<const Err&>(exception_matcher)));
+}
+
+template <typename Err, typename MessageMatcher>
+PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
+ MessageMatcher&& message_matcher) {
+ static_assert(std::is_base_of<std::exception, Err>::value,
+ "expected an std::exception-derived type");
+ return Throws<Err>(internal::WithWhat(
+ MatcherCast<std::string>(std::forward<MessageMatcher>(message_matcher))));
+}
+
+#endif // GTEST_HAS_EXCEPTIONS
+
// These macros allow using matchers to check values in Google Test
// 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)
+#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> { \
+ public: \
+ template <typename arg_type> \
+ class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
+ public: \
+ gmock_Impl() {} \
+ bool MatchAndExplain( \
+ const arg_type& arg, \
+ ::testing::MatchResultListener* result_listener) const override; \
+ void DescribeTo(::std::ostream* gmock_os) const override { \
+ *gmock_os << FormatDescription(false); \
+ } \
+ void DescribeNegationTo(::std::ostream* gmock_os) const override { \
+ *gmock_os << FormatDescription(true); \
+ } \
+ \
+ 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, \
+ {}, {}); \
+ } \
+ }; \
+ }; \
+ inline name##Matcher GMOCK_INTERNAL_WARNING_PUSH() \
+ GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-function") \
+ GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \
+ name GMOCK_INTERNAL_WARNING_POP()() { \
+ return {}; \
+ } \
+ template <typename arg_type> \
+ bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \
+ const arg_type& arg, \
+ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) \
+ const
+
+#define MATCHER_P(name, p0, description) \
+ 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))
+#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, 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)>> { \
+ public: \
+ using full_name::MatcherBaseImpl::MatcherBaseImpl; \
+ template <typename arg_type> \
+ class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
+ public: \
+ explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) \
+ : GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {} \
+ bool MatchAndExplain( \
+ const arg_type& arg, \
+ ::testing::MatchResultListener* result_listener) const override; \
+ void DescribeTo(::std::ostream* gmock_os) const override { \
+ *gmock_os << FormatDescription(false); \
+ } \
+ void DescribeNegationTo(::std::ostream* gmock_os) const override { \
+ *gmock_os << FormatDescription(true); \
+ } \
+ GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
+ \
+ private: \
+ ::std::string FormatDescription(bool negation) const { \
+ ::std::string gmock_description; \
+ gmock_description = (description); \
+ if (!gmock_description.empty()) { \
+ return gmock_description; \
+ } \
+ return ::testing::internal::FormatMatcherDescription( \
+ 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)))); \
+ } \
+ }; \
+ }; \
+ template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
+ inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name( \
+ GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) { \
+ return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
+ GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args)); \
+ } \
+ template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
+ template <typename arg_type> \
+ bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>::gmock_Impl< \
+ arg_type>::MatchAndExplain(const arg_type& arg, \
+ ::testing::MatchResultListener* \
+ result_listener GTEST_ATTRIBUTE_UNUSED_) \
+ const
+
+#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \
+ GMOCK_PP_TAIL( \
+ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args))
+#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \
+ , typename arg##_type
+
+#define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args))
+#define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \
+ , arg##_type
+
+#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \
+ GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH( \
+ GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args))
+#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \
+ , arg##_type gmock_p##i
+
+#define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args))
+#define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \
+ , arg(::std::forward<arg##_type>(gmock_p##i))
+
+#define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
+ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args)
+#define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \
+ const arg##_type arg;
+
+#define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args))
+#define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg
+
+#define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))
+#define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg_unused) \
+ , gmock_p##i
+
+// To prevent ADL on certain functions we put them on a separate namespace.
+using namespace no_adl; // NOLINT
} // namespace testing
@@ -4565,4 +5620,4 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
// declarations from this file.
#include "gmock/internal/custom/gmock-matchers.h"
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
diff --git a/googlemock/include/gmock/gmock-more-actions.h b/googlemock/include/gmock/gmock-more-actions.h
index d42484aef2bc..40300766f084 100644
--- a/googlemock/include/gmock/gmock-more-actions.h
+++ b/googlemock/include/gmock/gmock-more-actions.h
@@ -27,136 +27,632 @@
// (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 actions that depend on gmock-generated-actions.h.
+// 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 GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
-#include <algorithm>
-#include <type_traits>
+#include <memory>
+#include <utility>
-#include "gmock/gmock-generated-actions.h"
+#include "gmock/gmock-actions.h"
+#include "gmock/internal/gmock-port.h"
-namespace testing {
-namespace internal {
+// Include any custom callback actions added by the local installation.
+#include "gmock/internal/custom/gmock-generated-actions.h"
-// An internal replacement for std::copy which mimics its behavior. This is
-// necessary because Visual Studio deprecates ::std::copy, issuing warning 4996.
-// However Visual Studio 2010 and later do not honor #pragmas which disable that
-// warning.
-template<typename InputIterator, typename OutputIterator>
-inline OutputIterator CopyElements(InputIterator first,
- InputIterator last,
- OutputIterator output) {
- for (; first != last; ++first, ++output) {
- *output = *first;
- }
- return output;
-}
+// Sometimes you want to give an action explicit template parameters
+// that cannot be inferred from its value parameters. ACTION() and
+// ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that
+// and can be viewed as an extension to ACTION() and ACTION_P*().
+//
+// The syntax:
+//
+// ACTION_TEMPLATE(ActionName,
+// HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
+// AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
+//
+// defines an action template that takes m explicit template
+// parameters and n value parameters. name_i is the name of the i-th
+// template parameter, and kind_i specifies whether it's a typename,
+// an integral constant, or a template. p_i is the name of the i-th
+// value parameter.
+//
+// Example:
+//
+// // DuplicateArg<k, T>(output) converts the k-th argument of the mock
+// // function to type T and copies it to *output.
+// ACTION_TEMPLATE(DuplicateArg,
+// HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
+// AND_1_VALUE_PARAMS(output)) {
+// *output = T(::std::get<k>(args));
+// }
+// ...
+// int n;
+// EXPECT_CALL(mock, Foo(_, _))
+// .WillOnce(DuplicateArg<1, unsigned char>(&n));
+//
+// To create an instance of an action template, write:
+//
+// ActionName<t1, ..., t_m>(v1, ..., v_n)
+//
+// where the ts are the template arguments and the vs are the value
+// arguments. The value argument types are inferred by the compiler.
+// If you want to explicitly specify the value argument types, you can
+// provide additional template arguments:
+//
+// ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
+//
+// where u_i is the desired type of v_i.
+//
+// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
+// number of value parameters, but not on the number of template
+// parameters. Without the restriction, the meaning of the following
+// is unclear:
+//
+// OverloadedAction<int, bool>(x);
+//
+// Are we using a single-template-parameter action where 'bool' refers
+// to the type of x, or are we using a two-template-parameter action
+// where the compiler is asked to infer the type of x?
+//
+// Implementation notes:
+//
+// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
+// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
+// implementing ACTION_TEMPLATE. The main trick we use is to create
+// new macro invocations when expanding a macro. For example, we have
+//
+// #define ACTION_TEMPLATE(name, template_params, value_params)
+// ... GMOCK_INTERNAL_DECL_##template_params ...
+//
+// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
+// to expand to
+//
+// ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
+//
+// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
+// preprocessor will continue to expand it to
+//
+// ... typename T ...
+//
+// This technique conforms to the C++ standard and is portable. It
+// allows us to implement action templates using O(N) code, where N is
+// the maximum number of template/value parameters supported. Without
+// using it, we'd have to devote O(N^2) amount of code to implement all
+// combinations of m and n.
-} // namespace internal
+// 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_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ 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
+#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
+
+// 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_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ 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
+#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
+
+// 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_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
+#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
+#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
+#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
-// Various overloads for Invoke().
+// 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)), \
+ 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)), \
+ 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)), \
+ 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_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)), \
+ 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
+#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;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_4_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_5_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_6_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_7_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_8_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_9_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_10_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_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;
+
+// Lists the value parameters.
+#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
+#define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0
+#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_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ 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_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ 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
+#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
+#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
+
+// 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_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
+
+// The suffix of the class template implementing the action template.
+#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
+#define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P
+#define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2
+#define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3
+#define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4
+#define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5
+#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
+#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7, p8) \
+ P9
+#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ 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 ACTION_TEMPLATE(name, template_params, value_params) \
+ template <GMOCK_INTERNAL_DECL_##template_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; \
+ , \
+ : 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 { \
+ return GMOCK_PP_IF( \
+ GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
+ (::testing::internal::MakeAction<F, gmock_Impl>()), \
+ (::testing::internal::MakeAction<F>(impl_))); \
+ } \
+ \
+ private: \
+ class gmock_Impl { \
+ public: \
+ explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_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_INTERNAL_DEFN_##value_params \
+ }; \
+ 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_; \
+ 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); \
+ } \
+ template <GMOCK_INTERNAL_DECL_##template_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
+
+namespace testing {
// The ACTION*() macros trigger warning C4100 (unreferenced formal
// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
// the macro definition, as the warnings are generated when the macro
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#endif
-
-// Action ReturnArg<k>() returns the k-th argument of the mock function.
-ACTION_TEMPLATE(ReturnArg,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_0_VALUE_PARAMS()) {
- return ::std::get<k>(args);
-}
-
-// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
-// mock function to *pointer.
-ACTION_TEMPLATE(SaveArg,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_1_VALUE_PARAMS(pointer)) {
- *pointer = ::std::get<k>(args);
-}
-
-// Action SaveArgPointee<k>(pointer) saves the value pointed to
-// by the k-th (0-based) argument of the mock function to *pointer.
-ACTION_TEMPLATE(SaveArgPointee,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_1_VALUE_PARAMS(pointer)) {
- *pointer = *::std::get<k>(args);
-}
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
-// Action SetArgReferee<k>(value) assigns 'value' to the variable
-// referenced by the k-th (0-based) argument of the mock function.
-ACTION_TEMPLATE(SetArgReferee,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_1_VALUE_PARAMS(value)) {
- typedef typename ::std::tuple_element<k, args_type>::type argk_type;
- // Ensures that argument #k is a reference. If you get a compiler
- // error on the next line, you are using SetArgReferee<k>(value) in
- // a mock function whose k-th (0-based) argument is not a reference.
- GTEST_COMPILE_ASSERT_(std::is_reference<argk_type>::value,
- SetArgReferee_must_be_used_with_a_reference_argument);
- ::std::get<k>(args) = value;
-}
-
-// Action SetArrayArgument<k>(first, last) copies the elements in
-// source range [first, last) to the array pointed to by the k-th
-// (0-based) argument, which can be either a pointer or an
-// iterator. The action does not take ownership of the elements in the
-// source range.
-ACTION_TEMPLATE(SetArrayArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_2_VALUE_PARAMS(first, last)) {
- // Visual Studio deprecates ::std::copy, so we use our own copy in that case.
-#ifdef _MSC_VER
- internal::CopyElements(first, last, ::std::get<k>(args));
-#else
- ::std::copy(first, last, ::std::get<k>(args));
-#endif
-}
+namespace internal {
-// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
-// function.
-ACTION_TEMPLATE(DeleteArg,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_0_VALUE_PARAMS()) {
- delete ::std::get<k>(args);
+// internal::InvokeArgument - a helper for InvokeArgument action.
+// The basic overloads are provided here for generic functors.
+// Overloads for other custom-callables are provided in the
+// internal/custom/gmock-generated-actions.h header.
+template <typename F, typename... Args>
+auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) {
+ return f(args...);
}
-// This action returns the value pointed to by 'pointer'.
-ACTION_P(ReturnPointee, pointer) { return *pointer; }
+template <std::size_t index, typename... Params>
+struct InvokeArgumentAction {
+ 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 &>()...)) {
+ internal::FlatTuple<Args &&...> args_tuple(FlatTupleConstructTag{},
+ std::forward<Args>(args)...);
+ return params.Apply([&](const Params &...unpacked_params) {
+ auto &&callable = args_tuple.template Get<index>();
+ return internal::InvokeArgument(
+ std::forward<decltype(callable)>(callable), unpacked_params...);
+ });
+ }
-// Action Throw(exception) can be used in a mock function of any type
-// to throw the given exception. Any copyable value can be thrown.
-#if GTEST_HAS_EXCEPTIONS
+ internal::FlatTuple<Params...> params;
+};
-// Suppresses the 'unreachable code' warning that VC generates in opt modes.
-# ifdef _MSC_VER
-# pragma warning(push) // Saves the current warning state.
-# pragma warning(disable:4702) // Temporarily disables warning 4702.
-# endif
-ACTION_P(Throw, exception) { throw exception; }
-# ifdef _MSC_VER
-# pragma warning(pop) // Restores the warning state.
-# endif
+} // namespace internal
-#endif // GTEST_HAS_EXCEPTIONS
+// The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
+// (0-based) argument, which must be a k-ary callable, of the mock
+// function, with arguments a1, a2, ..., a_k.
+//
+// Notes:
+//
+// 1. The arguments are passed by value by default. If you need to
+// pass an argument by reference, wrap it inside std::ref(). For
+// example,
+//
+// InvokeArgument<1>(5, string("Hello"), std::ref(foo))
+//
+// passes 5 and string("Hello") by value, and passes foo by
+// reference.
+//
+// 2. If the callable takes an argument by reference but std::ref() is
+// not used, it will receive the reference to a copy of the value,
+// instead of the original value. For example, when the 0-th
+// argument of the mock function takes a const string&, the action
+//
+// InvokeArgument<0>(string("Hello"))
+//
+// makes a copy of the temporary string("Hello") object and passes a
+// reference of the copy, instead of the original temporary object,
+// to the callable. This makes it easy for a user to define an
+// InvokeArgument action from temporary values and have it performed
+// later.
+template <std::size_t index, typename... Params>
+internal::InvokeArgumentAction<index, typename std::decay<Params>::type...>
+InvokeArgument(Params &&...params) {
+ return {internal::FlatTuple<typename std::decay<Params>::type...>(
+ internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)};
+}
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
} // namespace testing
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
diff --git a/googlemock/include/gmock/gmock-more-matchers.h b/googlemock/include/gmock/gmock-more-matchers.h
index 1c9a399a341e..54ea68be969d 100644
--- a/googlemock/include/gmock/gmock-more-matchers.h
+++ b/googlemock/include/gmock/gmock-more-matchers.h
@@ -27,43 +27,71 @@
// (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-generated-matchers.h.
+// This file implements some matchers that depend on gmock-matchers.h.
//
// 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_
-#ifndef GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_
+#include <ostream>
+#include <string>
-#include "gmock/gmock-generated-matchers.h"
+#include "gmock/gmock-matchers.h"
namespace testing {
// Silence C4100 (unreferenced formal
// parameter) for MSVC
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#if (_MSC_VER == 1900)
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
+#if defined(_MSC_VER) && (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14
-# pragma warning(disable:4800)
- #endif
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#endif
-// Defines a matcher that matches an empty container. The container must
-// support both size() and empty(), which all STL-like containers provide.
-MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") {
- if (arg.empty()) {
- return true;
+namespace internal {
+
+// Implements the polymorphic IsEmpty matcher, which
+// can be used as a Matcher<T> as long as T is either a container that defines
+// empty() and size() (e.g. std::vector or std::string), or a C-style string.
+class IsEmptyMatcher {
+ public:
+ // Matches anything that defines empty() and size().
+ template <typename MatcheeContainerType>
+ bool MatchAndExplain(const MatcheeContainerType& c,
+ MatchResultListener* listener) const {
+ if (c.empty()) {
+ return true;
+ }
+ *listener << "whose size is " << c.size();
+ return false;
+ }
+
+ // Matches C-style strings.
+ bool MatchAndExplain(const char* s, MatchResultListener* listener) const {
+ return MatchAndExplain(std::string(s), listener);
}
- *result_listener << "whose size is " << arg.size();
- return false;
+
+ // Describes what this matcher matches.
+ void DescribeTo(std::ostream* os) const { *os << "is empty"; }
+
+ void DescribeNegationTo(std::ostream* os) const { *os << "isn't empty"; }
+};
+
+} // namespace internal
+
+// Creates a polymorphic matcher that matches an empty container or C-style
+// string. The container must support both size() and empty(), which all
+// STL-like containers provide.
+inline PolymorphicMatcher<internal::IsEmptyMatcher> IsEmpty() {
+ return MakePolymorphicMatcher(internal::IsEmptyMatcher());
}
// Define a matcher that matches a value that evaluates in boolean
@@ -82,11 +110,11 @@ MATCHER(IsFalse, negation ? "is true" : "is false") {
return !static_cast<bool>(arg);
}
-#ifdef _MSC_VER
-# pragma warning(pop)
+#if defined(_MSC_VER) && (_MSC_VER == 1900)
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#endif
-
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
} // namespace testing
-#endif // GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
diff --git a/googlemock/include/gmock/gmock-nice-strict.h b/googlemock/include/gmock/gmock-nice-strict.h
index 5495a9805b5f..056d471417e3 100644
--- a/googlemock/include/gmock/gmock-nice-strict.h
+++ b/googlemock/include/gmock/gmock-nice-strict.h
@@ -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,
@@ -58,22 +57,107 @@
// 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_
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
+#include <cstdint>
+#include <type_traits>
#include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-port.h"
namespace testing {
+template <class MockClass>
+class NiceMock;
+template <class MockClass>
+class NaggyMock;
+template <class MockClass>
+class StrictMock;
+
+namespace internal {
+template <typename T>
+std::true_type StrictnessModifierProbe(const NiceMock<T>&);
+template <typename T>
+std::true_type StrictnessModifierProbe(const NaggyMock<T>&);
+template <typename T>
+std::true_type StrictnessModifierProbe(const StrictMock<T>&);
+std::false_type StrictnessModifierProbe(...);
+
+template <typename T>
+constexpr bool HasStrictnessModifier() {
+ return decltype(StrictnessModifierProbe(std::declval<const T&>()))::value;
+}
+
+// Base classes that register and deregister with testing::Mock to alter the
+// default behavior around uninteresting calls. Inheriting from one of these
+// classes first and then MockClass ensures the MockClass constructor is run
+// after registration, and that the MockClass destructor runs before
+// deregistration. This guarantees that MockClass's constructor and destructor
+// run with the same level of strictness as its instance methods.
+
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) && \
+ (defined(_MSC_VER) || defined(__clang__))
+// We need to mark these classes with this declspec to ensure that
+// the empty base class optimization is performed.
+#define GTEST_INTERNAL_EMPTY_BASE_CLASS __declspec(empty_bases)
+#else
+#define GTEST_INTERNAL_EMPTY_BASE_CLASS
+#endif
+
+template <typename Base>
+class NiceMockImpl {
+ public:
+ NiceMockImpl() {
+ ::testing::Mock::AllowUninterestingCalls(reinterpret_cast<uintptr_t>(this));
+ }
+
+ ~NiceMockImpl() {
+ ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
+ }
+};
+
+template <typename Base>
+class NaggyMockImpl {
+ public:
+ NaggyMockImpl() {
+ ::testing::Mock::WarnUninterestingCalls(reinterpret_cast<uintptr_t>(this));
+ }
+
+ ~NaggyMockImpl() {
+ ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
+ }
+};
+
+template <typename Base>
+class StrictMockImpl {
+ public:
+ StrictMockImpl() {
+ ::testing::Mock::FailUninterestingCalls(reinterpret_cast<uintptr_t>(this));
+ }
+
+ ~StrictMockImpl() {
+ ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
+ }
+};
+
+} // namespace internal
template <class MockClass>
-class NiceMock : public MockClass {
+class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
+ : private internal::NiceMockImpl<MockClass>,
+ public MockClass {
public:
+ static_assert(!internal::HasStrictnessModifier<MockClass>(),
+ "Can't apply NiceMock to a class hierarchy that already has a "
+ "strictness modifier. See "
+ "https://google.github.io/googletest/"
+ "gmock_cook_book.html#NiceStrictNaggy");
NiceMock() : MockClass() {
- ::testing::Mock::AllowUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
// Ideally, we would inherit base class's constructors through a using
@@ -85,33 +169,37 @@ class NiceMock : public MockClass {
// made explicit.
template <typename A>
explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) {
- ::testing::Mock::AllowUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
- template <typename A1, typename A2, typename... An>
- NiceMock(A1&& arg1, A2&& arg2, An&&... args)
- : MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2),
+ template <typename TArg1, typename TArg2, typename... An>
+ NiceMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
+ : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
std::forward<An>(args)...) {
- ::testing::Mock::AllowUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
- }
-
- ~NiceMock() { // NOLINT
- ::testing::Mock::UnregisterCallReaction(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
+ NiceMock(const NiceMock&) = delete;
+ NiceMock& operator=(const NiceMock&) = delete;
};
template <class MockClass>
-class NaggyMock : public MockClass {
+class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
+ : private internal::NaggyMockImpl<MockClass>,
+ public MockClass {
+ static_assert(!internal::HasStrictnessModifier<MockClass>(),
+ "Can't apply NaggyMock to a class hierarchy that already has a "
+ "strictness modifier. See "
+ "https://google.github.io/googletest/"
+ "gmock_cook_book.html#NiceStrictNaggy");
+
public:
NaggyMock() : MockClass() {
- ::testing::Mock::WarnUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
// Ideally, we would inherit base class's constructors through a using
@@ -123,33 +211,37 @@ class NaggyMock : public MockClass {
// made explicit.
template <typename A>
explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) {
- ::testing::Mock::WarnUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
- template <typename A1, typename A2, typename... An>
- NaggyMock(A1&& arg1, A2&& arg2, An&&... args)
- : MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2),
+ template <typename TArg1, typename TArg2, typename... An>
+ NaggyMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
+ : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
std::forward<An>(args)...) {
- ::testing::Mock::WarnUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
- }
-
- ~NaggyMock() { // NOLINT
- ::testing::Mock::UnregisterCallReaction(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock);
+ NaggyMock(const NaggyMock&) = delete;
+ NaggyMock& operator=(const NaggyMock&) = delete;
};
template <class MockClass>
-class StrictMock : public MockClass {
+class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
+ : private internal::StrictMockImpl<MockClass>,
+ public MockClass {
public:
+ static_assert(
+ !internal::HasStrictnessModifier<MockClass>(),
+ "Can't apply StrictMock to a class hierarchy that already has a "
+ "strictness modifier. See "
+ "https://google.github.io/googletest/"
+ "gmock_cook_book.html#NiceStrictNaggy");
StrictMock() : MockClass() {
- ::testing::Mock::FailUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
// Ideally, we would inherit base class's constructors through a using
@@ -161,55 +253,25 @@ class StrictMock : public MockClass {
// made explicit.
template <typename A>
explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) {
- ::testing::Mock::FailUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
- template <typename A1, typename A2, typename... An>
- StrictMock(A1&& arg1, A2&& arg2, An&&... args)
- : MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2),
+ template <typename TArg1, typename TArg2, typename... An>
+ StrictMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
+ : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
std::forward<An>(args)...) {
- ::testing::Mock::FailUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
- }
-
- ~StrictMock() { // NOLINT
- ::testing::Mock::UnregisterCallReaction(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
+ StrictMock(const StrictMock&) = delete;
+ StrictMock& operator=(const StrictMock&) = delete;
};
-// The following specializations catch some (relatively more common)
-// user errors of nesting nice and strict mocks. They do NOT catch
-// all possible errors.
-
-// These specializations are declared but not defined, as NiceMock,
-// NaggyMock, and StrictMock cannot be nested.
-
-template <typename MockClass>
-class NiceMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class NiceMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class NiceMock<StrictMock<MockClass> >;
-
-template <typename MockClass>
-class NaggyMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class NaggyMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class NaggyMock<StrictMock<MockClass> >;
-
-template <typename MockClass>
-class StrictMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class StrictMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class StrictMock<StrictMock<MockClass> >;
+#undef GTEST_INTERNAL_EMPTY_BASE_CLASS
} // namespace testing
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h
index 80c13b554921..78ca15d05e0f 100644
--- a/googlemock/include/gmock/gmock-spec-builders.h
+++ b/googlemock/include/gmock/gmock-spec-builders.h
@@ -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.
@@ -56,20 +55,24 @@
// 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 GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
+#include <cstdint>
#include <functional>
#include <map>
#include <memory>
+#include <ostream>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
+
#include "gmock/gmock-actions.h"
#include "gmock/gmock-cardinalities.h"
#include "gmock/gmock-matchers.h"
@@ -78,7 +81,7 @@
#include "gtest/gtest.h"
#if GTEST_HAS_EXCEPTIONS
-# include <stdexcept> // NOLINT
+#include <stdexcept> // NOLINT
#endif
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
@@ -97,17 +100,27 @@ 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;
+// Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
+template <typename MockClass>
+class NiceMockImpl;
+template <typename MockClass>
+class StrictMockImpl;
+template <typename MockClass>
+class NaggyMockImpl;
+
// Protects the mock object registry (in class Mock), all function
// mockers, and all expectations.
//
@@ -121,9 +134,6 @@ class ExpectationTester;
// 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.
@@ -146,27 +156,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,
@@ -175,10 +170,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,
@@ -188,8 +182,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
@@ -200,26 +193,20 @@ 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;
using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
+ struct UninterestingCallCleanupHandler;
+ struct FailureCleanupHandler;
+
// Returns an Expectation object that references and co-owns exp,
// which must be an expectation on this mock function.
Expectation GetHandleOf(ExpectationBase* exp);
@@ -413,40 +400,37 @@ class GTEST_API_ Mock {
template <typename F>
friend class internal::FunctionMocker;
- template <typename M>
- friend class NiceMock;
-
- template <typename M>
- friend class NaggyMock;
-
- template <typename M>
- friend class StrictMock;
+ template <typename MockClass>
+ friend class internal::NiceMockImpl;
+ template <typename MockClass>
+ friend class internal::NaggyMockImpl;
+ template <typename MockClass>
+ friend class internal::StrictMockImpl;
// 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
@@ -459,17 +443,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
@@ -499,7 +482,10 @@ class GTEST_API_ Expectation {
public:
// Constructs a null object that doesn't reference any expectation.
Expectation();
-
+ Expectation(Expectation&&) = default;
+ Expectation(const Expectation&) = default;
+ Expectation& operator=(Expectation&&) = default;
+ Expectation& operator=(const Expectation&) = default;
~Expectation();
// This single-argument ctor must not be explicit, in order to support the
@@ -580,7 +566,7 @@ class ExpectationSet {
typedef Expectation::Set::value_type value_type;
// Constructs an empty set.
- ExpectationSet() {}
+ ExpectationSet() = default;
// This single-argument ctor must not be explicit, in order to support the
// ExpectationSet es = EXPECT_CALL(...);
@@ -623,7 +609,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).
@@ -669,11 +654,13 @@ class GTEST_API_ InSequence {
public:
InSequence();
~InSequence();
+
private:
bool sequence_created_;
- GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
-} GTEST_ATTRIBUTE_UNUSED_;
+ InSequence(const InSequence&) = delete;
+ InSequence& operator=(const InSequence&) = delete;
+};
namespace internal {
@@ -723,6 +710,12 @@ class GTEST_API_ ExpectationBase {
// describes it to the ostream.
virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
+ // Do not rely on this for correctness.
+ // This is only for making human-readable test output easier to understand.
+ void UntypedDescription(std::string description) {
+ description_ = std::move(description);
+ }
+
protected:
friend class ::testing::Expectation;
friend class UntypedFunctionMockerBase;
@@ -775,40 +768,38 @@ 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 a human-readable description of this expectation.
+ // Do not rely on this for correctness. It is only for human readability.
+ const std::string& GetDescription() const { return description_; }
+
// 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_);
}
@@ -823,15 +814,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_++;
}
@@ -840,8 +829,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;
@@ -854,12 +842,13 @@ 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.
+ std::string description_; // User-readable name for the expectation.
// 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
@@ -878,14 +867,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_.
-
- GTEST_DISALLOW_ASSIGN_(ExpectationBase);
-}; // 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;
@@ -931,6 +924,13 @@ class TypedExpectation : public ExpectationBase {
return *this;
}
+ // Do not rely on this for correctness.
+ // This is only for making human-readable test output easier to understand.
+ TypedExpectation& Description(std::string name) {
+ ExpectationBase::UntypedDescription(std::move(name));
+ return *this;
+ }
+
// Implements the .Times() clause.
TypedExpectation& Times(const Cardinality& a_cardinality) {
ExpectationBase::UntypedTimes(a_cardinality);
@@ -938,9 +938,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) {
@@ -1000,14 +998,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())));
}
@@ -1055,9 +1070,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 {
@@ -1081,6 +1094,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); }
@@ -1112,10 +1135,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()) {
@@ -1174,9 +1195,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);
}
@@ -1200,10 +1221,15 @@ class TypedExpectation : public ExpectationBase {
::std::ostream* why)
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
+ const ::std::string& expectation_description = GetDescription();
if (IsSaturated()) {
// We have an excessive call.
IncrementCallCount();
- *what << "Mock function called more times than expected - ";
+ *what << "Mock function ";
+ if (!expectation_description.empty()) {
+ *what << "\"" << expectation_description << "\" ";
+ }
+ *what << "called more times than expected - ";
mocker->DescribeDefaultActionTo(args, what);
DescribeCallCountTo(why);
@@ -1218,7 +1244,11 @@ class TypedExpectation : public ExpectationBase {
}
// Must be done after IncrementCount()!
- *what << "Mock function call matches " << source_text() <<"...\n";
+ *what << "Mock function ";
+ if (!expectation_description.empty()) {
+ *what << "\"" << expectation_description << "\" ";
+ }
+ *what << "call matches " << source_text() << "...\n";
return &(GetCurrentAction(mocker, args));
}
@@ -1229,7 +1259,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
@@ -1251,8 +1282,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.
@@ -1262,8 +1293,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_);
@@ -1271,13 +1303,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
@@ -1295,8 +1328,6 @@ class MockSpec {
internal::FunctionMocker<F>* const function_mocker_;
// The argument matchers specified in the spec.
ArgumentMatcherTuple matchers_;
-
- GTEST_DISALLOW_ASSIGN_(MockSpec);
}; // class MockSpec
// Wrapper type for generically holding an ordinary value or lvalue reference.
@@ -1312,9 +1343,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
@@ -1325,9 +1354,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_;
@@ -1341,8 +1368,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_; }
@@ -1350,108 +1376,62 @@ class ReferenceOrValueWrapper<T&> {
T* value_ptr_;
};
-// MSVC warns about using 'this' in base member initializer list, so
-// we need to temporarily disable the warning. We have to do it for
-// the entire class to suppress the warning, even though it's about
-// the constructor only.
-GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355)
-
-// 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);
- }
+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);
+}
- // 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)));
- }
+// 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);
- // 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))));
- }
+// A generic RAII type that runs a user-provided function in its destructor.
+class Cleanup final {
+ public:
+ explicit Cleanup(std::function<void()> f) : f_(std::move(f)) {}
+ ~Cleanup() { f_(); }
private:
- typedef ReferenceOrValueWrapper<T> Wrapper;
-
- explicit ActionResultHolder(Wrapper result)
- : result_(std::move(result)) {
- }
-
- Wrapper result_;
-
- GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
+ std::function<void()> f_;
};
-// Specialization for T = void.
-template <>
-class ActionResultHolder<void> : public UntypedActionResultHolderBase {
- public:
- void Unwrap() { }
-
- void PrintAsActionResult(::std::ostream* /* os */) const override {}
+struct UntypedFunctionMockerBase::UninterestingCallCleanupHandler {
+ CallReaction reaction;
+ std::stringstream& ss;
- // 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;
+ ~UninterestingCallCleanupHandler() {
+ ReportUninterestingCall(reaction, ss.str());
}
+};
- // 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;
+struct UntypedFunctionMockerBase::FailureCleanupHandler {
+ std::stringstream& ss;
+ std::stringstream& why;
+ std::stringstream& loc;
+ const ExpectationBase* untyped_expectation;
+ bool found;
+ bool is_excessive;
+
+ ~FailureCleanupHandler() {
+ 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);
+ }
}
-
- private:
- ActionResultHolder() {}
- GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
};
template <typename F>
@@ -1466,7 +1446,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
using ArgumentTuple = std::tuple<Args...>;
using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
- FunctionMocker() {}
+ FunctionMocker() = default;
// There is no generally useful and implementable semantics of
// copying a mock object, so copying a mock is usually a user error.
@@ -1496,14 +1476,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;
@@ -1511,15 +1489,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));
}
@@ -1537,32 +1514,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
@@ -1580,8 +1531,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);
}
@@ -1595,10 +1545,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) {
@@ -1609,13 +1556,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);
@@ -1645,7 +1589,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().
@@ -1729,9 +1674,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.
@@ -1748,11 +1692,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);
@@ -1761,15 +1704,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 =
@@ -1784,20 +1726,254 @@ 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
-GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355
+// 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()));
+ }
-// Reports an uninteresting call (whose description is in msg) in the
-// manner specified by 'reaction'.
-void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
+ // 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.
+ //
+ // Note that std::bind() is essential here.
+ // We *don't* use any local callback types (like lambdas).
+ // Doing so slows down compilation dramatically because the *constructor* of
+ // std::function<T> is re-instantiated with different template
+ // parameters each time.
+ const UninterestingCallCleanupHandler report_uninteresting_call = {
+ reaction, ss
+ };
+
+ 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.
+ //
+ // Note that we *don't* use any local callback types (like lambdas) here.
+ // Doing so slows down compilation dramatically because the *constructor* of
+ // std::function<T> is re-instantiated with different template
+ // parameters each time.
+ const FailureCleanupHandler handle_failures = {
+ ss, why, loc, untyped_expectation, found, is_excessive
+ };
+
+ return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
+ ss);
+}
} // namespace internal
-// A MockFunction<F> class has one mock method whose type is F. It is
-// useful when you just want your test code to emit some messages and
-// have Google Mock verify the right messages are sent (and perhaps at
-// the right times). For example, if you are exercising code:
+namespace internal {
+
+template <typename F>
+class MockFunction;
+
+template <typename R, typename... Args>
+class MockFunction<R(Args...)> {
+ public:
+ MockFunction(const MockFunction&) = delete;
+ MockFunction& operator=(const MockFunction&) = delete;
+
+ std::function<R(Args...)> AsStdFunction() {
+ return [this](Args... args) -> R {
+ return this->Call(std::forward<Args>(args)...);
+ };
+ }
+
+ // Implementation detail: the expansion of the MOCK_METHOD macro.
+ R Call(Args... args) {
+ mock_.SetOwnerAndName(this, "Call");
+ return mock_.Invoke(std::forward<Args>(args)...);
+ }
+
+ MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
+ mock_.RegisterOwner(this);
+ return mock_.With(std::move(m)...);
+ }
+
+ MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
+ return this->gmock_Call(::testing::A<Args>()...);
+ }
+
+ protected:
+ MockFunction() = default;
+ ~MockFunction() = default;
+
+ private:
+ FunctionMocker<R(Args...)> mock_;
+};
+
+/*
+The SignatureOf<F> struct is a meta-function returning function signature
+corresponding to the provided F argument.
+
+It makes use of MockFunction easier by allowing it to accept more F arguments
+than just function signatures.
+
+Specializations provided here cover a signature type itself and any template
+that can be parameterized with a signature, including std::function and
+boost::function.
+*/
+
+template <typename F, typename = void>
+struct SignatureOf;
+
+template <typename R, typename... Args>
+struct SignatureOf<R(Args...)> {
+ using type = R(Args...);
+};
+
+template <template <typename> class C, typename F>
+struct SignatureOf<C<F>,
+ typename std::enable_if<std::is_function<F>::value>::type>
+ : SignatureOf<F> {};
+
+template <typename F>
+using SignatureOfT = typename SignatureOf<F>::type;
+
+} // namespace internal
+
+// A MockFunction<F> type has one mock method whose type is
+// internal::SignatureOfT<F>. It is useful when you just want your
+// test code to emit some messages and have Google Mock verify the
+// right messages are sent (and perhaps at the right times). For
+// example, if you are exercising code:
//
// Foo(1);
// Foo(2);
@@ -1831,49 +2007,34 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
// Bar("a") is called by which call to Foo().
//
// MockFunction<F> can also be used to exercise code that accepts
-// std::function<F> callbacks. To do so, use AsStdFunction() method
-// to create std::function proxy forwarding to original object's Call.
-// Example:
+// std::function<internal::SignatureOfT<F>> callbacks. To do so, use
+// AsStdFunction() method to create std::function proxy forwarding to
+// original object's Call. Example:
//
// TEST(FooTest, RunsCallbackWithBarArgument) {
// MockFunction<int(string)> callback;
// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
// Foo(callback.AsStdFunction());
// }
+//
+// The internal::SignatureOfT<F> indirection allows to use other types
+// than just function signature type. This is typically useful when
+// providing a mock for a predefined std::function type. Example:
+//
+// using FilterPredicate = std::function<bool(string)>;
+// void MyFilterAlgorithm(FilterPredicate predicate);
+//
+// TEST(FooTest, FilterPredicateAlwaysAccepts) {
+// MockFunction<FilterPredicate> predicateMock;
+// EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
+// MyFilterAlgorithm(predicateMock.AsStdFunction());
+// }
template <typename F>
-class MockFunction;
+class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
+ using Base = internal::MockFunction<internal::SignatureOfT<F>>;
-template <typename R, typename... Args>
-class MockFunction<R(Args...)> {
public:
- MockFunction() {}
- MockFunction(const MockFunction&) = delete;
- MockFunction& operator=(const MockFunction&) = delete;
-
- std::function<R(Args...)> AsStdFunction() {
- return [this](Args... args) -> R {
- return this->Call(std::forward<Args>(args)...);
- };
- }
-
- // Implementation detail: the expansion of the MOCK_METHOD macro.
- R Call(Args... args) {
- mock_.SetOwnerAndName(this, "Call");
- return mock_.Invoke(std::forward<Args>(args)...);
- }
-
- internal::MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
- mock_.RegisterOwner(this);
- return mock_.With(std::move(m)...);
- }
-
- internal::MockSpec<R(Args...)> gmock_Call(const internal::WithoutMatchers&,
- R (*)(Args...)) {
- return this->gmock_Call(::testing::A<Args>()...);
- }
-
- private:
- internal::FunctionMocker<R(Args...)> mock_;
+ using Base::Base;
};
// The style guide prohibits "using" statements in a namespace scope
@@ -1899,7 +2060,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
@@ -1982,4 +2145,4 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#define EXPECT_CALL(obj, call) \
GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
diff --git a/googlemock/include/gmock/gmock.h b/googlemock/include/gmock/gmock.h
index 99c3d7871d0f..568c8c71d785 100644
--- a/googlemock/include/gmock/gmock.h
+++ b/googlemock/include/gmock/gmock.h
@@ -27,15 +27,12 @@
// (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 GMOCK_INCLUDE_GMOCK_GMOCK_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
// This file implements the following syntax:
//
@@ -59,22 +56,20 @@
#include "gmock/gmock-actions.h"
#include "gmock/gmock-cardinalities.h"
#include "gmock/gmock-function-mocker.h"
-#include "gmock/gmock-generated-actions.h"
-#include "gmock/gmock-generated-function-mockers.h"
-#include "gmock/gmock-generated-matchers.h"
#include "gmock/gmock-matchers.h"
#include "gmock/gmock-more-actions.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,
@@ -98,4 +93,4 @@ GTEST_API_ void InitGoogleMock();
} // namespace testing
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
diff --git a/googlemock/include/gmock/internal/custom/README.md b/googlemock/include/gmock/internal/custom/README.md
index f6c93f616d62..9c4874fd0cb3 100644
--- a/googlemock/include/gmock/internal/custom/README.md
+++ b/googlemock/include/gmock/internal/custom/README.md
@@ -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)`
diff --git a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h
index 92d910cf06df..bbcad31c76ef 100644
--- a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h
+++ b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h
@@ -1,10 +1,7 @@
-// This file was GENERATED by command:
-// pump.py gmock-generated-actions.h.pump
-// DO NOT EDIT BY HAND!!!
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
-// GOOGLETEST_CM0002 DO NOT DELETE
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
-
-#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
diff --git a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump
deleted file mode 100644
index 67c221f14c72..000000000000
--- a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump
+++ /dev/null
@@ -1,12 +0,0 @@
-$$ -*- mode: c++; -*-
-$$ This is a Pump source file. Please use Pump to convert
-$$ it to callback-actions.h.
-$$
-$var max_callback_arity = 5
-$$}} This meta comment fixes auto-indentation in editors.
-
-// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
-
-#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
diff --git a/googlemock/include/gmock/internal/custom/gmock-matchers.h b/googlemock/include/gmock/internal/custom/gmock-matchers.h
index 14aafaabe6b5..bb7dcbaa4cb2 100644
--- a/googlemock/include/gmock/internal/custom/gmock-matchers.h
+++ b/googlemock/include/gmock/internal/custom/gmock-matchers.h
@@ -26,11 +26,12 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
+
// Injection point for custom user configurations. See README for details
-//
-// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
-#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
+// 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_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
diff --git a/googlemock/include/gmock/internal/custom/gmock-port.h b/googlemock/include/gmock/internal/custom/gmock-port.h
index 0030fe91118a..f055f7506b82 100644
--- a/googlemock/include/gmock/internal/custom/gmock-port.h
+++ b/googlemock/include/gmock/internal/custom/gmock-port.h
@@ -26,14 +26,15 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
+
// 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 GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
-#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h
index fdc049c589cb..ead6d7c805e9 100644
--- a/googlemock/include/gmock/internal/gmock-internal-utils.h
+++ b/googlemock/include/gmock/internal/gmock-internal-utils.h
@@ -27,22 +27,25 @@
// (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 GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
+#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"
@@ -55,15 +58,12 @@ 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)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4805)
// 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
@@ -71,20 +71,6 @@ GTEST_API_ std::string JoinAsTuple(const Strings& fields);
// "foo_bar_123" are converted to "foo bar 123".
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
-// PointeeOf<Pointer>::type is the type of a value pointed to by a
-// Pointer, which can be either a smart pointer or a raw pointer. The
-// following default implementation is for the case where Pointer is a
-// smart pointer.
-template <typename Pointer>
-struct PointeeOf {
- // Smart pointer classes define type element_type as the type of
- // their pointees.
- typedef typename Pointer::element_type type;
-};
-// This specialization is for the raw pointer case.
-template <typename T>
-struct PointeeOf<T*> { typedef T type; }; // NOLINT
-
// GetRawPointer(p) returns the raw pointer underlying p when p is a
// smart pointer, or returns p itself when p is already a raw pointer.
// The following default implementation is for the smart pointer case.
@@ -92,9 +78,36 @@ 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;
+}
+
+// Default definitions for all compilers.
+// NOTE: If you implement support for other compilers, make sure to avoid
+// unexpected overlaps.
+// (e.g., Clang also processes #pragma GCC, and clang-cl also handles _MSC_VER.)
+#define GMOCK_INTERNAL_WARNING_PUSH()
+#define GMOCK_INTERNAL_WARNING_CLANG(Level, Name)
+#define GMOCK_INTERNAL_WARNING_POP()
+
+#if defined(__clang__)
+#undef GMOCK_INTERNAL_WARNING_PUSH
+#define GMOCK_INTERNAL_WARNING_PUSH() _Pragma("clang diagnostic push")
+#undef GMOCK_INTERNAL_WARNING_CLANG
+#define GMOCK_INTERNAL_WARNING_CLANG(Level, Warning) \
+ _Pragma(GMOCK_PP_INTERNAL_STRINGIZE(clang diagnostic Level Warning))
+#undef GMOCK_INTERNAL_WARNING_POP
+#define GMOCK_INTERNAL_WARNING_POP() _Pragma("clang diagnostic pop")
+#endif
// 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
@@ -103,7 +116,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
@@ -111,18 +124,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);
@@ -130,21 +145,19 @@ 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, 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_
GMOCK_DECLARE_KIND_(wchar_t, kInteger);
#endif
-// Non-standard integer types.
-GMOCK_DECLARE_KIND_(Int64, kInteger);
-GMOCK_DECLARE_KIND_(UInt64, kInteger);
-
// All standard floating-point types.
GMOCK_DECLARE_KIND_(float, kFloatingPoint);
GMOCK_DECLARE_KIND_(double, kFloatingPoint);
@@ -153,13 +166,10 @@ 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)
-// Evaluates to true if and only if integer type T is signed.
-#define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
-
// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
// is true if and only if arithmetic type From can be losslessly converted to
// arithmetic type To.
@@ -170,65 +180,30 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
// From, and kToKind is the kind of To; the value is
// implementation-defined when the above pre-condition is violated.
template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
-struct LosslessArithmeticConvertibleImpl : public std::false_type {};
-
-// Converting bool to bool is lossless.
-template <>
-struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>
- : public std::true_type {};
-
-// Converting bool to any integer type is lossless.
-template <typename To>
-struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>
- : public std::true_type {};
-
-// Converting bool to any floating-point type is lossless.
-template <typename To>
-struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>
- : public std::true_type {};
-
-// Converting an integer to bool is lossy.
-template <typename From>
-struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>
- : public std::false_type {};
-
-// Converting an integer to another non-bool integer is lossless
-// if and only if the target type's range encloses the source type's range.
-template <typename From, typename To>
-struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
- : public bool_constant<
- // When converting from a smaller size to a larger size, we are
- // fine as long as we are not converting from signed to unsigned.
- ((sizeof(From) < sizeof(To)) &&
- (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) ||
- // When converting between the same size, the signedness must match.
- ((sizeof(From) == sizeof(To)) &&
- (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT
-
-#undef GMOCK_IS_SIGNED_
-
-// Converting an integer to a floating-point type may be lossy, since
-// the format of a floating-point number is implementation-defined.
-template <typename From, typename To>
-struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
- : public std::false_type {};
-
-// Converting a floating-point to bool is lossy.
-template <typename From>
-struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
- : public std::false_type {};
-
-// Converting a floating-point to an integer is lossy.
-template <typename From, typename To>
-struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
- : public std::false_type {};
-
-// Converting a floating-point to another floating-point is lossless
-// if and only if the target type is at least as big as the source type.
-template <typename From, typename To>
-struct LosslessArithmeticConvertibleImpl<
- kFloatingPoint, From, kFloatingPoint, To>
- : public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT
+using LosslessArithmeticConvertibleImpl = std::integral_constant<
+ bool,
+ // clang-format off
+ // Converting from bool is always lossless
+ (kFromKind == kBool) ? true
+ // Converting between any other type kinds will be lossy if the type
+ // kinds are not the same.
+ : (kFromKind != kToKind) ? false
+ : (kFromKind == kInteger &&
+ // Converting between integers of different widths is allowed so long
+ // as the conversion does not go from signed to unsigned.
+ (((sizeof(From) < sizeof(To)) &&
+ !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||
+ // Converting between integers of the same width only requires the
+ // two types to have the same signedness.
+ ((sizeof(From) == sizeof(To)) &&
+ (std::is_signed<From>::value == std::is_signed<To>::value)))
+ ) ? true
+ // Floating point conversions are lossless if and only if `To` is at least
+ // as wide as `From`.
+ : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true
+ : false
+ // clang-format on
+ >;
// LosslessArithmeticConvertible<From, To>::value is true if and only if
// arithmetic type From can be losslessly converted to arithmetic type To.
@@ -238,20 +213,18 @@ struct LosslessArithmeticConvertibleImpl<
// reference) built-in arithmetic types; the value is
// implementation-defined when the above pre-condition is violated.
template <typename From, typename To>
-struct LosslessArithmeticConvertible
- : public LosslessArithmeticConvertibleImpl<
- GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT
+using LosslessArithmeticConvertible =
+ LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,
+ GMOCK_KIND_OF_(To), To>;
// This interface knows how to report a Google Mock failure (either
// non-fatal or fatal).
class FailureReporterInterface {
public:
// The type of a failure (either non-fatal or fatal).
- enum FailureType {
- kNonfatal, kFatal
- };
+ enum FailureType { kNonfatal, kFatal };
- virtual ~FailureReporterInterface() {}
+ virtual ~FailureReporterInterface() = default;
// Reports a failure that occurred at the given source file location.
virtual void ReportFailure(FailureType type, const char* file, int line,
@@ -269,8 +242,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) {
@@ -291,10 +264,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.
@@ -334,15 +304,6 @@ class WithoutMatchers {
// Internal use only: access the singleton instance of WithoutMatchers.
GTEST_API_ WithoutMatchers GetWithoutMatchers();
-// Type traits.
-
-// Disable MSVC warnings for infinite recursion, since in this case the
-// the recursion is unreachable.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4717)
-#endif
-
// Invalid<T>() is usable as an expression of type T, but will terminate
// the program with an assertion failure if actually run. This is useful
// when a value of type T is needed for compilation, but the statement
@@ -350,16 +311,16 @@ GTEST_API_ WithoutMatchers GetWithoutMatchers();
// crashes).
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.
+ Assert(/*condition=*/false, /*file=*/"", /*line=*/-1,
+ "Internal error: attempt to return invalid value");
+#if defined(__GNUC__) || defined(__clang__)
+ __builtin_unreachable();
+#elif defined(_MSC_VER)
+ __assume(0);
+#else
return Invalid<T>();
-}
-
-#ifdef _MSC_VER
-# pragma warning(pop)
#endif
+}
// Given a raw type (i.e. having no top-level reference or const
// modifier) RawContainer that's either an STL-style container or a
@@ -420,7 +381,8 @@ template <typename ElementPointer, typename Size>
class StlContainerView< ::std::tuple<ElementPointer, Size> > {
public:
typedef typename std::remove_const<
- typename internal::PointeeOf<ElementPointer>::type>::type RawElement;
+ typename std::pointer_traits<ElementPointer>::element_type>::type
+ RawElement;
typedef internal::NativeArray<RawElement> type;
typedef const type const_reference;
@@ -436,7 +398,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,
@@ -457,18 +420,21 @@ 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<Tuple>::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<Tuple>::value>());
+ MakeIndexSequence<std::tuple_size<
+ typename std::remove_reference<Tuple>::type>::value>());
}
// Template struct Function<F>, where F must be a function type, contains
@@ -492,22 +458,30 @@ struct Function<R(Args...)> {
using Result = R;
static constexpr size_t ArgumentCount = sizeof...(Args);
template <size_t I>
- using Arg = ElemFromList<I, typename MakeIndexSequence<sizeof...(Args)>::type,
- Args...>;
+ using Arg = ElemFromList<I, Args...>;
using ArgumentTuple = std::tuple<Args...>;
using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
using MakeResultVoid = void(Args...);
using MakeResultIgnoredValue = IgnoredValue(Args...);
};
+#ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
template <typename R, typename... Args>
constexpr size_t Function<R(Args...)>::ArgumentCount;
-
-#ifdef _MSC_VER
-# pragma warning(pop)
#endif
+// Workaround for MSVC error C2039: 'type': is not a member of 'std'
+// when std::tuple_element is used.
+// See: https://github.com/google/googletest/issues/3931
+// Can be replaced with std::tuple_element_t in C++14.
+template <size_t I, typename T>
+using TupleElement = typename std::tuple_element<I, T>::type;
+
+bool Base64Unescape(const std::string& encoded, std::string* decoded);
+
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4805
+
} // namespace internal
} // namespace testing
-#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
diff --git a/googlemock/include/gmock/internal/gmock-port.h b/googlemock/include/gmock/internal/gmock-port.h
index 063e2929acd5..55ddfb6c6a3b 100644
--- a/googlemock/include/gmock/internal/gmock-port.h
+++ b/googlemock/include/gmock/internal/gmock-port.h
@@ -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,13 +34,15 @@
// 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 GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
#include <assert.h>
#include <stdlib.h>
+#include <cstdint>
#include <iostream>
// Most of the utilities needed for porting Google Mock are also
@@ -52,36 +53,87 @@
// 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"
+
+#ifdef 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.
+#ifdef 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_ ::testing::internal::Int32 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_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val)
-# define GMOCK_DEFINE_string_(name, default_val, doc) \
- GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val)
+#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 // !defined(GMOCK_DECLARE_bool_)
+#endif // GTEST_HAS_ABSL
-#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
diff --git a/googlemock/include/gmock/internal/gmock-pp.h b/googlemock/include/gmock/internal/gmock-pp.h
index 1ab80e1cdbee..94d61c09c870 100644
--- a/googlemock/include/gmock/internal/gmock-pp.h
+++ b/googlemock/include/gmock/internal/gmock-pp.h
@@ -1,18 +1,5 @@
-#ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_PP_H_
-#define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_PP_H_
-
-#undef GMOCK_PP_INTERNAL_USE_MSVC
-#if defined(__clang__)
-#define GMOCK_PP_INTERNAL_USE_MSVC 0
-#elif defined(_MSC_VER)
-// TODO(iserna): Also verify tradional versus comformant preprocessor.
-static_assert(
- _MSC_VER >= 1900,
- "MSVC version not supported. There is support for MSVC 14.0 and above.");
-#define GMOCK_PP_INTERNAL_USE_MSVC 1
-#else
-#define GMOCK_PP_INTERNAL_USE_MSVC 0
-#endif
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
// Expands and concatenates the arguments. Constructed macros reevaluate.
#define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2)
@@ -29,10 +16,6 @@ static_assert(
// Returns the only argument.
#define GMOCK_PP_IDENTITY(_1) _1
-// MSVC preprocessor collapses __VA_ARGS__ in a single argument, we use a
-// CAT-like directive to force correct evaluation. Each macro has its own.
-#if GMOCK_PP_INTERNAL_USE_MSVC
-
// Evaluates to the number of arguments after expansion.
//
// #define PAIR x, y
@@ -43,45 +26,27 @@ static_assert(
// GMOCK_PP_NARG(PAIR) => 2
//
// Requires: the number of arguments after expansion is at most 15.
-#define GMOCK_PP_NARG(...) \
- GMOCK_PP_INTERNAL_NARG_CAT( \
- GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, \
- 8, 7, 6, 5, 4, 3, 2, 1), )
+#define GMOCK_PP_NARG(...) \
+ GMOCK_PP_INTERNAL_16TH( \
+ (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
// Returns 1 if the expansion of arguments has an unprotected comma. Otherwise
// returns 0. Requires no more than 15 unprotected commas.
-#define GMOCK_PP_HAS_COMMA(...) \
- GMOCK_PP_INTERNAL_HAS_COMMA_CAT( \
- GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
- 1, 1, 1, 1, 1, 0), )
+#define GMOCK_PP_HAS_COMMA(...) \
+ GMOCK_PP_INTERNAL_16TH( \
+ (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0))
+
// Returns the first argument.
-#define GMOCK_PP_HEAD(...) \
- GMOCK_PP_INTERNAL_HEAD_CAT(GMOCK_PP_INTERNAL_HEAD(__VA_ARGS__), )
+#define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__, unusedArg))
// Returns the tail. A variadic list of all arguments minus the first. Requires
// at least one argument.
-#define GMOCK_PP_TAIL(...) \
- GMOCK_PP_INTERNAL_TAIL_CAT(GMOCK_PP_INTERNAL_TAIL(__VA_ARGS__), )
+#define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL((__VA_ARGS__))
// Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__)
#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \
- GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT( \
- GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__), )
-
-#else // GMOCK_PP_INTERNAL_USE_MSVC
-
-#define GMOCK_PP_NARG(...) \
- GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, \
- 7, 6, 5, 4, 3, 2, 1)
-#define GMOCK_PP_HAS_COMMA(...) \
- GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
- 1, 1, 1, 1, 0)
-#define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD(__VA_ARGS__)
-#define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL(__VA_ARGS__)
-#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \
- GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__)
-
-#endif // GMOCK_PP_INTERNAL_USE_MSVC
+ GMOCK_PP_IDENTITY( \
+ GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__))
// If the arguments after expansion have no tokens, evaluates to `1`. Otherwise
// evaluates to `0`.
@@ -121,6 +86,14 @@ static_assert(
#define GMOCK_PP_IF(_Cond, _Then, _Else) \
GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else)
+// Similar to GMOCK_PP_IF but takes _Then and _Else in parentheses.
+//
+// GMOCK_PP_GENERIC_IF(1, (a, b, c), (d, e, f)) => a, b, c
+// GMOCK_PP_GENERIC_IF(0, (a, b, c), (d, e, f)) => d, e, f
+//
+#define GMOCK_PP_GENERIC_IF(_Cond, _Then, _Else) \
+ GMOCK_PP_REMOVE_PARENS(GMOCK_PP_IF(_Cond, _Then, _Else))
+
// Evaluates to the number of arguments after expansion. Identifies 'empty' as
// 0.
//
@@ -139,10 +112,9 @@ static_assert(
// Expands to 1 if the first argument starts with something in parentheses,
// otherwise to 0.
-#define GMOCK_PP_IS_BEGIN_PARENS(...) \
- GMOCK_PP_INTERNAL_ALTERNATE_HEAD( \
- GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \
- GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__))
+#define GMOCK_PP_IS_BEGIN_PARENS(...) \
+ GMOCK_PP_HEAD(GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \
+ GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__))
// Expands to 1 is there is only one argument and it is enclosed in parentheses.
#define GMOCK_PP_IS_ENCLOSED_PARENS(...) \
@@ -179,10 +151,6 @@ static_assert(
#define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , )
#define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2
#define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__
-#define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \
- _10, _11, _12, _13, _14, _15, _16, \
- ...) \
- _16
#define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5
#define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4) \
GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \
@@ -190,30 +158,24 @@ static_assert(
#define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 ,
#define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then
#define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else
-#define GMOCK_PP_INTERNAL_HEAD(_1, ...) _1
-#define GMOCK_PP_INTERNAL_TAIL(_1, ...) __VA_ARGS__
-#if GMOCK_PP_INTERNAL_USE_MSVC
-#define GMOCK_PP_INTERNAL_NARG_CAT(_1, _2) GMOCK_PP_INTERNAL_NARG_CAT_I(_1, _2)
-#define GMOCK_PP_INTERNAL_HEAD_CAT(_1, _2) GMOCK_PP_INTERNAL_HEAD_CAT_I(_1, _2)
-#define GMOCK_PP_INTERNAL_HAS_COMMA_CAT(_1, _2) \
- GMOCK_PP_INTERNAL_HAS_COMMA_CAT_I(_1, _2)
-#define GMOCK_PP_INTERNAL_TAIL_CAT(_1, _2) GMOCK_PP_INTERNAL_TAIL_CAT_I(_1, _2)
-#define GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT(_1, _2) \
- GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT_I(_1, _2)
-#define GMOCK_PP_INTERNAL_NARG_CAT_I(_1, _2) _1##_2
-#define GMOCK_PP_INTERNAL_HEAD_CAT_I(_1, _2) _1##_2
-#define GMOCK_PP_INTERNAL_HAS_COMMA_CAT_I(_1, _2) _1##_2
-#define GMOCK_PP_INTERNAL_TAIL_CAT_I(_1, _2) _1##_2
-#define GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT_I(_1, _2) _1##_2
-#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD(...) \
- GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT(GMOCK_PP_HEAD(__VA_ARGS__), )
-#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT(_1, _2) \
- GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT_I(_1, _2)
-#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT_I(_1, _2) _1##_2
-#else // GMOCK_PP_INTERNAL_USE_MSVC
-#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD(...) GMOCK_PP_HEAD(__VA_ARGS__)
-#endif // GMOCK_PP_INTERNAL_USE_MSVC
+// Because of MSVC treating a token with a comma in it as a single token when
+// passed to another macro, we need to force it to evaluate it as multiple
+// tokens. We do that by using a "IDENTITY(MACRO PARENTHESIZED_ARGS)" macro. We
+// define one per possible macro that relies on this behavior. Note "_Args" must
+// be parenthesized.
+#define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \
+ _10, _11, _12, _13, _14, _15, _16, \
+ ...) \
+ _16
+#define GMOCK_PP_INTERNAL_16TH(_Args) \
+ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_16TH _Args)
+#define GMOCK_PP_INTERNAL_INTERNAL_HEAD(_1, ...) _1
+#define GMOCK_PP_INTERNAL_HEAD(_Args) \
+ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_HEAD _Args)
+#define GMOCK_PP_INTERNAL_INTERNAL_TAIL(_1, ...) __VA_ARGS__
+#define GMOCK_PP_INTERNAL_TAIL(_Args) \
+ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_TAIL _Args)
#define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _
#define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1,
@@ -314,4 +276,4 @@ static_assert(
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
-#endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
diff --git a/googlemock/scripts/fuse_gmock_files.py b/googlemock/scripts/fuse_gmock_files.py
deleted file mode 100755
index c33c7253febf..000000000000
--- a/googlemock/scripts/fuse_gmock_files.py
+++ /dev/null
@@ -1,240 +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/googlemock/docs/cook_book.md for more
-information.
-"""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-import os
-import re
-import sets
-import sys
-
-# 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
-gtest = fuse_gtest_files
-
-# 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.
- """
-
- 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.
- """
-
- 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 = file(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w')
- processed_files = sets.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.
- for line in file(os.path.join(gmock_root, gmock_header_path), 'r'):
- m = INCLUDE_GMOCK_FILE_REGEX.match(line)
- if m:
- # It's '#include "gmock/..."' - let's process it recursively.
- ProcessFile('include/' + m.group(1))
- else:
- m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
- if m:
- # It's '#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 not gtest.GTEST_H_SEED 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 = sets.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.
- for line in file(os.path.join(gmock_root, gmock_source_file), 'r'):
- m = INCLUDE_GMOCK_FILE_REGEX.match(line)
- if m:
- # It's '#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.
-
- # There is no need to #include "gmock/gmock.h" more than once.
- if not GMOCK_H_SEED 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:
- # It's '#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."""
-
- output_file = file(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w')
- # 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)
- output_file.close()
-
-
-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
index 87ea0636510a..000000000000
--- a/googlemock/scripts/generator/LICENSE
+++ /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
index 01fd463dda7f..000000000000
--- a/googlemock/scripts/generator/README
+++ /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
index 65431b617593..000000000000
--- a/googlemock/scripts/generator/README.cppclean
+++ /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
index e69de29bb2d1..000000000000
--- a/googlemock/scripts/generator/cpp/__init__.py
+++ /dev/null
diff --git a/googlemock/scripts/generator/cpp/ast.py b/googlemock/scripts/generator/cpp/ast.py
deleted file mode 100755
index f14728b4612a..000000000000
--- a/googlemock/scripts/generator/cpp/ast.py
+++ /dev/null
@@ -1,1736 +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++."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-# TODO:
-# * 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 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
- for s in tokens:
- if not first_token:
- first_token = s
- 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)):
- 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._GetVarTokensUpTo(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
-
- # 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()
- return next(self.tokens)
-
- 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):
- token = self._GetNextToken()
- if not (token.token_type == tokenize.NAME and token.name == 'class'):
- self._AddBackToken(token)
- 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._GetTokensUpTo(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 = {}
- 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):
- token = self._GetNextToken()
- # Support anonymous namespaces.
- name = None
- if token.token_type == tokenize.NAME:
- name = token.name
- token = self._GetNextToken()
- 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
index f9966cbb4b0e..000000000000
--- a/googlemock/scripts/generator/cpp/gmock_class.py
+++ /dev/null
@@ -1,227 +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.
-"""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-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 _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.
- const = ''
- if node.modifiers & ast.FUNCTION_CONST:
- const = 'CONST_'
- return_type = 'void'
- if node.return_type:
- # Add modifiers like 'const'.
- modifiers = ''
- if node.return_type.modifiers:
- modifiers = ' '.join(node.return_type.modifiers) + ' '
- return_type = modifiers + node.return_type.name
- template_args = [arg.name for arg in node.return_type.templated_types]
- if template_args:
- return_type += '<' + ', '.join(template_args) + '>'
- if len(template_args) > 1:
- for line in [
- '// The following line won\'t really compile, as the return',
- '// type has multiple template arguments. To fix it, use a',
- '// typedef for the return type.']:
- output_lines.append(indent + line)
- if node.return_type.pointer:
- return_type += '*'
- if node.return_type.reference:
- return_type += '&'
- num_parameters = len(node.parameters)
- if len(node.parameters) == 1:
- first_param = node.parameters[0]
- if source[first_param.start:first_param.end].strip() == 'void':
- # We must treat T(void) as a function with no parameters.
- num_parameters = 0
- tmpl = ''
- if class_node.templated_types:
- tmpl = '_T'
- mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl)
-
- args = ''
- if node.parameters:
- # Due to the parser limitations, it is impossible to keep comments
- # while stripping the default parameters. When defaults are
- # present, we choose to strip them and comments (and produce
- # compilable code).
- # TODO(nnorwitz@google.com): Investigate whether it is possible to
- # preserve parameter name when reconstructing parameter text from
- # the AST.
- if len([param for param in node.parameters if param.default]) > 0:
- args = ', '.join(param.type.name for param in node.parameters)
- else:
- # Get the full text of the parameters from the start
- # of the first parameter to the end of the last parameter.
- start = node.parameters[0].start
- end = node.parameters[-1].end
- # Remove // comments.
- args_strings = re.sub(r'//.*', '', source[start:end])
- # Condense multiple spaces and eliminate newlines putting the
- # parameters together on a single line. Ensure there is a
- # space in an argument which is split by a newline without
- # intervening whitespace, e.g.: int\nBar
- args = re.sub(' +', ' ', args_strings.replace('\n', ' '))
-
- # Create the mock method definition.
- output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name),
- '%s%s(%s));' % (indent*3, return_type, args)])
-
-
-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): The AST doesn't preserve template argument order,
- # so we have to make up names here.
- # TODO(paulchang): Handle non-type template arguments (e.g.
- # template<typename T, int N>).
- template_arg_count = len(class_node.templated_types.keys())
- template_args = ['T%d' % n for n in range(template_arg_count)]
- 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
index c53e60003e1c..000000000000
--- a/googlemock/scripts/generator/cpp/gmock_class_test.py
+++ /dev/null
@@ -1,466 +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."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-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."""
-
- def StripLeadingWhitespace(self, 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):
-
- def GenerateMethodSource(self, 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_METHOD0(Bar,\nint());',
- 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_METHOD0(Bar,\nint());',
- self.GenerateMethodSource(source))
-
- def testVirtualDestructor(self):
- source = """
-class Foo {
- public:
- virtual ~Foo();
- virtual int Bar() = 0;
-};
-"""
- # The destructor should be ignored.
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0(Bar,\nint());',
- 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_METHOD0(Bar,\nint());',
- 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_METHOD0(Bar,\nint());',
- self.GenerateMethodSource(source))
-
- def testSimpleOverrideMethod(self):
- source = """
-class Foo {
- public:
- int Bar() override;
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0(Bar,\nint());',
- self.GenerateMethodSource(source))
-
- def testSimpleConstMethod(self):
- source = """
-class Foo {
- public:
- virtual void Bar(bool flag) const;
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));',
- self.GenerateMethodSource(source))
-
- def testExplicitVoid(self):
- source = """
-class Foo {
- public:
- virtual int Bar(void);
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0(Bar,\nint(void));',
- self.GenerateMethodSource(source))
-
- def testStrangeNewlineInParameter(self):
- source = """
-class Foo {
- public:
- virtual void Bar(int
-a) = 0;
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD1(Bar,\nvoid(int a));',
- self.GenerateMethodSource(source))
-
- def testDefaultParameters(self):
- source = """
-class Foo {
- public:
- virtual void Bar(int a, char c = 'x') = 0;
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD2(Bar,\nvoid(int, char));',
- self.GenerateMethodSource(source))
-
- def testMultipleDefaultParameters(self):
- source = """
-class Foo {
- public:
- virtual void Bar(int a = 42, char c = 'x') = 0;
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD2(Bar,\nvoid(int, char));',
- 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_METHOD2(Bar,\nvoid(int, char));',
- 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_CONST_METHOD2(Bar,\nvoid(int a, int b));',
- 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_METHOD2(Bar,\nconst string&(int /* keeper */, int b));',
- self.GenerateMethodSource(source))
-
- def testArgsOfTemplateTypes(self):
- source = """
-class Foo {
- public:
- virtual int Bar(const vector<int>& v, map<int, string>* output);
-};"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD2(Bar,\n'
- 'int(const vector<int>& v, map<int, string>* output));',
- self.GenerateMethodSource(source))
-
- def testReturnTypeWithOneTemplateArg(self):
- source = """
-class Foo {
- public:
- virtual vector<int>* Bar(int n);
-};"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD1(Bar,\nvector<int>*(int n));',
- self.GenerateMethodSource(source))
-
- def testReturnTypeWithManyTemplateArgs(self):
- source = """
-class Foo {
- public:
- virtual map<int, string> Bar();
-};"""
- # Comparing the comment text is brittle - we'll think of something
- # better in case this gets annoying, but for now let's keep it simple.
- self.assertEqualIgnoreLeadingWhitespace(
- '// The following line won\'t really compile, as the return\n'
- '// type has multiple template arguments. To fix it, use a\n'
- '// typedef for the return type.\n'
- 'MOCK_METHOD0(Bar,\nmap<int, string>());',
- self.GenerateMethodSource(source))
-
- def testSimpleMethodInTemplatedClass(self):
- source = """
-template<class T>
-class Foo {
- public:
- virtual int Bar();
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0_T(Bar,\nint());',
- self.GenerateMethodSource(source))
-
- def testPointerArgWithoutNames(self):
- source = """
-class Foo {
- virtual int Bar(C*);
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD1(Bar,\nint(C*));',
- self.GenerateMethodSource(source))
-
- def testReferenceArgWithoutNames(self):
- source = """
-class Foo {
- virtual int Bar(C&);
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD1(Bar,\nint(C&));',
- self.GenerateMethodSource(source))
-
- def testArrayArgWithoutNames(self):
- source = """
-class Foo {
- virtual int Bar(C[]);
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD1(Bar,\nint(C[]));',
- self.GenerateMethodSource(source))
-
-
-class GenerateMocksTest(TestCase):
-
- def GenerateMocks(self, 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 {
-
-class Test {
- public:
- virtual void Foo();
-};
-
-} // namespace Baz
-} // namespace Foo
-"""
- expected = """\
-namespace Foo {
-namespace Baz {
-
-class MockTest : public Test {
-public:
-MOCK_METHOD0(Foo,
-void());
-};
-
-} // namespace Baz
-} // 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_METHOD0(Foo,
-void());
-};
-"""
- 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_METHOD0(Foo,
-void());
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMocks(source))
-
- def testTemplatedClass(self):
- source = """
-template <typename S, typename T>
-class Test {
- public:
- virtual void Foo();
-};
-"""
- expected = """\
-template <typename T0, typename T1>
-class MockTest : public Test<T0, T1> {
-public:
-MOCK_METHOD0_T(Foo,
-void());
-};
-"""
- 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_METHOD1(Bar,
-void(const FooType& test_arg));
-};
-"""
- 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_METHOD1(Bar,
-void(const FooType& test_arg));
-};
-"""
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMocks(source))
-
- def testEnumClass(self):
- source = """
-class Test {
- public:
- enum class Baz { BAZINGA };
- virtual void Bar(const FooType& test_arg);
-};
-"""
- expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD1(Bar,
-void(const FooType& test_arg));
-};
-"""
- 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
index f694450e373e..000000000000
--- a/googlemock/scripts/generator/cpp/keywords.py
+++ /dev/null
@@ -1,59 +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."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-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
index 359d5562d78c..000000000000
--- a/googlemock/scripts/generator/cpp/tokenize.py
+++ /dev/null
@@ -1,287 +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."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-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
index eab36eec335e..000000000000
--- a/googlemock/scripts/generator/cpp/utils.py
+++ /dev/null
@@ -1,41 +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."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-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
index 8cc0d135d6f2..000000000000
--- a/googlemock/scripts/generator/gmock_gen.py
+++ /dev/null
@@ -1,31 +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."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-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()
diff --git a/googlemock/scripts/gmock-config.in b/googlemock/scripts/gmock-config.in
deleted file mode 100755
index 2baefe94d6fb..000000000000
--- a/googlemock/scripts/gmock-config.in
+++ /dev/null
@@ -1,303 +0,0 @@
-#!/bin/sh
-
-# These variables are automatically filled in by the configure script.
-name="@PACKAGE_TARNAME@"
-version="@PACKAGE_VERSION@"
-
-show_usage()
-{
- echo "Usage: gmock-config [OPTIONS...]"
-}
-
-show_help()
-{
- show_usage
- cat <<\EOF
-
-The `gmock-config' script provides access to the necessary compile and linking
-flags to connect with Google C++ Mocking 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 gmock. 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:
- gmock-config --min-version=1.0 || echo "Insufficient Google Mock version."
-
- g++ $(gmock-config --cppflags --cxxflags) -o foo.o -c foo.cpp
- g++ $(gmock-config --ldflags --libs) -o foo foo.o
-
- # When using a built but not installed Google Mock:
- g++ $(../../my_gmock_build/scripts/gmock-config ...) ...
-
- # When using an installed Google Mock, but with installation overrides:
- export GMOCK_PREFIX="/opt"
- g++ $(gmock-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 Mock 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=*) GMOCK_PREFIX=${1#--prefix=};;
- --exec-prefix=*) GMOCK_EXEC_PREFIX=${1#--exec-prefix=};;
- --libdir=*) GMOCK_LIBDIR=${1#--libdir=};;
- --includedir=*) GMOCK_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="${GMOCK_PREFIX:-@prefix@}"
-exec_prefix="${GMOCK_EXEC_PREFIX:-@exec_prefix@}"
-libdir="${GMOCK_LIBDIR:-@libdir@}"
-includedir="${GMOCK_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. We also locate Google Test using the configured
-# gtest-config script rather than searching the PATH and our bindir for one.
-# This allows building against a just-built gmock rather than an installed
-# gmock.
-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}/@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.
- gmock_libs="${build_dir}/lib/libgmock.la"
- gmock_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.
- gmock_cppflags="-I${build_dir}/include -I${src_dir}/include"
- gmock_cxxflags=""
-
- # Directly invoke the gtest-config script used during the build process.
- gtest_config="@GTEST_CONFIG@"
-else
- # We're using an installed gmock, 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.
- gmock_ldflags="-L${libdir}"
- gmock_libs="-l${name}"
- gmock_cppflags="-I${includedir}"
- gmock_cxxflags=""
-
- # We also prefer any gtest-config script installed in our prefix. Lacking
- # one, we look in the PATH for one.
- gtest_config="${bindir}/gtest-config"
- if test ! -x "${gtest_config}"; then
- gtest_config=`which gtest-config`
- fi
-fi
-
-# Ensure that we have located a Google Test to link against.
-if ! test -x "${gtest_config}"; then
- echo "Unable to locate Google Test, check your Google Mock configuration" \
- "and installation" >&2
- exit 1
-elif ! "${gtest_config}" "--exact-version=@GTEST_VERSION@"; then
- echo "The Google Test found is not the same version as Google Mock was " \
- "built against" >&2
- exit 1
-fi
-
-# Add the necessary Google Test bits into the various flag variables
-gmock_cppflags="${gmock_cppflags} `${gtest_config} --cppflags`"
-gmock_cxxflags="${gmock_cxxflags} `${gtest_config} --cxxflags`"
-gmock_ldflags="${gmock_ldflags} `${gtest_config} --ldflags`"
-gmock_libs="${gmock_libs} `${gtest_config} --libs`"
-
-# 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 $gmock_cppflags"
-test "$echo_cxxflags" = "yes" && output="$output $gmock_cxxflags"
-test "$echo_ldflags" = "yes" && output="$output $gmock_ldflags"
-test "$echo_libs" = "yes" && output="$output $gmock_libs"
-echo $output
-
-exit 0
diff --git a/googlemock/scripts/gmock_doctor.py b/googlemock/scripts/gmock_doctor.py
deleted file mode 100755
index 74992bc74481..000000000000
--- a/googlemock/scripts/gmock_doctor.py
+++ /dev/null
@@ -1,640 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2008, Google Inc.
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""Converts compiler's errors in code using Google Mock to plain English."""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-import re
-import sys
-
-_VERSION = '1.0.3'
-
-_EMAIL = 'googlemock@googlegroups.com'
-
-_COMMON_GMOCK_SYMBOLS = [
- # Matchers
- '_',
- 'A',
- 'AddressSatisfies',
- 'AllOf',
- 'An',
- 'AnyOf',
- 'ContainerEq',
- 'Contains',
- 'ContainsRegex',
- 'DoubleEq',
- 'ElementsAre',
- 'ElementsAreArray',
- 'EndsWith',
- 'Eq',
- 'Field',
- 'FloatEq',
- 'Ge',
- 'Gt',
- 'HasSubstr',
- 'IsInitializedProto',
- 'Le',
- 'Lt',
- 'MatcherCast',
- 'Matches',
- 'MatchesRegex',
- 'NanSensitiveDoubleEq',
- 'NanSensitiveFloatEq',
- 'Ne',
- 'Not',
- 'NotNull',
- 'Pointee',
- 'Property',
- 'Ref',
- 'ResultOf',
- 'SafeMatcherCast',
- 'StartsWith',
- 'StrCaseEq',
- 'StrCaseNe',
- 'StrEq',
- 'StrNe',
- 'Truly',
- 'TypedEq',
- 'Value',
-
- # Actions
- 'Assign',
- 'ByRef',
- 'DeleteArg',
- 'DoAll',
- 'DoDefault',
- 'IgnoreResult',
- 'Invoke',
- 'InvokeArgument',
- 'InvokeWithoutArgs',
- 'Return',
- 'ReturnNew',
- 'ReturnNull',
- 'ReturnRef',
- 'SaveArg',
- 'SetArgReferee',
- 'SetArgPointee',
- 'SetArgumentPointee',
- 'SetArrayArgument',
- 'SetErrnoAndReturn',
- 'Throw',
- 'WithArg',
- 'WithArgs',
- 'WithoutArgs',
-
- # Cardinalities
- 'AnyNumber',
- 'AtLeast',
- 'AtMost',
- 'Between',
- 'Exactly',
-
- # Sequences
- 'InSequence',
- 'Sequence',
-
- # Misc
- 'DefaultValue',
- 'Mock',
- ]
-
-# Regex for matching source file path and line number in the compiler's errors.
-_GCC_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(\d+:)?\s+'
-_CLANG_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(?P<column>\d+):\s+'
-_CLANG_NON_GMOCK_FILE_LINE_RE = (
- r'(?P<file>.*[/\\^](?!gmock-)[^/\\]+):(?P<line>\d+):(?P<column>\d+):\s+')
-
-
-def _FindAllMatches(regex, s):
- """Generates all matches of regex in string s."""
-
- r = re.compile(regex)
- return r.finditer(s)
-
-
-def _GenericDiagnoser(short_name, long_name, diagnoses, msg):
- """Diagnoses the given disease by pattern matching.
-
- Can provide different diagnoses for different patterns.
-
- Args:
- short_name: Short name of the disease.
- long_name: Long name of the disease.
- diagnoses: A list of pairs (regex, pattern for formatting the diagnosis
- for matching regex).
- msg: Compiler's error messages.
- Yields:
- Tuples of the form
- (short name of disease, long name of disease, diagnosis).
- """
- for regex, diagnosis in diagnoses:
- if re.search(regex, msg):
- diagnosis = '%(file)s:%(line)s:' + diagnosis
- for m in _FindAllMatches(regex, msg):
- yield (short_name, long_name, diagnosis % m.groupdict())
-
-
-def _NeedToReturnReferenceDiagnoser(msg):
- """Diagnoses the NRR disease, given the error messages by the compiler."""
-
- gcc_regex = (r'In member function \'testing::internal::ReturnAction<R>.*\n'
- + _GCC_FILE_LINE_RE + r'instantiated from here\n'
- r'.*gmock-actions\.h.*error: creating array with negative size')
- clang_regex = (r'error:.*array.*negative.*\r?\n'
- r'(.*\n)*?' +
- _CLANG_NON_GMOCK_FILE_LINE_RE +
- r'note: in instantiation of function template specialization '
- r'\'testing::internal::ReturnAction<(?P<type>.*)>'
- r'::operator Action<.*>\' requested here')
- clang11_re = (r'use_ReturnRef_instead_of_Return_to_return_a_reference.*'
- r'(.*\n)*?' + _CLANG_NON_GMOCK_FILE_LINE_RE)
-
- diagnosis = """
-You are using a Return() action in a function that returns a reference to
-%(type)s. Please use ReturnRef() instead."""
- return _GenericDiagnoser('NRR', 'Need to Return Reference',
- [(clang_regex, diagnosis),
- (clang11_re, diagnosis % {'type': 'a type'}),
- (gcc_regex, diagnosis % {'type': 'a type'})],
- msg)
-
-
-def _NeedToReturnSomethingDiagnoser(msg):
- """Diagnoses the NRS disease, given the error messages by the compiler."""
-
- gcc_regex = (_GCC_FILE_LINE_RE + r'(instantiated from here\n.'
- r'*gmock.*actions\.h.*error: void value not ignored)'
- r'|(error: control reaches end of non-void function)')
- clang_regex1 = (_CLANG_FILE_LINE_RE +
- r'error: cannot initialize return object '
- r'of type \'Result\' \(aka \'(?P<return_type>.*)\'\) '
- r'with an rvalue of type \'void\'')
- clang_regex2 = (_CLANG_FILE_LINE_RE +
- r'error: cannot initialize return object '
- r'of type \'(?P<return_type>.*)\' '
- r'with an rvalue of type \'void\'')
- diagnosis = """
-You are using an action that returns void, but it needs to return
-%(return_type)s. Please tell it *what* to return. Perhaps you can use
-the pattern DoAll(some_action, Return(some_value))?"""
- return _GenericDiagnoser(
- 'NRS',
- 'Need to Return Something',
- [(gcc_regex, diagnosis % {'return_type': '*something*'}),
- (clang_regex1, diagnosis),
- (clang_regex2, diagnosis)],
- msg)
-
-
-def _NeedToReturnNothingDiagnoser(msg):
- """Diagnoses the NRN disease, given the error messages by the compiler."""
-
- gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
- r'.*gmock-actions\.h.*error: instantiation of '
- r'\'testing::internal::ReturnAction<R>::Impl<F>::value_\' '
- r'as type \'void\'')
- clang_regex1 = (r'error: field has incomplete type '
- r'\'Result\' \(aka \'void\'\)(\r)?\n'
- r'(.*\n)*?' +
- _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
- r'of function template specialization '
- r'\'testing::internal::ReturnAction<(?P<return_type>.*)>'
- r'::operator Action<void \(.*\)>\' requested here')
- clang_regex2 = (r'error: field has incomplete type '
- r'\'Result\' \(aka \'void\'\)(\r)?\n'
- r'(.*\n)*?' +
- _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
- r'of function template specialization '
- r'\'testing::internal::DoBothAction<.*>'
- r'::operator Action<(?P<return_type>.*) \(.*\)>\' '
- r'requested here')
- diagnosis = """
-You are using an action that returns %(return_type)s, but it needs to return
-void. Please use a void-returning action instead.
-
-All actions but the last in DoAll(...) must return void. Perhaps you need
-to re-arrange the order of actions in a DoAll(), if you are using one?"""
- return _GenericDiagnoser(
- 'NRN',
- 'Need to Return Nothing',
- [(gcc_regex, diagnosis % {'return_type': '*something*'}),
- (clang_regex1, diagnosis),
- (clang_regex2, diagnosis)],
- msg)
-
-
-def _IncompleteByReferenceArgumentDiagnoser(msg):
- """Diagnoses the IBRA disease, given the error messages by the compiler."""
-
- gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
- r'.*gtest-printers\.h.*error: invalid application of '
- r'\'sizeof\' to incomplete type \'(?P<type>.*)\'')
-
- clang_regex = (r'.*gtest-printers\.h.*error: invalid application of '
- r'\'sizeof\' to an incomplete type '
- r'\'(?P<type>.*)( const)?\'\r?\n'
- r'(.*\n)*?' +
- _CLANG_NON_GMOCK_FILE_LINE_RE +
- r'note: in instantiation of member function '
- r'\'testing::internal2::TypeWithoutFormatter<.*>::'
- r'PrintValue\' requested here')
- diagnosis = """
-In order to mock this function, Google Mock needs to see the definition
-of type "%(type)s" - declaration alone is not enough. Either #include
-the header that defines it, or change the argument to be passed
-by pointer."""
-
- return _GenericDiagnoser('IBRA', 'Incomplete By-Reference Argument Type',
- [(gcc_regex, diagnosis),
- (clang_regex, diagnosis)],
- msg)
-
-
-def _OverloadedFunctionMatcherDiagnoser(msg):
- """Diagnoses the OFM disease, given the error messages by the compiler."""
-
- gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
- r'call to \'Truly\(<unresolved overloaded function type>\)')
- clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function for '
- r'call to \'Truly')
- diagnosis = """
-The argument you gave to Truly() is an overloaded function. Please tell
-your compiler which overloaded version you want to use.
-
-For example, if you want to use the version whose signature is
- bool Foo(int n);
-you should write
- Truly(static_cast<bool (*)(int n)>(Foo))"""
- return _GenericDiagnoser('OFM', 'Overloaded Function Matcher',
- [(gcc_regex, diagnosis),
- (clang_regex, diagnosis)],
- msg)
-
-
-def _OverloadedFunctionActionDiagnoser(msg):
- """Diagnoses the OFA disease, given the error messages by the compiler."""
-
- gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for call to '
- r'\'Invoke\(<unresolved overloaded function type>')
- clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching '
- r'function for call to \'Invoke\'\r?\n'
- r'(.*\n)*?'
- r'.*\bgmock-generated-actions\.h:\d+:\d+:\s+'
- r'note: candidate template ignored:\s+'
- r'couldn\'t infer template argument \'FunctionImpl\'')
- diagnosis = """
-Function you are passing to Invoke is overloaded. Please tell your compiler
-which overloaded version you want to use.
-
-For example, if you want to use the version whose signature is
- bool MyFunction(int n, double x);
-you should write something like
- Invoke(static_cast<bool (*)(int n, double x)>(MyFunction))"""
- return _GenericDiagnoser('OFA', 'Overloaded Function Action',
- [(gcc_regex, diagnosis),
- (clang_regex, diagnosis)],
- msg)
-
-
-def _OverloadedMethodActionDiagnoser(msg):
- """Diagnoses the OMA disease, given the error messages by the compiler."""
-
- gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
- r'call to \'Invoke\(.+, <unresolved overloaded function '
- r'type>\)')
- clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function '
- r'for call to \'Invoke\'\r?\n'
- r'(.*\n)*?'
- r'.*\bgmock-generated-actions\.h:\d+:\d+: '
- r'note: candidate function template not viable: '
- r'requires .*, but 2 (arguments )?were provided')
- diagnosis = """
-The second argument you gave to Invoke() is an overloaded method. Please
-tell your compiler which overloaded version you want to use.
-
-For example, if you want to use the version whose signature is
- class Foo {
- ...
- bool Bar(int n, double x);
- };
-you should write something like
- Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
- return _GenericDiagnoser('OMA', 'Overloaded Method Action',
- [(gcc_regex, diagnosis),
- (clang_regex, diagnosis)],
- msg)
-
-
-def _MockObjectPointerDiagnoser(msg):
- """Diagnoses the MOP disease, given the error messages by the compiler."""
-
- gcc_regex = (_GCC_FILE_LINE_RE + r'error: request for member '
- r'\'gmock_(?P<method>.+)\' in \'(?P<mock_object>.+)\', '
- r'which is of non-class type \'(.*::)*(?P<class_name>.+)\*\'')
- clang_regex = (_CLANG_FILE_LINE_RE + r'error: member reference type '
- r'\'(?P<class_name>.*?) *\' is a pointer; '
- r'(did you mean|maybe you meant) to use \'->\'\?')
- diagnosis = """
-The first argument to ON_CALL() and EXPECT_CALL() must be a mock *object*,
-not a *pointer* to it. Please write '*(%(mock_object)s)' instead of
-'%(mock_object)s' as your first argument.
-
-For example, given the mock class:
-
- class %(class_name)s : public ... {
- ...
- MOCK_METHOD0(%(method)s, ...);
- };
-
-and the following mock instance:
-
- %(class_name)s* mock_ptr = ...
-
-you should use the EXPECT_CALL like this:
-
- EXPECT_CALL(*mock_ptr, %(method)s(...));"""
-
- return _GenericDiagnoser(
- 'MOP',
- 'Mock Object Pointer',
- [(gcc_regex, diagnosis),
- (clang_regex, diagnosis % {'mock_object': 'mock_object',
- 'method': 'method',
- 'class_name': '%(class_name)s'})],
- msg)
-
-
-def _NeedToUseSymbolDiagnoser(msg):
- """Diagnoses the NUS disease, given the error messages by the compiler."""
-
- gcc_regex = (_GCC_FILE_LINE_RE + r'error: \'(?P<symbol>.+)\' '
- r'(was not declared in this scope|has not been declared)')
- clang_regex = (_CLANG_FILE_LINE_RE +
- r'error: (use of undeclared identifier|unknown type name|'
- r'no template named) \'(?P<symbol>[^\']+)\'')
- diagnosis = """
-'%(symbol)s' is defined by Google Mock in the testing namespace.
-Did you forget to write
- using testing::%(symbol)s;
-?"""
- for m in (list(_FindAllMatches(gcc_regex, msg)) +
- list(_FindAllMatches(clang_regex, msg))):
- symbol = m.groupdict()['symbol']
- if symbol in _COMMON_GMOCK_SYMBOLS:
- yield ('NUS', 'Need to Use Symbol', diagnosis % m.groupdict())
-
-
-def _NeedToUseReturnNullDiagnoser(msg):
- """Diagnoses the NRNULL disease, given the error messages by the compiler."""
-
- gcc_regex = ('instantiated from \'testing::internal::ReturnAction<R>'
- '::operator testing::Action<Func>\(\) const.*\n' +
- _GCC_FILE_LINE_RE + r'instantiated from here\n'
- r'.*error: no matching function for call to \'ImplicitCast_\('
- r'(:?long )?int&\)')
- clang_regex = (r'\bgmock-actions.h:.* error: no matching function for '
- r'call to \'ImplicitCast_\'\r?\n'
- r'(.*\n)*?' +
- _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
- r'of function template specialization '
- r'\'testing::internal::ReturnAction<(int|long)>::operator '
- r'Action<(?P<type>.*)\(\)>\' requested here')
- diagnosis = """
-You are probably calling Return(NULL) and the compiler isn't sure how to turn
-NULL into %(type)s. Use ReturnNull() instead.
-Note: the line number may be off; please fix all instances of Return(NULL)."""
- return _GenericDiagnoser(
- 'NRNULL', 'Need to use ReturnNull',
- [(clang_regex, diagnosis),
- (gcc_regex, diagnosis % {'type': 'the right type'})],
- msg)
-
-
-def _TypeInTemplatedBaseDiagnoser(msg):
- """Diagnoses the TTB disease, given the error messages by the compiler."""
-
- # This version works when the type is used as the mock function's return
- # type.
- gcc_4_3_1_regex_type_in_retval = (
- r'In member function \'int .*\n' + _GCC_FILE_LINE_RE +
- r'error: a function call cannot appear in a constant-expression')
- gcc_4_4_0_regex_type_in_retval = (
- r'error: a function call cannot appear in a constant-expression'
- + _GCC_FILE_LINE_RE + r'error: template argument 1 is invalid\n')
- # This version works when the type is used as the mock function's sole
- # parameter type.
- gcc_regex_type_of_sole_param = (
- _GCC_FILE_LINE_RE +
- r'error: \'(?P<type>.+)\' was not declared in this scope\n'
- r'.*error: template argument 1 is invalid\n')
- # This version works when the type is used as a parameter of a mock
- # function that has multiple parameters.
- gcc_regex_type_of_a_param = (
- r'error: expected `;\' before \'::\' token\n'
- + _GCC_FILE_LINE_RE +
- r'error: \'(?P<type>.+)\' was not declared in this scope\n'
- r'.*error: template argument 1 is invalid\n'
- r'.*error: \'.+\' was not declared in this scope')
- clang_regex_type_of_retval_or_sole_param = (
- _CLANG_FILE_LINE_RE +
- r'error: use of undeclared identifier \'(?P<type>.*)\'\n'
- r'(.*\n)*?'
- r'(?P=file):(?P=line):\d+: error: '
- r'non-friend class member \'Result\' cannot have a qualified name'
- )
- clang_regex_type_of_a_param = (
- _CLANG_FILE_LINE_RE +
- r'error: C\+\+ requires a type specifier for all declarations\n'
- r'(.*\n)*?'
- r'(?P=file):(?P=line):(?P=column): error: '
- r'C\+\+ requires a type specifier for all declarations'
- )
- clang_regex_unknown_type = (
- _CLANG_FILE_LINE_RE +
- r'error: unknown type name \'(?P<type>[^\']+)\''
- )
-
- diagnosis = """
-In a mock class template, types or typedefs defined in the base class
-template are *not* automatically visible. This is how C++ works. Before
-you can use a type or typedef named %(type)s defined in base class Base<T>, you
-need to make it visible. One way to do it is:
-
- typedef typename Base<T>::%(type)s %(type)s;"""
-
- for diag in _GenericDiagnoser(
- 'TTB', 'Type in Template Base',
- [(gcc_4_3_1_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
- (gcc_4_4_0_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
- (gcc_regex_type_of_sole_param, diagnosis),
- (gcc_regex_type_of_a_param, diagnosis),
- (clang_regex_type_of_retval_or_sole_param, diagnosis),
- (clang_regex_type_of_a_param, diagnosis % {'type': 'Foo'})],
- msg):
- yield diag
- # Avoid overlap with the NUS pattern.
- for m in _FindAllMatches(clang_regex_unknown_type, msg):
- type_ = m.groupdict()['type']
- if type_ not in _COMMON_GMOCK_SYMBOLS:
- yield ('TTB', 'Type in Template Base', diagnosis % m.groupdict())
-
-
-def _WrongMockMethodMacroDiagnoser(msg):
- """Diagnoses the WMM disease, given the error messages by the compiler."""
-
- gcc_regex = (_GCC_FILE_LINE_RE +
- r'.*this_method_does_not_take_(?P<wrong_args>\d+)_argument.*\n'
- r'.*\n'
- r'.*candidates are.*FunctionMocker<[^>]+A(?P<args>\d+)\)>')
- clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
- r'error:.*array.*negative.*r?\n'
- r'(.*\n)*?'
- r'(?P=file):(?P=line):(?P=column): error: too few arguments '
- r'to function call, expected (?P<args>\d+), '
- r'have (?P<wrong_args>\d+)')
- clang11_re = (_CLANG_NON_GMOCK_FILE_LINE_RE +
- r'.*this_method_does_not_take_'
- r'(?P<wrong_args>\d+)_argument.*')
- diagnosis = """
-You are using MOCK_METHOD%(wrong_args)s to define a mock method that has
-%(args)s arguments. Use MOCK_METHOD%(args)s (or MOCK_CONST_METHOD%(args)s,
-MOCK_METHOD%(args)s_T, MOCK_CONST_METHOD%(args)s_T as appropriate) instead."""
- return _GenericDiagnoser('WMM', 'Wrong MOCK_METHODn Macro',
- [(gcc_regex, diagnosis),
- (clang11_re, diagnosis % {'wrong_args': 'm',
- 'args': 'n'}),
- (clang_regex, diagnosis)],
- msg)
-
-
-def _WrongParenPositionDiagnoser(msg):
- """Diagnoses the WPP disease, given the error messages by the compiler."""
-
- gcc_regex = (_GCC_FILE_LINE_RE +
- r'error:.*testing::internal::MockSpec<.* has no member named \''
- r'(?P<method>\w+)\'')
- clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
- r'error: no member named \'(?P<method>\w+)\' in '
- r'\'testing::internal::MockSpec<.*>\'')
- diagnosis = """
-The closing parenthesis of ON_CALL or EXPECT_CALL should be *before*
-".%(method)s". For example, you should write:
- EXPECT_CALL(my_mock, Foo(_)).%(method)s(...);
-instead of:
- EXPECT_CALL(my_mock, Foo(_).%(method)s(...));"""
- return _GenericDiagnoser('WPP', 'Wrong Parenthesis Position',
- [(gcc_regex, diagnosis),
- (clang_regex, diagnosis)],
- msg)
-
-
-_DIAGNOSERS = [
- _IncompleteByReferenceArgumentDiagnoser,
- _MockObjectPointerDiagnoser,
- _NeedToReturnNothingDiagnoser,
- _NeedToReturnReferenceDiagnoser,
- _NeedToReturnSomethingDiagnoser,
- _NeedToUseReturnNullDiagnoser,
- _NeedToUseSymbolDiagnoser,
- _OverloadedFunctionActionDiagnoser,
- _OverloadedFunctionMatcherDiagnoser,
- _OverloadedMethodActionDiagnoser,
- _TypeInTemplatedBaseDiagnoser,
- _WrongMockMethodMacroDiagnoser,
- _WrongParenPositionDiagnoser,
- ]
-
-
-def Diagnose(msg):
- """Generates all possible diagnoses given the compiler error message."""
-
- msg = re.sub(r'\x1b\[[^m]*m', '', msg) # Strips all color formatting.
- # Assuming the string is using the UTF-8 encoding, replaces the left and
- # the right single quote characters with apostrophes.
- msg = re.sub(r'(\xe2\x80\x98|\xe2\x80\x99)', "'", msg)
-
- diagnoses = []
- for diagnoser in _DIAGNOSERS:
- for diag in diagnoser(msg):
- diagnosis = '[%s - %s]\n%s' % diag
- if not diagnosis in diagnoses:
- diagnoses.append(diagnosis)
- return diagnoses
-
-
-def main():
- print ('Google Mock Doctor v%s - '
- 'diagnoses problems in code using Google Mock.' % _VERSION)
-
- if sys.stdin.isatty():
- print ('Please copy and paste the compiler errors here. Press c-D when '
- 'you are done:')
- else:
- print ('Waiting for compiler errors on stdin . . .')
-
- msg = sys.stdin.read().strip()
- diagnoses = Diagnose(msg)
- count = len(diagnoses)
- if not count:
- print ("""
-Your compiler complained:
-8<------------------------------------------------------------
-%s
------------------------------------------------------------->8
-
-Uh-oh, I'm not smart enough to figure out what the problem is. :-(
-However...
-If you send your source code and the compiler's error messages to
-%s, you can be helped and I can get smarter --
-win-win for us!""" % (msg, _EMAIL))
- else:
- print ('------------------------------------------------------------')
- print ('Your code appears to have the following',)
- if count > 1:
- print ('%s diseases:' % (count,))
- else:
- print ('disease:')
- i = 0
- for d in diagnoses:
- i += 1
- if count > 1:
- print ('\n#%s:' % (i,))
- print (d)
- print ("""
-How did I do? If you think I'm wrong or unhelpful, please send your
-source code and the compiler's error messages to %s.
-Then you can be helped and I can get smarter -- I promise I won't be upset!""" %
- _EMAIL)
-
-
-if __name__ == '__main__':
- main()
diff --git a/googlemock/scripts/upload.py b/googlemock/scripts/upload.py
deleted file mode 100755
index 95239dc2cbed..000000000000
--- a/googlemock/scripts/upload.py
+++ /dev/null
@@ -1,1387 +0,0 @@
-#!/usr/bin/env python
-#
-# 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.
-
-"""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 (ouput 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/googlemock/scripts/upload_gmock.py b/googlemock/scripts/upload_gmock.py
deleted file mode 100755
index 5dc484b3912b..000000000000
--- a/googlemock/scripts/upload_gmock.py
+++ /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_gmock.py v0.1.0 -- uploads a Google Mock patch for review.
-
-This simple wrapper passes all command line flags and
---cc=googlemock@googlegroups.com to upload.py.
-
-USAGE: upload_gmock.py [options for upload.py]
-"""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-import os
-import sys
-
-CC_FLAG = '--cc='
-GMOCK_GROUP = 'googlemock@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 Mock 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 GMOCK_GROUP not in cc_list:
- cc_list.append(GMOCK_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 + GMOCK_GROUP)
-
- # Invokes upload.py with the modified command line flags.
- os.execv(upload_py_path, upload_py_argv)
-
-
-if __name__ == '__main__':
- main()
diff --git a/googlemock/src/gmock-cardinalities.cc b/googlemock/src/gmock-cardinalities.cc
index 7463f4383233..92cde3484abf 100644
--- a/googlemock/src/gmock-cardinalities.cc
+++ b/googlemock/src/gmock-cardinalities.cc
@@ -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.
@@ -35,9 +34,11 @@
#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.
diff --git a/googlemock/src/gmock-internal-utils.cc b/googlemock/src/gmock-internal-utils.cc
index e5b547981d14..5c2ce0d57eb6 100644
--- a/googlemock/src/gmock-internal-utils.cc
+++ b/googlemock/src/gmock-internal-utils.cc
@@ -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
@@ -37,8 +36,16 @@
#include "gmock/internal/gmock-internal-utils.h"
#include <ctype.h>
+
+#include <array>
+#include <cctype>
+#include <cstdint>
+#include <cstring>
+#include <iostream>
#include <ostream> // NOLINT
#include <string>
+#include <vector>
+
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
@@ -48,21 +55,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 +84,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.empty()) result += ' ';
result += ToLower(*p);
}
}
@@ -95,12 +102,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 +130,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 +152,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 +181,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(
+ actual_to_skip);
}
std::cout << ::std::flush;
}
@@ -196,5 +199,59 @@ GTEST_API_ void IllegalDoDefault(const char* file, int line) {
"the variable in various places.");
}
+constexpr char UndoWebSafeEncoding(char c) {
+ return c == '-' ? '+' : c == '_' ? '/' : c;
+}
+
+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, static_cast<char>(carry + 1));
+}
+
+template <size_t... I>
+constexpr std::array<char, 256> UnBase64Impl(IndexSequence<I...>,
+ const char* const base64) {
+ return {
+ {UnBase64Impl(UndoWebSafeEncoding(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
diff --git a/googlemock/src/gmock-matchers.cc b/googlemock/src/gmock-matchers.cc
index 4a3f7af2351d..07bba4f0103d 100644
--- a/googlemock/src/gmock-matchers.cc
+++ b/googlemock/src/gmock-matchers.cc
@@ -27,19 +27,19 @@
// (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
// utilities for defining matchers.
#include "gmock/gmock-matchers.h"
-#include "gmock/gmock-generated-matchers.h"
#include <string.h>
+
#include <iostream>
#include <sstream>
#include <string>
+#include <vector>
namespace testing {
namespace internal {
@@ -49,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.empty()) {
+ result += " " + JoinAsKeyValueTuple(param_names, param_values);
+ }
return negation ? "not (" + result + ")" : result;
}
@@ -219,8 +221,6 @@ class MaxBipartiteMatchState {
// right_[left_[i]] = i.
::std::vector<size_t> left_;
::std::vector<size_t> right_;
-
- GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
};
const size_t MaxBipartiteMatchState::kUnused;
@@ -370,6 +370,23 @@ void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(
const ::std::vector<std::string>& element_printouts,
const MatchMatrix& matrix, MatchResultListener* listener) const {
+ if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
+ return true;
+ }
+
+ if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
+ if (matrix.LhsSize() != matrix.RhsSize()) {
+ // The element count doesn't match. If the container is empty,
+ // there's no need to explain anything as Google Mock already
+ // prints the empty container. Otherwise we just need to show
+ // how many elements there actually are.
+ if (matrix.LhsSize() != 0 && listener->IsInterested()) {
+ *listener << "which has " << Elements(matrix.LhsSize());
+ }
+ return false;
+ }
+ }
+
bool result = true;
::std::vector<char> element_matched(matrix.LhsSize(), 0);
::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc
index f9d3434560b4..de8947163586 100644
--- a/googlemock/src/gmock-spec-builders.cc
+++ b/googlemock/src/gmock-spec-builders.cc
@@ -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
@@ -36,26 +35,31 @@
#include "gmock/gmock-spec-builders.h"
#include <stdlib.h>
+
#include <iostream> // NOLINT
#include <map>
#include <memory>
#include <set>
+#include <sstream>
#include <string>
+#include <unordered_map>
#include <vector>
+
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+#include "gtest/internal/gtest-port.h"
-#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
-# include <unistd.h> // NOLINT
+#if defined(GTEST_OS_CYGWIN) || defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC)
+#include <unistd.h> // NOLINT
+#endif
+#ifdef GTEST_OS_QURT
+#include <qurt_event.h>
#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)
-#endif
+#if defined(_MSC_VER) && (_MSC_VER == 1900)
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#endif
namespace testing {
@@ -70,7 +74,8 @@ GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
const char* file, int line,
const std::string& message) {
::std::ostringstream s;
- s << file << ":" << line << ": " << message << ::std::endl;
+ s << internal::FormatFileLocation(file, line) << " " << message
+ << ::std::endl;
Log(severity, s.str(), 0);
}
@@ -91,7 +96,7 @@ ExpectationBase::ExpectationBase(const char* a_file, int a_line,
action_count_checked_(false) {}
// Destructs an ExpectationBase object.
-ExpectationBase::~ExpectationBase() {}
+ExpectationBase::~ExpectationBase() = default;
// Explicitly specifies the cardinality of this expectation. Used by
// the subclasses to implement the .Times() clause.
@@ -191,11 +196,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
@@ -238,13 +244,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()";
}
@@ -260,10 +265,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;
@@ -279,7 +284,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);
@@ -291,9 +296,9 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
"call should not happen. Do not suppress it by blindly adding "
"an EXPECT_CALL() if you don't mean to enforce the call. "
"See "
- "https://github.com/google/googletest/blob/master/googlemock/"
- "docs/cook_book.md#"
- "knowing-when-to-expect for details.\n",
+ "https://github.com/google/googletest/blob/main/docs/"
+ "gmock_cook_book.md#"
+ "knowing-when-to-expect-useoncall for details.\n",
stack_frames_to_skip);
break;
default: // FAIL
@@ -304,7 +309,7 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
UntypedFunctionMockerBase::UntypedFunctionMockerBase()
: mock_obj_(nullptr), name_("") {}
-UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
+UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default;
// Sets the mock object this mock method belongs to, and registers
// this information in the global mock registry. Will be called
@@ -366,127 +371,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* const result =
- untyped_action == nullptr
- ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
- : this->UntypedPerformAction(untyped_action, untyped_args);
- if (result != nullptr) result->PrintAsActionResult(&ss);
- 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 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);
@@ -506,8 +396,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()) {
@@ -518,15 +407,22 @@ 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";
+
+ const ::std::string& expectation_name =
+ untyped_expectation->GetDescription();
+ ss << "Actual function ";
+ if (!expectation_name.empty()) {
+ ss << "\"" << expectation_name << "\" ";
+ }
+ ss << "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());
}
}
@@ -547,7 +443,7 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
return expectations_met;
}
-CallReaction intToCallReaction(int mock_behavior) {
+static CallReaction intToCallReaction(int mock_behavior) {
if (mock_behavior >= kAllow && mock_behavior <= kFail) {
return static_cast<internal::CallReaction>(mock_behavior);
}
@@ -593,8 +489,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();
@@ -609,18 +504,18 @@ class MockObjectRegistry {
std::cout << internal::FormatFileLocation(state.first_used_file,
state.first_used_line);
std::cout << " ERROR: this mock object";
- if (state.first_used_test != "") {
+ if (!state.first_used_test.empty()) {
std::cout << " (used in test " << state.first_used_test_suite << "."
<< 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) {
std::cout << "\nERROR: " << leaked_count << " leaked mock "
<< (leaked_count == 1 ? "object" : "objects")
- << " found at program exit. Expectations on a mock object is "
+ << " found at program exit. Expectations on a mock object are "
"verified when the object is destructed. Leaking a mock "
"means that its expectations aren't verified, which is "
"usually a test bug. If you really intend to leak a mock, "
@@ -632,8 +527,12 @@ class MockObjectRegistry {
// RUN_ALL_TESTS() has already returned when this destructor is
// called. Therefore we cannot use the normal Google Test
// failure reporting mechanism.
+#ifdef GTEST_OS_QURT
+ qurt_exception_raise_fatal();
+#else
_exit(1); // We cannot call exit() as it is not reentrant and
// may already have been called.
+#endif
}
}
@@ -648,57 +547,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
@@ -841,20 +746,20 @@ void Mock::ClearDefaultActionsLocked(void* mock_obj)
// needed by VerifyAndClearExpectationsLocked().
}
-Expectation::Expectation() {}
+Expectation::Expectation() = default;
Expectation::Expectation(
const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
: expectation_base_(an_expectation_base) {}
-Expectation::~Expectation() {}
+Expectation::~Expectation() = default;
// Adds an expectation to a sequence.
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;
}
@@ -881,8 +786,6 @@ InSequence::~InSequence() {
} // namespace testing
-#ifdef _MSC_VER
-#if _MSC_VER == 1900
-# pragma warning(pop)
-#endif
+#if defined(_MSC_VER) && (_MSC_VER == 1900)
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#endif
diff --git a/googlemock/src/gmock.cc b/googlemock/src/gmock.cc
index 32b2a7394fd0..b5e714da7d3c 100644
--- a/googlemock/src/gmock.cc
+++ b/googlemock/src/gmock.cc
@@ -27,17 +27,17 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
#include "gmock/gmock.h"
-#include "gmock/internal/gmock-port.h"
-namespace testing {
+#include <string>
+
+#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 +51,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 +60,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 +92,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 +111,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 +124,17 @@ static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
return true;
}
-static bool ParseGoogleMockIntFlag(const char* str, const char* flag,
- int* 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 +153,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
diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc
index 98611b935350..6b5541271bfe 100644
--- a/googlemock/src/gmock_main.cc
+++ b/googlemock/src/gmock_main.cc
@@ -27,12 +27,16 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
#include <iostream>
+
#include "gmock/gmock.h"
#include "gtest/gtest.h"
-#ifdef ARDUINO
+#if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) || \
+ (defined(GTEST_OS_NRF52) && defined(ARDUINO))
+#ifdef GTEST_OS_ESP8266
+extern "C" {
+#endif
void setup() {
// Since Google Mock depends on Google Test, InitGoogleMock() is
// also responsible for initializing Google Test. Therefore there's
@@ -40,6 +44,10 @@ void setup() {
testing::InitGoogleMock();
}
void loop() { RUN_ALL_TESTS(); }
+#ifdef GTEST_OS_ESP8266
+}
+#endif
+
#else
// MS C++ compiler/linker has a bug on Windows (not on Windows CE), which
@@ -48,8 +56,8 @@ void loop() { RUN_ALL_TESTS(); }
// Windows. See the following link to track the current status of this bug:
// 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
+#ifdef GTEST_OS_WINDOWS_MOBILE
+#include <tchar.h> // NOLINT
GTEST_API_ int _tmain(int argc, TCHAR** argv) {
#else
diff --git a/googlemock/test/BUILD.bazel b/googlemock/test/BUILD.bazel
index da95ed58bfd7..d4297c80fe8d 100644
--- a/googlemock/test/BUILD.bazel
+++ b/googlemock/test/BUILD.bazel
@@ -28,11 +28,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.
#
-# Author: misterg@google.com (Gennadiy Civil)
-#
# 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"])
@@ -41,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"],
}),
@@ -54,6 +52,9 @@ py_library(
name = "gmock_test_utils",
testonly = 1,
srcs = ["gmock_test_utils.py"],
+ deps = [
+ "//googletest/test:gtest_test_utils",
+ ],
)
cc_binary(
@@ -71,6 +72,10 @@ py_test(
":gmock_leak_test_",
":gmock_test_utils",
],
+ tags = [
+ "no_test_msvc2015",
+ "no_test_msvc2017",
+ ],
)
cc_test(
@@ -98,7 +103,10 @@ py_test(
":gmock_output_test_",
":gmock_output_test_golden.txt",
],
- python_version = "PY2",
+ tags = [
+ "no_test_msvc2015",
+ "no_test_msvc2017",
+ ],
deps = [":gmock_test_utils"],
)
diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc
index f63c8c5af926..da1675c525d1 100644
--- a/googlemock/test/gmock-actions_test.cc
+++ b/googlemock/test/gmock-actions_test.cc
@@ -27,63 +27,231 @@
// (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 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)
-#endif
-#endif
-
#include "gmock/gmock-actions.h"
+
#include <algorithm>
+#include <functional>
#include <iterator>
#include <memory>
+#include <sstream>
#include <string>
+#include <tuple>
+#include <type_traits>
+#include <utility>
+#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"
+#include "gtest/internal/gtest-port.h"
+
+// Silence C4100 (unreferenced formal parameter) and C4503 (decorated name
+// length exceeded) for MSVC.
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503)
+#if defined(_MSC_VER) && (_MSC_VER == 1900)
+// and silence C4800 (C4800: 'int *const ': forcing value
+// to bool 'true' or 'false') for MSVC 15
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
+#endif
+namespace testing {
namespace {
-// This list should be kept sorted.
-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::Ne;
-using testing::PolymorphicAction;
-using testing::Return;
-using testing::ReturnNull;
-using testing::ReturnRef;
-using testing::ReturnRefOfCopy;
-using testing::SetArgPointee;
-using testing::SetArgumentPointee;
-using testing::Unused;
-using testing::WithArgs;
-using testing::internal::BuiltInDefaultValue;
-using testing::internal::Int64;
-using testing::internal::UInt64;
-
-#if !GTEST_OS_WINDOWS_MOBILE
-using testing::SetErrnoAndReturn;
-#endif
+using ::testing::internal::BuiltInDefaultValue;
+
+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(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
+ GTEST_INTERNAL_CPLUSPLUS_LANG >= 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) {
@@ -113,16 +281,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<UInt64>::Get());
- EXPECT_EQ(0, BuiltInDefaultValue<Int64>::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 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());
}
@@ -137,16 +306,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<UInt64>::Exists());
- EXPECT_TRUE(BuiltInDefaultValue<Int64>::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 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());
}
@@ -164,13 +334,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
@@ -205,7 +375,6 @@ class MyNonDefaultConstructible {
int value_;
};
-
TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
}
@@ -214,25 +383,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.
@@ -278,26 +441,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::make_unique<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.
@@ -308,7 +467,7 @@ TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
}
-// Tests that DefaultValue<T&>::Exists is false initiallly.
+// Tests that DefaultValue<T&>::Exists is false initially.
TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
EXPECT_FALSE(DefaultValue<int&>::Exists());
EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
@@ -345,12 +504,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
@@ -381,7 +537,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);
@@ -430,7 +586,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')));
@@ -522,27 +678,137 @@ 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>& vec) : v(&vec) {} // 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}));
+
+ EXPECT_THAT(mock.AsStdFunction()(),
+ Field(&Result::v, Pointee(ElementsAre(17, 19, 23))));
+
+ 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 val) : x(val) {}
+ explicit Out(const In&) : x(0) {}
+ };
-// 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);
+ struct In {
+ operator Out() const { return Out{19}; } // NOLINT
+ };
- // 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));
+ // 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));
}
-// Tests that Return(v) is covaraint.
+// 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 covariant.
struct Base {
bool operator==(const Base&) { return true; }
@@ -573,8 +839,6 @@ class FromType {
private:
bool* const converted_;
-
- GTEST_DISALLOW_ASSIGN_(FromType);
};
class ToType {
@@ -595,19 +859,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();
@@ -646,6 +897,43 @@ TEST(ReturnRefTest, IsCovariant) {
EXPECT_EQ(&derived, &a.Perform(std::make_tuple()));
}
+template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>
+bool CanCallReturnRef(T&&) {
+ return true;
+}
+bool CanCallReturnRef(Unused) { return false; }
+
+// Tests that ReturnRef(v) is working with non-temporaries (T&)
+TEST(ReturnRefTest, WorksForNonTemporary) {
+ int scalar_value = 123;
+ EXPECT_TRUE(CanCallReturnRef(scalar_value));
+
+ std::string non_scalar_value("ABC");
+ EXPECT_TRUE(CanCallReturnRef(non_scalar_value));
+
+ const int const_scalar_value{321};
+ EXPECT_TRUE(CanCallReturnRef(const_scalar_value));
+
+ const std::string const_non_scalar_value("CBA");
+ EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value));
+}
+
+// Tests that ReturnRef(v) is not working with temporaries (T&&)
+TEST(ReturnRefTest, DoesNotWorkForTemporary) {
+ auto scalar_value = []() -> int { return 123; };
+ EXPECT_FALSE(CanCallReturnRef(scalar_value()));
+
+ auto non_scalar_value = []() -> std::string { return "ABC"; };
+ EXPECT_FALSE(CanCallReturnRef(non_scalar_value()));
+
+ // cannot use here callable returning "const scalar type",
+ // because such const for scalar return type is ignored
+ EXPECT_FALSE(CanCallReturnRef(static_cast<const int>(321)));
+
+ auto const_non_scalar_value = []() -> const std::string { return "CBA"; };
+ EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value()));
+}
+
// Tests that ReturnRefOfCopy(v) works for reference types.
TEST(ReturnRefOfCopyTest, WorksForReference) {
int n = 42;
@@ -670,11 +958,36 @@ TEST(ReturnRefOfCopyTest, IsCovariant) {
EXPECT_NE(&derived, &a.Perform(std::make_tuple()));
}
+// Tests that ReturnRoundRobin(v) works with initializer lists
+TEST(ReturnRoundRobinTest, WorksForInitList) {
+ Action<int()> ret = ReturnRoundRobin({1, 2, 3});
+
+ EXPECT_EQ(1, ret.Perform(std::make_tuple()));
+ EXPECT_EQ(2, ret.Perform(std::make_tuple()));
+ EXPECT_EQ(3, ret.Perform(std::make_tuple()));
+ EXPECT_EQ(1, ret.Perform(std::make_tuple()));
+ EXPECT_EQ(2, ret.Perform(std::make_tuple()));
+ EXPECT_EQ(3, ret.Perform(std::make_tuple()));
+}
+
+// Tests that ReturnRoundRobin(v) works with vectors
+TEST(ReturnRoundRobinTest, WorksForVector) {
+ std::vector<double> v = {4.4, 5.5, 6.6};
+ Action<double()> ret = ReturnRoundRobin(v);
+
+ EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
+ EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
+ EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
+ EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
+ EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
+ EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
+}
+
// Tests that DoDefault() does the default action for the mock method.
class MockClass {
public:
- MockClass() {}
+ MockClass() = default;
MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
MOCK_METHOD0(Foo, MyNonDefaultConstructible());
@@ -686,15 +999,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));
}
@@ -702,14 +1015,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
}
@@ -721,25 +1031,21 @@ 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
-// DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
+// DefaultValue<T>::Set() when it's not overridden by an ON_CALL().
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();
}
@@ -747,20 +1053,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
@@ -807,7 +1112,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");
@@ -815,7 +1120,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.
@@ -846,7 +1151,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";
@@ -855,7 +1160,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
@@ -1018,6 +1323,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) {
@@ -1114,11 +1572,32 @@ 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
+#ifndef GTEST_OS_WINDOWS_MOBILE
class SetErrnoAndReturnTest : public testing::Test {
protected:
@@ -1174,7 +1653,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);
}
@@ -1199,7 +1678,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);
@@ -1230,11 +1709,55 @@ TEST(ByRefTest, PrintsCorrectly) {
EXPECT_EQ(expected.str(), actual.str());
}
+struct UnaryConstructorClass {
+ explicit UnaryConstructorClass(int v) : value(v) {}
+ int value;
+};
+
+// Tests using ReturnNew() with a unary constructor.
+TEST(ReturnNewTest, Unary) {
+ Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
+ UnaryConstructorClass* c = a.Perform(std::make_tuple());
+ EXPECT_EQ(4000, c->value);
+ delete c;
+}
+
+TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
+ Action<UnaryConstructorClass*(bool, int)> a =
+ ReturnNew<UnaryConstructorClass>(4000);
+ UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
+ EXPECT_EQ(4000, c->value);
+ delete c;
+}
+
+TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
+ Action<const UnaryConstructorClass*()> a =
+ ReturnNew<UnaryConstructorClass>(4000);
+ const UnaryConstructorClass* c = a.Perform(std::make_tuple());
+ EXPECT_EQ(4000, c->value);
+ delete c;
+}
+
+class TenArgConstructorClass {
+ public:
+ TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
+ int a8, int a9, int a10)
+ : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
+ int value_;
+};
-std::unique_ptr<int> UniquePtrSource() {
- return std::unique_ptr<int>(new int(19));
+// Tests using ReturnNew() with a 10-argument constructor.
+TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
+ Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(
+ 1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90,
+ 0);
+ TenArgConstructorClass* c = a.Perform(std::make_tuple());
+ EXPECT_EQ(1234567890, c->value_);
+ delete c;
}
+std::unique_ptr<int> UniquePtrSource() { return std::make_unique<int>(19); }
+
std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
std::vector<std::unique_ptr<int>> out;
out.emplace_back(new int(7));
@@ -1268,9 +1791,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);
@@ -1280,9 +1804,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::make_unique<int>(42); });
EXPECT_EQ(42, *mock.MakeUnique());
EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
@@ -1302,7 +1825,7 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
TEST(MockMethodTest, CanTakeMoveOnlyValue) {
MockClass mock;
- auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };
+ auto make = [](int i) { return std::make_unique<int>(i); };
EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
return *i;
@@ -1342,6 +1865,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.
@@ -1356,12 +2051,12 @@ 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) {
- return std::unique_ptr<int>(new int(i));
-}
+std::unique_ptr<int> UniqueInt(int i) { return std::make_unique<int>(i); }
TEST(FunctorActionTest, ActionFromFunction) {
Action<int(int, int&, int*)> a = &Add;
@@ -1408,14 +2103,26 @@ TEST(FunctorActionTest, TypeConversion) {
EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));
// Also between the lambda and the action itself.
- const Action<bool(std::string)> x = [](Unused) { return 42; };
- EXPECT_TRUE(x.Perform(std::make_tuple("hello")));
+ const Action<bool(std::string)> x1 = [](Unused) { return 42; };
+ const Action<bool(std::string)> x2 = [] { return 42; };
+ EXPECT_TRUE(x1.Perform(std::make_tuple("hello")));
+ EXPECT_TRUE(x2.Perform(std::make_tuple("hello")));
+
+ // Ensure decay occurs where required.
+ std::function<int()> f = [] { return 7; };
+ Action<int(int)> d = f;
+ f = nullptr;
+ EXPECT_EQ(7, d.Perform(std::make_tuple(1)));
+
+ // Ensure creation of an empty action succeeds.
+ Action<void(int)>(nullptr);
}
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));
}
@@ -1434,12 +2141,29 @@ TEST(MoveOnlyArgumentsTest, ReturningActions) {
EXPECT_EQ(x, 3);
}
+ACTION(ReturnArity) { return std::tuple_size<args_type>::value; }
+
+TEST(ActionMacro, LargeArity) {
+ EXPECT_EQ(
+ 1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0)));
+ EXPECT_EQ(
+ 10,
+ testing::Action<int(int, int, int, int, int, int, int, int, int, int)>(
+ ReturnArity())
+ .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)));
+ EXPECT_EQ(
+ 20,
+ testing::Action<int(int, int, int, int, int, int, int, int, int, int, int,
+ int, int, int, int, int, int, int, int, int)>(
+ ReturnArity())
+ .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
+ 14, 15, 16, 17, 18, 19)));
+}
-} // Unnamed namespace
+} // namespace
+} // namespace testing
-#ifdef _MSC_VER
-#if _MSC_VER == 1900
-# pragma warning(pop)
-#endif
+#if defined(_MSC_VER) && (_MSC_VER == 1900)
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#endif
-
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4503
diff --git a/googlemock/test/gmock-cardinalities_test.cc b/googlemock/test/gmock-cardinalities_test.cc
index ca97cae24924..ad49752e172d 100644
--- a/googlemock/test/gmock-cardinalities_test.cc
+++ b/googlemock/test/gmock-cardinalities_test.cc
@@ -27,14 +27,15 @@
// (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 <ostream>
+
#include "gmock/gmock.h"
-#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
+#include "gtest/gtest.h"
namespace {
@@ -51,17 +52,16 @@ using testing::MakeCardinality;
class MockFoo {
public:
- MockFoo() {}
+ MockFoo() = default;
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 +119,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 +131,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 +148,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 +164,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 +184,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 +201,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 +217,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 +237,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 +272,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 +289,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 +306,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 +326,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 +338,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 +355,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 +368,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) {
diff --git a/googlemock/test/gmock-function-mocker_nc.cc b/googlemock/test/gmock-function-mocker_nc.cc
deleted file mode 100644
index d38fe85ef035..000000000000
--- a/googlemock/test/gmock-function-mocker_nc.cc
+++ /dev/null
@@ -1,16 +0,0 @@
-#include "gmock/gmock.h"
-
-#include <memory>
-#include <string>
-
-#if defined(TEST_MOCK_METHOD_INVALID_CONST_SPEC)
-
-struct Base {
- MOCK_METHOD(int, F, (), (onst));
-};
-
-#else
-
-// Sanity check - this should compile.
-
-#endif
diff --git a/googlemock/test/gmock-function-mocker_nc_test.py b/googlemock/test/gmock-function-mocker_nc_test.py
deleted file mode 100644
index 8ef6e09fa2b9..000000000000
--- a/googlemock/test/gmock-function-mocker_nc_test.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""Negative compilation tests for Google Mock macro MOCK_METHOD."""
-
-import os
-import sys
-
-IS_LINUX = os.name == "posix" and os.uname()[0] == "Linux"
-if not IS_LINUX:
- sys.stderr.write(
- "WARNING: Negative compilation tests are not supported on this platform")
- sys.exit(0)
-
-# Suppresses the 'Import not at the top of the file' lint complaint.
-# pylint: disable-msg=C6204
-from google3.testing.pybase import fake_target_util
-from google3.testing.pybase import googletest
-
-# pylint: enable-msg=C6204
-
-
-class GMockMethodNCTest(googletest.TestCase):
- """Negative compilation tests for MOCK_METHOD."""
-
- # The class body is intentionally empty. The actual test*() methods
- # will be defined at run time by a call to
- # DefineNegativeCompilationTests() later.
- pass
-
-
-# Defines a list of test specs, where each element is a tuple
-# (test name, list of regexes for matching the compiler errors).
-TEST_SPECS = [
- ("MOCK_METHOD_INVALID_CONST_SPEC",
- [r"onst cannot be recognized as a valid specification modifier"]),
-]
-
-# Define a test method in GMockNCTest for each element in TEST_SPECS.
-fake_target_util.DefineNegativeCompilationTests(
- GMockMethodNCTest,
- "google3/third_party/googletest/googlemock/test/gmock-function-mocker_nc",
- "gmock-function-mocker_nc.o", TEST_SPECS)
-
-if __name__ == "__main__":
- googletest.main()
diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc
index fbc5d5b2bb97..f7b31ae33852 100644
--- a/googlemock/test/gmock-function-mocker_test.cc
+++ b/googlemock/test/gmock-function-mocker_test.cc
@@ -27,21 +27,26 @@
// (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 function mocker classes.
-#include "gmock/gmock-generated-function-mockers.h"
+#include "gmock/gmock-function-mocker.h"
+
+// Silence C4503 (decorated name length exceeded) for MSVC.
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4503)
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// 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>
#include <map>
#include <string>
+#include <type_traits>
+
#include "gmock/gmock.h"
#include "gtest/gtest.h"
@@ -62,10 +67,10 @@ using testing::Return;
using testing::ReturnRef;
using testing::TypedEq;
-template<typename T>
+template <typename T>
class TemplatedCopyable {
public:
- TemplatedCopyable() {}
+ TemplatedCopyable() = default;
template <typename U>
TemplatedCopyable(const U& other) {} // NOLINT
@@ -73,13 +78,13 @@ class TemplatedCopyable {
class FooInterface {
public:
- virtual ~FooInterface() {}
+ virtual ~FooInterface() = default;
virtual void VoidReturning(int x) = 0;
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;
@@ -101,7 +106,21 @@ class FooInterface {
virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0;
virtual int TypeWithTemplatedCopyCtor(const TemplatedCopyable<int>&) = 0;
-#if GTEST_OS_WINDOWS
+ virtual int (*ReturnsFunctionPointer1(int))(bool) = 0;
+ using fn_ptr = int (*)(bool);
+ virtual fn_ptr ReturnsFunctionPointer2(int) = 0;
+
+ virtual int RefQualifiedConstRef() const& = 0;
+ virtual int RefQualifiedConstRefRef() const&& = 0;
+ virtual int RefQualifiedRef() & = 0;
+ virtual int RefQualifiedRefRef() && = 0;
+
+ virtual int RefQualifiedOverloaded() const& = 0;
+ virtual int RefQualifiedOverloaded() const&& = 0;
+ virtual int RefQualifiedOverloaded() & = 0;
+ virtual int RefQualifiedOverloaded() && = 0;
+
+#ifdef GTEST_OS_WINDOWS
STDMETHOD_(int, CTNullary)() = 0;
STDMETHOD_(bool, CTUnary)(int x) = 0;
STDMETHOD_(int, CTDecimal)
@@ -115,13 +134,10 @@ class FooInterface {
// significant in determining whether two virtual functions had the same
// 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)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4373)
class MockFoo : public FooInterface {
public:
- MockFoo() {}
+ MockFoo() = default;
// Makes sure that a mock function parameter can be named.
MOCK_METHOD(void, VoidReturning, (int n)); // NOLINT
@@ -159,7 +175,10 @@ class MockFoo : public FooInterface {
MOCK_METHOD(int, TypeWithTemplatedCopyCtor,
(const TemplatedCopyable<int>&)); // NOLINT
-#if GTEST_OS_WINDOWS
+ MOCK_METHOD(int (*)(bool), ReturnsFunctionPointer1, (int), ());
+ MOCK_METHOD(fn_ptr, ReturnsFunctionPointer2, (int), ());
+
+#ifdef GTEST_OS_WINDOWS
MOCK_METHOD(int, CTNullary, (), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(bool, CTUnary, (int), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(int, CTDecimal,
@@ -171,213 +190,340 @@ class MockFoo : public FooInterface {
(Calltype(STDMETHODCALLTYPE)));
#endif // GTEST_OS_WINDOWS
+ // Test reference qualified functions.
+ MOCK_METHOD(int, RefQualifiedConstRef, (), (const, ref(&), override));
+ MOCK_METHOD(int, RefQualifiedConstRefRef, (), (const, ref(&&), override));
+ MOCK_METHOD(int, RefQualifiedRef, (), (ref(&), override));
+ MOCK_METHOD(int, RefQualifiedRefRef, (), (ref(&&), override));
+
+ MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&), override));
+ MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&&), override));
+ MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&), override));
+ MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&&), override));
+
private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
+ MockFoo(const MockFoo&) = delete;
+ MockFoo& operator=(const MockFoo&) = delete;
};
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-class MockMethodFunctionMockerTest : public testing::Test {
+class LegacyMockFoo : public FooInterface {
+ public:
+ LegacyMockFoo() = default;
+
+ // Makes sure that a mock function parameter can be named.
+ MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT
+
+ MOCK_METHOD0(Nullary, int()); // NOLINT
+
+ // Makes sure that a mock function parameter can be unnamed.
+ MOCK_METHOD1(Unary, bool(int)); // NOLINT
+ MOCK_METHOD2(Binary, long(short, int)); // NOLINT
+ MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT
+ double, unsigned, char*, const std::string& str));
+
+ MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT
+ MOCK_METHOD1(TakesConstReference, std::string(const int&));
+ MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT
+
+ // Tests that the function return type can contain unprotected comma.
+ MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>());
+ MOCK_CONST_METHOD1(ReturnTypeWithComma,
+ std::map<int, std::string>(int)); // NOLINT
+
+ MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT
+ MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT
+
+ MOCK_METHOD1(OverloadedOnArgumentType, int(int)); // NOLINT
+ MOCK_METHOD1(OverloadedOnArgumentType, char(char)); // NOLINT
+
+ MOCK_METHOD0(OverloadedOnConstness, int()); // NOLINT
+ MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT
+
+ MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT
+ MOCK_METHOD1(TypeWithComma,
+ int(const std::map<int, std::string>&)); // NOLINT
+ MOCK_METHOD1(TypeWithTemplatedCopyCtor,
+ int(const TemplatedCopyable<int>&)); // NOLINT
+
+ MOCK_METHOD1(ReturnsFunctionPointer1, int (*(int))(bool));
+ MOCK_METHOD1(ReturnsFunctionPointer2, fn_ptr(int));
+
+#ifdef GTEST_OS_WINDOWS
+ MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
+ MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); // NOLINT
+ MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,
+ int(bool b, char c, short d, int e, // NOLINT
+ long f, float g, double h, // NOLINT
+ unsigned i, char* j, const std::string& k));
+ MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst,
+ char(int)); // NOLINT
+
+ // Tests that the function return type can contain unprotected comma.
+ MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,
+ std::map<int, std::string>());
+#endif // GTEST_OS_WINDOWS
+
+ // We can't mock these with the old macros, but we need to define them to make
+ // it concrete.
+ int RefQualifiedConstRef() const& override { return 0; }
+ int RefQualifiedConstRefRef() const&& override { return 0; }
+ int RefQualifiedRef() & override { return 0; }
+ int RefQualifiedRefRef() && override { return 0; }
+ int RefQualifiedOverloaded() const& override { return 0; }
+ int RefQualifiedOverloaded() const&& override { return 0; }
+ int RefQualifiedOverloaded() & override { return 0; }
+ int RefQualifiedOverloaded() && override { return 0; }
+
+ private:
+ LegacyMockFoo(const LegacyMockFoo&) = delete;
+ LegacyMockFoo& operator=(const LegacyMockFoo&) = delete;
+};
+
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4373
+
+template <class T>
+class FunctionMockerTest : public testing::Test {
protected:
- MockMethodFunctionMockerTest() : foo_(&mock_foo_) {}
+ FunctionMockerTest() : foo_(&mock_foo_) {}
FooInterface* const foo_;
- MockFoo mock_foo_;
+ T mock_foo_;
};
+using FunctionMockerTestTypes = ::testing::Types<MockFoo, LegacyMockFoo>;
+TYPED_TEST_SUITE(FunctionMockerTest, FunctionMockerTestTypes);
// Tests mocking a void-returning function.
-TEST_F(MockMethodFunctionMockerTest, MocksVoidFunction) {
- EXPECT_CALL(mock_foo_, VoidReturning(Lt(100)));
- foo_->VoidReturning(0);
+TYPED_TEST(FunctionMockerTest, MocksVoidFunction) {
+ EXPECT_CALL(this->mock_foo_, VoidReturning(Lt(100)));
+ this->foo_->VoidReturning(0);
}
// Tests mocking a nullary function.
-TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunction) {
- EXPECT_CALL(mock_foo_, Nullary())
+TYPED_TEST(FunctionMockerTest, MocksNullaryFunction) {
+ EXPECT_CALL(this->mock_foo_, Nullary())
.WillOnce(DoDefault())
.WillOnce(Return(1));
- EXPECT_EQ(0, foo_->Nullary());
- EXPECT_EQ(1, foo_->Nullary());
+ EXPECT_EQ(0, this->foo_->Nullary());
+ EXPECT_EQ(1, this->foo_->Nullary());
}
// Tests mocking a unary function.
-TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunction) {
- EXPECT_CALL(mock_foo_, Unary(Eq(2)))
- .Times(2)
- .WillOnce(Return(true));
+TYPED_TEST(FunctionMockerTest, MocksUnaryFunction) {
+ EXPECT_CALL(this->mock_foo_, Unary(Eq(2))).Times(2).WillOnce(Return(true));
- EXPECT_TRUE(foo_->Unary(2));
- EXPECT_FALSE(foo_->Unary(2));
+ EXPECT_TRUE(this->foo_->Unary(2));
+ EXPECT_FALSE(this->foo_->Unary(2));
}
// Tests mocking a binary function.
-TEST_F(MockMethodFunctionMockerTest, MocksBinaryFunction) {
- EXPECT_CALL(mock_foo_, Binary(2, _))
- .WillOnce(Return(3));
+TYPED_TEST(FunctionMockerTest, MocksBinaryFunction) {
+ EXPECT_CALL(this->mock_foo_, Binary(2, _)).WillOnce(Return(3));
- EXPECT_EQ(3, foo_->Binary(2, 1));
+ EXPECT_EQ(3, this->foo_->Binary(2, 1));
}
// Tests mocking a decimal function.
-TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunction) {
- EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(),
- Lt(100), 5U, NULL, "hi"))
+TYPED_TEST(FunctionMockerTest, MocksDecimalFunction) {
+ EXPECT_CALL(this->mock_foo_,
+ Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(5));
- EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
+ EXPECT_EQ(5, this->foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
}
// Tests mocking a function that takes a non-const reference.
-TEST_F(MockMethodFunctionMockerTest,
- MocksFunctionWithNonConstReferenceArgument) {
+TYPED_TEST(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) {
int a = 0;
- EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a)))
+ EXPECT_CALL(this->mock_foo_, TakesNonConstReference(Ref(a)))
.WillOnce(Return(true));
- EXPECT_TRUE(foo_->TakesNonConstReference(a));
+ EXPECT_TRUE(this->foo_->TakesNonConstReference(a));
}
// Tests mocking a function that takes a const reference.
-TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
+TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
int a = 0;
- EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a)))
+ EXPECT_CALL(this->mock_foo_, TakesConstReference(Ref(a)))
.WillOnce(Return("Hello"));
- EXPECT_EQ("Hello", foo_->TakesConstReference(a));
+ EXPECT_EQ("Hello", this->foo_->TakesConstReference(a));
}
// Tests mocking a function that takes a const variable.
-TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstArgument) {
- EXPECT_CALL(mock_foo_, TakesConst(Lt(10)))
- .WillOnce(DoDefault());
+TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstArgument) {
+ EXPECT_CALL(this->mock_foo_, TakesConst(Lt(10))).WillOnce(DoDefault());
- EXPECT_FALSE(foo_->TakesConst(5));
+ EXPECT_FALSE(this->foo_->TakesConst(5));
}
// Tests mocking functions overloaded on the number of arguments.
-TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber())
+TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
+ EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber())
.WillOnce(Return(1));
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_))
+ EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber(_))
.WillOnce(Return(2));
- EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1));
- EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber());
+ EXPECT_EQ(2, this->foo_->OverloadedOnArgumentNumber(1));
+ EXPECT_EQ(1, this->foo_->OverloadedOnArgumentNumber());
}
// Tests mocking functions overloaded on the types of argument.
-TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An<int>()))
+TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
+ EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(An<int>()))
.WillOnce(Return(1));
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
+ EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
.WillOnce(Return('b'));
- EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0));
- EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a'));
+ EXPECT_EQ(1, this->foo_->OverloadedOnArgumentType(0));
+ EXPECT_EQ('b', this->foo_->OverloadedOnArgumentType('a'));
}
// Tests mocking functions overloaded on the const-ness of this object.
-TEST_F(MockMethodFunctionMockerTest,
- MocksFunctionsOverloadedOnConstnessOfThis) {
- EXPECT_CALL(mock_foo_, OverloadedOnConstness());
- EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness())
+TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {
+ EXPECT_CALL(this->mock_foo_, OverloadedOnConstness());
+ EXPECT_CALL(Const(this->mock_foo_), OverloadedOnConstness())
.WillOnce(Return('a'));
- EXPECT_EQ(0, foo_->OverloadedOnConstness());
- EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness());
+ EXPECT_EQ(0, this->foo_->OverloadedOnConstness());
+ EXPECT_EQ('a', Const(*this->foo_).OverloadedOnConstness());
}
-TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithComma) {
+TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithComma) {
const std::map<int, std::string> a_map;
- EXPECT_CALL(mock_foo_, ReturnTypeWithComma())
- .WillOnce(Return(a_map));
- EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
- .WillOnce(Return(a_map));
+ EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma()).WillOnce(Return(a_map));
+ EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma(42)).WillOnce(Return(a_map));
- EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma());
- EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42));
+ EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma());
+ EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma(42));
}
-TEST_F(MockMethodFunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
- EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true));
- EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
+TYPED_TEST(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
+ EXPECT_CALL(this->mock_foo_, TypeWithTemplatedCopyCtor(_))
+ .WillOnce(Return(true));
+ EXPECT_TRUE(this->foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Tests mocking a nullary function with calltype.
-TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunctionWithCallType) {
- EXPECT_CALL(mock_foo_, CTNullary())
+TYPED_TEST(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
+ EXPECT_CALL(this->mock_foo_, CTNullary())
.WillOnce(Return(-1))
.WillOnce(Return(0));
- EXPECT_EQ(-1, foo_->CTNullary());
- EXPECT_EQ(0, foo_->CTNullary());
+ EXPECT_EQ(-1, this->foo_->CTNullary());
+ EXPECT_EQ(0, this->foo_->CTNullary());
}
// Tests mocking a unary function with calltype.
-TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunctionWithCallType) {
- EXPECT_CALL(mock_foo_, CTUnary(Eq(2)))
+TYPED_TEST(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
+ EXPECT_CALL(this->mock_foo_, CTUnary(Eq(2)))
.Times(2)
.WillOnce(Return(true))
.WillOnce(Return(false));
- EXPECT_TRUE(foo_->CTUnary(2));
- EXPECT_FALSE(foo_->CTUnary(2));
+ EXPECT_TRUE(this->foo_->CTUnary(2));
+ EXPECT_FALSE(this->foo_->CTUnary(2));
}
// Tests mocking a decimal function with calltype.
-TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunctionWithCallType) {
- EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
- Lt(100), 5U, NULL, "hi"))
+TYPED_TEST(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
+ EXPECT_CALL(this->mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
+ Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(10));
- EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
+ EXPECT_EQ(10, this->foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
}
// Tests mocking functions overloaded on the const-ness of this object.
-TEST_F(MockMethodFunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
- EXPECT_CALL(Const(mock_foo_), CTConst(_))
- .WillOnce(Return('a'));
+TYPED_TEST(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
+ EXPECT_CALL(Const(this->mock_foo_), CTConst(_)).WillOnce(Return('a'));
- EXPECT_EQ('a', Const(*foo_).CTConst(0));
+ EXPECT_EQ('a', Const(*this->foo_).CTConst(0));
}
-TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
+TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
const std::map<int, std::string> a_map;
- EXPECT_CALL(mock_foo_, CTReturnTypeWithComma())
- .WillOnce(Return(a_map));
+ EXPECT_CALL(this->mock_foo_, CTReturnTypeWithComma()).WillOnce(Return(a_map));
- EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma());
+ EXPECT_EQ(a_map, this->mock_foo_.CTReturnTypeWithComma());
}
#endif // GTEST_OS_WINDOWS
+TEST(FunctionMockerTest, RefQualified) {
+ MockFoo mock_foo;
+
+ EXPECT_CALL(mock_foo, RefQualifiedConstRef).WillOnce(Return(1));
+ EXPECT_CALL(std::move(mock_foo), // NOLINT
+ RefQualifiedConstRefRef)
+ .WillOnce(Return(2));
+ EXPECT_CALL(mock_foo, RefQualifiedRef).WillOnce(Return(3));
+ EXPECT_CALL(std::move(mock_foo), // NOLINT
+ RefQualifiedRefRef)
+ .WillOnce(Return(4));
+
+ EXPECT_CALL(static_cast<const MockFoo&>(mock_foo), RefQualifiedOverloaded())
+ .WillOnce(Return(5));
+ EXPECT_CALL(static_cast<const MockFoo&&>(mock_foo), RefQualifiedOverloaded())
+ .WillOnce(Return(6));
+ EXPECT_CALL(static_cast<MockFoo&>(mock_foo), RefQualifiedOverloaded())
+ .WillOnce(Return(7));
+ EXPECT_CALL(static_cast<MockFoo&&>(mock_foo), RefQualifiedOverloaded())
+ .WillOnce(Return(8));
+
+ EXPECT_EQ(mock_foo.RefQualifiedConstRef(), 1);
+ EXPECT_EQ(std::move(mock_foo).RefQualifiedConstRefRef(), 2); // NOLINT
+ EXPECT_EQ(mock_foo.RefQualifiedRef(), 3);
+ EXPECT_EQ(std::move(mock_foo).RefQualifiedRefRef(), 4); // NOLINT
+
+ EXPECT_EQ(std::cref(mock_foo).get().RefQualifiedOverloaded(), 5);
+ EXPECT_EQ(std::move(std::cref(mock_foo).get()) // NOLINT
+ .RefQualifiedOverloaded(),
+ 6);
+ EXPECT_EQ(mock_foo.RefQualifiedOverloaded(), 7);
+ EXPECT_EQ(std::move(mock_foo).RefQualifiedOverloaded(), 8); // NOLINT
+}
+
class MockB {
public:
- MockB() {}
+ MockB() = default;
MOCK_METHOD(void, DoB, ());
private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
+ MockB(const MockB&) = delete;
+ MockB& operator=(const MockB&) = delete;
};
+class LegacyMockB {
+ public:
+ LegacyMockB() = default;
+
+ MOCK_METHOD0(DoB, void());
+
+ private:
+ LegacyMockB(const LegacyMockB&) = delete;
+ LegacyMockB& operator=(const LegacyMockB&) = delete;
+};
+
+template <typename T>
+class ExpectCallTest : public ::testing::Test {};
+using ExpectCallTestTypes = ::testing::Types<MockB, LegacyMockB>;
+TYPED_TEST_SUITE(ExpectCallTest, ExpectCallTestTypes);
+
// Tests that functions with no EXPECT_CALL() rules can be called any
// number of times.
-TEST(MockMethodExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
- {
- MockB b;
- }
+TYPED_TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
+ { TypeParam b; }
{
- MockB b;
+ TypeParam b;
b.DoB();
}
{
- MockB b;
+ TypeParam b;
b.DoB();
b.DoB();
}
@@ -388,7 +534,7 @@ TEST(MockMethodExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
template <typename T>
class StackInterface {
public:
- virtual ~StackInterface() {}
+ virtual ~StackInterface() = default;
// Template parameter appears in function parameter.
virtual void Push(const T& value) = 0;
@@ -401,7 +547,7 @@ class StackInterface {
template <typename T>
class MockStack : public StackInterface<T> {
public:
- MockStack() {}
+ MockStack() = default;
MOCK_METHOD(void, Push, (const T& elem), ());
MOCK_METHOD(void, Pop, (), (final));
@@ -413,12 +559,38 @@ 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>
+class LegacyMockStack : public StackInterface<T> {
+ public:
+ LegacyMockStack() = default;
+
+ MOCK_METHOD1_T(Push, void(const T& elem));
+ MOCK_METHOD0_T(Pop, void());
+ MOCK_CONST_METHOD0_T(GetSize, int()); // NOLINT
+ MOCK_CONST_METHOD0_T(GetTop, const T&());
+
+ // Tests that the function return type can contain unprotected comma.
+ MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());
+ MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int)); // NOLINT
+
+ private:
+ LegacyMockStack(const LegacyMockStack&) = delete;
+ LegacyMockStack& operator=(const LegacyMockStack&) = delete;
};
+template <typename T>
+class TemplateMockTest : public ::testing::Test {};
+using TemplateMockTestTypes =
+ ::testing::Types<MockStack<int>, LegacyMockStack<int>>;
+TYPED_TEST_SUITE(TemplateMockTest, TemplateMockTestTypes);
+
// Tests that template mock works.
-TEST(MockMethodTemplateMockTest, Works) {
- MockStack<int> mock;
+TYPED_TEST(TemplateMockTest, Works) {
+ TypeParam mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
@@ -426,10 +598,8 @@ TEST(MockMethodTemplateMockTest, 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);
@@ -439,20 +609,18 @@ TEST(MockMethodTemplateMockTest, Works) {
EXPECT_EQ(0, mock.GetSize());
}
-TEST(MockMethodTemplateMockTest, MethodWithCommaInReturnTypeWorks) {
- MockStack<int> mock;
+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));
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Tests mocking template interfaces with calltype.
template <typename T>
@@ -481,12 +649,37 @@ 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>
+class LegacyMockStackWithCallType : public StackInterfaceWithCallType<T> {
+ public:
+ LegacyMockStackWithCallType() {}
+
+ MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem));
+ MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void());
+ MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int());
+ MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());
+
+ private:
+ LegacyMockStackWithCallType(const LegacyMockStackWithCallType&) = delete;
+ LegacyMockStackWithCallType& operator=(const LegacyMockStackWithCallType&) =
+ delete;
+};
+
+template <typename T>
+class TemplateMockTestWithCallType : public ::testing::Test {};
+using TemplateMockTestWithCallTypeTypes =
+ ::testing::Types<MockStackWithCallType<int>,
+ LegacyMockStackWithCallType<int>>;
+TYPED_TEST_SUITE(TemplateMockTestWithCallType,
+ TemplateMockTestWithCallTypeTypes);
+
// Tests that template mock with calltype works.
-TEST(MockMethodTemplateMockTestWithCallType, Works) {
- MockStackWithCallType<int> mock;
+TYPED_TEST(TemplateMockTestWithCallType, Works) {
+ TypeParam mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
@@ -494,10 +687,8 @@ TEST(MockMethodTemplateMockTestWithCallType, 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);
@@ -513,18 +704,45 @@ TEST(MockMethodTemplateMockTestWithCallType, Works) {
MOCK_METHOD(int, Overloaded, (int), (const)); \
MOCK_METHOD(bool, Overloaded, (bool f, int n))
+#define LEGACY_MY_MOCK_METHODS1_ \
+ MOCK_METHOD0(Overloaded, void()); \
+ MOCK_CONST_METHOD1(Overloaded, int(int n)); \
+ MOCK_METHOD2(Overloaded, bool(bool f, int n))
+
class MockOverloadedOnArgNumber {
public:
- MockOverloadedOnArgNumber() {}
+ MockOverloadedOnArgNumber() = default;
MY_MOCK_METHODS1_;
private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
+ MockOverloadedOnArgNumber(const MockOverloadedOnArgNumber&) = delete;
+ MockOverloadedOnArgNumber& operator=(const MockOverloadedOnArgNumber&) =
+ delete;
+};
+
+class LegacyMockOverloadedOnArgNumber {
+ public:
+ LegacyMockOverloadedOnArgNumber() = default;
+
+ LEGACY_MY_MOCK_METHODS1_;
+
+ private:
+ LegacyMockOverloadedOnArgNumber(const LegacyMockOverloadedOnArgNumber&) =
+ delete;
+ LegacyMockOverloadedOnArgNumber& operator=(
+ const LegacyMockOverloadedOnArgNumber&) = delete;
};
-TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
- MockOverloadedOnArgNumber mock;
+template <typename T>
+class OverloadedMockMethodTest : public ::testing::Test {};
+using OverloadedMockMethodTestTypes =
+ ::testing::Types<MockOverloadedOnArgNumber,
+ LegacyMockOverloadedOnArgNumber>;
+TYPED_TEST_SUITE(OverloadedMockMethodTest, OverloadedMockMethodTestTypes);
+
+TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
+ TypeParam mock;
EXPECT_CALL(mock, Overloaded());
EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));
@@ -534,18 +752,20 @@ TEST(MockMethodOverloadedMockMethodTest, 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:
- MockOverloadedOnConstness() {}
+ MockOverloadedOnConstness() = default;
MY_MOCK_METHODS2_;
private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnConstness);
+ MockOverloadedOnConstness(const MockOverloadedOnConstness&) = delete;
+ MockOverloadedOnConstness& operator=(const MockOverloadedOnConstness&) =
+ delete;
};
TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) {
@@ -566,9 +786,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());
}
@@ -581,19 +799,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));
@@ -603,9 +819,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));
@@ -623,15 +837,72 @@ 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));
}
+namespace {
+
+template <typename Expected, typename F>
+static constexpr bool IsMockFunctionTemplateArgumentDeducedTo(
+ const internal::MockFunction<F>&) {
+ return std::is_same<F, Expected>::value;
+}
+
+} // namespace
+
+template <typename F>
+class MockMethodMockFunctionSignatureTest : public Test {};
+
+using MockMethodMockFunctionSignatureTypes =
+ Types<void(), int(), void(int), int(int), int(bool, int),
+ int(bool, char, int, int, int, int, int, char, int, bool)>;
+TYPED_TEST_SUITE(MockMethodMockFunctionSignatureTest,
+ MockMethodMockFunctionSignatureTypes);
+
+TYPED_TEST(MockMethodMockFunctionSignatureTest,
+ IsMockFunctionTemplateArgumentDeducedForRawSignature) {
+ using Argument = TypeParam;
+ MockFunction<Argument> foo;
+ EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
+}
+
+TYPED_TEST(MockMethodMockFunctionSignatureTest,
+ IsMockFunctionTemplateArgumentDeducedForStdFunction) {
+ using Argument = std::function<TypeParam>;
+ MockFunction<Argument> foo;
+ EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
+}
+
+TYPED_TEST(
+ MockMethodMockFunctionSignatureTest,
+ IsMockFunctionCallMethodSignatureTheSameForRawSignatureAndStdFunction) {
+ using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);
+ using ForStdFunction =
+ decltype(&MockFunction<std::function<TypeParam>>::Call);
+ EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
+}
+
+template <typename F>
+struct AlternateCallable {};
+
+TYPED_TEST(MockMethodMockFunctionSignatureTest,
+ IsMockFunctionTemplateArgumentDeducedForAlternateCallable) {
+ using Argument = AlternateCallable<TypeParam>;
+ MockFunction<Argument> foo;
+ EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
+}
+
+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, ());
@@ -649,12 +920,79 @@ struct MockMethodSizes4 {
MOCK_METHOD(void, func, (int, int, int, int));
};
+struct LegacyMockMethodSizes0 {
+ MOCK_METHOD0(func, void());
+};
+struct LegacyMockMethodSizes1 {
+ MOCK_METHOD1(func, void(int));
+};
+struct LegacyMockMethodSizes2 {
+ MOCK_METHOD2(func, void(int, int));
+};
+struct LegacyMockMethodSizes3 {
+ MOCK_METHOD3(func, void(int, int, int));
+};
+struct LegacyMockMethodSizes4 {
+ MOCK_METHOD4(func, void(int, int, int, int));
+};
+
TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4));
+
+ EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes1));
+ EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes2));
+ EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes3));
+ EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes4));
+
+ EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(MockMethodSizes0));
+}
+
+TEST(MockMethodMockFunctionTest, EnsureNoUnusedMemberFunction) {
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic error "-Wunused-member-function"
+#endif
+ // https://github.com/google/googletest/issues/4052
+ struct Foo {
+ MOCK_METHOD(void, foo, ());
+ };
+ EXPECT_CALL(Foo(), foo()).Times(0);
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+}
+
+void hasTwoParams(int, int);
+void MaybeThrows();
+void DoesntThrow() noexcept;
+struct MockMethodNoexceptSpecifier {
+ MOCK_METHOD(void, func1, (), (noexcept));
+ MOCK_METHOD(void, func2, (), (noexcept(true)));
+ MOCK_METHOD(void, func3, (), (noexcept(false)));
+ MOCK_METHOD(void, func4, (), (noexcept(noexcept(MaybeThrows()))));
+ MOCK_METHOD(void, func5, (), (noexcept(noexcept(DoesntThrow()))));
+ MOCK_METHOD(void, func6, (), (noexcept(noexcept(DoesntThrow())), const));
+ MOCK_METHOD(void, func7, (), (const, noexcept(noexcept(DoesntThrow()))));
+ // Put commas in the noexcept expression
+ MOCK_METHOD(void, func8, (), (noexcept(noexcept(hasTwoParams(1, 2))), const));
+};
+
+TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) {
+ EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func1()));
+ EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func2()));
+ EXPECT_FALSE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func3()));
+ EXPECT_FALSE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func4()));
+ EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func5()));
+ EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func6()));
+ EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func7()));
+ EXPECT_EQ(noexcept(std::declval<MockMethodNoexceptSpecifier>().func8()),
+ noexcept(hasTwoParams(1, 2)));
}
} // namespace gmock_function_mocker_test
} // namespace testing
+
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4503
diff --git a/googlemock/test/gmock-generated-actions_test.cc b/googlemock/test/gmock-generated-actions_test.cc
deleted file mode 100644
index 4c649a7ee96a..000000000000
--- a/googlemock/test/gmock-generated-actions_test.cc
+++ /dev/null
@@ -1,1064 +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 the built-in actions generated by a script.
-
-#include "gmock/gmock-generated-actions.h"
-
-#include <functional>
-#include <memory>
-#include <sstream>
-#include <string>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace testing {
-namespace gmock_generated_actions_test {
-
-using ::std::plus;
-using ::std::string;
-using testing::_;
-using testing::Action;
-using testing::ActionInterface;
-using testing::ByRef;
-using testing::DoAll;
-using testing::Invoke;
-using testing::Return;
-using testing::ReturnNew;
-using testing::SetArgPointee;
-using testing::StaticAssertTypeEq;
-using testing::Unused;
-
-// For suppressing compiler warnings on conversion possibly losing precision.
-inline short Short(short n) { return n; } // NOLINT
-inline char Char(char ch) { return ch; }
-
-// Sample functions and functors for testing various actions.
-int Nullary() { return 1; }
-
-bool g_done = false;
-
-bool ByConstRef(const std::string& s) { return s == "Hi"; }
-
-const double g_double = 0;
-bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
-
-struct UnaryFunctor {
- int operator()(bool x) { return x ? 1 : -1; }
-};
-
-const char* Binary(const char* input, short n) { return input + n; } // NOLINT
-
-int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
-
-struct SumOf5Functor {
- int operator()(int a, int b, int c, int d, int e) {
- return a + b + c + d + e;
- }
-};
-
-std::string Concat5(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5) {
- return std::string(s1) + s2 + s3 + s4 + s5;
-}
-
-int SumOf6(int a, int b, int c, int d, int e, int f) {
- return a + b + c + d + e + f;
-}
-
-struct SumOf6Functor {
- int operator()(int a, int b, int c, int d, int e, int f) {
- return a + b + c + d + e + f;
- }
-};
-
-std::string Concat6(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6;
-}
-
-std::string Concat7(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6,
- const char* s7) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
-}
-
-std::string Concat8(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6,
- const char* s7, const char* s8) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
-}
-
-std::string Concat9(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6,
- const char* s7, const char* s8, const char* s9) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
-}
-
-std::string Concat10(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6,
- const char* s7, const char* s8, const char* s9,
- const char* s10) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
-}
-
-// A helper that turns the type of a C-string literal from const
-// char[N] to const char*.
-inline const char* CharPtr(const char* s) { return s; }
-
-// Tests InvokeArgument<N>(...).
-
-// Tests using InvokeArgument with a nullary function.
-TEST(InvokeArgumentTest, Function0) {
- Action<int(int, int(*)())> a = InvokeArgument<1>(); // NOLINT
- EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary)));
-}
-
-// Tests using InvokeArgument with a unary function.
-TEST(InvokeArgumentTest, Functor1) {
- Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT
- EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor())));
-}
-
-// Tests using InvokeArgument with a 5-ary function.
-TEST(InvokeArgumentTest, Function5) {
- Action<int(int(*)(int, int, int, int, int))> a = // NOLINT
- InvokeArgument<0>(10000, 2000, 300, 40, 5);
- EXPECT_EQ(12345, a.Perform(std::make_tuple(&SumOf5)));
-}
-
-// Tests using InvokeArgument with a 5-ary functor.
-TEST(InvokeArgumentTest, Functor5) {
- Action<int(SumOf5Functor)> a = // NOLINT
- InvokeArgument<0>(10000, 2000, 300, 40, 5);
- EXPECT_EQ(12345, a.Perform(std::make_tuple(SumOf5Functor())));
-}
-
-// Tests using InvokeArgument with a 6-ary function.
-TEST(InvokeArgumentTest, Function6) {
- Action<int(int(*)(int, int, int, int, int, int))> a = // NOLINT
- InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
- EXPECT_EQ(123456, a.Perform(std::make_tuple(&SumOf6)));
-}
-
-// Tests using InvokeArgument with a 6-ary functor.
-TEST(InvokeArgumentTest, Functor6) {
- Action<int(SumOf6Functor)> a = // NOLINT
- InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
- EXPECT_EQ(123456, a.Perform(std::make_tuple(SumOf6Functor())));
-}
-
-// Tests using InvokeArgument with a 7-ary function.
-TEST(InvokeArgumentTest, Function7) {
- Action<std::string(std::string(*)(const char*, const char*, const char*,
- const char*, const char*, const char*,
- const char*))>
- a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7");
- EXPECT_EQ("1234567", a.Perform(std::make_tuple(&Concat7)));
-}
-
-// Tests using InvokeArgument with a 8-ary function.
-TEST(InvokeArgumentTest, Function8) {
- Action<std::string(std::string(*)(const char*, const char*, const char*,
- const char*, const char*, const char*,
- const char*, const char*))>
- a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8");
- EXPECT_EQ("12345678", a.Perform(std::make_tuple(&Concat8)));
-}
-
-// Tests using InvokeArgument with a 9-ary function.
-TEST(InvokeArgumentTest, Function9) {
- Action<std::string(std::string(*)(const char*, const char*, const char*,
- const char*, const char*, const char*,
- const char*, const char*, const char*))>
- a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9");
- EXPECT_EQ("123456789", a.Perform(std::make_tuple(&Concat9)));
-}
-
-// Tests using InvokeArgument with a 10-ary function.
-TEST(InvokeArgumentTest, Function10) {
- Action<std::string(std::string(*)(
- const char*, const char*, const char*, const char*, const char*,
- const char*, const char*, const char*, const char*, const char*))>
- a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
- EXPECT_EQ("1234567890", a.Perform(std::make_tuple(&Concat10)));
-}
-
-// Tests using InvokeArgument with a function that takes a pointer argument.
-TEST(InvokeArgumentTest, ByPointerFunction) {
- Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT
- InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1));
- EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary)));
-}
-
-// Tests using InvokeArgument with a function that takes a const char*
-// by passing it a C-string literal.
-TEST(InvokeArgumentTest, FunctionWithCStringLiteral) {
- Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT
- InvokeArgument<0>("Hi", Short(1));
- EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary)));
-}
-
-// Tests using InvokeArgument with a function that takes a const reference.
-TEST(InvokeArgumentTest, ByConstReferenceFunction) {
- Action<bool(bool (*function)(const std::string& s))> a = // NOLINT
- InvokeArgument<0>(std::string("Hi"));
- // When action 'a' is constructed, it makes a copy of the temporary
- // string object passed to it, so it's OK to use 'a' later, when the
- // temporary object has already died.
- EXPECT_TRUE(a.Perform(std::make_tuple(&ByConstRef)));
-}
-
-// Tests using InvokeArgument with ByRef() and a function that takes a
-// const reference.
-TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) {
- Action<bool(bool(*)(const double& x))> a = // NOLINT
- InvokeArgument<0>(ByRef(g_double));
- // The above line calls ByRef() on a const value.
- EXPECT_TRUE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
-
- double x = 0;
- a = InvokeArgument<0>(ByRef(x)); // This calls ByRef() on a non-const.
- EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
-}
-
-// Tests DoAll(a1, a2).
-TEST(DoAllTest, TwoActions) {
- int n = 0;
- Action<int(int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT
- Return(2));
- EXPECT_EQ(2, a.Perform(std::make_tuple(&n)));
- EXPECT_EQ(1, n);
-}
-
-// Tests DoAll(a1, a2, a3).
-TEST(DoAllTest, ThreeActions) {
- int m = 0, n = 0;
- Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT
- SetArgPointee<1>(2),
- Return(3));
- EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
-}
-
-// Tests DoAll(a1, a2, a3, a4).
-TEST(DoAllTest, FourActions) {
- int m = 0, n = 0;
- char ch = '\0';
- Action<int(int*, int*, char*)> a = // NOLINT
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- Return(3));
- EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n, &ch)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', ch);
-}
-
-// Tests DoAll(a1, a2, a3, a4, a5).
-TEST(DoAllTest, FiveActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0';
- Action<int(int*, int*, char*, char*)> action = // NOLINT
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- Return(3));
- EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
-}
-
-// Tests DoAll(a1, a2, ..., a6).
-TEST(DoAllTest, SixActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0', c = '\0';
- Action<int(int*, int*, char*, char*, char*)> action = // NOLINT
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- SetArgPointee<4>('c'),
- Return(3));
- EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
- EXPECT_EQ('c', c);
-}
-
-// Tests DoAll(a1, a2, ..., a7).
-TEST(DoAllTest, SevenActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0', c = '\0', d = '\0';
- Action<int(int*, int*, char*, char*, char*, char*)> action = // NOLINT
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- SetArgPointee<4>('c'),
- SetArgPointee<5>('d'),
- Return(3));
- EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
- EXPECT_EQ('c', c);
- EXPECT_EQ('d', d);
-}
-
-// Tests DoAll(a1, a2, ..., a8).
-TEST(DoAllTest, EightActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0';
- Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
- char*)> action =
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- SetArgPointee<4>('c'),
- SetArgPointee<5>('d'),
- SetArgPointee<6>('e'),
- Return(3));
- EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
- EXPECT_EQ('c', c);
- EXPECT_EQ('d', d);
- EXPECT_EQ('e', e);
-}
-
-// Tests DoAll(a1, a2, ..., a9).
-TEST(DoAllTest, NineActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0', f = '\0';
- Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
- char*, char*)> action =
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- SetArgPointee<4>('c'),
- SetArgPointee<5>('d'),
- SetArgPointee<6>('e'),
- SetArgPointee<7>('f'),
- Return(3));
- EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
- EXPECT_EQ('c', c);
- EXPECT_EQ('d', d);
- EXPECT_EQ('e', e);
- EXPECT_EQ('f', f);
-}
-
-// Tests DoAll(a1, a2, ..., a10).
-TEST(DoAllTest, TenActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0', c = '\0', d = '\0';
- char e = '\0', f = '\0', g = '\0';
- Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
- char*, char*, char*)> action =
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- SetArgPointee<4>('c'),
- SetArgPointee<5>('d'),
- SetArgPointee<6>('e'),
- SetArgPointee<7>('f'),
- SetArgPointee<8>('g'),
- Return(3));
- EXPECT_EQ(
- 3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
- EXPECT_EQ('c', c);
- EXPECT_EQ('d', d);
- EXPECT_EQ('e', e);
- EXPECT_EQ('f', f);
- EXPECT_EQ('g', g);
-}
-
-// The ACTION*() macros trigger warning C4100 (unreferenced formal
-// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
-// the macro definition, as the warnings are generated when the macro
-// is expanded and macro expansion cannot contain #pragma. Therefore
-// we suppress them here.
-// Also suppress C4503 decorated name length exceeded, name was truncated
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-# pragma warning(disable:4503)
-#endif
-// Tests the ACTION*() macro family.
-
-// Tests that ACTION() can define an action that doesn't reference the
-// mock function arguments.
-ACTION(Return5) { return 5; }
-
-TEST(ActionMacroTest, WorksWhenNotReferencingArguments) {
- Action<double()> a1 = Return5();
- EXPECT_DOUBLE_EQ(5, a1.Perform(std::make_tuple()));
-
- Action<int(double, bool)> a2 = Return5();
- EXPECT_EQ(5, a2.Perform(std::make_tuple(1, true)));
-}
-
-// Tests that ACTION() can define an action that returns void.
-ACTION(IncrementArg1) { (*arg1)++; }
-
-TEST(ActionMacroTest, WorksWhenReturningVoid) {
- Action<void(int, int*)> a1 = IncrementArg1();
- int n = 0;
- a1.Perform(std::make_tuple(5, &n));
- EXPECT_EQ(1, n);
-}
-
-// Tests that the body of ACTION() can reference the type of the
-// argument.
-ACTION(IncrementArg2) {
- StaticAssertTypeEq<int*, arg2_type>();
- arg2_type temp = arg2;
- (*temp)++;
-}
-
-TEST(ActionMacroTest, CanReferenceArgumentType) {
- Action<void(int, bool, int*)> a1 = IncrementArg2();
- int n = 0;
- a1.Perform(std::make_tuple(5, false, &n));
- EXPECT_EQ(1, n);
-}
-
-// Tests that the body of ACTION() can reference the argument tuple
-// via args_type and args.
-ACTION(Sum2) {
- StaticAssertTypeEq<std::tuple<int, char, int*>, args_type>();
- args_type args_copy = args;
- return std::get<0>(args_copy) + std::get<1>(args_copy);
-}
-
-TEST(ActionMacroTest, CanReferenceArgumentTuple) {
- Action<int(int, char, int*)> a1 = Sum2();
- int dummy = 0;
- EXPECT_EQ(11, a1.Perform(std::make_tuple(5, Char(6), &dummy)));
-}
-
-// Tests that the body of ACTION() can reference the mock function
-// type.
-int Dummy(bool flag) { return flag? 1 : 0; }
-
-ACTION(InvokeDummy) {
- StaticAssertTypeEq<int(bool), function_type>();
- function_type* fp = &Dummy;
- return (*fp)(true);
-}
-
-TEST(ActionMacroTest, CanReferenceMockFunctionType) {
- Action<int(bool)> a1 = InvokeDummy();
- EXPECT_EQ(1, a1.Perform(std::make_tuple(true)));
- EXPECT_EQ(1, a1.Perform(std::make_tuple(false)));
-}
-
-// Tests that the body of ACTION() can reference the mock function's
-// return type.
-ACTION(InvokeDummy2) {
- StaticAssertTypeEq<int, return_type>();
- return_type result = Dummy(true);
- return result;
-}
-
-TEST(ActionMacroTest, CanReferenceMockFunctionReturnType) {
- Action<int(bool)> a1 = InvokeDummy2();
- EXPECT_EQ(1, a1.Perform(std::make_tuple(true)));
- EXPECT_EQ(1, a1.Perform(std::make_tuple(false)));
-}
-
-// Tests that ACTION() works for arguments passed by const reference.
-ACTION(ReturnAddrOfConstBoolReferenceArg) {
- StaticAssertTypeEq<const bool&, arg1_type>();
- return &arg1;
-}
-
-TEST(ActionMacroTest, WorksForConstReferenceArg) {
- Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg();
- const bool b = false;
- EXPECT_EQ(&b, a.Perform(std::tuple<int, const bool&>(0, b)));
-}
-
-// Tests that ACTION() works for arguments passed by non-const reference.
-ACTION(ReturnAddrOfIntReferenceArg) {
- StaticAssertTypeEq<int&, arg0_type>();
- return &arg0;
-}
-
-TEST(ActionMacroTest, WorksForNonConstReferenceArg) {
- Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg();
- int n = 0;
- EXPECT_EQ(&n, a.Perform(std::tuple<int&, bool, int>(n, true, 1)));
-}
-
-// Tests that ACTION() can be used in a namespace.
-namespace action_test {
-ACTION(Sum) { return arg0 + arg1; }
-} // namespace action_test
-
-TEST(ActionMacroTest, WorksInNamespace) {
- Action<int(int, int)> a1 = action_test::Sum();
- EXPECT_EQ(3, a1.Perform(std::make_tuple(1, 2)));
-}
-
-// Tests that the same ACTION definition works for mock functions with
-// different argument numbers.
-ACTION(PlusTwo) { return arg0 + 2; }
-
-TEST(ActionMacroTest, WorksForDifferentArgumentNumbers) {
- Action<int(int)> a1 = PlusTwo();
- EXPECT_EQ(4, a1.Perform(std::make_tuple(2)));
-
- Action<double(float, void*)> a2 = PlusTwo();
- int dummy;
- EXPECT_DOUBLE_EQ(6, a2.Perform(std::make_tuple(4.0f, &dummy)));
-}
-
-// Tests that ACTION_P can define a parameterized action.
-ACTION_P(Plus, n) { return arg0 + n; }
-
-TEST(ActionPMacroTest, DefinesParameterizedAction) {
- Action<int(int m, bool t)> a1 = Plus(9);
- EXPECT_EQ(10, a1.Perform(std::make_tuple(1, true)));
-}
-
-// Tests that the body of ACTION_P can reference the argument types
-// and the parameter type.
-ACTION_P(TypedPlus, n) {
- arg0_type t1 = arg0;
- n_type t2 = n;
- return t1 + t2;
-}
-
-TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) {
- Action<int(char m, bool t)> a1 = TypedPlus(9);
- EXPECT_EQ(10, a1.Perform(std::make_tuple(Char(1), true)));
-}
-
-// Tests that a parameterized action can be used in any mock function
-// whose type is compatible.
-TEST(ActionPMacroTest, WorksInCompatibleMockFunction) {
- Action<std::string(const std::string& s)> a1 = Plus("tail");
- const std::string re = "re";
- std::tuple<const std::string> dummy = std::make_tuple(re);
- EXPECT_EQ("retail", a1.Perform(dummy));
-}
-
-// Tests that we can use ACTION*() to define actions overloaded on the
-// number of parameters.
-
-ACTION(OverloadedAction) { return arg0 ? arg1 : "hello"; }
-
-ACTION_P(OverloadedAction, default_value) {
- return arg0 ? arg1 : default_value;
-}
-
-ACTION_P2(OverloadedAction, true_value, false_value) {
- return arg0 ? true_value : false_value;
-}
-
-TEST(ActionMacroTest, CanDefineOverloadedActions) {
- typedef Action<const char*(bool, const char*)> MyAction;
-
- const MyAction a1 = OverloadedAction();
- EXPECT_STREQ("hello", a1.Perform(std::make_tuple(false, CharPtr("world"))));
- EXPECT_STREQ("world", a1.Perform(std::make_tuple(true, CharPtr("world"))));
-
- const MyAction a2 = OverloadedAction("hi");
- EXPECT_STREQ("hi", a2.Perform(std::make_tuple(false, CharPtr("world"))));
- EXPECT_STREQ("world", a2.Perform(std::make_tuple(true, CharPtr("world"))));
-
- const MyAction a3 = OverloadedAction("hi", "you");
- EXPECT_STREQ("hi", a3.Perform(std::make_tuple(true, CharPtr("world"))));
- EXPECT_STREQ("you", a3.Perform(std::make_tuple(false, CharPtr("world"))));
-}
-
-// Tests ACTION_Pn where n >= 3.
-
-ACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; }
-
-TEST(ActionPnMacroTest, WorksFor3Parameters) {
- Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4);
- EXPECT_DOUBLE_EQ(3123.4, a1.Perform(std::make_tuple(3000, true)));
-
- Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">");
- const std::string re = "re";
- std::tuple<const std::string> dummy = std::make_tuple(re);
- EXPECT_EQ("retail->", a2.Perform(dummy));
-}
-
-ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; }
-
-TEST(ActionPnMacroTest, WorksFor4Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; }
-
-TEST(ActionPnMacroTest, WorksFor5Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) {
- return arg0 + p0 + p1 + p2 + p3 + p4 + p5;
-}
-
-TEST(ActionPnMacroTest, WorksFor6Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) {
- return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6;
-}
-
-TEST(ActionPnMacroTest, WorksFor7Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) {
- return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7;
-}
-
-TEST(ActionPnMacroTest, WorksFor8Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
- a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) {
- return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8;
-}
-
-TEST(ActionPnMacroTest, WorksFor9Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9,
- a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) {
- arg0_type t0 = arg0;
- last_param_type t9 = last_param;
- return t0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + t9;
-}
-
-TEST(ActionPnMacroTest, WorksFor10Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
- a1.Perform(std::make_tuple(10)));
-}
-
-// Tests that the action body can promote the parameter types.
-
-ACTION_P2(PadArgument, 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 prefix_str + arg0 + suffix_char;
-}
-
-TEST(ActionPnMacroTest, SimpleTypePromotion) {
- Action<std::string(const char*)> no_promo =
- PadArgument(std::string("foo"), 'r');
- Action<std::string(const char*)> promo =
- PadArgument("foo", static_cast<int>('r'));
- EXPECT_EQ("foobar", no_promo.Perform(std::make_tuple(CharPtr("ba"))));
- EXPECT_EQ("foobar", promo.Perform(std::make_tuple(CharPtr("ba"))));
-}
-
-// Tests that we can partially restrict parameter types using a
-// straight-forward pattern.
-
-// Defines a generic action that doesn't restrict the types of its
-// parameters.
-ACTION_P3(ConcatImpl, a, b, c) {
- std::stringstream ss;
- ss << a << b << c;
- return ss.str();
-}
-
-// Next, we try to restrict that either the first parameter is a
-// string, or the second parameter is an int.
-
-// Defines a partially specialized wrapper that restricts the first
-// parameter to std::string.
-template <typename T1, typename T2>
-// ConcatImplActionP3 is the class template ACTION_P3 uses to
-// implement ConcatImpl. We shouldn't change the name as this
-// pattern requires the user to use it directly.
-ConcatImplActionP3<std::string, T1, T2>
-Concat(const std::string& a, T1 b, T2 c) {
- GTEST_INTENTIONAL_CONST_COND_PUSH_()
- if (true) {
- GTEST_INTENTIONAL_CONST_COND_POP_()
- // This branch verifies that ConcatImpl() can be invoked without
- // explicit template arguments.
- return ConcatImpl(a, b, c);
- } else {
- // This branch verifies that ConcatImpl() can also be invoked with
- // explicit template arguments. It doesn't really need to be
- // executed as this is a compile-time verification.
- return ConcatImpl<std::string, T1, T2>(a, b, c);
- }
-}
-
-// Defines another partially specialized wrapper that restricts the
-// second parameter to int.
-template <typename T1, typename T2>
-ConcatImplActionP3<T1, int, T2>
-Concat(T1 a, int b, T2 c) {
- return ConcatImpl(a, b, c);
-}
-
-TEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) {
- Action<const std::string()> a1 = Concat("Hello", "1", 2);
- EXPECT_EQ("Hello12", a1.Perform(std::make_tuple()));
-
- a1 = Concat(1, 2, 3);
- EXPECT_EQ("123", a1.Perform(std::make_tuple()));
-}
-
-// Verifies the type of an ACTION*.
-
-ACTION(DoFoo) {}
-ACTION_P(DoFoo, p) {}
-ACTION_P2(DoFoo, p0, p1) {}
-
-TEST(ActionPnMacroTest, TypesAreCorrect) {
- // DoFoo() must be assignable to a DoFooAction variable.
- DoFooAction a0 = DoFoo();
-
- // DoFoo(1) must be assignable to a DoFooActionP variable.
- DoFooActionP<int> a1 = DoFoo(1);
-
- // DoFoo(p1, ..., pk) must be assignable to a DoFooActionPk
- // variable, and so on.
- DoFooActionP2<int, char> a2 = DoFoo(1, '2');
- PlusActionP3<int, int, char> a3 = Plus(1, 2, '3');
- PlusActionP4<int, int, int, char> a4 = Plus(1, 2, 3, '4');
- PlusActionP5<int, int, int, int, char> a5 = Plus(1, 2, 3, 4, '5');
- PlusActionP6<int, int, int, int, int, char> a6 = Plus(1, 2, 3, 4, 5, '6');
- PlusActionP7<int, int, int, int, int, int, char> a7 =
- Plus(1, 2, 3, 4, 5, 6, '7');
- PlusActionP8<int, int, int, int, int, int, int, char> a8 =
- Plus(1, 2, 3, 4, 5, 6, 7, '8');
- PlusActionP9<int, int, int, int, int, int, int, int, char> a9 =
- Plus(1, 2, 3, 4, 5, 6, 7, 8, '9');
- PlusActionP10<int, int, int, int, int, int, int, int, int, char> a10 =
- Plus(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 an ACTION_P*() action can be explicitly instantiated
-// with reference-typed parameters.
-
-ACTION_P(Plus1, x) { return x; }
-ACTION_P2(Plus2, x, y) { return x + y; }
-ACTION_P3(Plus3, x, y, z) { return x + y + z; }
-ACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
- return a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9;
-}
-
-TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) {
- int x = 1, y = 2, z = 3;
- const std::tuple<> empty = std::make_tuple();
-
- Action<int()> a = Plus1<int&>(x);
- EXPECT_EQ(1, a.Perform(empty));
-
- a = Plus2<const int&, int&>(x, y);
- EXPECT_EQ(3, a.Perform(empty));
-
- a = Plus3<int&, const int&, int&>(x, y, z);
- EXPECT_EQ(6, a.Perform(empty));
-
- int n[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
- a = Plus10<const int&, int&, const int&, int&, const int&, int&, const int&,
- int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7],
- n[8], n[9]);
- EXPECT_EQ(55, a.Perform(empty));
-}
-
-class NullaryConstructorClass {
- public:
- NullaryConstructorClass() : value_(123) {}
- int value_;
-};
-
-// Tests using ReturnNew() with a nullary constructor.
-TEST(ReturnNewTest, NoArgs) {
- Action<NullaryConstructorClass*()> a = ReturnNew<NullaryConstructorClass>();
- NullaryConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(123, c->value_);
- delete c;
-}
-
-class UnaryConstructorClass {
- public:
- explicit UnaryConstructorClass(int value) : value_(value) {}
- int value_;
-};
-
-// Tests using ReturnNew() with a unary constructor.
-TEST(ReturnNewTest, Unary) {
- Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
- UnaryConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(4000, c->value_);
- delete c;
-}
-
-TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
- Action<UnaryConstructorClass*(bool, int)> a =
- ReturnNew<UnaryConstructorClass>(4000);
- UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
- EXPECT_EQ(4000, c->value_);
- delete c;
-}
-
-TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
- Action<const UnaryConstructorClass*()> a =
- ReturnNew<UnaryConstructorClass>(4000);
- const UnaryConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(4000, c->value_);
- delete c;
-}
-
-class TenArgConstructorClass {
- public:
- TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5,
- int a6, int a7, int a8, int a9, int a10)
- : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {
- }
- int value_;
-};
-
-// Tests using ReturnNew() with a 10-argument constructor.
-TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
- Action<TenArgConstructorClass*()> a =
- ReturnNew<TenArgConstructorClass>(1000000000, 200000000, 30000000,
- 4000000, 500000, 60000,
- 7000, 800, 90, 0);
- TenArgConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(1234567890, c->value_);
- delete c;
-}
-
-// Tests that ACTION_TEMPLATE works when there is no value parameter.
-ACTION_TEMPLATE(CreateNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_0_VALUE_PARAMS()) {
- return new T;
-}
-
-TEST(ActionTemplateTest, WorksWithoutValueParam) {
- const Action<int*()> a = CreateNew<int>();
- int* p = a.Perform(std::make_tuple());
- delete p;
-}
-
-// Tests that ACTION_TEMPLATE works when there are value parameters.
-ACTION_TEMPLATE(CreateNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_1_VALUE_PARAMS(a0)) {
- return new T(a0);
-}
-
-TEST(ActionTemplateTest, WorksWithValueParams) {
- const Action<int*()> a = CreateNew<int>(42);
- int* p = a.Perform(std::make_tuple());
- EXPECT_EQ(42, *p);
- delete p;
-}
-
-// Tests that ACTION_TEMPLATE works for integral template parameters.
-ACTION_TEMPLATE(MyDeleteArg,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_0_VALUE_PARAMS()) {
- delete std::get<k>(args);
-}
-
-// Resets a bool variable in the destructor.
-class BoolResetter {
- public:
- explicit BoolResetter(bool* value) : value_(value) {}
- ~BoolResetter() { *value_ = false; }
- private:
- bool* value_;
-};
-
-TEST(ActionTemplateTest, WorksForIntegralTemplateParams) {
- const Action<void(int*, BoolResetter*)> a = MyDeleteArg<1>();
- int n = 0;
- bool b = true;
- BoolResetter* resetter = new BoolResetter(&b);
- a.Perform(std::make_tuple(&n, resetter));
- EXPECT_FALSE(b); // Verifies that resetter is deleted.
-}
-
-// Tests that ACTION_TEMPLATES works for template template parameters.
-ACTION_TEMPLATE(ReturnSmartPointer,
- HAS_1_TEMPLATE_PARAMS(template <typename Pointee> class,
- Pointer),
- AND_1_VALUE_PARAMS(pointee)) {
- return Pointer<pointee_type>(new pointee_type(pointee));
-}
-
-TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) {
- const Action<std::shared_ptr<int>()> a =
- ReturnSmartPointer<std::shared_ptr>(42);
- std::shared_ptr<int> p = a.Perform(std::make_tuple());
- EXPECT_EQ(42, *p);
-}
-
-// Tests that ACTION_TEMPLATE works for 10 template parameters.
-template <typename T1, typename T2, typename T3, int k4, bool k5,
- unsigned int k6, typename T7, typename T8, typename T9>
-struct GiantTemplate {
- public:
- explicit GiantTemplate(int a_value) : value(a_value) {}
- int value;
-};
-
-ACTION_TEMPLATE(ReturnGiant,
- HAS_10_TEMPLATE_PARAMS(
- typename, T1,
- typename, T2,
- typename, T3,
- int, k4,
- bool, k5,
- unsigned int, k6,
- class, T7,
- class, T8,
- class, T9,
- template <typename T> class, T10),
- AND_1_VALUE_PARAMS(value)) {
- return GiantTemplate<T10<T1>, T2, T3, k4, k5, k6, T7, T8, T9>(value);
-}
-
-TEST(ActionTemplateTest, WorksFor10TemplateParameters) {
- using Giant = GiantTemplate<std::shared_ptr<int>, bool, double, 5, true, 6,
- char, unsigned, int>;
- const Action<Giant()> a = ReturnGiant<int, bool, double, 5, true, 6, char,
- unsigned, int, std::shared_ptr>(42);
- Giant giant = a.Perform(std::make_tuple());
- EXPECT_EQ(42, giant.value);
-}
-
-// Tests that ACTION_TEMPLATE works for 10 value parameters.
-ACTION_TEMPLATE(ReturnSum,
- HAS_1_TEMPLATE_PARAMS(typename, Number),
- AND_10_VALUE_PARAMS(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10)) {
- return static_cast<Number>(v1) + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10;
-}
-
-TEST(ActionTemplateTest, WorksFor10ValueParameters) {
- const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
- EXPECT_EQ(55, a.Perform(std::make_tuple()));
-}
-
-// Tests that ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded
-// on the number of value parameters.
-
-ACTION(ReturnSum) { return 0; }
-
-ACTION_P(ReturnSum, x) { return x; }
-
-ACTION_TEMPLATE(ReturnSum,
- HAS_1_TEMPLATE_PARAMS(typename, Number),
- AND_2_VALUE_PARAMS(v1, v2)) {
- return static_cast<Number>(v1) + v2;
-}
-
-ACTION_TEMPLATE(ReturnSum,
- HAS_1_TEMPLATE_PARAMS(typename, Number),
- AND_3_VALUE_PARAMS(v1, v2, v3)) {
- return static_cast<Number>(v1) + v2 + v3;
-}
-
-ACTION_TEMPLATE(ReturnSum,
- HAS_2_TEMPLATE_PARAMS(typename, Number, int, k),
- AND_4_VALUE_PARAMS(v1, v2, v3, v4)) {
- return static_cast<Number>(v1) + v2 + v3 + v4 + k;
-}
-
-TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) {
- const Action<int()> a0 = ReturnSum();
- const Action<int()> a1 = ReturnSum(1);
- const Action<int()> a2 = ReturnSum<int>(1, 2);
- const Action<int()> a3 = ReturnSum<int>(1, 2, 3);
- const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5);
- EXPECT_EQ(0, a0.Perform(std::make_tuple()));
- EXPECT_EQ(1, a1.Perform(std::make_tuple()));
- EXPECT_EQ(3, a2.Perform(std::make_tuple()));
- EXPECT_EQ(6, a3.Perform(std::make_tuple()));
- EXPECT_EQ(12345, a4.Perform(std::make_tuple()));
-}
-
-
-} // namespace gmock_generated_actions_test
-} // namespace testing
diff --git a/googlemock/test/gmock-generated-function-mockers_test.cc b/googlemock/test/gmock-generated-function-mockers_test.cc
deleted file mode 100644
index dff3a9f0fadb..000000000000
--- a/googlemock/test/gmock-generated-function-mockers_test.cc
+++ /dev/null
@@ -1,659 +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 the function mocker classes.
-
-#include "gmock/gmock-generated-function-mockers.h"
-
-#if GTEST_OS_WINDOWS
-// 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>
-#endif // GTEST_OS_WINDOWS
-
-#include <map>
-#include <string>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace testing {
-namespace gmock_generated_function_mockers_test {
-
-using testing::_;
-using testing::A;
-using testing::An;
-using testing::AnyNumber;
-using testing::Const;
-using testing::DoDefault;
-using testing::Eq;
-using testing::Lt;
-using testing::MockFunction;
-using testing::Ref;
-using testing::Return;
-using testing::ReturnRef;
-using testing::TypedEq;
-
-template<typename T>
-class TemplatedCopyable {
- public:
- TemplatedCopyable() {}
-
- template <typename U>
- TemplatedCopyable(const U& other) {} // NOLINT
-};
-
-class FooInterface {
- public:
- virtual ~FooInterface() {}
-
- virtual void VoidReturning(int x) = 0;
-
- virtual int Nullary() = 0;
- virtual bool Unary(int x) = 0;
- 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;
-
- virtual bool TakesNonConstReference(int& n) = 0; // NOLINT
- virtual std::string TakesConstReference(const int& n) = 0;
- virtual bool TakesConst(const int x) = 0;
-
- virtual int OverloadedOnArgumentNumber() = 0;
- virtual int OverloadedOnArgumentNumber(int n) = 0;
-
- virtual int OverloadedOnArgumentType(int n) = 0;
- virtual char OverloadedOnArgumentType(char c) = 0;
-
- virtual int OverloadedOnConstness() = 0;
- virtual char OverloadedOnConstness() const = 0;
-
- virtual int TypeWithHole(int (*func)()) = 0;
- virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0;
- virtual int TypeWithTemplatedCopyCtor(
- const TemplatedCopyable<int>& a_vector) = 0;
-
-#if GTEST_OS_WINDOWS
- STDMETHOD_(int, CTNullary)() = 0;
- STDMETHOD_(bool, CTUnary)(int x) = 0;
- STDMETHOD_(int, CTDecimal)
- (bool b, char c, short d, int e, long f, // NOLINT
- float g, double h, unsigned i, char* j, const std::string& k) = 0;
- STDMETHOD_(char, CTConst)(int x) const = 0;
-#endif // GTEST_OS_WINDOWS
-};
-
-// Const qualifiers on arguments were once (incorrectly) considered
-// significant in determining whether two virtual functions had the same
-// 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)
-#endif
-class MockFoo : public FooInterface {
- public:
- MockFoo() {}
-
- // Makes sure that a mock function parameter can be named.
- MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT
-
- MOCK_METHOD0(Nullary, int()); // NOLINT
-
- // Makes sure that a mock function parameter can be unnamed.
- MOCK_METHOD1(Unary, bool(int)); // NOLINT
- MOCK_METHOD2(Binary, long(short, int)); // NOLINT
- MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT
- double, unsigned, char*, const std::string& str));
-
- MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT
- MOCK_METHOD1(TakesConstReference, std::string(const int&));
- MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT
-
- // Tests that the function return type can contain unprotected comma.
- MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>());
- MOCK_CONST_METHOD1(ReturnTypeWithComma,
- std::map<int, std::string>(int)); // NOLINT
-
- MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT
- MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT
-
- MOCK_METHOD1(OverloadedOnArgumentType, int(int)); // NOLINT
- MOCK_METHOD1(OverloadedOnArgumentType, char(char)); // NOLINT
-
- MOCK_METHOD0(OverloadedOnConstness, int()); // NOLINT
- MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT
-
- MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT
- MOCK_METHOD1(TypeWithComma,
- int(const std::map<int, std::string>&)); // NOLINT
- MOCK_METHOD1(TypeWithTemplatedCopyCtor,
- int(const TemplatedCopyable<int>&)); // NOLINT
-
-#if GTEST_OS_WINDOWS
- MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
- MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int));
- MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,
- int(bool b, char c, short d, int e, long f,
- float g, double h, unsigned i, char* j,
- const std::string& k));
- MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst, char(int));
-
- // Tests that the function return type can contain unprotected comma.
- MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,
- std::map<int, std::string>());
-#endif // GTEST_OS_WINDOWS
-
- private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
-};
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-
-class FunctionMockerTest : public testing::Test {
- protected:
- FunctionMockerTest() : foo_(&mock_foo_) {}
-
- FooInterface* const foo_;
- MockFoo mock_foo_;
-};
-
-// Tests mocking a void-returning function.
-TEST_F(FunctionMockerTest, MocksVoidFunction) {
- EXPECT_CALL(mock_foo_, VoidReturning(Lt(100)));
- foo_->VoidReturning(0);
-}
-
-// Tests mocking a nullary function.
-TEST_F(FunctionMockerTest, MocksNullaryFunction) {
- EXPECT_CALL(mock_foo_, Nullary())
- .WillOnce(DoDefault())
- .WillOnce(Return(1));
-
- EXPECT_EQ(0, foo_->Nullary());
- EXPECT_EQ(1, foo_->Nullary());
-}
-
-// Tests mocking a unary function.
-TEST_F(FunctionMockerTest, MocksUnaryFunction) {
- EXPECT_CALL(mock_foo_, Unary(Eq(2)))
- .Times(2)
- .WillOnce(Return(true));
-
- EXPECT_TRUE(foo_->Unary(2));
- EXPECT_FALSE(foo_->Unary(2));
-}
-
-// Tests mocking a binary function.
-TEST_F(FunctionMockerTest, MocksBinaryFunction) {
- EXPECT_CALL(mock_foo_, Binary(2, _))
- .WillOnce(Return(3));
-
- EXPECT_EQ(3, foo_->Binary(2, 1));
-}
-
-// Tests mocking a decimal function.
-TEST_F(FunctionMockerTest, MocksDecimalFunction) {
- EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U,
- nullptr, "hi"))
- .WillOnce(Return(5));
-
- EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
-}
-
-// Tests mocking a function that takes a non-const reference.
-TEST_F(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) {
- int a = 0;
- EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a)))
- .WillOnce(Return(true));
-
- EXPECT_TRUE(foo_->TakesNonConstReference(a));
-}
-
-// Tests mocking a function that takes a const reference.
-TEST_F(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
- int a = 0;
- EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a)))
- .WillOnce(Return("Hello"));
-
- EXPECT_EQ("Hello", foo_->TakesConstReference(a));
-}
-
-// Tests mocking a function that takes a const variable.
-TEST_F(FunctionMockerTest, MocksFunctionWithConstArgument) {
- EXPECT_CALL(mock_foo_, TakesConst(Lt(10)))
- .WillOnce(DoDefault());
-
- EXPECT_FALSE(foo_->TakesConst(5));
-}
-
-// Tests mocking functions overloaded on the number of arguments.
-TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber())
- .WillOnce(Return(1));
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_))
- .WillOnce(Return(2));
-
- EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1));
- EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber());
-}
-
-// Tests mocking functions overloaded on the types of argument.
-TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An<int>()))
- .WillOnce(Return(1));
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
- .WillOnce(Return('b'));
-
- EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0));
- EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a'));
-}
-
-// Tests mocking functions overloaded on the const-ness of this object.
-TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {
- EXPECT_CALL(mock_foo_, OverloadedOnConstness());
- EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness())
- .WillOnce(Return('a'));
-
- EXPECT_EQ(0, foo_->OverloadedOnConstness());
- EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness());
-}
-
-TEST_F(FunctionMockerTest, MocksReturnTypeWithComma) {
- const std::map<int, std::string> a_map;
- EXPECT_CALL(mock_foo_, ReturnTypeWithComma())
- .WillOnce(Return(a_map));
- EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
- .WillOnce(Return(a_map));
-
- EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma());
- EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42));
-}
-
-TEST_F(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
- EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true));
- EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
-}
-
-#if GTEST_OS_WINDOWS
-// Tests mocking a nullary function with calltype.
-TEST_F(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
- EXPECT_CALL(mock_foo_, CTNullary())
- .WillOnce(Return(-1))
- .WillOnce(Return(0));
-
- EXPECT_EQ(-1, foo_->CTNullary());
- EXPECT_EQ(0, foo_->CTNullary());
-}
-
-// Tests mocking a unary function with calltype.
-TEST_F(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
- EXPECT_CALL(mock_foo_, CTUnary(Eq(2)))
- .Times(2)
- .WillOnce(Return(true))
- .WillOnce(Return(false));
-
- EXPECT_TRUE(foo_->CTUnary(2));
- EXPECT_FALSE(foo_->CTUnary(2));
-}
-
-// Tests mocking a decimal function with calltype.
-TEST_F(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
- EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U,
- nullptr, "hi"))
- .WillOnce(Return(10));
-
- EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
-}
-
-// Tests mocking functions overloaded on the const-ness of this object.
-TEST_F(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
- EXPECT_CALL(Const(mock_foo_), CTConst(_))
- .WillOnce(Return('a'));
-
- EXPECT_EQ('a', Const(*foo_).CTConst(0));
-}
-
-TEST_F(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
- const std::map<int, std::string> a_map;
- EXPECT_CALL(mock_foo_, CTReturnTypeWithComma())
- .WillOnce(Return(a_map));
-
- EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma());
-}
-
-#endif // GTEST_OS_WINDOWS
-
-class MockB {
- public:
- MockB() {}
-
- MOCK_METHOD0(DoB, void());
-
- private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
-};
-
-// Tests that functions with no EXPECT_CALL() ruls can be called any
-// number of times.
-TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
- {
- MockB b;
- }
-
- {
- MockB b;
- b.DoB();
- }
-
- {
- MockB b;
- b.DoB();
- b.DoB();
- }
-}
-
-// Tests mocking template interfaces.
-
-template <typename T>
-class StackInterface {
- public:
- virtual ~StackInterface() {}
-
- // Template parameter appears in function parameter.
- virtual void Push(const T& value) = 0;
- virtual void Pop() = 0;
- virtual int GetSize() const = 0;
- // Template parameter appears in function return type.
- virtual const T& GetTop() const = 0;
-};
-
-template <typename T>
-class MockStack : public StackInterface<T> {
- public:
- MockStack() {}
-
- MOCK_METHOD1_T(Push, void(const T& elem));
- MOCK_METHOD0_T(Pop, void());
- MOCK_CONST_METHOD0_T(GetSize, int()); // NOLINT
- MOCK_CONST_METHOD0_T(GetTop, const T&());
-
- // Tests that the function return type can contain unprotected comma.
- MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());
- MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int)); // NOLINT
-
- private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
-};
-
-// Tests that template mock works.
-TEST(TemplateMockTest, Works) {
- MockStack<int> mock;
-
- EXPECT_CALL(mock, GetSize())
- .WillOnce(Return(0))
- .WillOnce(Return(1))
- .WillOnce(Return(0));
- EXPECT_CALL(mock, Push(_));
- int n = 5;
- EXPECT_CALL(mock, GetTop())
- .WillOnce(ReturnRef(n));
- EXPECT_CALL(mock, Pop())
- .Times(AnyNumber());
-
- EXPECT_EQ(0, mock.GetSize());
- mock.Push(5);
- EXPECT_EQ(1, mock.GetSize());
- EXPECT_EQ(5, mock.GetTop());
- mock.Pop();
- EXPECT_EQ(0, mock.GetSize());
-}
-
-TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
- MockStack<int> 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_EQ(a_map, mock.ReturnTypeWithComma());
- EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
-}
-
-#if GTEST_OS_WINDOWS
-// Tests mocking template interfaces with calltype.
-
-template <typename T>
-class StackInterfaceWithCallType {
- public:
- virtual ~StackInterfaceWithCallType() {}
-
- // Template parameter appears in function parameter.
- STDMETHOD_(void, Push)(const T& value) = 0;
- STDMETHOD_(void, Pop)() = 0;
- STDMETHOD_(int, GetSize)() const = 0;
- // Template parameter appears in function return type.
- STDMETHOD_(const T&, GetTop)() const = 0;
-};
-
-template <typename T>
-class MockStackWithCallType : public StackInterfaceWithCallType<T> {
- public:
- MockStackWithCallType() {}
-
- MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem));
- MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void());
- MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int());
- MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());
-
- private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType);
-};
-
-// Tests that template mock with calltype works.
-TEST(TemplateMockTestWithCallType, Works) {
- MockStackWithCallType<int> mock;
-
- EXPECT_CALL(mock, GetSize())
- .WillOnce(Return(0))
- .WillOnce(Return(1))
- .WillOnce(Return(0));
- EXPECT_CALL(mock, Push(_));
- int n = 5;
- EXPECT_CALL(mock, GetTop())
- .WillOnce(ReturnRef(n));
- EXPECT_CALL(mock, Pop())
- .Times(AnyNumber());
-
- EXPECT_EQ(0, mock.GetSize());
- mock.Push(5);
- EXPECT_EQ(1, mock.GetSize());
- EXPECT_EQ(5, mock.GetTop());
- mock.Pop();
- EXPECT_EQ(0, mock.GetSize());
-}
-#endif // GTEST_OS_WINDOWS
-
-#define MY_MOCK_METHODS1_ \
- MOCK_METHOD0(Overloaded, void()); \
- MOCK_CONST_METHOD1(Overloaded, int(int n)); \
- MOCK_METHOD2(Overloaded, bool(bool f, int n))
-
-class MockOverloadedOnArgNumber {
- public:
- MockOverloadedOnArgNumber() {}
-
- MY_MOCK_METHODS1_;
-
- private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
-};
-
-TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
- MockOverloadedOnArgNumber mock;
- EXPECT_CALL(mock, Overloaded());
- EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
- EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));
-
- mock.Overloaded();
- EXPECT_EQ(2, mock.Overloaded(1));
- EXPECT_TRUE(mock.Overloaded(true, 1));
-}
-
-#define MY_MOCK_METHODS2_ \
- MOCK_CONST_METHOD1(Overloaded, int(int n)); \
- MOCK_METHOD1(Overloaded, int(int n))
-
-class MockOverloadedOnConstness {
- public:
- MockOverloadedOnConstness() {}
-
- MY_MOCK_METHODS2_;
-
- private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnConstness);
-};
-
-TEST(OverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) {
- MockOverloadedOnConstness mock;
- const MockOverloadedOnConstness* const_mock = &mock;
- EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
- EXPECT_CALL(*const_mock, Overloaded(1)).WillOnce(Return(3));
-
- EXPECT_EQ(2, mock.Overloaded(1));
- EXPECT_EQ(3, const_mock->Overloaded(1));
-}
-
-TEST(MockFunctionTest, WorksForVoidNullary) {
- MockFunction<void()> foo;
- EXPECT_CALL(foo, Call());
- foo.Call();
-}
-
-TEST(MockFunctionTest, WorksForNonVoidNullary) {
- MockFunction<int()> foo;
- EXPECT_CALL(foo, Call())
- .WillOnce(Return(1))
- .WillOnce(Return(2));
- EXPECT_EQ(1, foo.Call());
- EXPECT_EQ(2, foo.Call());
-}
-
-TEST(MockFunctionTest, WorksForVoidUnary) {
- MockFunction<void(int)> foo;
- EXPECT_CALL(foo, Call(1));
- foo.Call(1);
-}
-
-TEST(MockFunctionTest, 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_EQ(1, foo.Call(false, 42));
- EXPECT_EQ(2, foo.Call(false, 42));
- EXPECT_EQ(3, foo.Call(true, 120));
-}
-
-TEST(MockFunctionTest, WorksFor10Arguments) {
- 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));
- EXPECT_EQ(1, foo.Call(false, 'a', 0, 0, 0, 0, 0, 'b', 0, true));
- EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false));
-}
-
-TEST(MockFunctionTest, AsStdFunction) {
- MockFunction<int(int)> foo;
- 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));
- EXPECT_EQ(-2, call(foo.AsStdFunction(), 2));
-}
-
-TEST(MockFunctionTest, AsStdFunctionReturnsReference) {
- MockFunction<int&()> foo;
- int value = 1;
- EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value));
- int& ref = foo.AsStdFunction()();
- EXPECT_EQ(1, ref);
- value = 2;
- EXPECT_EQ(2, ref);
-}
-
-TEST(MockFunctionTest, AsStdFunctionWithReferenceParameter) {
- 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));
-}
-
-
-struct MockMethodSizes0 {
- MOCK_METHOD0(func, void());
-};
-struct MockMethodSizes1 {
- MOCK_METHOD1(func, void(int));
-};
-struct MockMethodSizes2 {
- MOCK_METHOD2(func, void(int, int));
-};
-struct MockMethodSizes3 {
- MOCK_METHOD3(func, void(int, int, int));
-};
-struct MockMethodSizes4 {
- MOCK_METHOD4(func, void(int, int, int, int));
-};
-
-TEST(MockFunctionTest, MockMethodSizeOverhead) {
- EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
- EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));
- EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3));
- EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4));
-}
-
-} // namespace gmock_generated_function_mockers_test
-} // namespace testing
diff --git a/googlemock/test/gmock-generated-matchers_test.cc b/googlemock/test/gmock-generated-matchers_test.cc
deleted file mode 100644
index 6c4b30008b77..000000000000
--- a/googlemock/test/gmock-generated-matchers_test.cc
+++ /dev/null
@@ -1,1324 +0,0 @@
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests the built-in matchers generated by a script.
-
-// 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-generated-matchers.h"
-
-#include <list>
-#include <map>
-#include <memory>
-#include <set>
-#include <sstream>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "gtest/gtest-spi.h"
-
-namespace {
-
-using std::list;
-using std::map;
-using std::pair;
-using std::set;
-using std::stringstream;
-using std::vector;
-using testing::_;
-using testing::AllOf;
-using testing::AllOfArray;
-using testing::AnyOf;
-using testing::AnyOfArray;
-using testing::Args;
-using testing::Contains;
-using testing::ElementsAre;
-using testing::ElementsAreArray;
-using testing::Eq;
-using testing::Ge;
-using testing::Gt;
-using testing::Le;
-using testing::Lt;
-using testing::MakeMatcher;
-using testing::Matcher;
-using testing::MatcherInterface;
-using testing::MatchResultListener;
-using testing::Ne;
-using testing::Not;
-using testing::Pointee;
-using testing::PrintToString;
-using testing::Ref;
-using testing::StaticAssertTypeEq;
-using testing::StrEq;
-using testing::Value;
-using testing::internal::ElementsAreArrayMatcher;
-
-// Returns the description of the given matcher.
-template <typename T>
-std::string Describe(const Matcher<T>& m) {
- stringstream ss;
- m.DescribeTo(&ss);
- return ss.str();
-}
-
-// Returns the description of the negation of the given matcher.
-template <typename T>
-std::string DescribeNegation(const Matcher<T>& m) {
- stringstream ss;
- m.DescribeNegationTo(&ss);
- return ss.str();
-}
-
-// 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) {
- stringstream ss;
- m.ExplainMatchResultTo(x, &ss);
- return ss.str();
-}
-
-// For testing ExplainMatchResultTo().
-class GreaterThanMatcher : public MatcherInterface<int> {
- public:
- explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
-
- void DescribeTo(::std::ostream* os) const override {
- *os << "is greater than " << 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));
-}
-
-// 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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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) {
- const char* strings[] = {
- "Hi",
- "world"
- };
-
- vector<list<char> > nested;
- for (size_t i = 0; i < GTEST_ARRAY_SIZE_(strings); i++) {
- nested.push_back(list<char>(strings[i], strings[i] + strlen(strings[i])));
- }
-
- 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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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_METHOD2(Helper, void(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")));
-}
-
-#ifndef _MSC_VER
-
-// The following test passes a value of type const char[] to a
-// function template that expects const T&. Some versions of MSVC
-// generates a compiler error C2665 for that. We believe it's a bug
-// in MSVC. Therefore this test is #if-ed out for MSVC.
-
-// 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";
-
-#endif // _MSC_VER
-
-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(a, a + GTEST_ARRAY_SIZE_(a));
- EXPECT_THAT(test_vector, ElementsAreArray(a));
-
- test_vector[2] = 0;
- EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
- const char* a[] = { "one", "two", "three" };
-
- vector<std::string> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
- EXPECT_THAT(test_vector, ElementsAreArray(a, GTEST_ARRAY_SIZE_(a)));
-
- const char** p = a;
- test_vector[0] = "1";
- EXPECT_THAT(test_vector, Not(ElementsAreArray(p, GTEST_ARRAY_SIZE_(a))));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
- const char* a[] = { "one", "two", "three" };
-
- vector<std::string> test_vector(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(a));
- const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(a));
- const vector<Matcher<int> > expected(
- kMatchers, kMatchers + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(a));
- const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(a));
- EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
- // Pointers are iterators, too.
- EXPECT_THAT(test_vector, ElementsAreArray(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(a));
- vector<int> expect(a, a + GTEST_ARRAY_SIZE_(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.
- typedef vector<int>::iterator Iter;
- for (Iter it = expect.begin(); it != expect.end(); ++it) { *it += 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 == "";
-}
-
-MATCHER(IsEmptyStringByRef, "") {
- StaticAssertTypeEq<const ::std::string&, arg_type>();
- return arg == "";
-}
-
-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) {}
- private:
- UncopyableFoo(const UncopyableFoo&);
- void operator=(const UncopyableFoo&);
-
- 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&> m =
- ReferencesAnyOf<const UncopyableFoo&, const 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<const char*> 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<const char*> c_string_set;
- c_string_set.insert("hello");
- EXPECT_THAT(c_string_set, Not(Contains(std::string("hello").c_str())));
-}
-
-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<const char*, 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, "") { 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& t1, const T2& 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)));
-}
-
-
-} // namespace
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc
index d000e6924cdf..6c769a882a69 100644
--- a/googlemock/test/gmock-internal-utils_test.cc
+++ b/googlemock/test/gmock-internal-utils_test.cc
@@ -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.
@@ -36,11 +35,12 @@
#include <stdlib.h>
+#include <cstdint>
#include <map>
#include <memory>
#include <sstream>
#include <string>
-#include <type_traits>
+#include <tuple>
#include <vector>
#include "gmock/gmock.h"
@@ -57,8 +57,8 @@
#include "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION_
-#if GTEST_OS_CYGWIN
-# include <sys/types.h> // For ssize_t. NOLINT
+#ifdef GTEST_OS_CYGWIN
+#include <sys/types.h> // For ssize_t. NOLINT
#endif
namespace proto2 {
@@ -70,24 +70,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) {
@@ -124,20 +123,6 @@ TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
ConvertIdentifierNameToWords("_Chapter11Section_1_"));
}
-TEST(PointeeOfTest, WorksForSmartPointers) {
- EXPECT_TRUE(
- (std::is_same<int, PointeeOf<std::unique_ptr<int>>::type>::value));
- EXPECT_TRUE(
- (std::is_same<std::string,
- PointeeOf<std::shared_ptr<std::string>>::type>::value));
-}
-
-TEST(PointeeOfTest, WorksForRawPointers) {
- EXPECT_TRUE((std::is_same<int, PointeeOf<int*>::type>::value));
- EXPECT_TRUE((std::is_same<const char, PointeeOf<const char*>::type>::value));
- EXPECT_TRUE((std::is_void<PointeeOf<void*>::type>::value));
-}
-
TEST(GetRawPointerTest, WorksForSmartPointers) {
const char* const raw_p1 = new const char('a'); // NOLINT
const std::unique_ptr<const char> p1(raw_p1);
@@ -154,6 +139,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 {};
@@ -164,35 +155,35 @@ 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_(wchar_t)); // NOLINT
- EXPECT_EQ(kInteger, GMOCK_KIND_OF_(Int64)); // NOLINT
- EXPECT_EQ(kInteger, GMOCK_KIND_OF_(UInt64)); // NOLINT
- EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT
-#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN
+ 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
+#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || defined(GTEST_OS_CYGWIN)
// ssize_t is not defined on Windows and possibly some other OSes.
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); // NOLINT
#endif
}
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>.
@@ -223,32 +214,33 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));
// Unsigned => larger unsigned is fine.
- EXPECT_TRUE(
- (LosslessArithmeticConvertible<unsigned short, UInt64>::value)); // NOLINT
+ EXPECT_TRUE((LosslessArithmeticConvertible<unsigned short,
+ uint64_t>::value)); // NOLINT
// Signed => unsigned is not fine.
- EXPECT_FALSE((LosslessArithmeticConvertible<short, UInt64>::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, Int64>::value));
+ EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value));
// Larger size => smaller size is not fine.
EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value)); // NOLINT
EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value));
- EXPECT_FALSE((LosslessArithmeticConvertible<Int64, unsigned int>::value));
+ EXPECT_FALSE((LosslessArithmeticConvertible<int64_t, unsigned int>::value));
}
TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
@@ -256,8 +248,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) {
@@ -267,7 +259,7 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) {
EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value)); // NOLINT
- EXPECT_FALSE((LosslessArithmeticConvertible<double, Int64>::value));
+ EXPECT_FALSE((LosslessArithmeticConvertible<double, int64_t>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value));
}
@@ -285,7 +277,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));
@@ -304,7 +296,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));
@@ -312,7 +304,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');
@@ -325,7 +317,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"),
@@ -344,13 +336,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.
@@ -361,40 +350,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));
}
@@ -407,31 +400,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 {
@@ -453,7 +446,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"
@@ -462,13 +456,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
@@ -510,12 +504,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();
}
@@ -545,7 +539,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());
}
@@ -589,9 +583,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;
@@ -604,17 +598,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());
@@ -632,24 +625,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]);
@@ -728,6 +721,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
index 000000000000..f176962855ea
--- /dev/null
+++ b/googlemock/test/gmock-matchers-arithmetic_test.cc
@@ -0,0 +1,1516 @@
+// 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.
+
+#include <cmath>
+#include <limits>
+#include <memory>
+#include <string>
+
+#include "test/gmock-matchers_test.h"
+
+// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
+// possible loss of data and C4100, unreferenced local parameter
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
+
+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() = default;
+
+ 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() = default;
+
+ 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_(std::numeric_limits<RawType>::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
+
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
diff --git a/googlemock/test/gmock-matchers-comparisons_test.cc b/googlemock/test/gmock-matchers-comparisons_test.cc
new file mode 100644
index 000000000000..b2ce99e18d4f
--- /dev/null
+++ b/googlemock/test/gmock-matchers-comparisons_test.cc
@@ -0,0 +1,2361 @@
+// 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.
+
+#include <functional>
+#include <memory>
+#include <string>
+#include <tuple>
+#include <vector>
+
+#include "test/gmock-matchers_test.h"
+
+// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
+// possible loss of data and C4100, unreferenced local parameter
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
+
+
+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() = default;
+ Base() = default;
+
+ 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) {
+ // Verifies 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));
+}
+
+TEST(IsEmptyTest, MatchesContainer) {
+ const Matcher<std::vector<int>> m = IsEmpty();
+ std::vector<int> a = {};
+ std::vector<int> b = {1};
+ EXPECT_TRUE(m.Matches(a));
+ EXPECT_FALSE(m.Matches(b));
+}
+
+TEST(IsEmptyTest, MatchesStdString) {
+ const Matcher<std::string> m = IsEmpty();
+ std::string a = "z";
+ std::string b = "";
+ EXPECT_FALSE(m.Matches(a));
+ EXPECT_TRUE(m.Matches(b));
+}
+
+TEST(IsEmptyTest, MatchesCString) {
+ const Matcher<const char*> m = IsEmpty();
+ const char a[] = "";
+ const char b[] = "x";
+ EXPECT_TRUE(m.Matches(a));
+ EXPECT_FALSE(m.Matches(b));
+}
+
+// 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' doesn't 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 = std::make_unique<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));
+ struct MyVarType17 {
+ int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q;
+ };
+ EXPECT_THAT(MyVarType17{},
+ FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+ struct MyVarType18 {
+ int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r;
+ };
+ EXPECT_THAT(MyVarType18{},
+ FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+ struct MyVarType19 {
+ int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s;
+ };
+ EXPECT_THAT(MyVarType19{}, FieldsAre(0, 0, 0, 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!
+ EXPECT_TRUE(m1.Matches("+/-_IQ")); // \xfb\xff\xbf!
+
+ 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!
+ EXPECT_TRUE(m2.Matches("+/-_IQ")); // \xfb\xff\xbf!
+
+#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!
+ EXPECT_TRUE(m3.Matches("+/-_IQ")); // \xfb\xff\xbf!
+#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
+
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
diff --git a/googlemock/test/gmock-matchers-containers_test.cc b/googlemock/test/gmock-matchers-containers_test.cc
new file mode 100644
index 000000000000..38fd9a5dd76f
--- /dev/null
+++ b/googlemock/test/gmock-matchers-containers_test.cc
@@ -0,0 +1,3137 @@
+// 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.
+
+#include <algorithm>
+#include <array>
+#include <deque>
+#include <forward_list>
+#include <iterator>
+#include <list>
+#include <memory>
+#include <ostream>
+#include <string>
+#include <tuple>
+#include <vector>
+
+#include "gtest/gtest.h"
+
+// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
+// possible loss of data and C4100, unreferenced local parameter
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
+
+#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("has a size that is equal to 2", Describe(m));
+ EXPECT_EQ("has a size that 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[] = {false, true, false, true, true};
+ const bool b[] = {true, false, true, true, false};
+ 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() = default;
+
+ 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
+
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
diff --git a/googlemock/test/gmock-matchers-misc_test.cc b/googlemock/test/gmock-matchers-misc_test.cc
new file mode 100644
index 000000000000..b8f64587db14
--- /dev/null
+++ b/googlemock/test/gmock-matchers-misc_test.cc
@@ -0,0 +1,1823 @@
+// 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.
+
+#include <array>
+#include <memory>
+#include <ostream>
+#include <string>
+#include <tuple>
+#include <utility>
+#include <vector>
+
+#include "gtest/gtest.h"
+
+// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
+// possible loss of data and C4100, unreferenced local parameter
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
+
+#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()));
+}
+
+#ifdef 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(short{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(short{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(short{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(short{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 AllOfArray 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)));
+}
+
+MATCHER(EnsureNoUnusedButMarkedUnusedWarning, "") { return (arg % 2) == 0; }
+
+TEST(MockMethodMockFunctionTest, EnsureNoUnusedButMarkedUnusedWarning) {
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic error "-Wused-but-marked-unused"
+#endif
+ // https://github.com/google/googletest/issues/4055
+ EXPECT_THAT(0, EnsureNoUnusedButMarkedUnusedWarning());
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+}
+
+#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
+
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc
deleted file mode 100644
index 037352676f02..000000000000
--- a/googlemock/test/gmock-matchers_test.cc
+++ /dev/null
@@ -1,6801 +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 "gmock/gmock-more-matchers.h"
-
-#include <string.h>
-#include <time.h>
-#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 <utility>
-#include <vector>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "gtest/gtest-spi.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::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 " (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_HAS_ABSL
-// Tests that a C-string literal can be implicitly converted to a
-// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
-TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
- Matcher<absl::string_view> m1 = "cats";
- EXPECT_TRUE(m1.Matches("cats"));
- EXPECT_FALSE(m1.Matches("dogs"));
-
- Matcher<const absl::string_view&> 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<absl::string_view> or Matcher<const absl::string_view&>.
-TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
- Matcher<absl::string_view> m1 = std::string("cats");
- EXPECT_TRUE(m1.Matches("cats"));
- EXPECT_FALSE(m1.Matches("dogs"));
-
- Matcher<const absl::string_view&> m2 = std::string("cats");
- EXPECT_TRUE(m2.Matches("cats"));
- EXPECT_FALSE(m2.Matches("dogs"));
-}
-
-// Tests that a absl::string_view object can be implicitly converted to a
-// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
-TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
- Matcher<absl::string_view> m1 = absl::string_view("cats");
- EXPECT_TRUE(m1.Matches("cats"));
- EXPECT_FALSE(m1.Matches("dogs"));
-
- Matcher<const absl::string_view&> m2 = absl::string_view("cats");
- EXPECT_TRUE(m2.Matches("cats"));
- EXPECT_FALSE(m2.Matches("dogs"));
-}
-#endif // GTEST_HAS_ABSL
-
-// 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 = nullptr;
- 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<int> m1 = Eq(0);
- Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
- EXPECT_TRUE(m2.Matches(0));
- EXPECT_FALSE(m2.Matches(1));
-}
-
-// 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));
-};
-
-TEST(ComparisonBaseTest, WorksWithMoveOnly) {
- 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.
-
-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_HAS_ABSL
- Matcher<const absl::string_view&> m3 = StrEq("Hello");
- EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
- EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
- EXPECT_FALSE(m3.Matches(absl::string_view()));
-
- Matcher<const absl::string_view&> m_empty = StrEq("");
- EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
- EXPECT_TRUE(m_empty.Matches(absl::string_view()));
- EXPECT_FALSE(m_empty.Matches(absl::string_view("hello")));
-#endif // GTEST_HAS_ABSL
-}
-
-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_HAS_ABSL
- Matcher<const absl::string_view> m3 = StrNe("Hello");
- EXPECT_TRUE(m3.Matches(absl::string_view("")));
- EXPECT_TRUE(m3.Matches(absl::string_view()));
- EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
-#endif // GTEST_HAS_ABSL
-}
-
-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_HAS_ABSL
- Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello"));
- EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
- EXPECT_TRUE(m3.Matches(absl::string_view("hello")));
- EXPECT_FALSE(m3.Matches(absl::string_view("Hi")));
- EXPECT_FALSE(m3.Matches(absl::string_view()));
-#endif // GTEST_HAS_ABSL
-}
-
-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_HAS_ABSL
- Matcher<const absl::string_view> m3 = StrCaseNe("Hello");
- EXPECT_TRUE(m3.Matches(absl::string_view("Hi")));
- EXPECT_TRUE(m3.Matches(absl::string_view()));
- EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
- EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
-#endif // GTEST_HAS_ABSL
-}
-
-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_HAS_ABSL
-// Tests that HasSubstr() works for matching absl::string_view-typed values.
-TEST(HasSubstrTest, WorksForStringViewClasses) {
- const Matcher<absl::string_view> m1 = HasSubstr("foo");
- EXPECT_TRUE(m1.Matches(absl::string_view("I love food.")));
- EXPECT_FALSE(m1.Matches(absl::string_view("tofo")));
- EXPECT_FALSE(m1.Matches(absl::string_view()));
-
- const Matcher<const absl::string_view&> m2 = HasSubstr("foo");
- EXPECT_TRUE(m2.Matches(absl::string_view("I love food.")));
- EXPECT_FALSE(m2.Matches(absl::string_view("tofo")));
- EXPECT_FALSE(m2.Matches(absl::string_view()));
-
- const Matcher<const absl::string_view&> m3 = HasSubstr("");
- EXPECT_TRUE(m3.Matches(absl::string_view("foo")));
- EXPECT_TRUE(m3.Matches(absl::string_view("")));
- EXPECT_TRUE(m3.Matches(absl::string_view()));
-}
-#endif // GTEST_HAS_ABSL
-
-// 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(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_HAS_ABSL
- const Matcher<absl::string_view> m_empty = StartsWith("");
- EXPECT_TRUE(m_empty.Matches(absl::string_view()));
- EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
- EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty")));
-#endif // GTEST_HAS_ABSL
-}
-
-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_HAS_ABSL
- const Matcher<const absl::string_view&> m4 = EndsWith("");
- EXPECT_TRUE(m4.Matches("Hi"));
- EXPECT_TRUE(m4.Matches(""));
- EXPECT_TRUE(m4.Matches(absl::string_view()));
- EXPECT_TRUE(m4.Matches(absl::string_view("")));
-#endif // GTEST_HAS_ABSL
-}
-
-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_HAS_ABSL
- const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z");
- EXPECT_TRUE(m3.Matches(absl::string_view("az")));
- EXPECT_TRUE(m3.Matches(absl::string_view("abcz")));
- EXPECT_FALSE(m3.Matches(absl::string_view("1az")));
- EXPECT_FALSE(m3.Matches(absl::string_view()));
- const Matcher<const absl::string_view&> m4 = MatchesRegex("");
- EXPECT_TRUE(m4.Matches(absl::string_view("")));
- EXPECT_TRUE(m4.Matches(absl::string_view()));
-#endif // GTEST_HAS_ABSL
-}
-
-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_HAS_ABSL
- Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*"));
- EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
-#endif // GTEST_HAS_ABSL
-}
-
-// 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_HAS_ABSL
- const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z"));
- EXPECT_TRUE(m3.Matches(absl::string_view("azbz")));
- EXPECT_TRUE(m3.Matches(absl::string_view("az1")));
- EXPECT_FALSE(m3.Matches(absl::string_view("1a")));
- EXPECT_FALSE(m3.Matches(absl::string_view()));
- const Matcher<const absl::string_view&> m4 = ContainsRegex("");
- EXPECT_TRUE(m4.Matches(absl::string_view("")));
- EXPECT_TRUE(m4.Matches(absl::string_view()));
-#endif // GTEST_HAS_ABSL
-}
-
-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_HAS_ABSL
- Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*"));
- EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
-#endif // GTEST_HAS_ABSL
-}
-
-// 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 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 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_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;
-
- // VC++ prior to version 8.0 SP1 has a bug where it will not see any
- // functions declared in the namespace scope from within nested classes.
- // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
- // namespace-level functions invoked inside them need to be explicitly
- // resolved.
- EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
- "Value of: n\n"
- "Expected: is > 10\n"
- " Actual: 5" + OfType("unsigned short"));
- n = 0;
- EXPECT_NONFATAL_FAILURE(
- EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::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, ::testing::Not(::testing::Ref(n))),
- "Value of: n\n"
- "Expected: does not reference the variable @");
- // Tests the "Actual" part.
- EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::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));
-}
-
-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.
-
- private:
- GTEST_DISALLOW_ASSIGN_(AStruct);
-};
-
-// A derived struct for testing Field().
-struct DerivedStruct : public AStruct {
- char ch;
-
- private:
- GTEST_DISALLOW_ASSIGN_(DerivedStruct);
-};
-
-// 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(GreaterThan(1));
- 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, which is 1 less than 1",
- 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, which is 1 more than 1",
- 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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(a));
- std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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(a, a + GTEST_ARRAY_SIZE_(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);
- static const size_t kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
- for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++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<testing::internal::UInt32>(GTEST_FLAG(random_seed));
- if (seed == 0) {
- seed = static_cast<testing::internal::UInt32>(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, [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, [MatchAndExplain]";
- EXPECT_EQ(expect, result.message());
-}
-
-} // 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
index 000000000000..56956076dae0
--- /dev/null
+++ b/googlemock/test/gmock-matchers_test.h
@@ -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_
diff --git a/googlemock/test/gmock-more-actions_test.cc b/googlemock/test/gmock-more-actions_test.cc
index 97ec5cf08f3f..9980f3bc4567 100644
--- a/googlemock/test/gmock-more-actions_test.cc
+++ b/googlemock/test/gmock-more-actions_test.cc
@@ -27,31 +27,35 @@
// (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 in gmock-more-actions.h.
+// This file tests the built-in actions in gmock-actions.h.
#include "gmock/gmock-more-actions.h"
+#include <algorithm>
#include <functional>
+#include <iterator>
#include <memory>
#include <sstream>
#include <string>
+#include <tuple>
+#include <vector>
+
#include "gmock/gmock.h"
+#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4577)
+
namespace testing {
namespace gmock_more_actions_test {
using ::std::plus;
using ::std::string;
-using testing::_;
using testing::Action;
-using testing::ActionInterface;
using testing::DeleteArg;
using testing::Invoke;
-using testing::Return;
using testing::ReturnArg;
using testing::ReturnPointee;
using testing::SaveArg;
@@ -68,55 +72,27 @@ inline char Char(char ch) { return ch; }
// Sample functions and functors for testing Invoke() and etc.
int Nullary() { return 1; }
-class NullaryFunctor {
- public:
- int operator()() { return 2; }
-};
-
bool g_done = false;
-void VoidNullary() { g_done = true; }
-
-class VoidNullaryFunctor {
- public:
- void operator()() { g_done = true; }
-};
bool Unary(int x) { return x < 0; }
-const char* Plus1(const char* s) { return s + 1; }
-
-void VoidUnary(int /* n */) { g_done = true; }
-
bool ByConstRef(const std::string& s) { return s == "Hi"; }
const double g_double = 0;
bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
-std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT
-
struct UnaryFunctor {
int operator()(bool x) { return x ? 1 : -1; }
};
const char* Binary(const char* input, short n) { return input + n; } // NOLINT
-void VoidBinary(int, char) { g_done = true; }
-
int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
-void VoidTernary(int, char, bool) { g_done = true; }
-
int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
int SumOfFirst2(int a, int b, Unused, Unused) { return a + b; }
-void VoidFunctionWithFourArguments(char, int, float, double) { g_done = true; }
-
-std::string Concat4(const char* s1, const char* s2, const char* s3,
- const char* s4) {
- return std::string(s1) + s2 + s3 + s4;
-}
-
int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
struct SumOf5Functor {
@@ -125,11 +101,6 @@ struct SumOf5Functor {
}
};
-std::string Concat5(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5) {
- return std::string(s1) + s2 + s3 + s4 + s5;
-}
-
int SumOf6(int a, int b, int c, int d, int e, int f) {
return a + b + c + d + e + f;
}
@@ -140,11 +111,6 @@ struct SumOf6Functor {
}
};
-std::string Concat6(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6;
-}
-
std::string Concat7(const char* s1, const char* s2, const char* s3,
const char* s4, const char* s5, const char* s6,
const char* s7) {
@@ -180,7 +146,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_;
@@ -326,8 +292,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))));
}
@@ -338,8 +303,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)));
}
@@ -397,7 +361,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)));
}
@@ -497,6 +462,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);
@@ -552,15 +523,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_;
@@ -569,7 +537,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);
@@ -578,8 +546,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);
@@ -604,13 +573,40 @@ TEST(ThrowActionTest, ThrowsGivenExceptionInNullaryFunction) {
EXPECT_THROW(a.Perform(std::make_tuple()), MyException);
}
+class Object {
+ public:
+ virtual ~Object() {}
+ virtual void Func() {}
+};
+
+class MockObject : public Object {
+ public:
+ ~MockObject() override {}
+ MOCK_METHOD(void, Func, (), (override));
+};
+
+TEST(ThrowActionTest, Times0) {
+ EXPECT_NONFATAL_FAILURE(
+ [] {
+ try {
+ MockObject m;
+ ON_CALL(m, Func()).WillByDefault([] { throw "something"; });
+ EXPECT_CALL(m, Func()).Times(0);
+ m.Func();
+ } catch (...) {
+ // Exception is caught but Times(0) still triggers a failure.
+ }
+ }(),
+ "");
+}
+
#endif // GTEST_HAS_EXCEPTIONS
// Tests that SetArrayArgument<N>(first, last) sets the elements of the array
// pointed to by the N-th (0-based) argument to values in range [first, last).
TEST(SetArrayArgumentTest, SetsTheNthArray) {
- typedef void MyFunction(bool, int*, char*);
- int numbers[] = { 1, 2, 3 };
+ using MyFunction = void(bool, int*, char*);
+ int numbers[] = {1, 2, 3};
Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3);
int n[4] = {};
@@ -645,8 +641,8 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) {
// Tests SetArrayArgument<N>(first, last) where first == last.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
- typedef void MyFunction(bool, int*);
- int numbers[] = { 1, 2, 3 };
+ using MyFunction = void(bool, int*);
+ int numbers[] = {1, 2, 3};
Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers);
int n[4] = {};
@@ -661,11 +657,11 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
// Tests SetArrayArgument<N>(first, last) where *first is convertible
// (but not equal) to the argument type.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) {
- typedef void MyFunction(bool, int*);
- char chars[] = { 97, 98, 99 };
+ using MyFunction = void(bool, int*);
+ 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]);
@@ -676,12 +672,12 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) {
// Test SetArrayArgument<N>(first, last) with iterator as argument.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) {
- typedef void MyFunction(bool, std::back_insert_iterator<std::string>);
+ using MyFunction = void(bool, std::back_insert_iterator<std::string>);
std::string letters = "abc";
Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end());
std::string s;
- a.Perform(std::make_tuple(true, back_inserter(s)));
+ a.Perform(std::make_tuple(true, std::back_inserter(s)));
EXPECT_EQ(letters, s);
}
@@ -694,5 +690,861 @@ TEST(ReturnPointeeTest, Works) {
EXPECT_EQ(43, a.Perform(std::make_tuple()));
}
-} // namespace gmock_generated_actions_test
+// Tests InvokeArgument<N>(...).
+
+// Tests using InvokeArgument with a nullary function.
+TEST(InvokeArgumentTest, Function0) {
+ Action<int(int, int (*)())> a = InvokeArgument<1>(); // NOLINT
+ EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary)));
+}
+
+// Tests using InvokeArgument with a unary function.
+TEST(InvokeArgumentTest, Functor1) {
+ Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT
+ EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor())));
+}
+
+// Tests using InvokeArgument with a 5-ary function.
+TEST(InvokeArgumentTest, Function5) {
+ Action<int(int (*)(int, int, int, int, int))> a = // NOLINT
+ InvokeArgument<0>(10000, 2000, 300, 40, 5);
+ EXPECT_EQ(12345, a.Perform(std::make_tuple(&SumOf5)));
+}
+
+// Tests using InvokeArgument with a 5-ary functor.
+TEST(InvokeArgumentTest, Functor5) {
+ Action<int(SumOf5Functor)> a = // NOLINT
+ InvokeArgument<0>(10000, 2000, 300, 40, 5);
+ EXPECT_EQ(12345, a.Perform(std::make_tuple(SumOf5Functor())));
+}
+
+// Tests using InvokeArgument with a 6-ary function.
+TEST(InvokeArgumentTest, Function6) {
+ Action<int(int (*)(int, int, int, int, int, int))> a = // NOLINT
+ InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
+ EXPECT_EQ(123456, a.Perform(std::make_tuple(&SumOf6)));
+}
+
+// Tests using InvokeArgument with a 6-ary functor.
+TEST(InvokeArgumentTest, Functor6) {
+ Action<int(SumOf6Functor)> a = // NOLINT
+ InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
+ EXPECT_EQ(123456, a.Perform(std::make_tuple(SumOf6Functor())));
+}
+
+// Tests using InvokeArgument with a 7-ary function.
+TEST(InvokeArgumentTest, Function7) {
+ Action<std::string(std::string(*)(const char*, const char*, const char*,
+ const char*, const char*, const char*,
+ const char*))>
+ a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7");
+ EXPECT_EQ("1234567", a.Perform(std::make_tuple(&Concat7)));
+}
+
+// Tests using InvokeArgument with a 8-ary function.
+TEST(InvokeArgumentTest, Function8) {
+ Action<std::string(std::string(*)(const char*, const char*, const char*,
+ const char*, const char*, const char*,
+ const char*, const char*))>
+ a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8");
+ EXPECT_EQ("12345678", a.Perform(std::make_tuple(&Concat8)));
+}
+
+// Tests using InvokeArgument with a 9-ary function.
+TEST(InvokeArgumentTest, Function9) {
+ Action<std::string(std::string(*)(const char*, const char*, const char*,
+ const char*, const char*, const char*,
+ const char*, const char*, const char*))>
+ a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9");
+ EXPECT_EQ("123456789", a.Perform(std::make_tuple(&Concat9)));
+}
+
+// Tests using InvokeArgument with a 10-ary function.
+TEST(InvokeArgumentTest, Function10) {
+ Action<std::string(std::string(*)(
+ const char*, const char*, const char*, const char*, const char*,
+ const char*, const char*, const char*, const char*, const char*))>
+ a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
+ EXPECT_EQ("1234567890", a.Perform(std::make_tuple(&Concat10)));
+}
+
+// Tests using InvokeArgument with a function that takes a pointer argument.
+TEST(InvokeArgumentTest, ByPointerFunction) {
+ Action<const char*(const char* (*)(const char* input, short n))> // NOLINT
+ a = InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1));
+ EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary)));
+}
+
+// Tests using InvokeArgument with a function that takes a const char*
+// by passing it a C-string literal.
+TEST(InvokeArgumentTest, FunctionWithCStringLiteral) {
+ Action<const char*(const char* (*)(const char* input, short n))> // NOLINT
+ a = InvokeArgument<0>("Hi", Short(1));
+ EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary)));
+}
+
+// Tests using InvokeArgument with a function that takes a const reference.
+TEST(InvokeArgumentTest, ByConstReferenceFunction) {
+ Action<bool(bool (*function)(const std::string& s))> a = // NOLINT
+ InvokeArgument<0>(std::string("Hi"));
+ // When action 'a' is constructed, it makes a copy of the temporary
+ // string object passed to it, so it's OK to use 'a' later, when the
+ // temporary object has already died.
+ EXPECT_TRUE(a.Perform(std::make_tuple(&ByConstRef)));
+}
+
+// Tests using InvokeArgument with ByRef() and a function that takes a
+// const reference.
+TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) {
+ Action<bool(bool (*)(const double& x))> a = // NOLINT
+ InvokeArgument<0>(ByRef(g_double));
+ // The above line calls ByRef() on a const value.
+ EXPECT_TRUE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
+
+ double x = 0;
+ a = InvokeArgument<0>(ByRef(x)); // This calls ByRef() on a non-const.
+ EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
+}
+
+// Tests DoAll(a1, a2).
+TEST(DoAllTest, TwoActions) {
+ int n = 0;
+ Action<int(int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT
+ Return(2));
+ EXPECT_EQ(2, a.Perform(std::make_tuple(&n)));
+ EXPECT_EQ(1, n);
+}
+
+// Tests DoAll(a1, a2, a3).
+TEST(DoAllTest, ThreeActions) {
+ int m = 0, n = 0;
+ Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT
+ SetArgPointee<1>(2), Return(3));
+ EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+}
+
+// Tests DoAll(a1, a2, a3, a4).
+TEST(DoAllTest, FourActions) {
+ int m = 0, n = 0;
+ char ch = '\0';
+ Action<int(int*, int*, char*)> a = // NOLINT
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ Return(3));
+ EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n, &ch)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', ch);
+}
+
+// Tests DoAll(a1, a2, a3, a4, a5).
+TEST(DoAllTest, FiveActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0';
+ Action<int(int*, int*, char*, char*)> action = // NOLINT
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ SetArgPointee<3>('b'), Return(3));
+ EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+}
+
+// Tests DoAll(a1, a2, ..., a6).
+TEST(DoAllTest, SixActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0', c = '\0';
+ Action<int(int*, int*, char*, char*, char*)> action = // NOLINT
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ SetArgPointee<3>('b'), SetArgPointee<4>('c'), Return(3));
+ EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+ EXPECT_EQ('c', c);
+}
+
+// Tests DoAll(a1, a2, ..., a7).
+TEST(DoAllTest, SevenActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0', c = '\0', d = '\0';
+ Action<int(int*, int*, char*, char*, char*, char*)> action = // NOLINT
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'),
+ Return(3));
+ EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+ EXPECT_EQ('c', c);
+ EXPECT_EQ('d', d);
+}
+
+// Tests DoAll(a1, a2, ..., a8).
+TEST(DoAllTest, EightActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0';
+ Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
+ char*)>
+ action =
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ SetArgPointee<3>('b'), SetArgPointee<4>('c'),
+ SetArgPointee<5>('d'), SetArgPointee<6>('e'), Return(3));
+ EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+ EXPECT_EQ('c', c);
+ EXPECT_EQ('d', d);
+ EXPECT_EQ('e', e);
+}
+
+// Tests DoAll(a1, a2, ..., a9).
+TEST(DoAllTest, NineActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0', f = '\0';
+ Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
+ char*, char*)>
+ action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2),
+ SetArgPointee<2>('a'), SetArgPointee<3>('b'),
+ SetArgPointee<4>('c'), SetArgPointee<5>('d'),
+ SetArgPointee<6>('e'), SetArgPointee<7>('f'), Return(3));
+ EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+ EXPECT_EQ('c', c);
+ EXPECT_EQ('d', d);
+ EXPECT_EQ('e', e);
+ EXPECT_EQ('f', f);
+}
+
+// Tests DoAll(a1, a2, ..., a10).
+TEST(DoAllTest, TenActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0', c = '\0', d = '\0';
+ char e = '\0', f = '\0', g = '\0';
+ Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
+ char*, char*, char*)>
+ action =
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ SetArgPointee<3>('b'), SetArgPointee<4>('c'),
+ SetArgPointee<5>('d'), SetArgPointee<6>('e'),
+ SetArgPointee<7>('f'), SetArgPointee<8>('g'), Return(3));
+ EXPECT_EQ(
+ 3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+ EXPECT_EQ('c', c);
+ EXPECT_EQ('d', d);
+ EXPECT_EQ('e', e);
+ EXPECT_EQ('f', f);
+ EXPECT_EQ('g', g);
+}
+
+TEST(DoAllTest, NoArgs) {
+ bool ran_first = false;
+ Action<bool()> a =
+ DoAll([&] { ran_first = true; }, [&] { return ran_first; });
+ EXPECT_TRUE(a.Perform({}));
+}
+
+TEST(DoAllTest, MoveOnlyArgs) {
+ bool ran_first = false;
+ Action<int(std::unique_ptr<int>)> a =
+ DoAll(InvokeWithoutArgs([&] { ran_first = true; }),
+ [](std::unique_ptr<int> p) { return *p; });
+ EXPECT_EQ(7, a.Perform(std::make_tuple(std::unique_ptr<int>(new int(7)))));
+ EXPECT_TRUE(ran_first);
+}
+
+TEST(DoAllTest, ImplicitlyConvertsActionArguments) {
+ bool ran_first = false;
+ // Action<void(std::vector<int>)> isn't an
+ // Action<void(const std::vector<int>&) but can be converted.
+ Action<void(std::vector<int>)> first = [&] { ran_first = true; };
+ Action<int(std::vector<int>)> a =
+ DoAll(first, [](std::vector<int> arg) { return arg.front(); });
+ EXPECT_EQ(7, a.Perform(std::make_tuple(std::vector<int>{7})));
+ EXPECT_TRUE(ran_first);
+}
+
+// The ACTION*() macros trigger warning C4100 (unreferenced formal
+// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
+// the macro definition, as the warnings are generated when the macro
+// is expanded and macro expansion cannot contain #pragma. Therefore
+// we suppress them here.
+// Also suppress C4503 decorated name length exceeded, name was truncated
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503)
+// Tests the ACTION*() macro family.
+
+// Tests that ACTION() can define an action that doesn't reference the
+// mock function arguments.
+ACTION(Return5) { return 5; }
+
+TEST(ActionMacroTest, WorksWhenNotReferencingArguments) {
+ Action<double()> a1 = Return5();
+ EXPECT_DOUBLE_EQ(5, a1.Perform(std::make_tuple()));
+
+ Action<int(double, bool)> a2 = Return5();
+ EXPECT_EQ(5, a2.Perform(std::make_tuple(1, true)));
+}
+
+// Tests that ACTION() can define an action that returns void.
+ACTION(IncrementArg1) { (*arg1)++; }
+
+TEST(ActionMacroTest, WorksWhenReturningVoid) {
+ Action<void(int, int*)> a1 = IncrementArg1();
+ int n = 0;
+ a1.Perform(std::make_tuple(5, &n));
+ EXPECT_EQ(1, n);
+}
+
+// Tests that the body of ACTION() can reference the type of the
+// argument.
+ACTION(IncrementArg2) {
+ StaticAssertTypeEq<int*, arg2_type>();
+ arg2_type temp = arg2;
+ (*temp)++;
+}
+
+TEST(ActionMacroTest, CanReferenceArgumentType) {
+ Action<void(int, bool, int*)> a1 = IncrementArg2();
+ int n = 0;
+ a1.Perform(std::make_tuple(5, false, &n));
+ EXPECT_EQ(1, n);
+}
+
+// Tests that the body of ACTION() can reference the argument tuple
+// via args_type and args.
+ACTION(Sum2) {
+ StaticAssertTypeEq<std::tuple<int, char, int*>, args_type>();
+ args_type args_copy = args;
+ return std::get<0>(args_copy) + std::get<1>(args_copy);
+}
+
+TEST(ActionMacroTest, CanReferenceArgumentTuple) {
+ Action<int(int, char, int*)> a1 = Sum2();
+ int dummy = 0;
+ EXPECT_EQ(11, a1.Perform(std::make_tuple(5, Char(6), &dummy)));
+}
+
+namespace {
+
+// Tests that the body of ACTION() can reference the mock function
+// type.
+int Dummy(bool flag) { return flag ? 1 : 0; }
+
+} // namespace
+
+ACTION(InvokeDummy) {
+ StaticAssertTypeEq<int(bool), function_type>();
+ function_type* fp = &Dummy;
+ return (*fp)(true);
+}
+
+TEST(ActionMacroTest, CanReferenceMockFunctionType) {
+ Action<int(bool)> a1 = InvokeDummy();
+ EXPECT_EQ(1, a1.Perform(std::make_tuple(true)));
+ EXPECT_EQ(1, a1.Perform(std::make_tuple(false)));
+}
+
+// Tests that the body of ACTION() can reference the mock function's
+// return type.
+ACTION(InvokeDummy2) {
+ StaticAssertTypeEq<int, return_type>();
+ return_type result = Dummy(true);
+ return result;
+}
+
+TEST(ActionMacroTest, CanReferenceMockFunctionReturnType) {
+ Action<int(bool)> a1 = InvokeDummy2();
+ EXPECT_EQ(1, a1.Perform(std::make_tuple(true)));
+ EXPECT_EQ(1, a1.Perform(std::make_tuple(false)));
+}
+
+// Tests that ACTION() works for arguments passed by const reference.
+ACTION(ReturnAddrOfConstBoolReferenceArg) {
+ StaticAssertTypeEq<const bool&, arg1_type>();
+ return &arg1;
+}
+
+TEST(ActionMacroTest, WorksForConstReferenceArg) {
+ Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg();
+ const bool b = false;
+ EXPECT_EQ(&b, a.Perform(std::tuple<int, const bool&>(0, b)));
+}
+
+// Tests that ACTION() works for arguments passed by non-const reference.
+ACTION(ReturnAddrOfIntReferenceArg) {
+ StaticAssertTypeEq<int&, arg0_type>();
+ return &arg0;
+}
+
+TEST(ActionMacroTest, WorksForNonConstReferenceArg) {
+ Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg();
+ int n = 0;
+ EXPECT_EQ(&n, a.Perform(std::tuple<int&, bool, int>(n, true, 1)));
+}
+
+// Tests that ACTION() can be used in a namespace.
+namespace action_test {
+ACTION(Sum) { return arg0 + arg1; }
+} // namespace action_test
+
+TEST(ActionMacroTest, WorksInNamespace) {
+ Action<int(int, int)> a1 = action_test::Sum();
+ EXPECT_EQ(3, a1.Perform(std::make_tuple(1, 2)));
+}
+
+// Tests that the same ACTION definition works for mock functions with
+// different argument numbers.
+ACTION(PlusTwo) { return arg0 + 2; }
+
+TEST(ActionMacroTest, WorksForDifferentArgumentNumbers) {
+ Action<int(int)> a1 = PlusTwo();
+ EXPECT_EQ(4, a1.Perform(std::make_tuple(2)));
+
+ Action<double(float, void*)> a2 = PlusTwo();
+ int dummy;
+ EXPECT_DOUBLE_EQ(6, a2.Perform(std::make_tuple(4.0f, &dummy)));
+}
+
+// Tests that ACTION_P can define a parameterized action.
+ACTION_P(Plus, n) { return arg0 + n; }
+
+TEST(ActionPMacroTest, DefinesParameterizedAction) {
+ Action<int(int m, bool t)> a1 = Plus(9);
+ EXPECT_EQ(10, a1.Perform(std::make_tuple(1, true)));
+}
+
+// Tests that the body of ACTION_P can reference the argument types
+// and the parameter type.
+ACTION_P(TypedPlus, n) {
+ arg0_type t1 = arg0;
+ n_type t2 = n;
+ return t1 + t2;
+}
+
+TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) {
+ Action<int(char m, bool t)> a1 = TypedPlus(9);
+ EXPECT_EQ(10, a1.Perform(std::make_tuple(Char(1), true)));
+}
+
+// Tests that a parameterized action can be used in any mock function
+// whose type is compatible.
+TEST(ActionPMacroTest, WorksInCompatibleMockFunction) {
+ Action<std::string(const std::string& s)> a1 = Plus("tail");
+ const std::string re = "re";
+ std::tuple<const std::string> dummy = std::make_tuple(re);
+ EXPECT_EQ("retail", a1.Perform(dummy));
+}
+
+// Tests that we can use ACTION*() to define actions overloaded on the
+// number of parameters.
+
+ACTION(OverloadedAction) { return arg0 ? arg1 : "hello"; }
+
+ACTION_P(OverloadedAction, default_value) {
+ return arg0 ? arg1 : default_value;
+}
+
+ACTION_P2(OverloadedAction, true_value, false_value) {
+ return arg0 ? true_value : false_value;
+}
+
+TEST(ActionMacroTest, CanDefineOverloadedActions) {
+ using MyAction = Action<const char*(bool, const char*)>;
+
+ const MyAction a1 = OverloadedAction();
+ EXPECT_STREQ("hello", a1.Perform(std::make_tuple(false, CharPtr("world"))));
+ EXPECT_STREQ("world", a1.Perform(std::make_tuple(true, CharPtr("world"))));
+
+ const MyAction a2 = OverloadedAction("hi");
+ EXPECT_STREQ("hi", a2.Perform(std::make_tuple(false, CharPtr("world"))));
+ EXPECT_STREQ("world", a2.Perform(std::make_tuple(true, CharPtr("world"))));
+
+ const MyAction a3 = OverloadedAction("hi", "you");
+ EXPECT_STREQ("hi", a3.Perform(std::make_tuple(true, CharPtr("world"))));
+ EXPECT_STREQ("you", a3.Perform(std::make_tuple(false, CharPtr("world"))));
+}
+
+// Tests ACTION_Pn where n >= 3.
+
+ACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; }
+
+TEST(ActionPnMacroTest, WorksFor3Parameters) {
+ Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4);
+ EXPECT_DOUBLE_EQ(3123.4, a1.Perform(std::make_tuple(3000, true)));
+
+ Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">");
+ const std::string re = "re";
+ std::tuple<const std::string> dummy = std::make_tuple(re);
+ EXPECT_EQ("retail->", a2.Perform(dummy));
+}
+
+ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; }
+
+TEST(ActionPnMacroTest, WorksFor4Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; }
+
+TEST(ActionPnMacroTest, WorksFor5Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) {
+ return arg0 + p0 + p1 + p2 + p3 + p4 + p5;
+}
+
+TEST(ActionPnMacroTest, WorksFor6Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) {
+ return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6;
+}
+
+TEST(ActionPnMacroTest, WorksFor7Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) {
+ return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7;
+}
+
+TEST(ActionPnMacroTest, WorksFor8Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
+ a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) {
+ return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8;
+}
+
+TEST(ActionPnMacroTest, WorksFor9Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9,
+ a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) {
+ arg0_type t0 = arg0;
+ last_param_type t9 = last_param;
+ return t0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + t9;
+}
+
+TEST(ActionPnMacroTest, WorksFor10Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
+ a1.Perform(std::make_tuple(10)));
+}
+
+// Tests that the action body can promote the parameter types.
+
+ACTION_P2(PadArgument, 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 prefix_str + arg0 + suffix_char;
+}
+
+TEST(ActionPnMacroTest, SimpleTypePromotion) {
+ Action<std::string(const char*)> no_promo =
+ PadArgument(std::string("foo"), 'r');
+ Action<std::string(const char*)> promo =
+ PadArgument("foo", static_cast<int>('r'));
+ EXPECT_EQ("foobar", no_promo.Perform(std::make_tuple(CharPtr("ba"))));
+ EXPECT_EQ("foobar", promo.Perform(std::make_tuple(CharPtr("ba"))));
+}
+
+// Tests that we can partially restrict parameter types using a
+// straight-forward pattern.
+
+// Defines a generic action that doesn't restrict the types of its
+// parameters.
+ACTION_P3(ConcatImpl, a, b, c) {
+ std::stringstream ss;
+ ss << a << b << c;
+ return ss.str();
+}
+
+// Next, we try to restrict that either the first parameter is a
+// string, or the second parameter is an int.
+
+// Defines a partially specialized wrapper that restricts the first
+// parameter to std::string.
+template <typename T1, typename T2>
+// ConcatImplActionP3 is the class template ACTION_P3 uses to
+// implement ConcatImpl. We shouldn't change the name as this
+// pattern requires the user to use it directly.
+ConcatImplActionP3<std::string, T1, T2> Concat(const std::string& a, T1 b,
+ T2 c) {
+ GTEST_INTENTIONAL_CONST_COND_PUSH_()
+ if (true) {
+ GTEST_INTENTIONAL_CONST_COND_POP_()
+ // This branch verifies that ConcatImpl() can be invoked without
+ // explicit template arguments.
+ return ConcatImpl(a, b, c);
+ } else {
+ // This branch verifies that ConcatImpl() can also be invoked with
+ // explicit template arguments. It doesn't really need to be
+ // executed as this is a compile-time verification.
+ return ConcatImpl<std::string, T1, T2>(a, b, c);
+ }
+}
+
+// Defines another partially specialized wrapper that restricts the
+// second parameter to int.
+template <typename T1, typename T2>
+ConcatImplActionP3<T1, int, T2> Concat(T1 a, int b, T2 c) {
+ return ConcatImpl(a, b, c);
+}
+
+TEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) {
+ Action<const std::string()> a1 = Concat("Hello", "1", 2);
+ EXPECT_EQ("Hello12", a1.Perform(std::make_tuple()));
+
+ a1 = Concat(1, 2, 3);
+ EXPECT_EQ("123", a1.Perform(std::make_tuple()));
+}
+
+// Verifies the type of an ACTION*.
+
+ACTION(DoFoo) {}
+ACTION_P(DoFoo, p) {}
+ACTION_P2(DoFoo, p0, p1) {}
+
+TEST(ActionPnMacroTest, TypesAreCorrect) {
+ // DoFoo() must be assignable to a DoFooAction variable.
+ DoFooAction a0 = DoFoo();
+
+ // DoFoo(1) must be assignable to a DoFooActionP variable.
+ DoFooActionP<int> a1 = DoFoo(1);
+
+ // DoFoo(p1, ..., pk) must be assignable to a DoFooActionPk
+ // variable, and so on.
+ DoFooActionP2<int, char> a2 = DoFoo(1, '2');
+ PlusActionP3<int, int, char> a3 = Plus(1, 2, '3');
+ PlusActionP4<int, int, int, char> a4 = Plus(1, 2, 3, '4');
+ PlusActionP5<int, int, int, int, char> a5 = Plus(1, 2, 3, 4, '5');
+ PlusActionP6<int, int, int, int, int, char> a6 = Plus(1, 2, 3, 4, 5, '6');
+ PlusActionP7<int, int, int, int, int, int, char> a7 =
+ Plus(1, 2, 3, 4, 5, 6, '7');
+ PlusActionP8<int, int, int, int, int, int, int, char> a8 =
+ Plus(1, 2, 3, 4, 5, 6, 7, '8');
+ PlusActionP9<int, int, int, int, int, int, int, int, char> a9 =
+ Plus(1, 2, 3, 4, 5, 6, 7, 8, '9');
+ PlusActionP10<int, int, int, int, int, int, int, int, int, char> a10 =
+ Plus(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 an ACTION_P*() action can be explicitly instantiated
+// with reference-typed parameters.
+
+ACTION_P(Plus1, x) { return x; }
+ACTION_P2(Plus2, x, y) { return x + y; }
+ACTION_P3(Plus3, x, y, z) { return x + y + z; }
+ACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
+ return a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9;
+}
+
+TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) {
+ int x = 1, y = 2, z = 3;
+ const std::tuple<> empty = std::make_tuple();
+
+ Action<int()> a = Plus1<int&>(x);
+ EXPECT_EQ(1, a.Perform(empty));
+
+ a = Plus2<const int&, int&>(x, y);
+ EXPECT_EQ(3, a.Perform(empty));
+
+ a = Plus3<int&, const int&, int&>(x, y, z);
+ EXPECT_EQ(6, a.Perform(empty));
+
+ int n[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
+ a = Plus10<const int&, int&, const int&, int&, const int&, int&, const int&,
+ int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6],
+ n[7], n[8], n[9]);
+ EXPECT_EQ(55, a.Perform(empty));
+}
+
+class TenArgConstructorClass {
+ public:
+ TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
+ int a8, int a9, int a10)
+ : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
+ int value_;
+};
+
+// Tests that ACTION_TEMPLATE works when there is no value parameter.
+ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T),
+ AND_0_VALUE_PARAMS()) {
+ return new T;
+}
+
+TEST(ActionTemplateTest, WorksWithoutValueParam) {
+ const Action<int*()> a = CreateNew<int>();
+ int* p = a.Perform(std::make_tuple());
+ delete p;
+}
+
+// Tests that ACTION_TEMPLATE works when there are value parameters.
+ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T),
+ AND_1_VALUE_PARAMS(a0)) {
+ return new T(a0);
+}
+
+TEST(ActionTemplateTest, WorksWithValueParams) {
+ const Action<int*()> a = CreateNew<int>(42);
+ int* p = a.Perform(std::make_tuple());
+ EXPECT_EQ(42, *p);
+ delete p;
+}
+
+// Tests that ACTION_TEMPLATE works for integral template parameters.
+ACTION_TEMPLATE(MyDeleteArg, HAS_1_TEMPLATE_PARAMS(int, k),
+ AND_0_VALUE_PARAMS()) {
+ delete std::get<k>(args);
+}
+
+// Resets a bool variable in the destructor.
+class BoolResetter {
+ public:
+ explicit BoolResetter(bool* value) : value_(value) {}
+ ~BoolResetter() { *value_ = false; }
+
+ private:
+ bool* value_;
+};
+
+TEST(ActionTemplateTest, WorksForIntegralTemplateParams) {
+ const Action<void(int*, BoolResetter*)> a = MyDeleteArg<1>();
+ int n = 0;
+ bool b = true;
+ auto* resetter = new BoolResetter(&b);
+ a.Perform(std::make_tuple(&n, resetter));
+ EXPECT_FALSE(b); // Verifies that resetter is deleted.
+}
+
+// Tests that ACTION_TEMPLATES works for template template parameters.
+ACTION_TEMPLATE(ReturnSmartPointer,
+ HAS_1_TEMPLATE_PARAMS(template <typename Pointee> class,
+ Pointer),
+ AND_1_VALUE_PARAMS(pointee)) {
+ return Pointer<pointee_type>(new pointee_type(pointee));
+}
+
+TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) {
+ const Action<std::shared_ptr<int>()> a =
+ ReturnSmartPointer<std::shared_ptr>(42);
+ std::shared_ptr<int> p = a.Perform(std::make_tuple());
+ EXPECT_EQ(42, *p);
+}
+
+// Tests that ACTION_TEMPLATE works for 10 template parameters.
+template <typename T1, typename T2, typename T3, int k4, bool k5,
+ unsigned int k6, typename T7, typename T8, typename T9>
+struct GiantTemplate {
+ public:
+ explicit GiantTemplate(int a_value) : value(a_value) {}
+ int value;
+};
+
+ACTION_TEMPLATE(ReturnGiant,
+ HAS_10_TEMPLATE_PARAMS(typename, T1, typename, T2, typename, T3,
+ int, k4, bool, k5, unsigned int, k6,
+ class, T7, class, T8, class, T9,
+ template <typename T> class, T10),
+ AND_1_VALUE_PARAMS(value)) {
+ return GiantTemplate<T10<T1>, T2, T3, k4, k5, k6, T7, T8, T9>(value);
+}
+
+TEST(ActionTemplateTest, WorksFor10TemplateParameters) {
+ using Giant = GiantTemplate<std::shared_ptr<int>, bool, double, 5, true, 6,
+ char, unsigned, int>;
+ const Action<Giant()> a = ReturnGiant<int, bool, double, 5, true, 6, char,
+ unsigned, int, std::shared_ptr>(42);
+ Giant giant = a.Perform(std::make_tuple());
+ EXPECT_EQ(42, giant.value);
+}
+
+// Tests that ACTION_TEMPLATE works for 10 value parameters.
+ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),
+ AND_10_VALUE_PARAMS(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10)) {
+ return static_cast<Number>(v1) + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10;
+}
+
+TEST(ActionTemplateTest, WorksFor10ValueParameters) {
+ const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ EXPECT_EQ(55, a.Perform(std::make_tuple()));
+}
+
+// Tests that ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded
+// on the number of value parameters.
+
+ACTION(ReturnSum) { return 0; }
+
+ACTION_P(ReturnSum, x) { return x; }
+
+ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),
+ AND_2_VALUE_PARAMS(v1, v2)) {
+ return static_cast<Number>(v1) + v2;
+}
+
+ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),
+ AND_3_VALUE_PARAMS(v1, v2, v3)) {
+ return static_cast<Number>(v1) + v2 + v3;
+}
+
+ACTION_TEMPLATE(ReturnSum, HAS_2_TEMPLATE_PARAMS(typename, Number, int, k),
+ AND_4_VALUE_PARAMS(v1, v2, v3, v4)) {
+ return static_cast<Number>(v1) + v2 + v3 + v4 + k;
+}
+
+TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) {
+ const Action<int()> a0 = ReturnSum();
+ const Action<int()> a1 = ReturnSum(1);
+ const Action<int()> a2 = ReturnSum<int>(1, 2);
+ const Action<int()> a3 = ReturnSum<int>(1, 2, 3);
+ const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5);
+ EXPECT_EQ(0, a0.Perform(std::make_tuple()));
+ EXPECT_EQ(1, a1.Perform(std::make_tuple()));
+ EXPECT_EQ(3, a2.Perform(std::make_tuple()));
+ EXPECT_EQ(6, a3.Perform(std::make_tuple()));
+ EXPECT_EQ(12345, a4.Perform(std::make_tuple()));
+}
+
+} // namespace gmock_more_actions_test
} // namespace testing
+
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4503
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4577
diff --git a/googlemock/test/gmock-nice-strict_test.cc b/googlemock/test/gmock-nice-strict_test.cc
index 0a201ed7ebb0..95f096903583 100644
--- a/googlemock/test/gmock-nice-strict_test.cc
+++ b/googlemock/test/gmock-nice-strict_test.cc
@@ -31,6 +31,7 @@
#include <string>
#include <utility>
+
#include "gmock/gmock.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
@@ -39,18 +40,18 @@
// clash with ::testing::Mock.
class Mock {
public:
- Mock() {}
+ Mock() = default;
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;
@@ -67,11 +68,17 @@ class NotDefaultConstructible {
explicit NotDefaultConstructible(int) {}
};
+class CallsMockMethodInDestructor {
+ public:
+ ~CallsMockMethodInDestructor() { OnDestroy(); }
+ MOCK_METHOD(void, OnDestroy, ());
+};
+
// Defines some mock classes needed by the tests.
class Foo {
public:
- virtual ~Foo() {}
+ virtual ~Foo() = default;
virtual void DoThis() = 0;
virtual int DoThat(bool flag) = 0;
@@ -79,7 +86,7 @@ class Foo {
class MockFoo : public Foo {
public:
- MockFoo() {}
+ MockFoo() = default;
void Delete() { delete this; }
MOCK_METHOD0(DoThis, void());
@@ -87,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 {
@@ -97,10 +105,11 @@ 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() {}
+ virtual ~MockBar() = default;
const std::string& str() const { return str_; }
@@ -110,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 {
@@ -134,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;
@@ -145,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
@@ -172,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) {
@@ -217,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
@@ -275,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();
@@ -302,6 +310,13 @@ TEST(NiceMockTest, AcceptsClassNamedMock) {
nice.DoThis();
}
+TEST(NiceMockTest, IsNiceInDestructor) {
+ {
+ NiceMock<CallsMockMethodInDestructor> nice_on_destroy;
+ // Don't add an expectation for the call before the mock goes out of scope.
+ }
+}
+
TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) {
NiceMock<MockFoo> nice_foo;
EXPECT_FALSE(Mock::IsNaggy(&nice_foo));
@@ -313,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;
@@ -324,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>;
@@ -343,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
@@ -378,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();
@@ -405,6 +420,22 @@ TEST(NaggyMockTest, AcceptsClassNamedMock) {
naggy.DoThis();
}
+TEST(NaggyMockTest, IsNaggyInDestructor) {
+ const std::string saved_flag = GMOCK_FLAG_GET(verbose);
+ GMOCK_FLAG_SET(verbose, "warning");
+ CaptureStdout();
+
+ {
+ NaggyMock<CallsMockMethodInDestructor> naggy_on_destroy;
+ // Don't add an expectation for the call before the mock goes out of scope.
+ }
+
+ EXPECT_THAT(GetCapturedStdout(),
+ HasSubstr("Uninteresting mock function call"));
+
+ GMOCK_FLAG_SET(verbose, saved_flag);
+}
+
TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) {
NaggyMock<MockFoo> naggy_foo;
EXPECT_TRUE(Mock::IsNaggy(&naggy_foo));
@@ -462,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),
@@ -489,6 +520,16 @@ TEST(StrictMockTest, AcceptsClassNamedMock) {
strict.DoThis();
}
+TEST(StrictMockTest, IsStrictInDestructor) {
+ EXPECT_NONFATAL_FAILURE(
+ {
+ StrictMock<CallsMockMethodInDestructor> strict_on_destroy;
+ // Don't add an expectation for the call before the mock goes out of
+ // scope.
+ },
+ "Uninteresting mock function call");
+}
+
TEST(StrictMockTest, IsNaggy_IsNice_IsStrict) {
StrictMock<MockFoo> strict_foo;
EXPECT_FALSE(Mock::IsNaggy(&strict_foo));
diff --git a/googlemock/test/gmock-port_test.cc b/googlemock/test/gmock-port_test.cc
index a2c2be248864..c31af821559b 100644
--- a/googlemock/test/gmock-port_test.cc
+++ b/googlemock/test/gmock-port_test.cc
@@ -27,12 +27,12 @@
// (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
diff --git a/googlemock/test/gmock-pp-string_test.cc b/googlemock/test/gmock-pp-string_test.cc
index 6f66cf156a90..53c80f4e3d2f 100644
--- a/googlemock/test/gmock-pp-string_test.cc
+++ b/googlemock/test/gmock-pp-string_test.cc
@@ -30,11 +30,10 @@
// 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 {
diff --git a/googlemock/test/gmock-pp_test.cc b/googlemock/test/gmock-pp_test.cc
index 7387d3989974..5d1566e38853 100644
--- a/googlemock/test/gmock-pp_test.cc
+++ b/googlemock/test/gmock-pp_test.cc
@@ -1,5 +1,10 @@
#include "gmock/internal/gmock-pp.h"
+// Used to test MSVC treating __VA_ARGS__ with a comma in it as one value
+#define GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_comma ,
+#define GMOCK_TEST_REPLACE_comma_WITH_COMMA(x) \
+ GMOCK_PP_CAT(GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_, x)
+
// Static assertions.
namespace testing {
namespace internal {
@@ -17,6 +22,11 @@ static_assert(GMOCK_PP_NARG(x, y, z, w) == 4, "");
static_assert(!GMOCK_PP_HAS_COMMA(), "");
static_assert(GMOCK_PP_HAS_COMMA(b, ), "");
static_assert(!GMOCK_PP_HAS_COMMA((, )), "");
+static_assert(GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma)),
+ "");
+static_assert(
+ GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma(unrelated))),
+ "");
static_assert(!GMOCK_PP_IS_EMPTY(, ), "");
static_assert(!GMOCK_PP_IS_EMPTY(a), "");
static_assert(!GMOCK_PP_IS_EMPTY(()), "");
diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc
index 7bf5a8ad7bfa..221de2d20b3d 100644
--- a/googlemock/test/gmock-spec-builders_test.cc
+++ b/googlemock/test/gmock-spec-builders_test.cc
@@ -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.
@@ -38,74 +37,28 @@
#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::ContainsRegex;
-using testing::Const;
-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
@@ -146,7 +98,7 @@ class NonDefaultConstructible {
class MockA {
public:
- MockA() {}
+ MockA() = default;
MOCK_METHOD1(DoA, void(int n));
MOCK_METHOD1(ReturnResult, Result(int n));
@@ -155,28 +107,31 @@ 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 {
public:
- MockB() {}
+ MockB() = default;
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 {
public:
- ReferenceHoldingMock() {}
+ ReferenceHoldingMock() = default;
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
@@ -188,17 +143,18 @@ class ReferenceHoldingMock {
class CC {
public:
- virtual ~CC() {}
+ virtual ~CC() = default;
virtual int Method() = 0;
};
class MockCC : public CC {
public:
- MockCC() {}
+ MockCC() = default;
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,25 @@ 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)).Description("DoB Method").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 \"DoB Method\" 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 +754,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 +782,79 @@ 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(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
+ GTEST_INTERNAL_CPLUSPLUS_LANG >= 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 NonMoveableStruct {
+ explicit NonMoveableStruct(int x_in) : x(x_in) {}
+ NonMoveableStruct(NonMoveableStruct&&) = delete;
+
+ int x;
+ };
+
+ static_assert(!std::is_move_constructible_v<NonMoveableStruct>);
+ static_assert(!std::is_copy_constructible_v<NonMoveableStruct>);
+
+ static_assert(!std::is_move_assignable_v<NonMoveableStruct>);
+ static_assert(!std::is_copy_assignable_v<NonMoveableStruct>);
+
+ // 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 NonMoveableStruct(17); };
+
+ static_cast<void>(OnceAction<NonMoveableStruct()>{return_17});
+ static_cast<void>(Action<NonMoveableStruct()>{return_17});
+
+ static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17});
+ static_cast<void>(Action<NonMoveableStruct(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<NonMoveableStruct()> 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 +865,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 +878,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 +940,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 +954,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 +965,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 +1044,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,27 +1058,21 @@ 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);
}
// Tests that Google Mock explains that an expectation with
// unsatisfied pre-requisites doesn't match the call.
-TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
+TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {
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;
{
@@ -1146,27 +1089,22 @@ 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"));
-#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"));
+#ifdef 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"));
#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
+#endif // GTEST_USES_POSIX_RE
b.DoB(1);
b.DoB(3);
@@ -1192,8 +1130,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,11 +1141,11 @@ 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)).Description("DoB Method").Times(0);
int n = -1;
- EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
- "Mock function called more times than expected");
+ EXPECT_NONFATAL_FAILURE(
+ n = b.DoB(0),
+ "Mock function \"DoB Method\" called more times than expected");
EXPECT_EQ(0, n);
}
@@ -1216,11 +1153,11 @@ 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(_)).Description("DoA Method").Times(0);
EXPECT_NONFATAL_FAILURE(
a.DoA(9),
- "Mock function called more times than expected - returning directly.\n"
+ "Mock function \"DoA Method\" called more times than expected - "
+ "returning directly.\n"
" Function call: DoA(9)\n"
" Expected: to be never called\n"
" Actual: called once - over-saturated and active");
@@ -1253,9 +1190,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 +1214,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 +1235,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 +1253,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 +1264,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 +1275,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 +1295,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 +1312,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 +1320,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 +1375,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 +1442,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 +1519,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 +1529,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 +1542,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 +1559,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 +1579,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 +1595,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 +1621,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 +1638,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 +1655,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 +1671,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 +1684,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 +1694,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 +1711,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 +1730,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 +1755,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.
@@ -1875,16 +1771,11 @@ TEST(DeletingMockEarlyTest, Success2) {
// Suppresses warning on unreferenced formal parameter in MSVC with
// -W4.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
ACTION_P(Delete, ptr) { delete ptr; }
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
MockA* const a = new MockA;
@@ -1894,8 +1785,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 +1797,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 +1818,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 +1849,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 +1869,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";
@@ -2011,29 +1882,32 @@ struct Unprintable {
class MockC {
public:
- MockC() {}
+ MockC() = default;
MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
const Printable& x, Unprintable y));
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 +1917,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 +1931,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 +1939,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 +1955,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 +1971,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 +1980,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 +2002,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 +2019,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.
@@ -2179,41 +2049,37 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
"call should not happen. Do not suppress it by blindly adding "
"an EXPECT_CALL() if you don't mean to enforce the call. "
"See "
- "https://github.com/google/googletest/blob/master/googlemock/docs/"
- "cook_book.md#"
- "knowing-when-to-expect for details.";
+ "https://github.com/google/googletest/blob/main/docs/"
+ "gmock_cook_book.md#"
+ "knowing-when-to-expect-useoncall for details.";
// 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 +2087,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 +2095,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 +2103,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);
}
@@ -2256,12 +2122,13 @@ void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
class LogTestHelper {
public:
- LogTestHelper() {}
+ LogTestHelper() = default;
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 +2137,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 +2211,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 +2226,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 +2242,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 +2258,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 +2280,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 +2304,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 +2316,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 +2332,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 +2347,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 +2361,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 +2377,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 +2396,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 +2414,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 +2434,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 +2481,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 +2502,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 +2587,14 @@ 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) {
-#else
-int main(int argc, char **argv) {
-#endif // GMOCK_RENAME_MAIN
+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) = testing::internal::kWarningVerbosity;
+ GMOCK_FLAG_SET(catch_leaked_mocks, true);
+ GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity);
return RUN_ALL_TESTS();
}
diff --git a/googlemock/test/gmock_all_test.cc b/googlemock/test/gmock_all_test.cc
index b2b2027db991..6db0086bb724 100644
--- a/googlemock/test/gmock_all_test.cc
+++ b/googlemock/test/gmock_all_test.cc
@@ -37,11 +37,11 @@
// below list of actual *_test.cc files might change).
#include "test/gmock-actions_test.cc"
#include "test/gmock-cardinalities_test.cc"
-#include "test/gmock-generated-actions_test.cc"
-#include "test/gmock-generated-function-mockers_test.cc"
-#include "test/gmock-generated-matchers_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"
diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc
index 72eb43f74ef4..e174122d9f63 100644
--- a/googlemock/test/gmock_ex_test.cc
+++ b/googlemock/test/gmock_ex_test.cc
@@ -27,9 +27,10 @@
// (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 <exception>
+
#include "gmock/gmock.h"
#include "gtest/gtest.h"
@@ -75,6 +76,5 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) {
}
}
-
} // unnamed namespace
#endif
diff --git a/googlemock/test/gmock_leak_test.py b/googlemock/test/gmock_leak_test.py
index 7e4b1eea9ae8..8b02bc465d38 100755
--- a/googlemock/test/gmock_leak_test.py
+++ b/googlemock/test/gmock_leak_test.py
@@ -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*']
@@ -54,50 +54,59 @@ class GMockLeakTest(gmock_test_utils.TestCase):
def testCatchesLeakedMockByDefault(self):
self.assertNotEqual(
0,
- gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL,
- env=environ).exit_code)
+ gmock_test_utils.Subprocess(
+ TEST_WITH_EXPECT_CALL, env=environ
+ ).exit_code,
+ )
self.assertNotEqual(
- 0,
- gmock_test_utils.Subprocess(TEST_WITH_ON_CALL,
- env=environ).exit_code)
+ 0, gmock_test_utils.Subprocess(TEST_WITH_ON_CALL, env=environ).exit_code
+ )
def testDoesNotCatchLeakedMockWhenDisabled(self):
- self.assertEquals(
+ self.assertEqual(
0,
- gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
- ['--gmock_catch_leaked_mocks=0'],
- env=environ).exit_code)
- self.assertEquals(
+ gmock_test_utils.Subprocess(
+ TEST_WITH_EXPECT_CALL + ['--gmock_catch_leaked_mocks=0'],
+ env=environ,
+ ).exit_code,
+ )
+ self.assertEqual(
0,
- gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
- ['--gmock_catch_leaked_mocks=0'],
- env=environ).exit_code)
+ gmock_test_utils.Subprocess(
+ TEST_WITH_ON_CALL + ['--gmock_catch_leaked_mocks=0'], env=environ
+ ).exit_code,
+ )
def testCatchesLeakedMockWhenEnabled(self):
self.assertNotEqual(
0,
- gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
- ['--gmock_catch_leaked_mocks'],
- env=environ).exit_code)
+ gmock_test_utils.Subprocess(
+ TEST_WITH_EXPECT_CALL + ['--gmock_catch_leaked_mocks'], env=environ
+ ).exit_code,
+ )
self.assertNotEqual(
0,
- gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
- ['--gmock_catch_leaked_mocks'],
- env=environ).exit_code)
+ gmock_test_utils.Subprocess(
+ TEST_WITH_ON_CALL + ['--gmock_catch_leaked_mocks'], env=environ
+ ).exit_code,
+ )
def testCatchesLeakedMockWhenEnabledWithExplictFlagValue(self):
self.assertNotEqual(
0,
- gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
- ['--gmock_catch_leaked_mocks=1'],
- env=environ).exit_code)
+ gmock_test_utils.Subprocess(
+ TEST_WITH_EXPECT_CALL + ['--gmock_catch_leaked_mocks=1'],
+ env=environ,
+ ).exit_code,
+ )
def testCatchesMultipleLeakedMocks(self):
self.assertNotEqual(
0,
- gmock_test_utils.Subprocess(TEST_MULTIPLE_LEAKS +
- ['--gmock_catch_leaked_mocks'],
- env=environ).exit_code)
+ gmock_test_utils.Subprocess(
+ TEST_MULTIPLE_LEAKS + ['--gmock_catch_leaked_mocks'], env=environ
+ ).exit_code,
+ )
if __name__ == '__main__':
diff --git a/googlemock/test/gmock_leak_test_.cc b/googlemock/test/gmock_leak_test_.cc
index 2e095abcf496..a6bb339219f5 100644
--- a/googlemock/test/gmock_leak_test_.cc
+++ b/googlemock/test/gmock_leak_test_.cc
@@ -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
@@ -41,18 +40,19 @@ using ::testing::Return;
class FooInterface {
public:
- virtual ~FooInterface() {}
+ virtual ~FooInterface() = default;
virtual void DoThis() = 0;
};
class MockFoo : public FooInterface {
public:
- MockFoo() {}
+ MockFoo() = default;
MOCK_METHOD0(DoThis, void());
private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
+ MockFoo(const MockFoo&) = delete;
+ MockFoo& operator=(const MockFoo&) = delete;
};
TEST(LeakTest, LeakedMockWithExpectCallCausesFailureWhenLeakCheckingIsEnabled) {
diff --git a/googlemock/test/gmock_link2_test.cc b/googlemock/test/gmock_link2_test.cc
index d27ce176887b..cd3d69088761 100644
--- a/googlemock/test/gmock_link2_test.cc
+++ b/googlemock/test/gmock_link2_test.cc
@@ -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
diff --git a/googlemock/test/gmock_link_test.cc b/googlemock/test/gmock_link_test.cc
index e7c54cc23068..f51e3988df3a 100644
--- a/googlemock/test/gmock_link_test.cc
+++ b/googlemock/test/gmock_link_test.cc
@@ -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
diff --git a/googlemock/test/gmock_link_test.h b/googlemock/test/gmock_link_test.h
index 175d2bdd1b44..db11c2d24d1a 100644
--- a/googlemock/test/gmock_link_test.h
+++ b/googlemock/test/gmock_link_test.h
@@ -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:
@@ -112,13 +111,13 @@
// is defined as LinkTest1 in gmock_link_test.cc and as LinkTest2 in
// gmock_link2_test.cc to avoid producing linker errors.
-#ifndef GMOCK_TEST_GMOCK_LINK_TEST_H_
-#define GMOCK_TEST_GMOCK_LINK_TEST_H_
+#ifndef GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
+#define GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
#include "gmock/gmock.h"
-#if !GTEST_OS_WINDOWS_MOBILE
-# include <errno.h>
+#ifndef GTEST_OS_WINDOWS_MOBILE
+#include <errno.h>
#endif
#include <iostream>
@@ -182,7 +181,7 @@ using testing::WithArg;
using testing::WithArgs;
using testing::WithoutArgs;
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
using testing::SetErrnoAndReturn;
#endif
@@ -195,34 +194,35 @@ using testing::MatchesRegex;
class Interface {
public:
- virtual ~Interface() {}
+ virtual ~Interface() = default;
virtual void VoidFromString(char* str) = 0;
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() {}
+ Mock() = default;
MOCK_METHOD1(VoidFromString, void(char* str));
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,12 +301,12 @@ 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);
}
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
// Tests the linkage of the SetErrnoAndReturn action.
TEST(LinkTest, TestSetErrnoAndReturn) {
@@ -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);
}
@@ -423,15 +423,12 @@ TEST(LinkTest, TestThrow) {
// the macro definition, as the warnings are generated when the macro
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
// Tests the linkage of actions created using ACTION macro.
namespace {
ACTION(Return1) { return 1; }
-}
+} // namespace
TEST(LinkTest, TestActionMacro) {
Mock mock;
@@ -443,7 +440,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,11 +454,9 @@ namespace {
ACTION_P2(ReturnEqualsEitherOf, first, second) {
return arg0 == first || arg0 == second;
}
-}
+} // namespace
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
TEST(LinkTest, TestActionP2Macro) {
Mock mock;
@@ -492,8 +487,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 +586,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());
}
@@ -687,4 +681,4 @@ TEST(LinkTest, TestMatcherCast) {
EXPECT_TRUE(m.Matches(nullptr));
}
-#endif // GMOCK_TEST_GMOCK_LINK_TEST_H_
+#endif // GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
diff --git a/googlemock/test/gmock_output_test.py b/googlemock/test/gmock_output_test.py
index 25f99f2b7977..7c24d683202c 100755
--- a/googlemock/test/gmock_output_test.py
+++ b/googlemock/test/gmock_output_test.py
@@ -39,11 +39,11 @@ gmock_output_test.py
"""
-from io import open # pylint: disable=redefined-builtin, g-importing-member
+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
@@ -159,15 +159,22 @@ class GMockOutputTest(gmock_test_utils.TestCase):
golden_file = open(GOLDEN_PATH, 'rb')
golden = golden_file.read().decode('utf-8')
golden_file.close()
+ # On Windows the repository might have been checked out with \r\n line
+ # endings, so normalize it here.
+ golden = ToUnixLineEnding(golden)
# 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__':
diff --git a/googlemock/test/gmock_output_test_.cc b/googlemock/test/gmock_output_test_.cc
index 3955c7331a12..03d842139fa8 100644
--- a/googlemock/test/gmock_output_test_.cc
+++ b/googlemock/test/gmock_output_test_.cc
@@ -27,22 +27,18 @@
// (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)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
using testing::_;
using testing::AnyNumber;
@@ -56,14 +52,15 @@ using testing::Value;
class MockFoo {
public:
- MockFoo() {}
+ MockFoo() = default;
MOCK_METHOD3(Bar, char(const std::string& s, int i, double x));
MOCK_METHOD2(Bar2, bool(int x, int y));
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 +69,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 +129,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 +154,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 +170,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 +184,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 +208,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 +221,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 +272,15 @@ 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)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
diff --git a/googlemock/test/gmock_output_test_golden.txt b/googlemock/test/gmock_output_test_golden.txt
index 4c90b41a3abc..ca88af0291df 100644
--- a/googlemock/test/gmock_output_test_golden.txt
+++ b/googlemock/test/gmock_output_test_golden.txt
@@ -40,6 +40,7 @@ FILE:#: EXPECT_CALL(foo_, Bar2(0, _))...
Actual: 1
Expected: to be called once
Actual: never called - unsatisfied and active
+
[ FAILED ] GMockOutputTest.UnexpectedCall
[ RUN ] GMockOutputTest.UnexpectedCallToVoidFunction
unknown file: Failure
@@ -53,6 +54,7 @@ FILE:#: EXPECT_CALL(foo_, Bar3(0, _))...
Actual: 1
Expected: to be called once
Actual: never called - unsatisfied and active
+
[ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction
[ RUN ] GMockOutputTest.ExcessiveCall
FILE:#: Failure
@@ -61,6 +63,7 @@ Mock function called more times than expected - returning default value.
Returns: false
Expected: to be called once
Actual: called twice - over-saturated and active
+
[ FAILED ] GMockOutputTest.ExcessiveCall
[ RUN ] GMockOutputTest.ExcessiveCallToVoidFunction
FILE:#: Failure
@@ -68,6 +71,7 @@ Mock function called more times than expected - returning directly.
Function call: Bar3(0, 1)
Expected: to be called once
Actual: called twice - over-saturated and active
+
[ FAILED ] GMockOutputTest.ExcessiveCallToVoidFunction
[ RUN ] GMockOutputTest.UninterestingCall
@@ -75,14 +79,14 @@ GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: Bar2(0, 1)
Returns: false
-NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
+NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
[ OK ] GMockOutputTest.UninterestingCall
[ RUN ] GMockOutputTest.UninterestingCallToVoidFunction
GMOCK WARNING:
Uninteresting mock function call - returning directly.
Function call: Bar3(0, 1)
-NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
+NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
[ OK ] GMockOutputTest.UninterestingCallToVoidFunction
[ RUN ] GMockOutputTest.RetiredExpectation
unknown file: Failure
@@ -104,6 +108,7 @@ FILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(0, 0))...
Actual: 1
Expected: to be called once
Actual: never called - unsatisfied and active
+
[ FAILED ] GMockOutputTest.RetiredExpectation
[ RUN ] GMockOutputTest.UnsatisfiedPrerequisite
unknown file: Failure
@@ -125,6 +130,7 @@ FILE:#: pre-requisite #0
(end of pre-requisites)
Expected: to be called once
Actual: never called - unsatisfied and active
+
[ FAILED ] GMockOutputTest.UnsatisfiedPrerequisite
[ RUN ] GMockOutputTest.UnsatisfiedPrerequisites
unknown file: Failure
@@ -147,6 +153,7 @@ FILE:#: pre-requisite #1
(end of pre-requisites)
Expected: to be called once
Actual: never called - unsatisfied and active
+
[ FAILED ] GMockOutputTest.UnsatisfiedPrerequisites
[ RUN ] GMockOutputTest.UnsatisfiedWith
FILE:#: Failure
@@ -154,16 +161,19 @@ Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(_, _))...
Expected args: are a pair where the first >= the second
Expected: to be called once
Actual: never called - unsatisfied and active
+
[ FAILED ] GMockOutputTest.UnsatisfiedWith
[ RUN ] GMockOutputTest.UnsatisfiedExpectation
FILE:#: Failure
Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(0, _))...
Expected: to be called twice
Actual: called once - unsatisfied and active
+
FILE:#: Failure
Actual function call count doesn't match EXPECT_CALL(foo_, Bar(_, _, _))...
Expected: to be called once
Actual: never called - unsatisfied and active
+
[ FAILED ] GMockOutputTest.UnsatisfiedExpectation
[ RUN ] GMockOutputTest.MismatchArguments
unknown file: Failure
@@ -180,6 +190,7 @@ FILE:#: EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0)))...
Actual: -0.1
Expected: to be called once
Actual: never called - unsatisfied and active
+
[ FAILED ] GMockOutputTest.MismatchArguments
[ RUN ] GMockOutputTest.MismatchWith
unknown file: Failure
@@ -194,6 +205,7 @@ FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...
Actual: don't match
Expected: to be called once
Actual: never called - unsatisfied and active
+
[ FAILED ] GMockOutputTest.MismatchWith
[ RUN ] GMockOutputTest.MismatchArgumentsAndWith
unknown file: Failure
@@ -210,6 +222,7 @@ FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...
Actual: don't match
Expected: to be called once
Actual: never called - unsatisfied and active
+
[ FAILED ] GMockOutputTest.MismatchArgumentsAndWith
[ RUN ] GMockOutputTest.UnexpectedCallWithDefaultAction
unknown file: Failure
@@ -227,6 +240,7 @@ FILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...
Actual: 0
Expected: to be called once
Actual: never called - unsatisfied and active
+
unknown file: Failure
Unexpected mock function call - taking default action specified at:
@@ -242,6 +256,7 @@ FILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...
Actual: 0
Expected: to be called once
Actual: never called - unsatisfied and active
+
[ FAILED ] GMockOutputTest.UnexpectedCallWithDefaultAction
[ RUN ] GMockOutputTest.ExcessiveCallWithDefaultAction
FILE:#: Failure
@@ -251,6 +266,7 @@ FILE:#:
Returns: true
Expected: to be called once
Actual: called twice - over-saturated and active
+
FILE:#: Failure
Mock function called more times than expected - taking default action specified at:
FILE:#:
@@ -258,6 +274,7 @@ FILE:#:
Returns: false
Expected: to be called once
Actual: called twice - over-saturated and active
+
[ FAILED ] GMockOutputTest.ExcessiveCallWithDefaultAction
[ RUN ] GMockOutputTest.UninterestingCallWithDefaultAction
@@ -266,14 +283,14 @@ Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(2, 2)
Returns: true
-NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
+NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(1, 1)
Returns: false
-NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
+NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
[ OK ] GMockOutputTest.UninterestingCallWithDefaultAction
[ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction
@@ -291,8 +308,9 @@ Stack trace:
[ RUN ] GMockOutputTest.PrintsMatcher
FILE:#: Failure
Value of: (std::pair<int, bool>(42, true))
-Expected: is pair (is >= 48, true)
- Actual: (42, true) (of type std::pair<int, bool>)
+Expected: is pair (first: is >= 48, second: true)
+ Actual: (42, true) (of type std::pair<int,bool>)
+
[ FAILED ] GMockOutputTest.PrintsMatcher
[ FAILED ] GMockOutputTest.UnexpectedCall
[ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction
@@ -314,4 +332,4 @@ Expected: is pair (is >= 48, true)
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
-ERROR: 3 leaked mock objects found at program exit. Expectations on a mock object is verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.
+ERROR: 3 leaked mock objects found at program exit. Expectations on a mock object are verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.
diff --git a/googlemock/test/gmock_stress_test.cc b/googlemock/test/gmock_stress_test.cc
index 20725d69b7bf..9e42cd935847 100644
--- a/googlemock/test/gmock_stress_test.cc
+++ b/googlemock/test/gmock_stress_test.cc
@@ -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.
diff --git a/googlemock/test/gmock_test.cc b/googlemock/test/gmock_test.cc
index e9840a337db8..8cfff3066783 100644
--- a/googlemock/test/gmock_test.cc
+++ b/googlemock/test/gmock_test.cc
@@ -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.
@@ -35,13 +34,12 @@
#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).empty();
(void)dummy; // Avoids the "unused local variable" warning.
}
diff --git a/googlemock/test/gmock_test_utils.py b/googlemock/test/gmock_test_utils.py
index 7dc4e119d3c5..edad1f752f0c 100755
--- a/googlemock/test/gmock_test_utils.py
+++ b/googlemock/test/gmock_test_utils.py
@@ -30,21 +30,9 @@
"""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():
@@ -89,9 +77,6 @@ def GetExitStatus(exit_code):
return -1
-# Suppresses the "Invalid const name" lint complaint
-# pylint: disable-msg=C6409
-
# Exposes utilities from gtest_test_utils.
Subprocess = gtest_test_utils.Subprocess
TestCase = gtest_test_utils.TestCase
@@ -99,8 +84,6 @@ environ = gtest_test_utils.environ
SetEnvVar = gtest_test_utils.SetEnvVar
PREMATURE_EXIT_FILE_ENV_VAR = gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR
-# pylint: enable-msg=C6409
-
def Main():
"""Runs the unit test."""
diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt
index db292946a594..caafa8c76853 100644
--- a/googletest/CMakeLists.txt
+++ b/googletest/CMakeLists.txt
@@ -46,18 +46,8 @@ 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.6.4)
-
-if (POLICY CMP0063) # Visibility
- cmake_policy(SET CMP0063 NEW)
-endif (POLICY CMP0063)
+cmake_minimum_required(VERSION 3.13)
+project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
if (COMMAND set_up_hermetic_build)
set_up_hermetic_build()
@@ -92,22 +82,27 @@ include(cmake/internal_utils.cmake)
config_compiler_and_linker() # Defined in internal_utils.cmake.
+# Needed to set the namespace for both the export targets and the
+# alias libraries
+set(cmake_package_name GTest CACHE INTERNAL "")
+
# Create the CMake package file descriptors.
if (INSTALL_GTEST)
include(CMakePackageConfigHelpers)
- set(cmake_package_name GTest)
set(targets_export_name ${cmake_package_name}Targets CACHE INTERNAL "")
set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated" CACHE INTERNAL "")
set(cmake_files_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${cmake_package_name}")
set(version_file "${generated_dir}/${cmake_package_name}ConfigVersion.cmake")
write_basic_package_version_file(${version_file} VERSION ${GOOGLETEST_VERSION} COMPATIBILITY AnyNewerVersion)
install(EXPORT ${targets_export_name}
+ COMPONENT "${PROJECT_NAME}"
NAMESPACE ${cmake_package_name}::
DESTINATION ${cmake_files_install_dir})
set(config_file "${generated_dir}/${cmake_package_name}Config.cmake")
configure_package_config_file("${gtest_SOURCE_DIR}/cmake/Config.cmake.in"
"${config_file}" INSTALL_DESTINATION ${cmake_files_install_dir})
install(FILES ${version_file} ${config_file}
+ COMPONENT "${PROJECT_NAME}"
DESTINATION ${cmake_files_install_dir})
endif()
@@ -126,17 +121,34 @@ include_directories(${gtest_build_include_dirs})
# are used for other targets, to ensure that gtest can be compiled by a user
# aggressive about warnings.
cxx_library(gtest "${cxx_strict}" src/gtest-all.cc)
+set_target_properties(gtest PROPERTIES VERSION ${GOOGLETEST_VERSION})
+if(GTEST_HAS_ABSL)
+ target_compile_definitions(gtest PUBLIC GTEST_HAS_ABSL=1)
+ target_link_libraries(gtest PUBLIC
+ absl::failure_signal_handler
+ absl::stacktrace
+ absl::symbolize
+ absl::flags_parse
+ absl::flags_reflection
+ absl::flags_usage
+ absl::strings
+ absl::any
+ absl::optional
+ absl::variant
+ re2::re2
+ )
+endif()
cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc)
-# If the CMake version supports it, attach header directory information
-# 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")
- target_include_directories(gtest SYSTEM INTERFACE
- "$<BUILD_INTERFACE:${gtest_build_include_dirs}>"
- "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
- target_include_directories(gtest_main SYSTEM INTERFACE
- "$<BUILD_INTERFACE:${gtest_build_include_dirs}>"
- "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
+set_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
+string(REPLACE ";" "$<SEMICOLON>" dirs "${gtest_build_include_dirs}")
+target_include_directories(gtest SYSTEM INTERFACE
+ "$<BUILD_INTERFACE:${dirs}>"
+ "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
+target_include_directories(gtest_main SYSTEM INTERFACE
+ "$<BUILD_INTERFACE:${dirs}>"
+ "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
+if(CMAKE_SYSTEM_NAME MATCHES "QNX")
+ target_link_libraries(gtest PUBLIC regex)
endif()
target_link_libraries(gtest_main PUBLIC gtest)
@@ -182,20 +194,6 @@ if (gtest_build_tests)
# 'make test' or ctest.
enable_testing()
- if (WIN32)
- file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1"
- CONTENT
-"$project_bin = \"${CMAKE_BINARY_DIR}/bin/$<CONFIG>\"
-$env:Path = \"$project_bin;$env:Path\"
-& $args")
- elseif (MINGW OR CYGWIN)
- file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1"
- CONTENT
-"$project_bin = (cygpath --windows ${CMAKE_BINARY_DIR}/bin)
-$env:Path = \"$project_bin;$env:Path\"
-& $args")
- endif()
-
############################################################
# C++ tests built with standard compiler flags.
@@ -266,6 +264,7 @@ $env:Path = \"$project_bin;$env:Path\"
cxx_executable(googletest-break-on-failure-unittest_ test gtest)
py_test(googletest-break-on-failure-unittest)
+ py_test(gtest_skip_check_output_test)
py_test(gtest_skip_environment_check_output_test)
# Visual Studio .NET 2003 does not support STL with exceptions disabled.
@@ -317,6 +316,9 @@ $env:Path = \"$project_bin;$env:Path\"
cxx_executable(googletest-uninitialized-test_ test gtest)
py_test(googletest-uninitialized-test)
+ cxx_executable(gtest_list_output_unittest_ test gtest)
+ py_test(gtest_list_output_unittest)
+
cxx_executable(gtest_xml_outfile1_test_ test gtest_main)
cxx_executable(gtest_xml_outfile2_test_ test gtest_main)
py_test(gtest_xml_outfiles_test)
diff --git a/googletest/LICENSE b/googletest/LICENSE
deleted file mode 100644
index 1941a11f8ce9..000000000000
--- a/googletest/LICENSE
+++ /dev/null
@@ -1,28 +0,0 @@
-Copyright 2008, Google Inc.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/googletest/README.md b/googletest/README.md
index 766ddc1e074d..815f3fc02bab 100644
--- a/googletest/README.md
+++ b/googletest/README.md
@@ -2,39 +2,51 @@
#### Setup
-To build Google Test and your tests that use it, you need to tell your build
+To build GoogleTest and your tests that use it, you need to tell your build
system where to find its headers and source files. The exact way to do it
depends on which build system you use, and is usually straightforward.
### Build with CMake
-Google Test comes with a CMake build script (
-[CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt))
+GoogleTest comes with a CMake build script
+([CMakeLists.txt](https://github.com/google/googletest/blob/main/CMakeLists.txt))
that can be used on a wide range of platforms ("C" stands for cross-platform.).
If you don't have CMake installed already, you can download it for free from
<http://www.cmake.org/>.
CMake works by generating native makefiles or build projects that can be used in
-the compiler environment of your choice. You can either build Google Test as a
+the compiler environment of your choice. You can either build GoogleTest as a
standalone project or it can be incorporated into an existing CMake build for
another project.
#### Standalone CMake Project
-When building Google Test as a standalone project, the typical workflow starts
-with:
+When building GoogleTest as a standalone project, the typical workflow starts
+with
- mkdir mybuild # Create a directory to hold the build output.
- cd mybuild
- cmake ${GTEST_DIR} # Generate native build scripts.
+```
+git clone https://github.com/google/googletest.git -b v1.13.0
+cd googletest # Main directory of the cloned repository.
+mkdir build # Create a directory to hold the build output.
+cd build
+cmake .. # Generate native build scripts for GoogleTest.
+```
-If you want to build Google Test's samples, you should replace the last command
-with
+The above command also includes GoogleMock by default. And so, if you want to
+build only GoogleTest, you should replace the last command with
- cmake -Dgtest_build_samples=ON ${GTEST_DIR}
+```
+cmake .. -DBUILD_GMOCK=OFF
+```
If you are on a \*nix system, you should now see a Makefile in the current
-directory. Just type 'make' to build gtest.
+directory. Just type `make` to build GoogleTest. And then you can simply install
+GoogleTest if you are a system administrator.
+
+```
+make
+sudo make install # Install in /usr/local/ by default
+```
If you use Windows and have Visual Studio installed, a `gtest.sln` file and
several `.vcproj` files will be created. You can then build them using Visual
@@ -44,13 +56,19 @@ On Mac OS X with Xcode installed, a `.xcodeproj` file will be generated.
#### Incorporating Into An Existing CMake Project
-If you want to use gtest in a project which already uses CMake, then a more
-robust and flexible approach is to build gtest as part of that project directly.
-This is done by making the GoogleTest source code available to the main build
-and adding it using CMake's `add_subdirectory()` command. This has the
-significant advantage that the same compiler and linker settings are used
-between gtest and the rest of your project, so issues associated with using
-incompatible libraries (eg debug/release), etc. are avoided. This is
+If you want to use GoogleTest in a project which already uses CMake, the easiest
+way is to get installed libraries and headers.
+
+* Import GoogleTest by using `find_package` (or `pkg_check_modules`). For
+ example, if `find_package(GTest CONFIG REQUIRED)` succeeds, you can use the
+ libraries as `GTest::gtest`, `GTest::gmock`.
+
+And a more robust and flexible approach is to build GoogleTest as part of that
+project directly. This is done by making the GoogleTest source code available to
+the main build and adding it using CMake's `add_subdirectory()` command. This
+has the significant advantage that the same compiler and linker settings are
+used between GoogleTest and the rest of your project, so issues associated with
+using incompatible libraries (eg debug/release), etc. are avoided. This is
particularly useful on Windows. Making GoogleTest's source code available to the
main build can be done a few different ways:
@@ -64,68 +82,23 @@ main build can be done a few different ways:
possible or appropriate. Git submodules, for example, have their own set of
advantages and drawbacks.
* Use CMake to download GoogleTest as part of the build's configure step. This
- is just a little more complex, but doesn't have the limitations of the other
- methods.
+ approach doesn't have the limitations of the other methods.
-The last of the above methods is implemented with a small piece of CMake code in
-a separate file (e.g. `CMakeLists.txt.in`) which is copied to the build area and
-then invoked as a sub-build _during the CMake stage_. That directory is then
-pulled into the main build with `add_subdirectory()`. For example:
+The last of the above methods is implemented with a small piece of CMake code
+that downloads and pulls the GoogleTest code into the main build.
-New file `CMakeLists.txt.in`:
+Just add to your `CMakeLists.txt`:
```cmake
-cmake_minimum_required(VERSION 2.8.2)
-
-project(googletest-download NONE)
-
-include(ExternalProject)
-ExternalProject_Add(googletest
- GIT_REPOSITORY https://github.com/google/googletest.git
- GIT_TAG master
- SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-src"
- BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-build"
- CONFIGURE_COMMAND ""
- BUILD_COMMAND ""
- INSTALL_COMMAND ""
- TEST_COMMAND ""
+include(FetchContent)
+FetchContent_Declare(
+ googletest
+ # Specify the commit you depend on and update it regularly.
+ URL https://github.com/google/googletest/archive/5376968f6948923e2411081fd9372e71a59d8e77.zip
)
-```
-
-Existing build's `CMakeLists.txt`:
-
-```cmake
-# Download and unpack googletest at configure time
-configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt)
-execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
- RESULT_VARIABLE result
- WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
-if(result)
- message(FATAL_ERROR "CMake step for googletest failed: ${result}")
-endif()
-execute_process(COMMAND ${CMAKE_COMMAND} --build .
- RESULT_VARIABLE result
- WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
-if(result)
- message(FATAL_ERROR "Build step for googletest failed: ${result}")
-endif()
-
-# Prevent overriding the parent project's compiler/linker
-# settings on Windows
+# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
-
-# Add googletest directly to our build. This defines
-# the gtest and gtest_main targets.
-add_subdirectory(${CMAKE_CURRENT_BINARY_DIR}/googletest-src
- ${CMAKE_CURRENT_BINARY_DIR}/googletest-build
- EXCLUDE_FROM_ALL)
-
-# The gtest/gtest_main targets carry header search path
-# dependencies automatically when using CMake 2.8.11 or
-# later. Otherwise we have to add them here ourselves.
-if (CMAKE_VERSION VERSION_LESS 2.8.11)
- include_directories("${gtest_SOURCE_DIR}/include")
-endif()
+FetchContent_MakeAvailable(googletest)
# Now simply link against gtest or gtest_main as needed. Eg
add_executable(example example.cpp)
@@ -133,112 +106,126 @@ target_link_libraries(example gtest_main)
add_test(NAME example_test COMMAND example)
```
-Note that this approach requires CMake 2.8.2 or later due to its use of the
-`ExternalProject_Add()` command. The above technique is discussed in more detail
-in [this separate article](http://crascit.com/2015/07/25/cmake-gtest/) which
-also contains a link to a fully generalized implementation of the technique.
+Note that this approach requires CMake 3.14 or later due to its use of the
+`FetchContent_MakeAvailable()` command.
##### Visual Studio Dynamic vs Static Runtimes
By default, new Visual Studio projects link the C runtimes dynamically but
-Google Test links them statically. This will generate an error that looks
+GoogleTest links them statically. This will generate an error that looks
something like the following: gtest.lib(gtest-all.obj) : error LNK2038: mismatch
detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value
'MDd_DynamicDebug' in main.obj
-Google Test already has a CMake option for this: `gtest_force_shared_crt`
+GoogleTest already has a CMake option for this: `gtest_force_shared_crt`
Enabling this option will make gtest link the runtimes dynamically too, and
match the project in which it is included.
#### C++ Standard Version
-An environment that supports C++11 is required in order to successfully build
-Google Test. One way to ensure this is to specify the standard in the top-level
-project, for example by using the `set(CMAKE_CXX_STANDARD 11)` command. If this
-is not feasible, for example in a C project using Google Test for validation,
-then it can be specified by adding it to the options for cmake via the
-`DCMAKE_CXX_FLAGS` option.
+An environment that supports C++14 is required in order to successfully build
+GoogleTest. One way to ensure this is to specify the standard in the top-level
+project, for example by using the `set(CMAKE_CXX_STANDARD 14)` command along
+with `set(CMAKE_CXX_STANDARD_REQUIRED ON)`. If this is not feasible, for example
+in a C project using GoogleTest for validation, then it can be specified by
+adding it to the options for cmake via the`-DCMAKE_CXX_FLAGS` option.
-### Tweaking Google Test
+### Tweaking GoogleTest
-Google Test can be used in diverse environments. The default configuration may
+GoogleTest can be used in diverse environments. The default configuration may
not work (or may not work well) out of the box in some environments. However,
-you can easily tweak Google Test by defining control macros on the compiler
+you can easily tweak GoogleTest by defining control macros on the compiler
command line. Generally, these macros are named like `GTEST_XYZ` and you define
them to either 1 or 0 to enable or disable a certain feature.
We list the most frequently used macros below. For a complete list, see file
-[include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/master/googletest/include/gtest/internal/gtest-port.h).
+[include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/main/googletest/include/gtest/internal/gtest-port.h).
### Multi-threaded Tests
-Google Test is thread-safe where the pthread library is available. After
-`#include "gtest/gtest.h"`, you can check the
+GoogleTest is thread-safe where the pthread library is available. After
+`#include <gtest/gtest.h>`, you can check the
`GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is
`#defined` to 1, no if it's undefined.).
-If Google Test doesn't correctly detect whether pthread is available in your
+If GoogleTest doesn't correctly detect whether pthread is available in your
environment, you can force it with
- -DGTEST_HAS_PTHREAD=1
+```
+-DGTEST_HAS_PTHREAD=1
+```
or
- -DGTEST_HAS_PTHREAD=0
+```
+-DGTEST_HAS_PTHREAD=0
+```
-When Google Test uses pthread, you may need to add flags to your compiler and/or
+When GoogleTest uses pthread, you may need to add flags to your compiler and/or
linker to select the pthread library, or you'll get link errors. If you use the
-CMake script or the deprecated Autotools script, this is taken care of for you.
-If you use your own build script, you'll need to read your compiler and linker's
-manual to figure out what flags to add.
+CMake script, this is taken care of for you. If you use your own build script,
+you'll need to read your compiler and linker's manual to figure out what flags
+to add.
### As a Shared Library (DLL)
-Google Test is compact, so most users can build and link it as a static library
-for the simplicity. You can choose to use Google Test as a shared library (known
+GoogleTest is compact, so most users can build and link it as a static library
+for the simplicity. You can choose to use GoogleTest as a shared library (known
as a DLL on Windows) if you prefer.
To compile *gtest* as a shared library, add
- -DGTEST_CREATE_SHARED_LIBRARY=1
+```
+-DGTEST_CREATE_SHARED_LIBRARY=1
+```
to the compiler flags. You'll also need to tell the linker to produce a shared
library instead - consult your linker's manual for how to do it.
To compile your *tests* that use the gtest shared library, add
- -DGTEST_LINKED_AS_SHARED_LIBRARY=1
+```
+-DGTEST_LINKED_AS_SHARED_LIBRARY=1
+```
to the compiler flags.
Note: while the above steps aren't technically necessary today when using some
compilers (e.g. GCC), they may become necessary in the future, if we decide to
improve the speed of loading the library (see
-<http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are recommended
-to always add the above flags when using Google Test as a shared library.
-Otherwise a future release of Google Test may break your build script.
+<https://gcc.gnu.org/wiki/Visibility> for details). Therefore you are
+recommended to always add the above flags when using GoogleTest as a shared
+library. Otherwise a future release of GoogleTest may break your build script.
### Avoiding Macro Name Clashes
In C++, macros don't obey namespaces. Therefore two libraries that both define a
macro of the same name will clash if you `#include` both definitions. In case a
-Google Test macro clashes with another library, you can force Google Test to
+GoogleTest macro clashes with another library, you can force GoogleTest to
rename its macro to avoid the conflict.
-Specifically, if both Google Test and some other code define macro FOO, you can
+Specifically, if both GoogleTest and some other code define macro FOO, you can
add
- -DGTEST_DONT_DEFINE_FOO=1
+```
+-DGTEST_DONT_DEFINE_FOO=1
+```
-to the compiler flags to tell Google Test to change the macro's name from `FOO`
-to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, or `TEST`. For
+to the compiler flags to tell GoogleTest to change the macro's name from `FOO`
+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) { ... }
+```
+GTEST_TEST(SomeTest, DoesThis) { ... }
+```
instead of
- TEST(SomeTest, DoesThis) { ... }
+```
+TEST(SomeTest, DoesThis) { ... }
+```
in order to define a test.
diff --git a/googletest/cmake/gtest.pc.in b/googletest/cmake/gtest.pc.in
index 9aae29e267f0..b4148fae42b1 100644
--- a/googletest/cmake/gtest.pc.in
+++ b/googletest/cmake/gtest.pc.in
@@ -1,10 +1,9 @@
-prefix=${pcfiledir}/../..
-libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
-includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
+libdir=@CMAKE_INSTALL_FULL_LIBDIR@
+includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
Name: gtest
Description: GoogleTest (without main() function)
Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest
Libs: -L${libdir} -lgtest @CMAKE_THREAD_LIBS_INIT@
-Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@
+Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
diff --git a/googletest/cmake/gtest_main.pc.in b/googletest/cmake/gtest_main.pc.in
index 915f2973af79..38c88c54d538 100644
--- a/googletest/cmake/gtest_main.pc.in
+++ b/googletest/cmake/gtest_main.pc.in
@@ -1,11 +1,10 @@
-prefix=${pcfiledir}/../..
-libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
-includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
+libdir=@CMAKE_INSTALL_FULL_LIBDIR@
+includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
Name: gtest_main
Description: GoogleTest (with main() function)
Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest
-Requires: gtest
+Requires: gtest = @PROJECT_VERSION@
Libs: -L${libdir} -lgtest_main @CMAKE_THREAD_LIBS_INIT@
-Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@
+Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake
index 2f70f0b084b9..64fa340fd9eb 100644
--- a/googletest/cmake/internal_utils.cmake
+++ b/googletest/cmake/internal_utils.cmake
@@ -12,17 +12,14 @@
# Test and Google Mock's option() definitions, and thus must be
# called *after* the options have been defined.
-if (POLICY CMP0054)
- cmake_policy(SET CMP0054 NEW)
-endif (POLICY CMP0054)
-
# Tweaks CMake's default compiler/linker settings to suit Google Test's needs.
#
# This must be a macro(), as inside a function string() can only
# update variables in the function scope.
macro(fix_default_compiler_settings_)
- if (MSVC)
- # For MSVC, CMake sets certain flags to defaults we want to override.
+ if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC|Clang")
+ # For MSVC and Clang, CMake sets certain flags to defaults we want to
+ # override.
# This replacement code is taken from sample in the CMake Wiki at
# https://gitlab.kitware.com/cmake/community/wikis/FAQ#dynamic-replace.
foreach (flag_var
@@ -39,6 +36,10 @@ macro(fix_default_compiler_settings_)
# on CRT DLLs being available. CMake always defaults to using shared
# CRT libraries, so we override that default here.
string(REPLACE "/MD" "-MT" ${flag_var} "${${flag_var}}")
+
+ # When using Ninja with Clang, static builds pass -D_DLL on Windows.
+ # This is incorrect and should not happen, so we fix that here.
+ string(REPLACE "-D_DLL" "" ${flag_var} "${${flag_var}}")
endif()
# We prefer more strict warning checking for building Google Test.
@@ -72,7 +73,7 @@ macro(config_compiler_and_linker)
if (MSVC)
# Newlines inside flags variables break CMake's NMake generator.
# TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds.
- set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J -Zi")
+ set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J")
set(cxx_base_flags "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32")
set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN")
set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1")
@@ -81,14 +82,28 @@ macro(config_compiler_and_linker)
# Suppress "unreachable code" warning
# http://stackoverflow.com/questions/3232669 explains the issue.
set(cxx_base_flags "${cxx_base_flags} -wd4702")
- elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
- set(cxx_base_flags "-Wall -Wshadow -Werror -Wconversion")
+ # Ensure MSVC treats source files as UTF-8 encoded.
+ if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
+ set(cxx_base_flags "${cxx_base_flags} -utf-8")
+ endif()
+ if (CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
+ set(cxx_base_flags "${cxx_base_flags} /fp:precise -Wno-inconsistent-missing-override -Wno-microsoft-exception-spec -Wno-unused-function -Wno-unused-but-set-variable")
+ endif()
+ elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR
+ CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
+ set(cxx_base_flags "-Wall -Wshadow -Wconversion -Wundef")
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_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Winline -Wredundant-decls")
set(cxx_no_rtti_flags "-fno-rtti")
+ if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
+ set(cxx_strict_flags "${cxx_strict_flags} -Wchar-subscripts")
+ endif()
+ if (CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
+ set(cxx_base_flags "${cxx_base_flags} -Wno-implicit-float-size-conversion -ffp-model=precise")
+ endif()
elseif (CMAKE_COMPILER_IS_GNUCXX)
- set(cxx_base_flags "-Wall -Wshadow -Werror")
+ set(cxx_base_flags "-Wall -Wshadow -Wundef")
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0)
set(cxx_base_flags "${cxx_base_flags} -Wno-error=dangling-else")
endif()
@@ -148,20 +163,18 @@ function(cxx_library_with_type name type cxx_flags)
# type can be either STATIC or SHARED to denote a static or shared library.
# ARGN refers to additional arguments after 'cxx_flags'.
add_library(${name} ${type} ${ARGN})
+ add_library(${cmake_package_name}::${name} ALIAS ${name})
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
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
- PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
+ PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
+ COMPILE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib")
# make PDBs match library name
get_target_property(pdb_debug_postfix ${name} DEBUG_POSTFIX)
set_target_properties(${name}
@@ -175,19 +188,14 @@ function(cxx_library_with_type name type cxx_flags)
set_target_properties(${name}
PROPERTIES
COMPILE_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1")
- if (NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
- target_compile_definitions(${name} INTERFACE
- $<INSTALL_INTERFACE:GTEST_LINKED_AS_SHARED_LIBRARY=1>)
- endif()
+ target_compile_definitions(${name} INTERFACE
+ $<INSTALL_INTERFACE:GTEST_LINKED_AS_SHARED_LIBRARY=1>)
endif()
if (DEFINED GTEST_HAS_PTHREAD)
- if ("${CMAKE_VERSION}" VERSION_LESS "3.1.0")
- set(threads_spec ${CMAKE_THREAD_LIBS_INIT})
- else()
- set(threads_spec Threads::Threads)
- endif()
- target_link_libraries(${name} PUBLIC ${threads_spec})
+ target_link_libraries(${name} PUBLIC Threads::Threads)
endif()
+
+ target_compile_features(${name} PUBLIC cxx_std_14)
endfunction()
########################################################################
@@ -239,8 +247,7 @@ function(cxx_executable name dir libs)
${name} "${cxx_default}" "${libs}" "${dir}/${name}.cc" ${ARGN})
endfunction()
-# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE.
-find_package(PythonInterp)
+find_package(Python3)
# cxx_test_with_flags(name cxx_flags libs srcs...)
#
@@ -248,13 +255,7 @@ find_package(PythonInterp)
# from the given source files with the given compiler flags.
function(cxx_test_with_flags name cxx_flags libs)
cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN})
- if (WIN32 OR MINGW)
- add_test(NAME ${name}
- COMMAND "powershell" "-Command" "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1" "$<TARGET_FILE:${name}>")
- else()
- add_test(NAME ${name}
- COMMAND "$<TARGET_FILE:${name}>")
- endif()
+ add_test(NAME ${name} COMMAND "$<TARGET_FILE:${name}>")
endfunction()
# cxx_test(name libs srcs...)
@@ -272,53 +273,22 @@ endfunction()
# creates a Python test with the given name whose main module is in
# test/name.py. It does nothing if Python is not installed.
function(py_test name)
- if (PYTHONINTERP_FOUND)
- if ("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" VERSION_GREATER 3.1)
- if (CMAKE_CONFIGURATION_TYPES)
- # Multi-configuration build generators as for Visual Studio save
- # output in a subdirectory of CMAKE_CURRENT_BINARY_DIR (Debug,
- # Release etc.), so we have to provide it here.
- if (WIN32 OR MINGW)
- add_test(NAME ${name}
- COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1
- ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
- --build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
- else()
- add_test(NAME ${name}
- COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
- --build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
- endif()
- else (CMAKE_CONFIGURATION_TYPES)
- # Single-configuration build generators like Makefile generators
- # don't have subdirs below CMAKE_CURRENT_BINARY_DIR.
- if (WIN32 OR MINGW)
- add_test(NAME ${name}
- COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1
- ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
- --build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
- else()
- add_test(NAME ${name}
- COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
- --build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
- endif()
- endif (CMAKE_CONFIGURATION_TYPES)
- else()
- # ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can
- # directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known
- # only at ctest runtime (by calling ctest -c <Configuration>), so
- # we have to escape $ to delay variable substitution here.
- if (WIN32 OR MINGW)
- add_test(NAME ${name}
- COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1
- ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
- --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
- else()
- add_test(NAME ${name}
- COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
- --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
- endif()
- endif()
- endif(PYTHONINTERP_FOUND)
+ if (NOT Python3_Interpreter_FOUND)
+ return()
+ endif()
+
+ get_cmake_property(is_multi "GENERATOR_IS_MULTI_CONFIG")
+ set(build_dir "${CMAKE_CURRENT_BINARY_DIR}")
+ if (is_multi)
+ set(build_dir "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>")
+ endif()
+
+ add_test(NAME ${name}
+ COMMAND Python3::Interpreter ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
+ --build_dir=${build_dir} ${ARGN})
+
+ # Make the Python import path consistent between Bazel and CMake.
+ set_tests_properties(${name} PROPERTIES ENVIRONMENT PYTHONPATH=${CMAKE_SOURCE_DIR})
endfunction()
# install_project(targets...)
@@ -327,10 +297,12 @@ endfunction()
function(install_project)
if(INSTALL_GTEST)
install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/"
+ COMPONENT "${PROJECT_NAME}"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
# Install the project targets.
install(TARGETS ${ARGN}
EXPORT ${targets_export_name}
+ COMPONENT "${PROJECT_NAME}"
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}")
@@ -342,6 +314,7 @@ function(install_project)
get_target_property(t_pdb_output_directory ${t} PDB_OUTPUT_DIRECTORY)
install(FILES
"${t_pdb_output_directory}/\${CMAKE_INSTALL_CONFIG_NAME}/$<$<CONFIG:Debug>:${t_pdb_name_debug}>$<$<NOT:$<CONFIG:Debug>>:${t_pdb_name}>.pdb"
+ COMPONENT "${PROJECT_NAME}"
DESTINATION ${CMAKE_INSTALL_LIBDIR}
OPTIONAL)
endforeach()
@@ -352,6 +325,7 @@ function(install_project)
configure_file("${PROJECT_SOURCE_DIR}/cmake/${t}.pc.in"
"${configured_pc}" @ONLY)
install(FILES "${configured_pc}"
+ COMPONENT "${PROJECT_NAME}"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
endforeach()
endif()
diff --git a/googletest/docs/README.md b/googletest/docs/README.md
new file mode 100644
index 000000000000..1bc57b799cce
--- /dev/null
+++ b/googletest/docs/README.md
@@ -0,0 +1,4 @@
+# Content Moved
+
+We are working on updates to the GoogleTest documentation, which has moved to
+the top-level [docs](../../docs) directory.
diff --git a/googletest/docs/pkgconfig.md b/googletest/docs/pkgconfig.md
deleted file mode 100644
index 6dc0673889c4..000000000000
--- a/googletest/docs/pkgconfig.md
+++ /dev/null
@@ -1,141 +0,0 @@
-## Using GoogleTest from various build systems
-
-GoogleTest comes with pkg-config files that can be used to determine all
-necessary flags for compiling and linking to GoogleTest (and GoogleMock).
-Pkg-config is a standardised plain-text format containing
-
-* the includedir (-I) path
-* necessary macro (-D) definitions
-* further required flags (-pthread)
-* the library (-L) path
-* the library (-l) to link to
-
-All current build systems support pkg-config in one way or another. For all
-examples here we assume you want to compile the sample
-`samples/sample3_unittest.cc`.
-
-### CMake
-
-Using `pkg-config` in CMake is fairly easy:
-
-```cmake
-cmake_minimum_required(VERSION 3.0)
-
-cmake_policy(SET CMP0048 NEW)
-project(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX)
-
-find_package(PkgConfig)
-pkg_search_module(GTEST REQUIRED gtest_main)
-
-add_executable(testapp samples/sample3_unittest.cc)
-target_link_libraries(testapp ${GTEST_LDFLAGS})
-target_compile_options(testapp PUBLIC ${GTEST_CFLAGS})
-
-include(CTest)
-add_test(first_and_only_test testapp)
-```
-
-It is generally recommended that you use `target_compile_options` + `_CFLAGS`
-over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not
-just -I flags (GoogleTest might require a macro indicating to internal headers
-that all libraries have been compiled with threading enabled. In addition,
-GoogleTest might also require `-pthread` in the compiling step, and as such
-splitting the pkg-config `Cflags` variable into include dirs and macros for
-`target_compile_definitions()` might still miss this). The same recommendation
-goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens
-to discard `-L` flags and `-pthread`.
-
-### Autotools
-
-Finding GoogleTest in Autoconf and using it from Automake is also fairly easy:
-
-In your `configure.ac`:
-
-```
-AC_PREREQ([2.69])
-AC_INIT([my_gtest_pkgconfig], [0.0.1])
-AC_CONFIG_SRCDIR([samples/sample3_unittest.cc])
-AC_PROG_CXX
-
-PKG_CHECK_MODULES([GTEST], [gtest_main])
-
-AM_INIT_AUTOMAKE([foreign subdir-objects])
-AC_CONFIG_FILES([Makefile])
-AC_OUTPUT
-```
-
-and in your `Makefile.am`:
-
-```
-check_PROGRAMS = testapp
-TESTS = $(check_PROGRAMS)
-
-testapp_SOURCES = samples/sample3_unittest.cc
-testapp_CXXFLAGS = $(GTEST_CFLAGS)
-testapp_LDADD = $(GTEST_LIBS)
-```
-
-### Meson
-
-Meson natively uses pkgconfig to query dependencies:
-
-```
-project('my_gtest_pkgconfig', 'cpp', version : '0.0.1')
-
-gtest_dep = dependency('gtest_main')
-
-testapp = executable(
- 'testapp',
- files(['samples/sample3_unittest.cc']),
- dependencies : gtest_dep,
- install : false)
-
-test('first_and_only_test', testapp)
-```
-
-### Plain Makefiles
-
-Since `pkg-config` is a small Unix command-line utility, it can be used in
-handwritten `Makefile`s too:
-
-```makefile
-GTEST_CFLAGS = `pkg-config --cflags gtest_main`
-GTEST_LIBS = `pkg-config --libs gtest_main`
-
-.PHONY: tests all
-
-tests: all
- ./testapp
-
-all: testapp
-
-testapp: testapp.o
- $(CXX) $(CXXFLAGS) $(LDFLAGS) $< -o $@ $(GTEST_LIBS)
-
-testapp.o: samples/sample3_unittest.cc
- $(CXX) $(CPPFLAGS) $(CXXFLAGS) $< -c -o $@ $(GTEST_CFLAGS)
-```
-
-### Help! pkg-config can't find GoogleTest!
-
-Let's say you have a `CMakeLists.txt` along the lines of the one in this
-tutorial and you try to run `cmake`. It is very possible that you get a failure
-along the lines of:
-
-```
--- Checking for one of the modules 'gtest_main'
-CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message):
- None of the required 'gtest_main' found
-```
-
-These failures are common if you installed GoogleTest yourself and have not
-sourced it from a distro or other package manager. If so, you need to tell
-pkg-config where it can find the `.pc` files containing the information. Say you
-installed GoogleTest to `/usr/local`, then it might be that the `.pc` files are
-installed under `/usr/local/lib64/pkgconfig`. If you set
-
-```
-export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig
-```
-
-pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`.
diff --git a/googletest/docs/pump_manual.md b/googletest/docs/pump_manual.md
deleted file mode 100644
index 10b3c5ff0849..000000000000
--- a/googletest/docs/pump_manual.md
+++ /dev/null
@@ -1,190 +0,0 @@
-<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming.
-
-# The Problem
-
-Template and macro libraries often need to define many classes, functions, or
-macros that vary only (or almost only) in the number of arguments they take.
-It's a lot of repetitive, mechanical, and error-prone work.
-
-Variadic templates and variadic macros can alleviate the problem. However, while
-both are being considered by the C++ committee, neither is in the standard yet
-or widely supported by compilers. Thus they are often not a good choice,
-especially when your code needs to be portable. And their capabilities are still
-limited.
-
-As a result, authors of such libraries often have to write scripts to generate
-their implementation. However, our experience is that it's tedious to write such
-scripts, which tend to reflect the structure of the generated code poorly and
-are often hard to read and edit. For example, a small change needed in the
-generated code may require some non-intuitive, non-trivial changes in the
-script. This is especially painful when experimenting with the code.
-
-# Our Solution
-
-Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta
-Programming, or Practical Utility for Meta Programming, whichever you prefer) is
-a simple meta-programming tool for C++. The idea is that a programmer writes a
-`foo.pump` file which contains C++ code plus meta code that manipulates the C++
-code. The meta code can handle iterations over a range, nested iterations, local
-meta variable definitions, simple arithmetic, and conditional expressions. You
-can view it as a small Domain-Specific Language. The meta language is designed
-to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, for example) and
-concise, making Pump code intuitive and easy to maintain.
-
-## Highlights
-
-* The implementation is in a single Python script and thus ultra portable: no
- build or installation is needed and it works cross platforms.
-* Pump tries to be smart with respect to
- [Google's style guide](https://github.com/google/styleguide): it breaks long
- lines (easy to have when they are generated) at acceptable places to fit
- within 80 columns and indent the continuation lines correctly.
-* The format is human-readable and more concise than XML.
-* The format works relatively well with Emacs' C++ mode.
-
-## Examples
-
-The following Pump code (where meta keywords start with `$`, `[[` and `]]` are
-meta brackets, and `$$` starts a meta comment that ends with the line):
-
-```
-$var n = 3 $$ Defines a meta variable n.
-$range i 0..n $$ Declares the range of meta iterator i (inclusive).
-$for i [[
- $$ Meta loop.
-// Foo$i does blah for $i-ary predicates.
-$range j 1..i
-template <size_t N $for j [[, typename A$j]]>
-class Foo$i {
-$if i == 0 [[
- blah a;
-]] $elif i <= 2 [[
- blah b;
-]] $else [[
- blah c;
-]]
-};
-
-]]
-```
-
-will be translated by the Pump compiler to:
-
-```cpp
-// Foo0 does blah for 0-ary predicates.
-template <size_t N>
-class Foo0 {
- blah a;
-};
-
-// Foo1 does blah for 1-ary predicates.
-template <size_t N, typename A1>
-class Foo1 {
- blah b;
-};
-
-// Foo2 does blah for 2-ary predicates.
-template <size_t N, typename A1, typename A2>
-class Foo2 {
- blah b;
-};
-
-// Foo3 does blah for 3-ary predicates.
-template <size_t N, typename A1, typename A2, typename A3>
-class Foo3 {
- blah c;
-};
-```
-
-In another example,
-
-```
-$range i 1..n
-Func($for i + [[a$i]]);
-$$ The text between i and [[ is the separator between iterations.
-```
-
-will generate one of the following lines (without the comments), depending on
-the value of `n`:
-
-```cpp
-Func(); // If n is 0.
-Func(a1); // If n is 1.
-Func(a1 + a2); // If n is 2.
-Func(a1 + a2 + a3); // If n is 3.
-// And so on...
-```
-
-## Constructs
-
-We support the following meta programming constructs:
-
-| `$var id = exp` | Defines a named constant value. `$id` is |
-: : valid util the end of the current meta :
-: : lexical block. :
-| :------------------------------- | :--------------------------------------- |
-| `$range id exp..exp` | Sets the range of an iteration variable, |
-: : which can be reused in multiple loops :
-: : later. :
-| `$for id sep [[ code ]]` | Iteration. The range of `id` must have |
-: : been defined earlier. `$id` is valid in :
-: : `code`. :
-| `$($)` | Generates a single `$` character. |
-| `$id` | Value of the named constant or iteration |
-: : variable. :
-| `$(exp)` | Value of the expression. |
-| `$if exp [[ code ]] else_branch` | Conditional. |
-| `[[ code ]]` | Meta lexical block. |
-| `cpp_code` | Raw C++ code. |
-| `$$ comment` | Meta comment. |
-
-**Note:** To give the user some freedom in formatting the Pump source code, Pump
-ignores a new-line character if it's right after `$for foo` or next to `[[` or
-`]]`. Without this rule you'll often be forced to write very long lines to get
-the desired output. Therefore sometimes you may need to insert an extra new-line
-in such places for a new-line to show up in your output.
-
-## Grammar
-
-```ebnf
-code ::= atomic_code*
-atomic_code ::= $var id = exp
- | $var id = [[ code ]]
- | $range id exp..exp
- | $for id sep [[ code ]]
- | $($)
- | $id
- | $(exp)
- | $if exp [[ code ]] else_branch
- | [[ code ]]
- | cpp_code
-sep ::= cpp_code | empty_string
-else_branch ::= $else [[ code ]]
- | $elif exp [[ code ]] else_branch
- | empty_string
-exp ::= simple_expression_in_Python_syntax
-```
-
-## Code
-
-You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py).
-It is still very unpolished and lacks automated tests, although it has been
-successfully used many times. If you find a chance to use it in your project,
-please let us know what you think! We also welcome help on improving Pump.
-
-## Real Examples
-
-You can find real-world applications of Pump in
-[Google Test](https://github.com/google/googletest/tree/master/googletest) and
-[Google Mock](https://github.com/google/googletest/tree/master/googlemock). The
-source file `foo.h.pump` generates `foo.h`.
-
-## Tips
-
-* If a meta variable is followed by a letter or digit, you can separate them
- using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper`
- generate `Foo1Helper` when `j` is 1.
-* To avoid extra-long Pump source lines, you can break a line anywhere you
- want by inserting `[[]]` followed by a new line. Since any new-line
- character next to `[[` or `]]` is ignored, the generated code won't contain
- this new line.
diff --git a/googletest/include/gtest/gtest-assertion-result.h b/googletest/include/gtest/gtest-assertion-result.h
new file mode 100644
index 000000000000..56fe128f2a5a
--- /dev/null
+++ b/googletest/include/gtest/gtest-assertion-result.h
@@ -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_ != 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_ == nullptr) message_ = ::std::make_unique<::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_
diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h
index dc878ffbb3ae..08fef8c7d346 100644
--- a/googletest/include/gtest/gtest-death-test.h
+++ b/googletest/include/gtest/gtest-death-test.h
@@ -27,20 +27,20 @@
// (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
-#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
-#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
-#include "gtest/internal/gtest-death-test-internal.h"
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
-namespace testing {
+#include "gtest/internal/gtest-death-test-internal.h"
// 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
@@ -49,7 +49,9 @@ namespace testing {
// after forking.
GTEST_DECLARE_string_(death_test_style);
-#if GTEST_HAS_DEATH_TEST
+namespace testing {
+
+#ifdef GTEST_HAS_DEATH_TEST
namespace internal {
@@ -97,9 +99,12 @@ GTEST_API_ bool InDeathTestChild();
//
// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
//
+// The final parameter to each of these macros is a matcher applied to any data
+// the sub-process wrote to stderr. For compatibility with existing tests, a
+// bare string is interpreted as a regular expression matcher.
+//
// 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.
//
@@ -162,27 +167,27 @@ GTEST_API_ bool InDeathTestChild();
// directory in PATH.
//
-// Asserts that a given statement causes the program to exit, with an
-// integer exit status that satisfies predicate, and emitting error output
-// that matches regex.
-# define ASSERT_EXIT(statement, predicate, regex) \
- GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_)
+// 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_)
-// Like ASSERT_EXIT, but continues on to successive tests in the
+// Like `ASSERT_EXIT`, but continues on to successive tests in the
// test suite, if any:
-# define EXPECT_EXIT(statement, predicate, regex) \
- GTEST_DEATH_TEST_(statement, predicate, regex, 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
+// Asserts that a given `statement` causes the program to exit, either by
// explicitly exiting with a nonzero exit code or being killed by a
-// signal, and emitting error output that matches regex.
-# define ASSERT_DEATH(statement, regex) \
- ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
+// signal, and emitting error output that matches `matcher`.
+#define ASSERT_DEATH(statement, matcher) \
+ ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
-// Like ASSERT_DEATH, but continues on to successive tests in the
+// Like `ASSERT_DEATH`, but continues on to successive tests in the
// test suite, if any:
-# define EXPECT_DEATH(statement, regex) \
- EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
+#define EXPECT_DEATH(statement, matcher) \
+ EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
@@ -190,26 +195,26 @@ GTEST_API_ bool InDeathTestChild();
class GTEST_API_ ExitedWithCode {
public:
explicit ExitedWithCode(int exit_code);
+ ExitedWithCode(const ExitedWithCode&) = default;
+ void operator=(const ExitedWithCode& other) = delete;
bool operator()(int exit_status) const;
- private:
- // No implementation - assignment is unsupported.
- void operator=(const ExitedWithCode& other);
+ private:
const int exit_code_;
};
-# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#if !defined(GTEST_OS_WINDOWS) && !defined(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,
@@ -254,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
@@ -308,36 +311,35 @@ 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
// death tests are supported; otherwise they just issue a warning. This is
// 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)
+#ifdef 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)
#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
-#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
diff --git a/googletest/include/gtest/gtest-matchers.h b/googletest/include/gtest/gtest-matchers.h
index 9de6c2e10a20..eae210e99dda 100644
--- a/googletest/include/gtest/gtest-matchers.h
+++ b/googletest/include/gtest/gtest-matchers.h
@@ -32,13 +32,15 @@
// This file implements just enough of the matcher interface to allow
// EXPECT_DEATH and friends to accept a matcher argument.
-// IWYU pragma: private, include "testing/base/public/gunit.h"
-// IWYU pragma: friend third_party/googletest/googlemock/.*
-// IWYU pragma: friend third_party/googletest/googletest/.*
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
-#ifndef GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
-#define GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
+#include <atomic>
+#include <functional>
#include <memory>
#include <ostream>
#include <string>
@@ -63,20 +65,16 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(
namespace testing {
// To implement a matcher Foo for type T, define:
-// 1. a class FooMatcherImpl that implements the
-// MatcherInterface<T> interface, and
-// 2. a factory function that creates a Matcher<T> object from a
-// FooMatcherImpl*.
-//
-// The two-level delegation design makes it possible to allow a user
-// to write "v" instead of "Eq(v)" where a Matcher is expected, which
-// is impossible if we pass matchers by pointers. It also eases
-// ownership management as Matcher objects can now be copied like
-// plain values.
-
-// MatchResultListener is an abstract class. Its << operator can be
-// used by a matcher to explain why a value matches or doesn't match.
+// 1. a class FooMatcherMatcher that implements the matcher interface:
+// using is_gtest_matcher = void;
+// bool MatchAndExplain(const T&, std::ostream*);
+// (MatchResultListener* can also be used instead of std::ostream*)
+// void DescribeTo(std::ostream*);
+// void DescribeNegationTo(std::ostream*);
//
+// 2. a factory function that creates a Matcher<T> object from a
+// FooMatcherMatcher.
+
class MatchResultListener {
public:
// Creates a listener object with the given underlying ostream. The
@@ -105,17 +103,17 @@ 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() = default;
// An instance of a subclass of this knows how to describe itself as a
// matcher.
-class MatcherDescriberInterface {
+class GTEST_API_ MatcherDescriberInterface {
public:
- virtual ~MatcherDescriberInterface() {}
+ virtual ~MatcherDescriberInterface() = default;
// Describes this matcher to an ostream. The function should print
// a verb phrase that describes the property a value matching this
@@ -181,63 +179,14 @@ class MatcherInterface : public MatcherDescriberInterface {
namespace internal {
-// Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
-template <typename T>
-class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
- public:
- explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
- : impl_(impl) {}
- ~MatcherInterfaceAdapter() override { delete impl_; }
-
- void DescribeTo(::std::ostream* os) const override { impl_->DescribeTo(os); }
-
- void DescribeNegationTo(::std::ostream* os) const override {
- impl_->DescribeNegationTo(os);
- }
-
- bool MatchAndExplain(const T& x,
- MatchResultListener* listener) const override {
- return impl_->MatchAndExplain(x, listener);
- }
-
- private:
- const MatcherInterface<T>* const impl_;
-
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
-};
-
-struct AnyEq {
- template <typename A, typename 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; }
-};
-struct AnyLt {
- template <typename A, typename 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; }
-};
-struct AnyLe {
- template <typename A, typename 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; }
-};
-
// A match result listener that ignores the explanation.
class DummyMatchResultListener : public MatchResultListener {
public:
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
@@ -249,19 +198,40 @@ class StreamMatchResultListener : public MatchResultListener {
: MatchResultListener(os) {}
private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
+ StreamMatchResultListener(const StreamMatchResultListener&) = delete;
+ StreamMatchResultListener& operator=(const StreamMatchResultListener&) =
+ delete;
+};
+
+struct SharedPayloadBase {
+ std::atomic<int> ref{1};
+ void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
+ bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
+};
+
+template <typename T>
+struct SharedPayload : SharedPayloadBase {
+ explicit SharedPayload(const T& v) : value(v) {}
+ explicit SharedPayload(T&& v) : value(std::move(v)) {}
+
+ static void Destroy(SharedPayloadBase* shared) {
+ delete static_cast<SharedPayload*>(shared);
+ }
+
+ T value;
};
// An internal class for implementing Matcher<T>, which will derive
// from it. We put functionalities common to all Matcher<T>
// specializations here to avoid code duplication.
template <typename T>
-class MatcherBase {
+class MatcherBase : private MatcherDescriberInterface {
public:
// Returns true if and only if the matcher matches x; also explains the
// match result to 'listener'.
bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
- return impl_->MatchAndExplain(x, listener);
+ GTEST_CHECK_(vtable_ != nullptr);
+ return vtable_->match_and_explain(*this, x, listener);
}
// Returns true if and only if this matcher matches x.
@@ -271,11 +241,15 @@ class MatcherBase {
}
// Describes this matcher to an ostream.
- void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
+ void DescribeTo(::std::ostream* os) const final {
+ GTEST_CHECK_(vtable_ != nullptr);
+ vtable_->describe(*this, os, false);
+ }
// Describes the negation of this matcher to an ostream.
- void DescribeNegationTo(::std::ostream* os) const {
- impl_->DescribeNegationTo(os);
+ void DescribeNegationTo(::std::ostream* os) const final {
+ GTEST_CHECK_(vtable_ != nullptr);
+ vtable_->describe(*this, os, true);
}
// Explains why x matches, or doesn't match, the matcher.
@@ -288,31 +262,195 @@ class MatcherBase {
// of the describer, which is only guaranteed to be alive when
// this matcher object is alive.
const MatcherDescriberInterface* GetDescriber() const {
- return impl_.get();
+ if (vtable_ == nullptr) return nullptr;
+ return vtable_->get_describer(*this);
}
protected:
- MatcherBase() {}
+ MatcherBase() : vtable_(nullptr), buffer_() {}
// Constructs a matcher from its implementation.
- explicit MatcherBase(const MatcherInterface<const T&>* impl) : impl_(impl) {}
-
template <typename U>
- explicit MatcherBase(
- const MatcherInterface<U>* impl,
- typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
- nullptr)
- : impl_(new internal::MatcherInterfaceAdapter<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) : vtable_(nullptr), buffer_() { // NOLINT
+ Init(std::forward<M>(m));
+ }
+
+ MatcherBase(const MatcherBase& other)
+ : vtable_(other.vtable_), buffer_(other.buffer_) {
+ if (IsShared()) buffer_.shared->Ref();
+ }
- MatcherBase(const MatcherBase&) = default;
- MatcherBase& operator=(const MatcherBase&) = default;
- MatcherBase(MatcherBase&&) = default;
- MatcherBase& operator=(MatcherBase&&) = default;
+ MatcherBase& operator=(const MatcherBase& other) {
+ if (this == &other) return *this;
+ Destroy();
+ vtable_ = other.vtable_;
+ buffer_ = other.buffer_;
+ if (IsShared()) buffer_.shared->Ref();
+ return *this;
+ }
+
+ MatcherBase(MatcherBase&& other)
+ : vtable_(other.vtable_), buffer_(other.buffer_) {
+ other.vtable_ = nullptr;
+ }
+
+ MatcherBase& operator=(MatcherBase&& other) {
+ if (this == &other) return *this;
+ Destroy();
+ vtable_ = other.vtable_;
+ buffer_ = other.buffer_;
+ other.vtable_ = nullptr;
+ return *this;
+ }
- virtual ~MatcherBase() {}
+ ~MatcherBase() override { Destroy(); }
private:
- std::shared_ptr<const MatcherInterface<const T&>> impl_;
+ struct VTable {
+ bool (*match_and_explain)(const MatcherBase&, const T&,
+ MatchResultListener*);
+ void (*describe)(const MatcherBase&, std::ostream*, bool negation);
+ // Returns the captured object if it implements the interface, otherwise
+ // returns the MatcherBase itself.
+ const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
+ // Called on shared instances when the reference count reaches 0.
+ void (*shared_destroy)(SharedPayloadBase*);
+ };
+
+ bool IsShared() const {
+ return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
+ }
+
+ // If the implementation uses a listener, call that.
+ template <typename P>
+ static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
+ MatchResultListener* listener)
+ -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
+ return P::Get(m).MatchAndExplain(value, listener->stream());
+ }
+
+ template <typename P>
+ static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
+ MatchResultListener* listener)
+ -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
+ return P::Get(m).MatchAndExplain(value, listener);
+ }
+
+ template <typename P>
+ static void DescribeImpl(const MatcherBase& m, std::ostream* os,
+ bool negation) {
+ if (negation) {
+ P::Get(m).DescribeNegationTo(os);
+ } else {
+ P::Get(m).DescribeTo(os);
+ }
+ }
+
+ template <typename P>
+ static const MatcherDescriberInterface* GetDescriberImpl(
+ const MatcherBase& m) {
+ // If the impl is a MatcherDescriberInterface, then return it.
+ // Otherwise use MatcherBase itself.
+ // This allows us to implement the GetDescriber() function without support
+ // from the impl, but some users really want to get their impl back when
+ // they call GetDescriber().
+ // We use std::get on a tuple as a workaround of not having `if constexpr`.
+ return std::get<(
+ std::is_convertible<decltype(&P::Get(m)),
+ const MatcherDescriberInterface*>::value
+ ? 1
+ : 0)>(std::make_tuple(&m, &P::Get(m)));
+ }
+
+ template <typename P>
+ const VTable* GetVTable() {
+ static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
+ &DescribeImpl<P>, &GetDescriberImpl<P>,
+ P::shared_destroy};
+ return &kVTable;
+ }
+
+ union Buffer {
+ // Add some types to give Buffer some common alignment/size use cases.
+ void* ptr;
+ double d;
+ int64_t i;
+ // And add one for the out-of-line cases.
+ SharedPayloadBase* shared;
+ };
+
+ void Destroy() {
+ if (IsShared() && buffer_.shared->Unref()) {
+ vtable_->shared_destroy(buffer_.shared);
+ }
+ }
+
+ template <typename M>
+ static constexpr bool IsInlined() {
+ return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
+ std::is_trivially_copy_constructible<M>::value &&
+ std::is_trivially_destructible<M>::value;
+ }
+
+ template <typename M, bool = MatcherBase::IsInlined<M>()>
+ struct ValuePolicy {
+ 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_));
+ return *ptr;
+ }
+ static void Init(MatcherBase& m, M impl) {
+ ::new (static_cast<void*>(&m.buffer_)) M(impl);
+ }
+ static constexpr auto shared_destroy = nullptr;
+ };
+
+ template <typename M>
+ struct ValuePolicy<M, false> {
+ using Shared = SharedPayload<M>;
+ static const M& Get(const MatcherBase& m) {
+ return static_cast<Shared*>(m.buffer_.shared)->value;
+ }
+ template <typename Arg>
+ static void Init(MatcherBase& m, Arg&& arg) {
+ m.buffer_.shared = new Shared(std::forward<Arg>(arg));
+ }
+ static constexpr auto shared_destroy = &Shared::Destroy;
+ };
+
+ template <typename U, bool B>
+ struct ValuePolicy<const MatcherInterface<U>*, B> {
+ using M = const MatcherInterface<U>;
+ using Shared = SharedPayload<std::unique_ptr<M>>;
+ static const M& Get(const MatcherBase& m) {
+ return *static_cast<Shared*>(m.buffer_.shared)->value;
+ }
+ static void Init(MatcherBase& m, M* impl) {
+ m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
+ }
+
+ static constexpr auto shared_destroy = &Shared::Destroy;
+ };
+
+ template <typename M>
+ void Init(M&& m) {
+ using MM = typename std::decay<M>::type;
+ using Policy = ValuePolicy<MM>;
+ vtable_ = GetVTable<Policy>();
+ Policy::Init(*this, std::forward<M>(m));
+ }
+
+ const VTable* vtable_;
+ Buffer buffer_;
};
} // namespace internal
@@ -340,6 +478,10 @@ class Matcher : public internal::MatcherBase<T> {
nullptr)
: internal::MatcherBase<T>(impl) {}
+ template <typename M, typename = typename std::remove_reference<
+ M>::type::is_gtest_matcher>
+ Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
+
// Implicit constructor here allows people to write
// EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
Matcher(T value); // NOLINT
@@ -352,11 +494,16 @@ template <>
class GTEST_API_ Matcher<const std::string&>
: public internal::MatcherBase<const std::string&> {
public:
- Matcher() {}
+ Matcher() = default;
explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<const std::string&>(impl) {}
+ template <typename M, typename = typename std::remove_reference<
+ M>::type::is_gtest_matcher>
+ Matcher(M&& m) // NOLINT
+ : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
+
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
Matcher(const std::string& s); // NOLINT
@@ -369,13 +516,18 @@ template <>
class GTEST_API_ Matcher<std::string>
: public internal::MatcherBase<std::string> {
public:
- Matcher() {}
+ Matcher() = default;
explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<std::string>(impl) {}
explicit Matcher(const MatcherInterface<std::string>* impl)
: internal::MatcherBase<std::string>(impl) {}
+ template <typename M, typename = typename std::remove_reference<
+ M>::type::is_gtest_matcher>
+ Matcher(M&& m) // NOLINT
+ : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
+
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a string object.
Matcher(const std::string& s); // NOLINT
@@ -384,18 +536,24 @@ class GTEST_API_ Matcher<std::string>
Matcher(const char* s); // NOLINT
};
-#if GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_STRING_VIEW
// The following two specializations allow the user to write str
// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
// matcher is expected.
template <>
-class GTEST_API_ Matcher<const absl::string_view&>
- : public internal::MatcherBase<const absl::string_view&> {
+class GTEST_API_ Matcher<const internal::StringView&>
+ : public internal::MatcherBase<const internal::StringView&> {
public:
- Matcher() {}
+ Matcher() = default;
- explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
- : internal::MatcherBase<const absl::string_view&>(impl) {}
+ explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
+ : internal::MatcherBase<const internal::StringView&>(impl) {}
+
+ template <typename M, typename = typename std::remove_reference<
+ M>::type::is_gtest_matcher>
+ Matcher(M&& m) // NOLINT
+ : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
+ }
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
@@ -404,20 +562,25 @@ class GTEST_API_ Matcher<const absl::string_view&>
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
- // Allows the user to pass absl::string_views directly.
- Matcher(absl::string_view s); // NOLINT
+ // Allows the user to pass absl::string_views or std::string_views directly.
+ Matcher(internal::StringView s); // NOLINT
};
template <>
-class GTEST_API_ Matcher<absl::string_view>
- : public internal::MatcherBase<absl::string_view> {
+class GTEST_API_ Matcher<internal::StringView>
+ : public internal::MatcherBase<internal::StringView> {
public:
- Matcher() {}
+ Matcher() = default;
+
+ explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
+ : internal::MatcherBase<internal::StringView>(impl) {}
+ explicit Matcher(const MatcherInterface<internal::StringView>* impl)
+ : internal::MatcherBase<internal::StringView>(impl) {}
- explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
- : internal::MatcherBase<absl::string_view>(impl) {}
- explicit Matcher(const MatcherInterface<absl::string_view>* impl)
- : internal::MatcherBase<absl::string_view>(impl) {}
+ template <typename M, typename = typename std::remove_reference<
+ M>::type::is_gtest_matcher>
+ Matcher(M&& m) // NOLINT
+ : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
@@ -426,10 +589,10 @@ class GTEST_API_ Matcher<absl::string_view>
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
- // Allows the user to pass absl::string_views directly.
- Matcher(absl::string_view s); // NOLINT
+ // Allows the user to pass absl::string_views or std::string_views directly.
+ Matcher(internal::StringView s); // NOLINT
};
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Prints a matcher in a human-readable format.
template <typename T>
@@ -474,13 +637,13 @@ class PolymorphicMatcher {
public:
explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
- virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); }
+ void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
- virtual void DescribeNegationTo(::std::ostream* os) const {
+ void DescribeNegationTo(::std::ostream* os) const override {
impl_.DescribeNegationTo(os);
}
- virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
+ bool MatchAndExplain(T x, MatchResultListener* listener) const override {
return impl_.MatchAndExplain(x, listener);
}
@@ -529,89 +692,91 @@ template <typename D, typename Rhs, typename Op>
class ComparisonBase {
public:
explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
+
+ using is_gtest_matcher = void;
+
template <typename Lhs>
- operator Matcher<Lhs>() const {
- return Matcher<Lhs>(new Impl<const Lhs&>(rhs_));
+ bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
+ return Op()(lhs, Unwrap(rhs_));
+ }
+ void DescribeTo(std::ostream* os) const {
+ *os << D::Desc() << " ";
+ UniversalPrint(Unwrap(rhs_), os);
+ }
+ void DescribeNegationTo(std::ostream* os) const {
+ *os << D::NegatedDesc() << " ";
+ UniversalPrint(Unwrap(rhs_), os);
}
private:
template <typename T>
- static const T& Unwrap(const T& v) { return v; }
+ static const T& Unwrap(const T& v) {
+ return v;
+ }
template <typename T>
- static const T& Unwrap(std::reference_wrapper<T> v) { return v; }
-
- template <typename Lhs, typename = Rhs>
- class Impl : public MatcherInterface<Lhs> {
- public:
- explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
- bool MatchAndExplain(Lhs lhs,
- MatchResultListener* /* listener */) const override {
- return Op()(lhs, Unwrap(rhs_));
- }
- void DescribeTo(::std::ostream* os) const override {
- *os << D::Desc() << " ";
- UniversalPrint(Unwrap(rhs_), os);
- }
- void DescribeNegationTo(::std::ostream* os) const override {
- *os << D::NegatedDesc() << " ";
- UniversalPrint(Unwrap(rhs_), os);
- }
+ static const T& Unwrap(std::reference_wrapper<T> v) {
+ return v;
+ }
- private:
- Rhs rhs_;
- };
Rhs rhs_;
};
template <typename Rhs>
-class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
+class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>> {
public:
explicit EqMatcher(const Rhs& rhs)
- : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
+ : ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>>(rhs) {}
static const char* Desc() { return "is equal to"; }
static const char* NegatedDesc() { return "isn't equal to"; }
};
template <typename Rhs>
-class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
+class NeMatcher
+ : public ComparisonBase<NeMatcher<Rhs>, Rhs, std::not_equal_to<>> {
public:
explicit NeMatcher(const Rhs& rhs)
- : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
+ : ComparisonBase<NeMatcher<Rhs>, Rhs, std::not_equal_to<>>(rhs) {}
static const char* Desc() { return "isn't equal to"; }
static const char* NegatedDesc() { return "is equal to"; }
};
template <typename Rhs>
-class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
+class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>> {
public:
explicit LtMatcher(const Rhs& rhs)
- : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
+ : ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>>(rhs) {}
static const char* Desc() { return "is <"; }
static const char* NegatedDesc() { return "isn't <"; }
};
template <typename Rhs>
-class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
+class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>> {
public:
explicit GtMatcher(const Rhs& rhs)
- : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
+ : ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>>(rhs) {}
static const char* Desc() { return "is >"; }
static const char* NegatedDesc() { return "isn't >"; }
};
template <typename Rhs>
-class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
+class LeMatcher
+ : public ComparisonBase<LeMatcher<Rhs>, Rhs, std::less_equal<>> {
public:
explicit LeMatcher(const Rhs& rhs)
- : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
+ : ComparisonBase<LeMatcher<Rhs>, Rhs, std::less_equal<>>(rhs) {}
static const char* Desc() { return "is <="; }
static const char* NegatedDesc() { return "isn't <="; }
};
template <typename Rhs>
-class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
+class GeMatcher
+ : public ComparisonBase<GeMatcher<Rhs>, Rhs, std::greater_equal<>> {
public:
explicit GeMatcher(const Rhs& rhs)
- : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
+ : ComparisonBase<GeMatcher<Rhs>, Rhs, std::greater_equal<>>(rhs) {}
static const char* Desc() { return "is >="; }
static const char* NegatedDesc() { return "isn't >="; }
};
+template <typename T, typename = typename std::enable_if<
+ std::is_constructible<std::string, T>::value>::type>
+using StringLike = T;
+
// Implements polymorphic matchers MatchesRegex(regex) and
// ContainsRegex(regex), which can be used as a Matcher<T> as long as
// T can be converted to a string.
@@ -620,12 +785,12 @@ class MatchesRegexMatcher {
MatchesRegexMatcher(const RE* regex, bool full_match)
: regex_(regex), full_match_(full_match) {}
-#if GTEST_HAS_ABSL
- bool MatchAndExplain(const absl::string_view& s,
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const {
return MatchAndExplain(std::string(s), listener);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly:
// const char*
@@ -644,7 +809,7 @@ class MatchesRegexMatcher {
template <class MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const {
- const std::string& s2(s);
+ const std::string s2(s);
return full_match_ ? RE::FullMatch(s2, *regex_)
: RE::PartialMatch(s2, *regex_);
}
@@ -672,9 +837,10 @@ inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
}
-inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
- const std::string& regex) {
- return MatchesRegex(new internal::RE(regex));
+template <typename T = std::string>
+PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
+ const internal::StringLike<T>& regex) {
+ return MatchesRegex(new internal::RE(std::string(regex)));
}
// Matches a string that contains regular expression 'regex'.
@@ -683,21 +849,26 @@ inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
}
-inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
- const std::string& regex) {
- return ContainsRegex(new internal::RE(regex));
+template <typename T = std::string>
+PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
+ const internal::StringLike<T>& regex) {
+ return ContainsRegex(new internal::RE(std::string(regex)));
}
// Creates a polymorphic matcher that matches anything equal to x.
// 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(...)
@@ -712,7 +883,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>
@@ -747,4 +920,4 @@ inline internal::NeMatcher<Rhs> Ne(Rhs x) {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
-#endif // GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h
index 4a80e11e6b2d..59b805e4e462 100644
--- a/googletest/include/gtest/gtest-message.h
+++ b/googletest/include/gtest/gtest-message.h
@@ -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,16 +41,28 @@
// 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 GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
-#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
#include <limits>
#include <memory>
+#include <ostream>
+#include <sstream>
+#include <string>
#include "gtest/internal/gtest-port.h"
+#ifdef GTEST_HAS_ABSL
+#include <type_traits>
+
+#include "absl/strings/internal/has_absl_stringify.h"
+#include "absl/strings/str_cat.h"
+#endif // GTEST_HAS_ABSL
+
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
@@ -107,10 +118,19 @@ class GTEST_API_ Message {
*ss_ << str;
}
- // Streams a non-pointer value to this object.
- template <typename T>
- inline Message& operator <<(const T& val) {
- // Some libraries overload << for STL containers. These
+ // Streams a non-pointer value to this object. If building a version of
+ // GoogleTest with ABSL, this overload is only enabled if the value does not
+ // have an AbslStringify definition.
+ template <typename T
+#ifdef GTEST_HAS_ABSL
+ ,
+ typename std::enable_if<
+ !absl::strings_internal::HasAbslStringify<T>::value, // NOLINT
+ int>::type = 0
+#endif // GTEST_HAS_ABSL
+ >
+ 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
@@ -124,11 +144,27 @@ 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;
}
+#ifdef GTEST_HAS_ABSL
+ // Streams a non-pointer value with an AbslStringify definition to this
+ // object.
+ template <typename T,
+ typename std::enable_if<
+ absl::strings_internal::HasAbslStringify<T>::value, // NOLINT
+ int>::type = 0>
+ inline Message& operator<<(const T& val) {
+ // ::operator<< is needed here for a similar reason as with the non-Abseil
+ // version above
+ using ::operator<<;
+ *ss_ << absl::StrCat(val);
+ return *this;
+ }
+#endif // GTEST_HAS_ABSL
+
// Streams a pointer value to this object.
//
// This function is an overload of the previous one. When you
@@ -143,7 +179,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 {
@@ -158,25 +194,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.
@@ -195,7 +229,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();
}
@@ -215,4 +249,4 @@ std::string StreamableToString(const T& streamable) {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
-#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h
index c2e6eae3d832..49a47ead03b7 100644
--- a/googletest/include/gtest/gtest-param-test.h
+++ b/googletest/include/gtest/gtest-param-test.h
@@ -26,16 +26,16 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
+
// Macros and functions for implementing parameterized tests
// in Google C++ Testing and Mocking Framework (Google Test)
-//
-// This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
-//
-// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
-#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
+// 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_
// Value-parameterized tests allow you to test your code with different
// parameters without writing multiple copies of the same test.
@@ -356,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.
@@ -371,8 +369,6 @@ inline internal::ParamGenerator<bool> Bool() {
// std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
// of elements from sequences produces by gen1, gen2, ..., genN.
//
-// Combine can have up to 10 arguments.
-//
// Example:
//
// This will instantiate tests in test suite AnimalTest each one with
@@ -411,29 +407,69 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
return internal::CartesianProductHolder<Generator...>(g...);
}
+// ConvertGenerator() wraps a parameter generator in order to cast each produced
+// value through a known type before supplying it to the test suite
+//
+// Synopsis:
+// ConvertGenerator<T>(gen)
+// - returns a generator producing the same elements as generated by gen, but
+// each element is static_cast to type T before being returned
+//
+// It is useful when using the Combine() function to get the generated
+// parameters in a custom type instead of std::tuple
+//
+// Example:
+//
+// This will instantiate tests in test suite AnimalTest each one with
+// the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
+// tuple("dog", BLACK), and tuple("dog", WHITE):
+//
+// enum Color { BLACK, GRAY, WHITE };
+// struct ParamType {
+// using TupleT = std::tuple<const char*, Color>;
+// std::string animal;
+// Color color;
+// ParamType(TupleT t) : animal(std::get<0>(t)), color(std::get<1>(t)) {}
+// };
+// class AnimalTest
+// : public testing::TestWithParam<ParamType> {...};
+//
+// TEST_P(AnimalTest, AnimalLooksNice) {...}
+//
+// INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
+// ConvertGenerator<ParamType::TupleT>(
+// Combine(Values("cat", "dog"),
+// Values(BLACK, WHITE))));
+//
+template <typename T>
+internal::ParamConverterGenerator<T> ConvertGenerator(
+ internal::ParamGenerator<T> gen) {
+ return internal::ParamConverterGenerator<T>(gen);
+}
+
#define TEST_P(test_suite_name, test_name) \
class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
- : public test_suite_name { \
+ : public test_suite_name, \
+ private ::testing::internal::GTestNonCopyable { \
public: \
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
- virtual void TestBody(); \
+ void TestBody() override; \
\
private: \
static int AddToRegistry() { \
::testing::UnitTest::GetInstance() \
->parameterized_test_registry() \
.GetTestSuitePatternHolder<test_suite_name>( \
- #test_suite_name, \
+ GTEST_STRINGIFY_(test_suite_name), \
::testing::internal::CodeLocation(__FILE__, __LINE__)) \
->AddTestPattern( \
GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
- test_suite_name, test_name)>()); \
+ test_suite_name, test_name)>(), \
+ ::testing::internal::CodeLocation(__FILE__, __LINE__)); \
return 0; \
} \
static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
- GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
- test_name)); \
}; \
int GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name)::gtest_registering_dummy_ = \
@@ -457,39 +493,46 @@ 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>( \
- #test_suite_name, \
- ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
- ->AddTestSuiteInstantiation( \
- #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) \
+ namespace gtest_do_not_use_outside_namespace_scope {} \
+ static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
+ GTEST_STRINGIFY_(T))
+
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
#define INSTANTIATE_TEST_CASE_P \
@@ -500,4 +543,4 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h
index 56a05450ef5e..d1766e640f28 100644
--- a/googletest/include/gtest/gtest-printers.h
+++ b/googletest/include/gtest/gtest-printers.h
@@ -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
@@ -44,6 +43,9 @@
// 1. foo::PrintTo(const T&, ostream*)
// 2. operator<<(ostream&, const T&) defined in either foo or the
// global namespace.
+// * Prefer AbslStringify(..) to operator<<(..), per https://abseil.io/tips/215.
+// * Define foo::PrintTo(..) if the type already has AbslStringify(..), but an
+// alternative presentation in test results is of interest.
//
// However if T is an STL-style container then it is printed element-wise
// unless foo::PrintTo(const T&, ostream*) is defined. Note that
@@ -95,77 +97,146 @@
// 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 GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
-#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#include <functional>
+#include <memory>
#include <ostream> // NOLINT
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
+#include <typeinfo>
#include <utility>
#include <vector>
-#include "gtest/internal/gtest-internal.h"
-#include "gtest/internal/gtest-port.h"
-#if GTEST_HAS_ABSL
-#include "absl/strings/string_view.h"
-#include "absl/types/optional.h"
-#include "absl/types/variant.h"
+#ifdef GTEST_HAS_ABSL
+#include "absl/strings/internal/has_absl_stringify.h"
+#include "absl/strings/str_cat.h"
#endif // GTEST_HAS_ABSL
+#include "gtest/internal/gtest-internal.h"
+#include "gtest/internal/gtest-port.h"
namespace testing {
-// Definitions in the 'internal' and 'internal2' name spaces are
-// subject to change without notice. DO NOT USE THEM IN USER CODE!
-namespace internal2 {
+// Definitions in the internal* namespaces are subject to change without notice.
+// DO NOT USE THEM IN USER CODE!
+namespace internal {
-// 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);
-
-// For selecting which printer to use when a given type has neither <<
-// nor PrintTo().
-enum TypeKind {
- kProtobuf, // a protobuf type
- kConvertibleToInteger, // a type implicitly convertible to BiggestInt
- // (e.g. a named or unnamed enum type)
-#if GTEST_HAS_ABSL
- kConvertibleToStringView, // a type implicitly convertible to
- // absl::string_view
-#endif
- kOtherType // anything else
+template <typename T>
+void UniversalPrint(const T& value, ::std::ostream* os);
+
+// Used to print an STL-style container when the user doesn't define
+// a PrintTo() for it.
+struct ContainerPrinter {
+ template <typename T,
+ typename = typename std::enable_if<
+ (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
+ !IsRecursiveContainer<T>::value>::type>
+ static void PrintValue(const T& container, std::ostream* os) {
+ const size_t kMaxCount = 32; // The maximum number of elements to print.
+ *os << '{';
+ size_t count = 0;
+ for (auto&& elem : container) {
+ if (count > 0) {
+ *os << ',';
+ if (count == kMaxCount) { // Enough has been printed.
+ *os << " ...";
+ break;
+ }
+ }
+ *os << ' ';
+ // We cannot call PrintTo(elem, os) here as PrintTo() doesn't
+ // handle `elem` being a native array.
+ internal::UniversalPrint(elem, os);
+ ++count;
+ }
+
+ if (count > 0) {
+ *os << ' ';
+ }
+ *os << '}';
+ }
};
-// TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
-// by the universal printer to print a value of type T when neither
-// operator<< nor PrintTo() is defined for T, where kTypeKind is the
-// "kind" of T as defined by enum TypeKind.
-template <typename T, TypeKind kTypeKind>
-class TypeWithoutFormatter {
- public:
- // This default version is called when kTypeKind is kOtherType.
- static void PrintValue(const T& value, ::std::ostream* os) {
- PrintBytesInObjectTo(
- static_cast<const unsigned char*>(
- reinterpret_cast<const void*>(std::addressof(value))),
- sizeof(value), os);
+// Used to print a pointer that is neither a char pointer nor a member
+// pointer, when the user doesn't define PrintTo() for it. (A member
+// variable pointer or member function pointer doesn't really point to
+// a location in the address space. Their representation is
+// implementation-defined. Therefore they will be printed as raw
+// bytes.)
+struct FunctionPointerPrinter {
+ template <typename T, typename = typename std::enable_if<
+ std::is_function<T>::value>::type>
+ static void PrintValue(T* p, ::std::ostream* os) {
+ if (p == nullptr) {
+ *os << "NULL";
+ } else {
+ // T is a function type, so '*os << p' doesn't do what we want
+ // (it just prints p as bool). We want to print p as a const
+ // void*.
+ *os << reinterpret_cast<const void*>(p);
+ }
}
};
-// We print a protobuf using its ShortDebugString() when the string
-// doesn't exceed this many characters; otherwise we print it using
-// DebugString() for better readability.
-const size_t kProtobufOneLinerMaxLength = 50;
+struct PointerPrinter {
+ template <typename T>
+ static void PrintValue(T* p, ::std::ostream* os) {
+ if (p == nullptr) {
+ *os << "NULL";
+ } else {
+ // T is not a function type. We just call << to print p,
+ // relying on ADL to pick up user-defined << for their pointer
+ // types, if any.
+ *os << p;
+ }
+ }
+};
-template <typename T>
-class TypeWithoutFormatter<T, kProtobuf> {
- public:
+namespace internal_stream_operator_without_lexical_name_lookup {
+
+// The presence of an operator<< here will terminate lexical scope lookup
+// straight away (even though it cannot be a match because of its argument
+// types). Thus, the two operator<< calls in StreamPrinter will find only ADL
+// candidates.
+struct LookupBlocker {};
+void operator<<(LookupBlocker, LookupBlocker);
+
+struct StreamPrinter {
+ template <typename T,
+ // Don't accept member pointers here. We'd print them via implicit
+ // conversion to bool, which isn't useful.
+ typename = typename std::enable_if<
+ !std::is_member_pointer<T>::value>::type>
+ // Only accept types for which we can find a streaming operator via
+ // ADL (possibly involving implicit conversions).
+ // (Use SFINAE via return type, because it seems GCC < 12 doesn't handle name
+ // lookup properly when we do it in the template parameter list.)
+ static auto PrintValue(const T& value, ::std::ostream* os)
+ -> decltype((void)(*os << value)) {
+ // Call streaming operator found by ADL, possibly with implicit conversions
+ // of the arguments.
+ *os << value;
+ }
+};
+
+} // namespace internal_stream_operator_without_lexical_name_lookup
+
+struct ProtobufPrinter {
+ // We print a protobuf using its ShortDebugString() when the string
+ // doesn't exceed this many characters; otherwise we print it using
+ // DebugString() for better readability.
+ static const size_t kProtobufOneLinerMaxLength = 50;
+
+ template <typename T,
+ typename = typename std::enable_if<
+ internal::HasDebugStringAndShortDebugString<T>::value>::type>
static void PrintValue(const T& value, ::std::ostream* os) {
std::string pretty_str = value.ShortDebugString();
if (pretty_str.length() > kProtobufOneLinerMaxLength) {
@@ -175,9 +246,7 @@ class TypeWithoutFormatter<T, kProtobuf> {
}
};
-template <typename T>
-class TypeWithoutFormatter<T, kConvertibleToInteger> {
- public:
+struct ConvertibleToIntegerPrinter {
// Since T has no << operator or PrintTo() but can be implicitly
// converted to BiggestInt, we print it as a BiggestInt.
//
@@ -185,113 +254,88 @@ class TypeWithoutFormatter<T, kConvertibleToInteger> {
// case printing it as an integer is the desired behavior. In case
// T is not an enum, printing it as an integer is the best we can do
// given that it has no user-defined printer.
+ static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
+ *os << value;
+ }
+};
+
+struct ConvertibleToStringViewPrinter {
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ static void PrintValue(internal::StringView value, ::std::ostream* os) {
+ internal::UniversalPrint(value, os);
+ }
+#endif
+};
+
+#ifdef GTEST_HAS_ABSL
+struct ConvertibleToAbslStringifyPrinter {
+ template <
+ typename T,
+ typename = typename std::enable_if<
+ absl::strings_internal::HasAbslStringify<T>::value>::type> // NOLINT
static void PrintValue(const T& value, ::std::ostream* os) {
- const internal::BiggestInt kBigInt = value;
- *os << kBigInt;
+ *os << absl::StrCat(value);
}
};
+#endif // GTEST_HAS_ABSL
-#if GTEST_HAS_ABSL
-template <typename T>
-class TypeWithoutFormatter<T, kConvertibleToStringView> {
- public:
- // Since T has neither operator<< nor PrintTo() but can be implicitly
- // converted to absl::string_view, we print it as a absl::string_view.
- //
- // Note: the implementation is further below, as it depends on
- // internal::PrintTo symbol which is defined later in the file.
- static void PrintValue(const T& value, ::std::ostream* os);
+// 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);
+struct RawBytesPrinter {
+ // SFINAE on `sizeof` to make sure we have a complete type.
+ template <typename T, size_t = sizeof(T)>
+ static void PrintValue(const T& value, ::std::ostream* os) {
+ PrintBytesInObjectTo(
+ static_cast<const unsigned char*>(
+ // Load bearing cast to void* to support iOS
+ reinterpret_cast<const void*>(std::addressof(value))),
+ sizeof(value), os);
+ }
};
-#endif
-// Prints the given value to the given ostream. If the value is a
-// protocol message, its debug string is printed; if it's an enum or
-// of a type implicitly convertible to BiggestInt, it's printed as an
-// integer; otherwise the bytes in the value are printed. This is
-// what UniversalPrinter<T>::Print() does when it knows nothing about
-// type T and T has neither << operator nor PrintTo().
-//
-// A user can override this behavior for a class type Foo by defining
-// a << operator in the namespace where Foo is defined.
-//
-// We put this operator in namespace 'internal2' instead of 'internal'
-// to simplify the implementation, as much code in 'internal' needs to
-// use << in STL, which would conflict with our own << were it defined
-// in 'internal'.
-//
-// Note that this operator<< takes a generic std::basic_ostream<Char,
-// CharTraits> type instead of the more restricted std::ostream. If
-// we define it to take an std::ostream instead, we'll get an
-// "ambiguous overloads" compiler error when trying to print a type
-// Foo that supports streaming to std::basic_ostream<Char,
-// CharTraits>, as the compiler cannot tell whether
-// operator<<(std::ostream&, const T&) or
-// operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
-// specific.
-template <typename Char, typename CharTraits, typename T>
-::std::basic_ostream<Char, CharTraits>& operator<<(
- ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
- TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
- ? kProtobuf
- : std::is_convertible<
- const T&, internal::BiggestInt>::value
- ? kConvertibleToInteger
- :
-#if GTEST_HAS_ABSL
- std::is_convertible<
- const T&, absl::string_view>::value
- ? kConvertibleToStringView
- :
-#endif
- kOtherType)>::PrintValue(x, &os);
- return os;
-}
+struct FallbackPrinter {
+ template <typename T>
+ static void PrintValue(const T&, ::std::ostream* os) {
+ *os << "(incomplete type)";
+ }
+};
-} // namespace internal2
-} // namespace testing
+// Try every printer in order and return the first one that works.
+template <typename T, typename E, typename Printer, typename... Printers>
+struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
-// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up
-// magic needed for implementing UniversalPrinter won't work.
-namespace testing_internal {
+template <typename T, typename Printer, typename... Printers>
+struct FindFirstPrinter<
+ T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
+ Printer, Printers...> {
+ using type = Printer;
+};
-// Used to print a value that is not an STL-style container when the
-// user doesn't define PrintTo() for it.
+// Select the best printer in the following order:
+// - Print containers (they have begin/end/etc).
+// - Print function pointers.
+// - Print object pointers.
+// - Print protocol buffers.
+// - Use the stream operator, if available.
+// - Print types convertible to BiggestInt.
+// - Print types convertible to StringView, if available.
+// - Fallback to printing the raw bytes of the object.
template <typename T>
-void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) {
- // With the following statement, during unqualified name lookup,
- // testing::internal2::operator<< appears as if it was declared in
- // the nearest enclosing namespace that contains both
- // ::testing_internal and ::testing::internal2, i.e. the global
- // namespace. For more details, refer to the C++ Standard section
- // 7.3.4-1 [namespace.udir]. This allows us to fall back onto
- // testing::internal2::operator<< in case T doesn't come with a <<
- // operator.
- //
- // We cannot write 'using ::testing::internal2::operator<<;', which
- // gcc 3.3 fails to compile due to a compiler bug.
- using namespace ::testing::internal2; // NOLINT
-
- // Assuming T is defined in namespace foo, in the next statement,
- // the compiler will consider all of:
- //
- // 1. foo::operator<< (thanks to Koenig look-up),
- // 2. ::operator<< (as the current namespace is enclosed in ::),
- // 3. testing::internal2::operator<< (thanks to the using statement above).
- //
- // The operator<< whose type matches T best will be picked.
- //
- // We deliberately allow #2 to be a candidate, as sometimes it's
- // impossible to define #1 (e.g. when foo is ::std, defining
- // anything in it is undefined behavior unless you are a compiler
- // vendor.).
- *os << value;
+void PrintWithFallback(const T& value, ::std::ostream* os) {
+ using Printer = typename FindFirstPrinter<
+ T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
+ ProtobufPrinter,
+#ifdef GTEST_HAS_ABSL
+ ConvertibleToAbslStringifyPrinter,
+#endif // GTEST_HAS_ABSL
+ internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
+ ConvertibleToIntegerPrinter, ConvertibleToStringViewPrinter,
+ RawBytesPrinter, FallbackPrinter>::type;
+ Printer::PrintValue(value, os);
}
-} // namespace testing_internal
-
-namespace testing {
-namespace internal {
-
// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
// value of type ToPrint that is an operand of a comparison assertion
// (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
@@ -340,6 +384,14 @@ 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_lib_char8_t
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
+#endif
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
@@ -347,16 +399,24 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_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);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
+#ifdef __cpp_lib_char8_t
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
+#endif
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
#if GTEST_HAS_STD_WSTRING
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
@@ -374,8 +434,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);
}
@@ -389,85 +449,6 @@ std::string FormatForComparisonFailureMessage(
template <typename T>
class UniversalPrinter;
-template <typename T>
-void UniversalPrint(const T& value, ::std::ostream* os);
-
-enum DefaultPrinterType {
- kPrintContainer,
- kPrintPointer,
- kPrintFunctionPointer,
- kPrintOther,
-};
-template <DefaultPrinterType type> struct WrapPrinterType {};
-
-// Used to print an STL-style container when the user doesn't define
-// a PrintTo() for it.
-template <typename C>
-void DefaultPrintTo(WrapPrinterType<kPrintContainer> /* dummy */,
- const C& container, ::std::ostream* os) {
- const size_t kMaxCount = 32; // The maximum number of elements to print.
- *os << '{';
- size_t count = 0;
- for (typename C::const_iterator it = container.begin();
- it != container.end(); ++it, ++count) {
- if (count > 0) {
- *os << ',';
- if (count == kMaxCount) { // Enough has been printed.
- *os << " ...";
- break;
- }
- }
- *os << ' ';
- // We cannot call PrintTo(*it, os) here as PrintTo() doesn't
- // handle *it being a native array.
- internal::UniversalPrint(*it, os);
- }
-
- if (count > 0) {
- *os << ' ';
- }
- *os << '}';
-}
-
-// Used to print a pointer that is neither a char pointer nor a member
-// pointer, when the user doesn't define PrintTo() for it. (A member
-// variable pointer or member function pointer doesn't really point to
-// a location in the address space. Their representation is
-// implementation-defined. Therefore they will be printed as raw
-// bytes.)
-template <typename T>
-void DefaultPrintTo(WrapPrinterType<kPrintPointer> /* dummy */,
- T* p, ::std::ostream* os) {
- if (p == nullptr) {
- *os << "NULL";
- } else {
- // T is not a function type. We just call << to print p,
- // relying on ADL to pick up user-defined << for their pointer
- // types, if any.
- *os << p;
- }
-}
-template <typename T>
-void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
- T* p, ::std::ostream* os) {
- if (p == nullptr) {
- *os << "NULL";
- } else {
- // T is a function type, so '*os << p' doesn't do what we want
- // (it just prints p as bool). We want to print p as a const
- // void*.
- *os << reinterpret_cast<const void*>(p);
- }
-}
-
-// Used to print a non-container, non-pointer value when the user
-// doesn't define PrintTo() for it.
-template <typename T>
-void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
- const T& value, ::std::ostream* os) {
- ::testing_internal::DefaultPrintNonContainerTo(value, os);
-}
-
// Prints the given value using the << operator if it has one;
// otherwise prints the bytes in it. This is what
// UniversalPrinter<T>::Print() does when PrintTo() is not specialized
@@ -481,36 +462,7 @@ void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
// wants).
template <typename T>
void PrintTo(const T& value, ::std::ostream* os) {
- // DefaultPrintTo() is overloaded. The type of its first argument
- // determines which version will be picked.
- //
- // Note that we check for container types here, prior to we check
- // for protocol message types in our operator<<. The rationale is:
- //
- // For protocol messages, we want to give people a chance to
- // override Google Mock's format by defining a PrintTo() or
- // operator<<. For STL containers, other formats can be
- // incompatible with Google Mock's format for the container
- // elements; therefore we check for container types here to ensure
- // that our format is used.
- //
- // Note that MSVC and clang-cl do allow an implicit conversion from
- // pointer-to-function to pointer-to-object, but clang-cl warns on it.
- // So don't use ImplicitlyConvertible if it can be helped since it will
- // cause this warning, and use a separate overload of DefaultPrintTo for
- // function pointers so that the `*os << p` in the object pointer overload
- // doesn't cause that warning either.
- DefaultPrintTo(
- WrapPrinterType <
- (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
- !IsRecursiveContainer<T>::value
- ? kPrintContainer
- : !std::is_pointer<T>::value
- ? kPrintOther
- : std::is_function<typename std::remove_pointer<T>::type>::value
- ? kPrintFunctionPointer
- : kPrintPointer > (),
- value, os);
+ internal::PrintWithFallback(value, os);
}
// The following list of PrintTo() overloads tells
@@ -541,6 +493,103 @@ inline void PrintTo(bool x, ::std::ostream* os) {
// is implemented as an unsigned type.
GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
+GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
+inline void PrintTo(char16_t c, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<char32_t>(c), os);
+}
+#ifdef __cpp_lib_char8_t
+inline void PrintTo(char8_t c, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<char32_t>(c), 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__
+
+// The default resolution used to print floating-point values uses only
+// 6 digits, which can be confusing if a test compares two values whose
+// difference lies in the 7th digit. So we'd like to print out numbers
+// in full precision.
+// However if the value is something simple like 1.1, full will print a
+// long string like 1.100000001 due to floating-point numbers not using
+// a base of 10. This routiune returns an appropriate resolution for a
+// given floating-point number, that is, 6 if it will be accurate, or a
+// max_digits10 value (full precision) if it won't, for values between
+// 0.0001 and one million.
+// It does this by computing what those digits would be (by multiplying
+// by an appropriate power of 10), then dividing by that power again to
+// see if gets the original value back.
+// A similar algorithm applies for values larger than one million; note
+// that for those values, we must divide to get a six-digit number, and
+// then multiply to possibly get the original value again.
+template <typename FloatType>
+int AppropriateResolution(FloatType val) {
+ int full = std::numeric_limits<FloatType>::max_digits10;
+ if (val < 0) val = -val;
+
+ if (val < 1000000) {
+ FloatType mulfor6 = 1e10;
+ if (val >= 100000.0) { // 100,000 to 999,999
+ mulfor6 = 1.0;
+ } else if (val >= 10000.0) {
+ mulfor6 = 1e1;
+ } else if (val >= 1000.0) {
+ mulfor6 = 1e2;
+ } else if (val >= 100.0) {
+ mulfor6 = 1e3;
+ } else if (val >= 10.0) {
+ mulfor6 = 1e4;
+ } else if (val >= 1.0) {
+ mulfor6 = 1e5;
+ } else if (val >= 0.1) {
+ mulfor6 = 1e6;
+ } else if (val >= 0.01) {
+ mulfor6 = 1e7;
+ } else if (val >= 0.001) {
+ mulfor6 = 1e8;
+ } else if (val >= 0.0001) {
+ mulfor6 = 1e9;
+ }
+ if (static_cast<FloatType>(static_cast<int32_t>(val * mulfor6 + 0.5)) /
+ mulfor6 ==
+ val)
+ return 6;
+ } else if (val < 1e10) {
+ FloatType divfor6 = 1.0;
+ if (val >= 1e9) { // 1,000,000,000 to 9,999,999,999
+ divfor6 = 10000;
+ } else if (val >= 1e8) { // 100,000,000 to 999,999,999
+ divfor6 = 1000;
+ } else if (val >= 1e7) { // 10,000,000 to 99,999,999
+ divfor6 = 100;
+ } else if (val >= 1e6) { // 1,000,000 to 9,999,999
+ divfor6 = 10;
+ }
+ if (static_cast<FloatType>(static_cast<int32_t>(val / divfor6 + 0.5)) *
+ divfor6 ==
+ val)
+ return 6;
+ }
+ return full;
+}
+
+inline void PrintTo(float f, ::std::ostream* os) {
+ auto old_precision = os->precision();
+ os->precision(AppropriateResolution(f));
+ *os << f;
+ os->precision(old_precision);
+}
+
+inline void PrintTo(double d, ::std::ostream* os) {
+ auto old_precision = os->precision();
+ os->precision(AppropriateResolution(d));
+ *os << d;
+ os->precision(old_precision);
+}
+
// Overloads for C strings.
GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
inline void PrintTo(char* s, ::std::ostream* os) {
@@ -561,6 +610,23 @@ inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
inline void PrintTo(unsigned char* s, ::std::ostream* os) {
PrintTo(ImplicitCast_<const void*>(s), os);
}
+#ifdef __cpp_lib_char8_t
+// Overloads for u8 strings.
+GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
+inline void PrintTo(char8_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const char8_t*>(s), os);
+}
+#endif
+// Overloads for u16 strings.
+GTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);
+inline void PrintTo(char16_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const char16_t*>(s), os);
+}
+// Overloads for u32 strings.
+GTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);
+inline void PrintTo(char32_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const char32_t*>(s), os);
+}
// MSVC can be configured to define wchar_t as a typedef of unsigned
// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
@@ -590,33 +656,96 @@ 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);
}
+// Overloads for ::std::u8string
+#ifdef __cpp_lib_char8_t
+GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
+inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
+ PrintU8StringTo(s, os);
+}
+#endif
+
+// Overloads for ::std::u16string
+GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
+inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
+ PrintU16StringTo(s, os);
+}
+
+// Overloads for ::std::u32string
+GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
+inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
+ PrintU32StringTo(s, 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);
}
#endif // GTEST_HAS_STD_WSTRING
-#if GTEST_HAS_ABSL
-// Overload for absl::string_view.
-inline void PrintTo(absl::string_view sp, ::std::ostream* os) {
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+// Overload for internal::StringView.
+inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
PrintTo(::std::string(sp), os);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
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);
}
+inline const void* VoidifyPointer(const void* p) { return p; }
+inline const void* VoidifyPointer(volatile const void* p) {
+ return const_cast<const void*>(p);
+}
+
+template <typename T, typename Ptr>
+void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
+ if (ptr == nullptr) {
+ *os << "(nullptr)";
+ } else {
+ // We can't print the value. Just print the pointer..
+ *os << "(" << (VoidifyPointer)(ptr.get()) << ")";
+ }
+}
+template <typename T, typename Ptr,
+ typename = typename std::enable_if<!std::is_void<T>::value &&
+ !std::is_array<T>::value>::type>
+void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
+ if (ptr == nullptr) {
+ *os << "(nullptr)";
+ } else {
+ *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
+ UniversalPrinter<T>::Print(*ptr, os);
+ *os << ")";
+ }
+}
+
+template <typename T, typename D>
+void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
+ (PrintSmartPointer<T>)(ptr, os, 0);
+}
+
+template <typename T>
+void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
+ (PrintSmartPointer<T>)(ptr, os, 0);
+}
+
// Helper function for printing a tuple. T must be instantiated with
// a tuple type.
template <typename T>
@@ -682,14 +811,46 @@ class UniversalPrinter {
GTEST_DISABLE_MSC_WARNINGS_POP_()
};
-#if GTEST_HAS_ABSL
+// Remove any const-qualifiers before passing a type to UniversalPrinter.
+template <typename T>
+class UniversalPrinter<const T> : public UniversalPrinter<T> {};
+
+#if GTEST_INTERNAL_HAS_ANY
-// Printer for absl::optional
+// Printer for std::any / absl::any
+
+template <>
+class UniversalPrinter<Any> {
+ public:
+ static void Print(const Any& value, ::std::ostream* os) {
+ if (value.has_value()) {
+ *os << "value of type " << GetTypeName(value);
+ } else {
+ *os << "no value";
+ }
+ }
+
+ private:
+ static std::string GetTypeName(const Any& value) {
+#if GTEST_HAS_RTTI
+ return internal::GetTypeName(value.type());
+#else
+ static_cast<void>(value); // possibly unused
+ return "<unknown_type>";
+#endif // GTEST_HAS_RTTI
+ }
+};
+
+#endif // GTEST_INTERNAL_HAS_ANY
+
+#if GTEST_INTERNAL_HAS_OPTIONAL
+
+// Printer for std::optional / absl::optional
template <typename T>
-class UniversalPrinter<::absl::optional<T>> {
+class UniversalPrinter<Optional<T>> {
public:
- static void Print(const ::absl::optional<T>& value, ::std::ostream* os) {
+ static void Print(const Optional<T>& value, ::std::ostream* os) {
*os << '(';
if (!value) {
*os << "nullopt";
@@ -700,14 +861,30 @@ class UniversalPrinter<::absl::optional<T>> {
}
};
-// Printer for absl::variant
+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
+
+// Printer for std::variant / absl::variant
template <typename... T>
-class UniversalPrinter<::absl::variant<T...>> {
+class UniversalPrinter<Variant<T...>> {
public:
- static void Print(const ::absl::variant<T...>& value, ::std::ostream* os) {
+ static void Print(const Variant<T...>& value, ::std::ostream* os) {
*os << '(';
- absl::visit(Visitor{os}, value);
+#ifdef GTEST_HAS_ABSL
+ absl::visit(Visitor{os, value.index()}, value);
+#else
+ std::visit(Visitor{os, value.index()}, value);
+#endif // GTEST_HAS_ABSL
*os << ')';
}
@@ -715,14 +892,16 @@ class UniversalPrinter<::absl::variant<T...>> {
struct Visitor {
template <typename U>
void operator()(const U& u) const {
- *os << "'" << GetTypeName<U>() << "' with value ";
+ *os << "'" << GetTypeName<U>() << "(index = " << index
+ << ")' with value ";
UniversalPrint(u, os);
}
::std::ostream* os;
+ std::size_t index;
};
};
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_VARIANT
// UniversalPrintArray(begin, len, os) prints an array of 'len'
// elements, starting at address 'begin'.
@@ -748,12 +927,26 @@ 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_lib_char8_t
+// This overload prints a (const) char8_t array compactly.
+GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
+ ::std::ostream* os);
+#endif
+
+// This overload prints a (const) char16_t array compactly.
+GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
+ ::std::ostream* os);
+
+// This overload prints a (const) char32_t array compactly.
+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>
@@ -804,6 +997,13 @@ class UniversalTersePrinter<T&> {
UniversalPrint(value, os);
}
};
+template <typename T>
+class UniversalTersePrinter<std::reference_wrapper<T>> {
+ public:
+ static void Print(std::reference_wrapper<T> value, ::std::ostream* os) {
+ UniversalTersePrinter<T>::Print(value.get(), os);
+ }
+};
template <typename T, size_t N>
class UniversalTersePrinter<T[N]> {
public:
@@ -823,12 +1023,55 @@ class UniversalTersePrinter<const char*> {
}
};
template <>
-class UniversalTersePrinter<char*> {
+class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
+};
+
+#ifdef __cpp_lib_char8_t
+template <>
+class UniversalTersePrinter<const char8_t*> {
public:
- static void Print(char* str, ::std::ostream* os) {
- UniversalTersePrinter<const char*>::Print(str, os);
+ static void Print(const char8_t* str, ::std::ostream* os) {
+ if (str == nullptr) {
+ *os << "NULL";
+ } else {
+ UniversalPrint(::std::u8string(str), os);
+ }
}
};
+template <>
+class UniversalTersePrinter<char8_t*>
+ : public UniversalTersePrinter<const char8_t*> {};
+#endif
+
+template <>
+class UniversalTersePrinter<const char16_t*> {
+ public:
+ static void Print(const char16_t* str, ::std::ostream* os) {
+ if (str == nullptr) {
+ *os << "NULL";
+ } else {
+ UniversalPrint(::std::u16string(str), os);
+ }
+ }
+};
+template <>
+class UniversalTersePrinter<char16_t*>
+ : public UniversalTersePrinter<const char16_t*> {};
+
+template <>
+class UniversalTersePrinter<const char32_t*> {
+ public:
+ static void Print(const char32_t* str, ::std::ostream* os) {
+ if (str == nullptr) {
+ *os << "NULL";
+ } else {
+ UniversalPrint(::std::u32string(str), os);
+ }
+ }
+};
+template <>
+class UniversalTersePrinter<char32_t*>
+ : public UniversalTersePrinter<const char32_t*> {};
#if GTEST_HAS_STD_WSTRING
template <>
@@ -869,10 +1112,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*) {}
@@ -901,16 +1144,6 @@ Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
} // namespace internal
-#if GTEST_HAS_ABSL
-namespace internal2 {
-template <typename T>
-void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
- const T& value, ::std::ostream* os) {
- internal::PrintTo(absl::string_view(value), os);
-}
-} // namespace internal2
-#endif
-
template <typename T>
::std::string PrintToString(const T& value) {
::std::stringstream ss;
@@ -925,4 +1158,4 @@ template <typename T>
// declarations from this file.
#include "gtest/internal/custom/gtest-printers.h"
-#endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
diff --git a/googletest/include/gtest/gtest-spi.h b/googletest/include/gtest/gtest-spi.h
index aa38870e8e1c..c0613b695956 100644
--- a/googletest/include/gtest/gtest-spi.h
+++ b/googletest/include/gtest/gtest-spi.h
@@ -27,14 +27,13 @@
// (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_
-#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
-#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
+#include <string>
#include "gtest/gtest.h"
@@ -88,7 +87,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 +106,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 +123,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 +146,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 +214,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 // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
diff --git a/googletest/include/gtest/gtest-test-part.h b/googletest/include/gtest/gtest-test-part.h
index 05a79853586a..41c8a9a0d0e3 100644
--- a/googletest/include/gtest/gtest-test-part.h
+++ b/googletest/include/gtest/gtest-test-part.h
@@ -26,14 +26,19 @@
// 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
-#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
-#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
+// 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 <ostream>
+#include <string>
#include <vector>
+
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-string.h"
@@ -128,7 +133,7 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
// virtual.
class GTEST_API_ TestPartResultArray {
public:
- TestPartResultArray() {}
+ TestPartResultArray() = default;
// Appends the given TestPartResult to the array.
void Append(const TestPartResult& result);
@@ -142,13 +147,14 @@ 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.
class GTEST_API_ TestPartResultReporterInterface {
public:
- virtual ~TestPartResultReporterInterface() {}
+ virtual ~TestPartResultReporterInterface() = default;
virtual void ReportTestPartResult(const TestPartResult& result) = 0;
};
@@ -168,11 +174,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
@@ -181,4 +189,4 @@ class GTEST_API_ HasNewFatalFailureHelper
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
-#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h
index 095ce058022f..72de536bceec 100644
--- a/googletest/include/gtest/gtest-typed-test.h
+++ b/googletest/include/gtest/gtest-typed-test.h
@@ -27,11 +27,12 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
-// GOOGLETEST_CM0001 DO NOT DELETE
-
-#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
-#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
// This header implements typed tests and type-parameterized tests.
@@ -170,13 +171,12 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
#endif // 0
+#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
#include "gtest/internal/gtest-type-util.h"
// Implements typed tests.
-#if GTEST_HAS_TYPED_TEST
-
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// Expands to the name of the typedef for the type parameters of the
@@ -188,24 +188,25 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
#define GTEST_NAME_GENERATOR_(TestSuiteName) \
gtest_type_params_##TestSuiteName##_NameGenerator
-#define TYPED_TEST_SUITE(CaseName, Types, ...) \
- typedef ::testing::internal::TypeList<Types>::type GTEST_TYPE_PARAMS_( \
- CaseName); \
- typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
- GTEST_NAME_GENERATOR_(CaseName)
+#define TYPED_TEST_SUITE(CaseName, Types, ...) \
+ typedef ::testing::internal::GenerateTypeList<Types>::type \
+ GTEST_TYPE_PARAMS_(CaseName); \
+ typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
+ GTEST_NAME_GENERATOR_(CaseName)
-# define TYPED_TEST(CaseName, TestName) \
+#define TYPED_TEST(CaseName, TestName) \
+ static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \
+ "test-name must not be empty"); \
template <typename gtest_TypeParam_> \
class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
: public CaseName<gtest_TypeParam_> { \
private: \
typedef CaseName<gtest_TypeParam_> TestFixture; \
typedef gtest_TypeParam_ TypeParam; \
- virtual void TestBody(); \
+ void TestBody() override; \
}; \
static bool gtest_##CaseName##_##TestName##_registered_ \
- GTEST_ATTRIBUTE_UNUSED_ = \
- ::testing::internal::TypeParameterizedTest< \
+ GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \
CaseName, \
::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
TestName)>, \
@@ -213,7 +214,8 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
CaseName)>::Register("", \
::testing::internal::CodeLocation( \
__FILE__, __LINE__), \
- #CaseName, #TestName, 0, \
+ GTEST_STRINGIFY_(CaseName), \
+ GTEST_STRINGIFY_(TestName), 0, \
::testing::internal::GenerateNames< \
GTEST_NAME_GENERATOR_(CaseName), \
GTEST_TYPE_PARAMS_(CaseName)>()); \
@@ -228,12 +230,8 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
TYPED_TEST_SUITE
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
-#endif // GTEST_HAS_TYPED_TEST
-
// Implements type-parameterized tests.
-#if GTEST_HAS_TYPED_TEST_P
-
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// Expands to the namespace name that the type-parameterized tests for
@@ -260,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_
@@ -269,31 +267,33 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
TYPED_TEST_SUITE_P
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
-#define TYPED_TEST_P(SuiteName, TestName) \
- namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
- template <typename gtest_TypeParam_> \
- class TestName : public SuiteName<gtest_TypeParam_> { \
- private: \
- typedef SuiteName<gtest_TypeParam_> TestFixture; \
- typedef gtest_TypeParam_ TypeParam; \
- virtual void TestBody(); \
- }; \
- static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
- GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
- __FILE__, __LINE__, #SuiteName, #TestName); \
- } \
- template <typename gtest_TypeParam_> \
- void GTEST_SUITE_NAMESPACE_( \
+#define TYPED_TEST_P(SuiteName, TestName) \
+ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
+ template <typename gtest_TypeParam_> \
+ class TestName : public SuiteName<gtest_TypeParam_> { \
+ private: \
+ typedef SuiteName<gtest_TypeParam_> TestFixture; \
+ typedef gtest_TypeParam_ TypeParam; \
+ void TestBody() override; \
+ }; \
+ static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
+ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
+ __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
+ GTEST_STRINGIFY_(TestName)); \
+ } \
+ template <typename gtest_TypeParam_> \
+ void GTEST_SUITE_NAMESPACE_( \
SuiteName)::TestName<gtest_TypeParam_>::TestBody()
-#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
- namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
- typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \
- } \
- static const char* const GTEST_REGISTERED_TEST_NAMES_( \
- SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
- GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
- __FILE__, __LINE__, #__VA_ARGS__)
+// Note: this won't work correctly if the trailing arguments are macros.
+#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
+ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
+ typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
+ } \
+ static const char* const GTEST_REGISTERED_TEST_NAMES_( \
+ SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
+ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
+ GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
@@ -303,19 +303,22 @@ 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 bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
- ::testing::internal::TypeParameterizedTestSuite< \
- SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
- ::testing::internal::TypeList<Types>::type>:: \
- Register(#Prefix, \
- ::testing::internal::CodeLocation(__FILE__, __LINE__), \
- &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), #SuiteName, \
- GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
- ::testing::internal::GenerateNames< \
- ::testing::internal::NameGeneratorSelector< \
- __VA_ARGS__>::type, \
- ::testing::internal::TypeList<Types>::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
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
@@ -325,6 +328,4 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
INSTANTIATE_TYPED_TEST_SUITE_P
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
-#endif // GTEST_HAS_TYPED_TEST_P
-
-#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h
index dbe5b1c2c3f6..de7d528fc687 100644
--- a/googletest/include/gtest/gtest.h
+++ b/googletest/include/gtest/gtest.h
@@ -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,43 +46,37 @@
// registration from Barthelemy Dagenais' (barthelemy@prologique.com)
// easyUnit framework.
-// GOOGLETEST_CM0001 DO NOT DELETE
-
-#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
-#define GTEST_INCLUDE_GTEST_GTEST_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
#include <cstddef>
+#include <cstdint>
+#include <iomanip>
#include <limits>
#include <memory>
#include <ostream>
+#include <set>
+#include <sstream>
+#include <string>
#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.
@@ -101,6 +94,10 @@ GTEST_DECLARE_bool_(catch_exceptions);
// to let Google Test decide.
GTEST_DECLARE_string_(color);
+// This flag controls whether the test runner should continue execution past
+// first failure.
+GTEST_DECLARE_bool_(fail_fast);
+
// This flag sets up the filter to select by name using a glob pattern
// the tests to run. If the filter is not given all tests are executed.
GTEST_DECLARE_string_(filter);
@@ -117,6 +114,9 @@ GTEST_DECLARE_bool_(list_tests);
// in addition to its normal textual output.
GTEST_DECLARE_string_(output);
+// This flags control whether Google Test prints only test failures.
+GTEST_DECLARE_bool_(brief);
+
// This flags control whether Google Test prints the elapsed time for each
// test.
GTEST_DECLARE_bool_(print_time);
@@ -131,6 +131,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);
@@ -156,6 +162,12 @@ 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'
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4805 4100)
+
// The upper limit for valid stack trace depths.
const int kMaxStackTraceDepth = 100;
@@ -177,6 +189,18 @@ class FuchsiaDeathTest;
class UnitTestImpl* GetUnitTestImpl();
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const std::string& message);
+std::set<std::string>* GetIgnoredParameterizedTestSuites();
+
+// A base class that prevents subclasses from being copyable.
+// We do this instead of using '= delete' so as to avoid triggering warnings
+// inside user code regarding any of our declarations.
+class GTestNonCopyable {
+ public:
+ GTestNonCopyable() = default;
+ GTestNonCopyable(const GTestNonCopyable&) = delete;
+ GTestNonCopyable& operator=(const GTestNonCopyable&) = delete;
+ ~GTestNonCopyable() = default;
+};
} // namespace internal
@@ -193,189 +217,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);
-
-#if defined(_MSC_VER) && _MSC_VER < 1910
- 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
- 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
@@ -406,27 +247,24 @@ class GTEST_API_ Test {
// The d'tor is virtual as we intend to inherit from Test.
virtual ~Test();
- // Sets up the stuff shared by all tests in this test case.
+ // Sets up the stuff shared by all tests in this test suite.
//
// Google Test will call Foo::SetUpTestSuite() before running the first
- // test in test case Foo. Hence a sub-class can define its own
+ // test in test suite Foo. Hence a sub-class can define its own
// SetUpTestSuite() method to shadow the one defined in the super
// class.
- // Failures that happen during SetUpTestSuite are logged but otherwise
- // ignored.
static void SetUpTestSuite() {}
// Tears down the stuff shared by all tests in this test suite.
//
// Google Test will call Foo::TearDownTestSuite() after running the last
- // test in test case Foo. Hence a sub-class can define its own
+ // test in test suite Foo. Hence a sub-class can define its own
// TearDownTestSuite() method to shadow the one defined in the super
// class.
- // Failures that happen during TearDownTestSuite are logged but otherwise
- // ignored.
static void TearDownTestSuite() {}
- // Legacy API is deprecated but still available
+ // Legacy API is deprecated but still available. Use SetUpTestSuite and
+ // TearDownTestSuite instead.
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
static void TearDownTestCase() {}
static void SetUpTestCase() {}
@@ -459,7 +297,13 @@ class GTEST_API_ Test {
// SetUp/TearDown method of Environment objects registered with Google
// Test) will be output as attributes of the <testsuites> element.
static void RecordProperty(const std::string& key, const std::string& value);
- static void RecordProperty(const std::string& key, int value);
+ // We do not define a custom serialization except for values that can be
+ // converted to int64_t, but other values could be logged in this way.
+ template <typename T, std::enable_if_t<std::is_convertible<T, int64_t>::value,
+ bool> = true>
+ static void RecordProperty(const std::string& key, const T& value) {
+ RecordProperty(key, (Message() << value).GetString());
+ }
protected:
// Creates a Test object.
@@ -513,7 +357,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;
@@ -527,24 +372,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.
@@ -664,7 +502,7 @@ class GTEST_API_ TestResult {
// Protects mutable state of the property vector and of owned
// properties, whose values may be updated.
- internal::Mutex test_properites_mutex_;
+ internal::Mutex test_properties_mutex_;
// The vector of TestPartResults
std::vector<TestPartResult> test_part_results_;
@@ -678,7 +516,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:
@@ -712,14 +551,14 @@ class GTEST_API_ TestInfo {
// Returns the name of the parameter type, or NULL if this is not a typed
// or a type-parameterized test.
const char* type_param() const {
- if (type_param_.get() != nullptr) return type_param_->c_str();
+ if (type_param_ != nullptr) return type_param_->c_str();
return nullptr;
}
// Returns the text representation of the value parameter, or NULL if this
// is not a value-parameterized test.
const char* value_param() const {
- if (value_param_.get() != nullptr) return value_param_->c_str();
+ if (value_param_ != nullptr) return value_param_->c_str();
return nullptr;
}
@@ -761,7 +600,7 @@ class GTEST_API_ TestInfo {
const TestResult* result() const { return &result_; }
private:
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
friend class internal::DefaultDeathTestFactory;
#endif // GTEST_HAS_DEATH_TEST
friend class Test;
@@ -794,13 +633,16 @@ class GTEST_API_ TestInfo {
// deletes it.
void Run();
+ // Skip and records the test result for this object.
+ void Skip();
+
static void ClearTestResult(TestInfo* test_info) {
test_info->result_.Clear();
}
// 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_;
@@ -821,7 +663,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.
@@ -854,7 +697,7 @@ class GTEST_API_ TestSuite {
// Returns the name of the parameter type, or NULL if this is not a
// type-parameterized test suite.
const char* type_param() const {
- if (type_param_.get() != nullptr) return type_param_->c_str();
+ if (type_param_ != nullptr) return type_param_->c_str();
return nullptr;
}
@@ -889,7 +732,9 @@ class GTEST_API_ TestSuite {
bool Passed() const { return !Failed(); }
// Returns true if and only if the test suite failed.
- bool Failed() const { return failed_test_count() > 0; }
+ bool Failed() const {
+ return failed_test_count() > 0 || ad_hoc_test_result().Failed();
+ }
// Returns the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; }
@@ -927,7 +772,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();
@@ -940,6 +785,9 @@ class GTEST_API_ TestSuite {
// Runs every test in this TestSuite.
void Run();
+ // Skips the execution of tests under this TestSuite
+ void Skip();
+
// Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
// for catching exceptions thrown from SetUpTestSuite().
void RunSetUpTestSuite() {
@@ -1025,7 +873,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
@@ -1045,13 +894,14 @@ class GTEST_API_ TestSuite {
class Environment {
public:
// The d'tor is virtual as we need to subclass Environment.
- virtual ~Environment() {}
+ virtual ~Environment() = default;
// Override this to define how to set up the environment.
virtual void SetUp() {}
// 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().
@@ -1075,7 +925,7 @@ class GTEST_API_ AssertionException
// the order the corresponding events are fired.
class TestEventListener {
public:
- virtual ~TestEventListener() {}
+ virtual ~TestEventListener() = default;
// Fired before any test activity starts.
virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
@@ -1103,6 +953,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.
@@ -1126,8 +979,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;
@@ -1152,6 +1004,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 {}
@@ -1202,6 +1055,10 @@ class GTEST_API_ TestEventListeners {
return default_xml_generator_;
}
+ // Controls whether events will be forwarded by the repeater to the
+ // listeners in the list.
+ void SuppressEventForwarding(bool);
+
private:
friend class TestSuite;
friend class TestInfo;
@@ -1231,7 +1088,6 @@ class GTEST_API_ TestEventListeners {
// Controls whether events will be forwarded by the repeater to the
// listeners in the list.
bool EventForwardingEnabled() const;
- void SuppressEventForwarding();
// The actual list of listeners.
internal::TestEventRepeater* repeater_;
@@ -1241,7 +1097,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.
@@ -1284,8 +1141,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;
@@ -1391,8 +1247,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_);
@@ -1420,10 +1275,10 @@ class GTEST_API_ UnitTest {
friend class internal::StreamingListenerTest;
friend class internal::UnitTestRecordPropertyTestHelper;
friend Environment* AddGlobalTestEnvironment(Environment* env);
+ 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();
@@ -1437,8 +1292,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.
@@ -1451,7 +1305,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
@@ -1502,13 +1357,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==/!=
@@ -1521,8 +1374,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();
@@ -1531,14 +1383,6 @@ AssertionResult CmpHelperEQ(const char* lhs_expression,
return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
}
-// With this overloaded version, we allow anonymous enums to be used
-// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums
-// can be implicitly cast to BiggestInt.
-GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression,
- const char* rhs_expression,
- BiggestInt lhs,
- BiggestInt rhs);
-
class EqHelper {
public:
// This templatized version is for the general case.
@@ -1561,8 +1405,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);
}
@@ -1595,38 +1438,31 @@ AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
// of similar code.
//
-// For each templatized helper function, we also define an overloaded
-// version for BiggestInt in order to reduce code bloat and allow
-// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled
-// with gcc 4.
-//
// 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);\
- }\
-}\
-GTEST_API_ AssertionResult CmpHelper##op_name(\
- const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2)
+#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.
// Implements the helper function for {ASSERT|EXPECT}_NE
-GTEST_IMPL_CMP_HELPER_(NE, !=);
+GTEST_IMPL_CMP_HELPER_(NE, !=)
// Implements the helper function for {ASSERT|EXPECT}_LE
-GTEST_IMPL_CMP_HELPER_(LE, <=);
+GTEST_IMPL_CMP_HELPER_(LE, <=)
// Implements the helper function for {ASSERT|EXPECT}_LT
-GTEST_IMPL_CMP_HELPER_(LT, <);
+GTEST_IMPL_CMP_HELPER_(LT, <)
// Implements the helper function for {ASSERT|EXPECT}_GE
-GTEST_IMPL_CMP_HELPER_(GE, >=);
+GTEST_IMPL_CMP_HELPER_(GE, >=)
// Implements the helper function for {ASSERT|EXPECT}_GT
-GTEST_IMPL_CMP_HELPER_(GT, >);
+GTEST_IMPL_CMP_HELPER_(GT, >)
#undef GTEST_IMPL_CMP_HELPER_
@@ -1635,49 +1471,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
@@ -1689,32 +1518,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 {
@@ -1729,8 +1566,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)) {
@@ -1745,10 +1581,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);
}
@@ -1758,8 +1592,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.
@@ -1767,9 +1600,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();
@@ -1783,11 +1614,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;
@@ -1795,20 +1624,16 @@ 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;
};
-enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW };
-
-GTEST_API_ GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color,
- const char* fmt,
- ...);
-
} // namespace internal
// The pure interface class that all value-parameterized tests inherit from.
@@ -1821,7 +1646,7 @@ GTEST_API_ GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color,
// the GetParam() method.
//
// Use it with one of the parameter generator defining functions, like Range(),
-// Values(), ValuesIn(), Bool(), and Combine().
+// Values(), ValuesIn(), Bool(), Combine(), and ConvertGenerator<T>().
//
// class FooTest : public ::testing::TestWithParam<int> {
// protected:
@@ -1849,7 +1674,7 @@ template <typename T>
class WithParamInterface {
public:
typedef T ParamType;
- virtual ~WithParamInterface() {}
+ virtual ~WithParamInterface() = default;
// The current parameter value. Is also available in the test fixture's
// constructor.
@@ -1863,15 +1688,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>
@@ -1881,15 +1705,14 @@ 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.
// Skips test in runtime.
// Skipping test aborts current function.
// Skipped tests are neither successful nor failed.
-#define GTEST_SKIP() GTEST_SKIP_("Skipped")
+#define GTEST_SKIP() GTEST_SKIP_("")
// ADD_FAILURE unconditionally adds a failure to the current test.
// SUCCEED generates a success - it doesn't automatically make the
@@ -1913,7 +1736,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)
@@ -1921,14 +1744,14 @@ class TestWithParam : public Test, public WithParamInterface<T> {
#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
// Like GTEST_FAIL(), but at the given source file location.
-#define GTEST_FAIL_AT(file, line) \
- GTEST_MESSAGE_AT_(file, line, "Failed", \
- ::testing::TestPartResult::kFatalFailure)
+#define GTEST_FAIL_AT(file, line) \
+ return GTEST_MESSAGE_AT_(file, line, "Failed", \
+ ::testing::TestPartResult::kFatalFailure)
// 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()
+#if !(defined(GTEST_DONT_DEFINE_FAIL) && GTEST_DONT_DEFINE_FAIL)
+#define FAIL() GTEST_FAIL()
#endif
// Generates a success with a generic message.
@@ -1936,8 +1759,8 @@ 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()
+#if !(defined(GTEST_DONT_DEFINE_SUCCEED) && GTEST_DONT_DEFINE_SUCCEED)
+#define SUCCEED() GTEST_SUCCEED()
#endif
// Macros for testing exceptions.
@@ -1965,19 +1788,37 @@ 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 EXPECT_TRUE(condition) \
+#define GTEST_EXPECT_TRUE(condition) \
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_NONFATAL_FAILURE_)
-#define EXPECT_FALSE(condition) \
+#define GTEST_EXPECT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_NONFATAL_FAILURE_)
-#define ASSERT_TRUE(condition) \
- GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
- GTEST_FATAL_FAILURE_)
-#define ASSERT_FALSE(condition) \
+#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, true, false, \
GTEST_FATAL_FAILURE_)
+// Define these macros to 1 to omit the definition of the corresponding
+// EXPECT or ASSERT, which clashes with some users' own code.
+
+#if !(defined(GTEST_DONT_DEFINE_EXPECT_TRUE) && GTEST_DONT_DEFINE_EXPECT_TRUE)
+#define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
+#endif
+
+#if !(defined(GTEST_DONT_DEFINE_EXPECT_FALSE) && GTEST_DONT_DEFINE_EXPECT_FALSE)
+#define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
+#endif
+
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_TRUE) && GTEST_DONT_DEFINE_ASSERT_TRUE)
+#define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
+#endif
+
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_FALSE) && GTEST_DONT_DEFINE_ASSERT_FALSE)
+#define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
+#endif
+
// Macros for testing equalities and inequalities.
//
// * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
@@ -2053,28 +1894,28 @@ class TestWithParam : public Test, public WithParamInterface<T> {
// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
// 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)
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_EQ) && GTEST_DONT_DEFINE_ASSERT_EQ)
+#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)
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_NE) && GTEST_DONT_DEFINE_ASSERT_NE)
+#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)
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_LE) && GTEST_DONT_DEFINE_ASSERT_LE)
+#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)
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_LT) && GTEST_DONT_DEFINE_ASSERT_LT)
+#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)
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_GE) && GTEST_DONT_DEFINE_ASSERT_GE)
+#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)
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_GT) && GTEST_DONT_DEFINE_ASSERT_GT)
+#define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
#endif
// C-string Comparisons. All tests treat NULL and any non-NULL string
@@ -2099,7 +1940,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) \
@@ -2108,7 +1949,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.
@@ -2125,29 +1966,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.
@@ -2161,8 +2002,7 @@ 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
+#ifdef GTEST_OS_WINDOWS
// Macros that test for HRESULT failure and success, these are only useful
// on Windows, and rely on Windows SDK macros and APIs to compile.
@@ -2173,17 +2013,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
@@ -2198,9 +2038,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
@@ -2242,10 +2082,9 @@ class GTEST_API_ ScopedTrace {
private:
void PushTrace(const char* file, int line, std::string message);
- GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
-} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
- // c'tor and d'tor. Therefore it doesn't
- // need to be used otherwise.
+ ScopedTrace(const ScopedTrace&) = delete;
+ ScopedTrace& operator=(const ScopedTrace&) = delete;
+};
// Causes a trace (including the source file path, the current line
// number, and the given message) to be included in every test failure
@@ -2262,9 +2101,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) \
+ const ::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
@@ -2298,8 +2137,7 @@ class GTEST_API_ ScopedTrace {
// to cause a compiler error.
template <typename T1, typename T2>
constexpr bool StaticAssertTypeEq() noexcept {
- static_assert(std::is_same<T1, T2>::value,
- "type1 and type2 are not the same type");
+ static_assert(std::is_same<T1, T2>::value, "T1 and T2 are not the same type");
return true;
}
@@ -2334,7 +2172,7 @@ constexpr bool StaticAssertTypeEq() noexcept {
// Define this macro to 1 to omit the definition of TEST(), which
// is a generic name and clashes with some other libraries.
-#if !GTEST_DONT_DEFINE_TEST
+#if !(defined(GTEST_DONT_DEFINE_TEST) && GTEST_DONT_DEFINE_TEST)
#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
#endif
@@ -2363,19 +2201,25 @@ constexpr bool StaticAssertTypeEq() noexcept {
// EXPECT_EQ(a_.size(), 0);
// EXPECT_EQ(b_.size(), 1);
// }
-//
-// GOOGLETEST_CM0011 DO NOT DELETE
-#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>())
+#if !(defined(GTEST_DONT_DEFINE_TEST_F) && 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.
+// Returns a path to a temporary directory, which should be writable. It is
+// implementation-dependent whether or not the path is terminated by the
+// directory-separator character.
GTEST_API_ std::string TempDir();
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
+// Returns a path to a directory that contains ancillary data files that might
+// be used by tests. It is implementation dependent whether or not the path is
+// terminated by the directory-separator character. The directory and the files
+// in it should be considered read-only.
+GTEST_API_ std::string SrcDir();
+
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4805 4100
// Dynamically registers a test with the framework.
//
@@ -2428,6 +2272,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);
// ...
@@ -2469,10 +2314,8 @@ 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
-#endif // GTEST_INCLUDE_GTEST_GTEST_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_H_
diff --git a/googletest/include/gtest/gtest_pred_impl.h b/googletest/include/gtest/gtest_pred_impl.h
index d514255c733b..47a24aa687af 100644
--- a/googletest/include/gtest/gtest_pred_impl.h
+++ b/googletest/include/gtest/gtest_pred_impl.h
@@ -26,17 +26,19 @@
// 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
-#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
-#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
+// 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 // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
diff --git a/googletest/include/gtest/gtest_prod.h b/googletest/include/gtest/gtest_prod.h
index e651671ebde8..1f37dc31c347 100644
--- a/googletest/include/gtest/gtest_prod.h
+++ b/googletest/include/gtest/gtest_prod.h
@@ -27,12 +27,11 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// 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 GTEST_INCLUDE_GTEST_GTEST_PROD_H_
-#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
// When you need to test the private or protected members of a class,
// use the FRIEND_TEST macro to declare your tests as friends of the
@@ -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 // GTEST_INCLUDE_GTEST_GTEST_PROD_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
diff --git a/googletest/include/gtest/internal/custom/README.md b/googletest/include/gtest/internal/custom/README.md
index ff391fb4e2b5..cb49e2c754c2 100644
--- a/googletest/include/gtest/internal/custom/README.md
+++ b/googletest/include/gtest/internal/custom/README.md
@@ -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)`
diff --git a/googletest/include/gtest/internal/custom/gtest-port.h b/googletest/include/gtest/internal/custom/gtest-port.h
index cd85d956d2dc..db02881c0c89 100644
--- a/googletest/include/gtest/internal/custom/gtest-port.h
+++ b/googletest/include/gtest/internal/custom/gtest-port.h
@@ -31,7 +31,7 @@
//
// ** Custom implementation starts here **
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
diff --git a/googletest/include/gtest/internal/custom/gtest-printers.h b/googletest/include/gtest/internal/custom/gtest-printers.h
index eb4467abcabe..b9495d83783b 100644
--- a/googletest/include/gtest/internal/custom/gtest-printers.h
+++ b/googletest/include/gtest/internal/custom/gtest-printers.h
@@ -36,7 +36,7 @@
//
// ** Custom implementation starts here **
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
diff --git a/googletest/include/gtest/internal/custom/gtest.h b/googletest/include/gtest/internal/custom/gtest.h
index 4c8e07be23f1..afaaf17ba28e 100644
--- a/googletest/include/gtest/internal/custom/gtest.h
+++ b/googletest/include/gtest/internal/custom/gtest.h
@@ -31,7 +31,7 @@
//
// ** Custom implementation starts here **
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h
index 68bd3530618f..8e9c988b98ce 100644
--- a/googletest/include/gtest/internal/gtest-death-test-internal.h
+++ b/googletest/include/gtest/internal/gtest-death-test-internal.h
@@ -26,33 +26,38 @@
// 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
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
-#include "gtest/gtest-matchers.h"
-#include "gtest/internal/gtest-internal.h"
+#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 <string>
-namespace testing {
-namespace internal {
+#include "gtest/gtest-matchers.h"
+#include "gtest/internal/gtest-internal.h"
GTEST_DECLARE_string_(internal_run_death_test);
+namespace testing {
+namespace internal {
+
// Names of the flags (needed for parsing Google Test flags).
const char kDeathTestStyleFlag[] = "death_test_style";
const char kDeathTestUseFork[] = "death_test_use_fork";
const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
@@ -83,17 +88,19 @@ 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() = default;
// 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);
- } GTEST_ATTRIBUTE_UNUSED_;
+ ReturnSentinel(const ReturnSentinel&) = delete;
+ ReturnSentinel& operator=(const ReturnSentinel&) = delete;
+ };
// An enumeration of possible roles that may be taken when a death
// test is encountered. EXECUTE means that the death test logic should
@@ -137,7 +144,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 +153,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() = default;
virtual bool Create(const char* statement,
Matcher<const std::string&> matcher, const char* file,
int line, DeathTest** test) = 0;
@@ -186,28 +194,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*.
@@ -230,14 +238,12 @@ inline Matcher<const ::std::string&> MakeDeathTestMatcher(
} \
break; \
case ::testing::internal::DeathTest::EXECUTE_TEST: { \
- ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
+ const ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
gtest_dt); \
GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
break; \
} \
- default: \
- break; \
} \
} \
} else \
@@ -265,16 +271,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 +290,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
@@ -301,4 +304,4 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
} // namespace internal
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
diff --git a/googletest/include/gtest/internal/gtest-filepath.h b/googletest/include/gtest/internal/gtest-filepath.h
index c11b101516e5..5189c81dabfa 100644
--- a/googletest/include/gtest/internal/gtest-filepath.h
+++ b/googletest/include/gtest/internal/gtest-filepath.h
@@ -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,16 +35,23 @@
// 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 GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
+#include <string>
+
+#include "gtest/internal/gtest-port.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 */)
+#if GTEST_HAS_FILE_SYSTEM
+
namespace testing {
namespace internal {
@@ -61,8 +68,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 +80,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 +93,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",
@@ -195,11 +199,21 @@ class GTEST_API_ FilePath {
void Normalize();
- // Returns a pointer to the last occurence of a valid path separator in
+ // Returns a pointer to the last occurrence of a valid path separator in
// the FilePath. On Windows, for example, both '/' and '\' are valid path
// separators. Returns NULL if no path separator was found.
const char* FindLastPathSeparator() const;
+ // Returns the length of the path root, including the directory separator at
+ // the end of the prefix. Returns zero by definition if the path is relative.
+ // Examples:
+ // - [Windows] "..\Sibling" => 0
+ // - [Windows] "\Windows" => 1
+ // - [Windows] "C:/Windows\Notepad.exe" => 3
+ // - [Windows] "\\Host\Share\C$/Windows" => 13
+ // - [UNIX] "/bin" => 1
+ size_t CalculateRootLength() const;
+
std::string pathname_;
}; // class FilePath
@@ -208,4 +222,6 @@ class GTEST_API_ FilePath {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
+#endif // GTEST_HAS_FILE_SYSTEM
+
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h
index 94c816a28bdb..a04a9201c616 100644
--- a/googletest/include/gtest/internal/gtest-internal.h
+++ b/googletest/include/gtest/internal/gtest-internal.h
@@ -26,39 +26,45 @@
// 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 GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
+#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>
+#ifdef GTEST_OS_LINUX
+#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 <functional>
#include <iomanip>
#include <limits>
#include <map>
#include <set>
#include <string>
#include <type_traits>
+#include <utility>
#include <vector>
#include "gtest/gtest-message.h"
@@ -75,32 +81,43 @@
// 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.
-#define GTEST_STRINGIFY_(name) #name
+// Work around a bug in visual studio which doesn't accept code like this:
+//
+// #define GTEST_STRINGIFY_(name) #name
+// #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...
+// MACRO(, x, y)
+//
+// Complaining about the argument to GTEST_STRINGIFY_ being empty.
+// This is allowed by the spec.
+#define GTEST_STRINGIFY_HELPER_(name, ...) #name
+#define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
-namespace proto2 { class Message; }
+namespace proto2 {
+class MessageLite;
+}
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.
@@ -109,6 +126,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
@@ -124,13 +142,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
@@ -169,14 +187,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.
//
@@ -200,10 +210,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
@@ -244,11 +252,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;
@@ -257,8 +265,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);
@@ -275,7 +283,7 @@ class FloatingPoint {
//
// See the following article for more details on ULP:
// http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
- static const size_t kMaxUlps = 4;
+ static const uint32_t kMaxUlps = 4;
// Constructs a FloatingPoint from a raw floating-point number.
//
@@ -297,17 +305,12 @@ class FloatingPoint {
}
// Returns the floating-point number that represent positive infinity.
- static RawType Infinity() {
- return ReinterpretBits(kExponentBitMask);
- }
-
- // Returns the maximum representable finite floating-point number.
- static RawType Max();
+ static RawType Infinity() { return ReinterpretBits(kExponentBitMask); }
// Non-static methods
// Returns the bits that represents this number.
- const Bits &bits() const { return u_.bits_; }
+ const Bits& bits() const { return u_.bits_; }
// Returns the exponent bits of this number.
Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
@@ -336,8 +339,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:
@@ -362,7 +365,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 Bits& sam) {
if (kSignBitMask & sam) {
// sam represents a negative number.
return ~sam + 1;
@@ -374,8 +377,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 Bits& sam1,
+ const Bits& sam2) {
const Bits biased1 = SignAndMagnitudeToBiased(sam1);
const Bits biased2 = SignAndMagnitudeToBiased(sam2);
return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
@@ -384,13 +387,6 @@ class FloatingPoint {
FloatingPointUnion u_;
};
-// 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; }
-template <>
-inline double FloatingPoint<double>::Max() { return DBL_MAX; }
-
// Typedefs the instances of the FloatingPoint template class that we
// care to use.
typedef FloatingPoint<float> Float;
@@ -439,7 +435,7 @@ GTEST_API_ TypeId GetTestTypeId();
// of a Test object.
class TestFactoryBase {
public:
- virtual ~TestFactoryBase() {}
+ virtual ~TestFactoryBase() = default;
// Creates a test instance to run. The instance is both created and destroyed
// within TestInfoImpl::Run()
@@ -449,10 +445,11 @@ 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.
+// This class provides implementation of TestFactoryBase interface.
// It is used in TEST and TEST_F macros.
template <class TestClass>
class TestFactoryImpl : public TestFactoryBase {
@@ -460,7 +457,7 @@ class TestFactoryImpl : public TestFactoryBase {
Test* CreateTest() override { return new TestClass; }
};
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Predicate-formatters for implementing the HRESULT checking macros
// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
@@ -498,16 +495,17 @@ 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;
static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
int line_num) {
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
SetUpTearDownSuiteFuncType test_case_fp =
GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
SetUpTearDownSuiteFuncType test_suite_fp =
@@ -519,10 +517,16 @@ struct SuiteApiResolver : T {
<< filename << ":" << line_num;
return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
+#else
+ (void)(filename);
+ (void)(line_num);
+ return &T::SetUpTestSuite;
+#endif
}
static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
int line_num) {
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
SetUpTearDownSuiteFuncType test_case_fp =
GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
SetUpTearDownSuiteFuncType test_suite_fp =
@@ -534,6 +538,11 @@ struct SuiteApiResolver : T {
<< filename << ":" << line_num;
return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
+#else
+ (void)(filename);
+ (void)(line_num);
+ return &T::TearDownTestSuite;
+#endif
}
};
@@ -542,11 +551,11 @@ struct SuiteApiResolver : T {
//
// Arguments:
//
-// test_suite_name: name of the test suite
+// test_suite_name: name of the test suite
// name: name of the test
-// type_param the name of the test's type parameter, or NULL if
+// type_param: the name of the test's type parameter, or NULL if
// this is not a typed or a type-parameterized test.
-// value_param text representation of the test's value parameter,
+// value_param: text representation of the test's value parameter,
// or NULL if this is not a type-parameterized test.
// code_location: code location where the test is defined
// fixture_class_id: ID of the test fixture class
@@ -566,8 +575,6 @@ GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
// and returns false. None of pstr, *pstr, and prefix can be NULL.
GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
-#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
-
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
@@ -607,11 +614,12 @@ class GTEST_API_ TypedTestSuitePState {
// Verifies that registered_tests match the test names in
// defined_test_names_; returns registered_tests if successful, or
// aborts the program otherwise.
- const char* VerifyRegisteredTestNames(
- const char* file, int line, const char* registered_tests);
+ const char* VerifyRegisteredTestNames(const char* test_suite_name,
+ const char* file, int line,
+ const char* registered_tests);
private:
- typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
+ typedef ::std::map<std::string, CodeLocation, std::less<>> RegisteredTestsMap;
bool registered_;
RegisteredTestsMap registered_tests_;
@@ -631,7 +639,8 @@ inline const char* SkipComma(const char* str) {
if (comma == nullptr) {
return nullptr;
}
- while (IsSpace(*(++comma))) {}
+ while (IsSpace(*(++comma))) {
+ }
return comma;
}
@@ -645,7 +654,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.
@@ -662,7 +671,7 @@ struct NameGeneratorSelector {
};
template <typename NameGenerator>
-void GenerateNamesRecursively(Types0, std::vector<std::string>*, int) {}
+void GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {}
template <typename NameGenerator, typename Types>
void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
@@ -729,7 +738,7 @@ class TypeParameterizedTest {
// The base case for the compile time recursion.
template <GTEST_TEMPLATE_ Fixture, class TestSel>
-class TypeParameterizedTest<Fixture, TestSel, Types0> {
+class TypeParameterizedTest<Fixture, TestSel, internal::None> {
public:
static bool Register(const char* /*prefix*/, const CodeLocation&,
const char* /*case_name*/, const char* /*test_names*/,
@@ -740,6 +749,11 @@ class TypeParameterizedTest<Fixture, TestSel, Types0> {
}
};
+GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
+ CodeLocation code_location);
+GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(
+ const char* case_name);
+
// TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
// registers *all combinations* of 'Tests' and 'Types' with Google
// Test. The return value is insignificant - we just need to return
@@ -752,13 +766,14 @@ class TypeParameterizedTestSuite {
const char* test_names,
const std::vector<std::string>& type_names =
GenerateNames<DefaultNameGenerator, Types>()) {
- std::string test_name = StripTrailingSpaces(
- GetPrefixUntilComma(test_names));
+ RegisterTypeParameterizedTestSuiteInstantiation(case_name);
+ 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();
}
@@ -781,7 +796,7 @@ class TypeParameterizedTestSuite {
// The base case for the compile time recursion.
template <GTEST_TEMPLATE_ Fixture, typename Types>
-class TypeParameterizedTestSuite<Fixture, Templates0, Types> {
+class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
public:
static bool Register(const char* /*prefix*/, const CodeLocation&,
const TypedTestSuitePState* /*state*/,
@@ -792,8 +807,6 @@ class TypeParameterizedTestSuite<Fixture, Templates0, Types> {
}
};
-#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
-
// Returns the current OS stack trace as an std::string.
//
// The maximum number of stack frames to be included is specified by
@@ -804,8 +817,7 @@ class TypeParameterizedTestSuite<Fixture, Templates0, 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(int skip_count);
// Helpers for suppressing warnings on unreachable code or constant
// condition.
@@ -825,6 +837,16 @@ struct GTEST_API_ ConstCharPtr {
const char* value;
};
+// Helper for declaring std::string within 'if' statement
+// in pre C++17 build environment.
+struct TrueWithString {
+ TrueWithString() = default;
+ explicit TrueWithString(const char* str) : value(str) {}
+ explicit TrueWithString(const std::string& str) : value(str) {}
+ explicit operator bool() const { return true; }
+ std::string value;
+};
+
// A simple Linear Congruential Generator for generating random
// numbers with a uniform distribution. Unlike rand() and srand(), it
// doesn't use global state (and therefore can't interfere with user
@@ -832,31 +854,56 @@ struct GTEST_API_ ConstCharPtr {
// but it's good enough for our purposes.
class GTEST_API_ Random {
public:
- static const UInt32 kMaxRange = 1u << 31;
+ static const uint32_t kMaxRange = 1u << 31;
- explicit Random(UInt32 seed) : state_(seed) {}
+ explicit Random(uint32_t seed) : state_(seed) {}
- void Reseed(UInt32 seed) { state_ = seed; }
+ void Reseed(uint32_t seed) { state_ = seed; }
// Generates a random number from [0, range). Crashes if 'range' is
// 0 or greater than kMaxRange.
- UInt32 Generate(UInt32 range);
+ uint32_t Generate(uint32_t range);
private:
- UInt32 state_;
- GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
+ uint32_t state_;
+ Random(const Random&) = delete;
+ Random& operator=(const Random&) = delete;
};
// Turns const U&, U&, const U, and U all into U.
#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
typename std::remove_const<typename std::remove_reference<T>::type>::type
-// IsAProtocolMessage<T>::value is a compile-time bool constant that's
-// true if and only if T is type proto2::Message or a subclass of it.
+// HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
+// that's true if and only if T has methods DebugString() and ShortDebugString()
+// that return std::string.
+template <typename T>
+class HasDebugStringAndShortDebugString {
+ private:
+ template <typename C>
+ static auto CheckDebugString(C*) -> typename std::is_same<
+ std::string, decltype(std::declval<const C>().DebugString())>::type;
+ template <typename>
+ static std::false_type CheckDebugString(...);
+
+ template <typename C>
+ static auto CheckShortDebugString(C*) -> typename std::is_same<
+ std::string, decltype(std::declval<const C>().ShortDebugString())>::type;
+ template <typename>
+ static std::false_type CheckShortDebugString(...);
+
+ using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));
+ using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));
+
+ public:
+ static constexpr bool value =
+ HasDebugStringType::value && HasShortDebugStringType::value;
+};
+
+#ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
template <typename T>
-struct IsAProtocolMessage
- : public bool_constant<
- std::is_convertible<const T*, const ::proto2::Message*>::value> {};
+constexpr bool HasDebugStringAndShortDebugString<T>::value;
+#endif
// When the compiler sees expression IsContainerTest<C>(0), if C is an
// STL-style container class, the first overload of IsContainerTest
@@ -895,7 +942,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
@@ -958,11 +1007,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);
}
@@ -972,8 +1023,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;
}
@@ -983,8 +1033,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;
}
@@ -998,11 +1047,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);
}
@@ -1055,8 +1106,7 @@ class NativeArray {
}
~NativeArray() {
- if (clone_ != &NativeArray::InitRef)
- delete[] array_;
+ if (clone_ != &NativeArray::InitRef) delete[] array_;
}
// STL-style container methods.
@@ -1064,8 +1114,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:
@@ -1092,8 +1141,6 @@ class NativeArray {
const Element* array_;
size_t size_;
void (NativeArray::*clone_)(const Element*, size_t);
-
- GTEST_DISALLOW_ASSIGN_(NativeArray);
};
// Backport of std::index_sequence.
@@ -1117,32 +1164,44 @@ struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
// Backport of std::make_index_sequence.
// It uses O(ln(N)) instantiation depth.
template <size_t N>
-struct MakeIndexSequence
- : DoubleSequence<N % 2 == 1, typename MakeIndexSequence<N / 2>::type,
+struct MakeIndexSequenceImpl
+ : DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,
N / 2>::type {};
template <>
-struct MakeIndexSequence<0> : IndexSequence<> {};
+struct MakeIndexSequenceImpl<0> : IndexSequence<> {};
-// FIXME: This implementation of ElemFromList is O(1) in instantiation depth,
-// but it is O(N^2) in total instantiations. Not sure if this is the best
-// tradeoff, as it will make it somewhat slow to compile.
-template <typename T, size_t, size_t>
-struct ElemFromListImpl {};
+template <size_t N>
+using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;
+
+template <typename... T>
+using IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;
-template <typename T, size_t I>
-struct ElemFromListImpl<T, I, I> {
- using type = T;
+template <size_t>
+struct Ignore {
+ Ignore(...); // NOLINT
};
-// Get the Nth element from T...
-// It uses O(1) instantiation depth.
-template <size_t N, typename I, typename... T>
-struct ElemFromList;
+template <typename>
+struct ElemFromListImpl;
+template <size_t... I>
+struct ElemFromListImpl<IndexSequence<I...>> {
+ // We make Ignore a template to solve a problem with MSVC.
+ // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but
+ // MSVC doesn't understand how to deal with that pack expansion.
+ // Use `0 * I` to have a single instantiation of Ignore.
+ template <typename R>
+ static R Apply(Ignore<0 * I>..., R (*)(), ...);
+};
+
+template <size_t N, typename... T>
+struct ElemFromList {
+ using type =
+ decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply(
+ static_cast<T (*)()>(nullptr)...));
+};
-template <size_t N, size_t... I, typename... T>
-struct ElemFromList<N, IndexSequence<I...>, T...>
- : ElemFromListImpl<T, N, I>... {};
+struct FlatTupleConstructTag {};
template <typename... T>
class FlatTuple;
@@ -1152,11 +1211,11 @@ struct FlatTupleElemBase;
template <typename... T, size_t I>
struct FlatTupleElemBase<FlatTuple<T...>, I> {
- using value_type =
- typename ElemFromList<I, typename MakeIndexSequence<sizeof...(T)>::type,
- T...>::type;
+ using value_type = typename ElemFromList<I, T...>::type;
FlatTupleElemBase() = default;
- explicit FlatTupleElemBase(value_type t) : value(std::move(t)) {}
+ template <typename Arg>
+ explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)
+ : value(std::forward<Arg>(t)) {}
value_type value;
};
@@ -1168,13 +1227,35 @@ struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
: FlatTupleElemBase<FlatTuple<T...>, Idx>... {
using Indices = IndexSequence<Idx...>;
FlatTupleBase() = default;
- explicit FlatTupleBase(T... t)
- : FlatTupleElemBase<FlatTuple<T...>, Idx>(std::move(t))... {}
+ template <typename... Args>
+ explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)
+ : FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},
+ std::forward<Args>(args))... {}
+
+ template <size_t I>
+ const typename ElemFromList<I, T...>::type& Get() const {
+ return FlatTupleElemBase<FlatTuple<T...>, I>::value;
+ }
+
+ template <size_t I>
+ typename ElemFromList<I, T...>::type& Get() {
+ return FlatTupleElemBase<FlatTuple<T...>, I>::value;
+ }
+
+ template <typename F>
+ auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
+ return std::forward<F>(f)(Get<Idx>()...);
+ }
+
+ template <typename F>
+ auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
+ return std::forward<F>(f)(Get<Idx>()...);
+ }
};
// Analog to std::tuple but with different tradeoffs.
// This class minimizes the template instantiation depth, thus allowing more
-// elements that std::tuple would. std::tuple has been seen to require an
+// elements than std::tuple would. std::tuple has been seen to require an
// instantiation depth of more than 10x the number of elements in some
// implementations.
// FlatTuple and ElemFromList are not recursive and have a fixed depth
@@ -1185,21 +1266,17 @@ template <typename... T>
class FlatTuple
: private FlatTupleBase<FlatTuple<T...>,
typename MakeIndexSequence<sizeof...(T)>::type> {
- using Indices = typename FlatTuple::FlatTupleBase::Indices;
+ using Indices = typename FlatTupleBase<
+ FlatTuple<T...>, typename MakeIndexSequence<sizeof...(T)>::type>::Indices;
public:
FlatTuple() = default;
- explicit FlatTuple(T... t) : FlatTuple::FlatTupleBase(std::move(t)...) {}
-
- template <size_t I>
- const typename ElemFromList<I, Indices, T...>::type& Get() const {
- return static_cast<const FlatTupleElemBase<FlatTuple, I>*>(this)->value;
- }
+ template <typename... Args>
+ explicit FlatTuple(FlatTupleConstructTag tag, Args&&... args)
+ : FlatTuple::FlatTupleBase(tag, std::forward<Args>(args)...) {}
- template <size_t I>
- typename ElemFromList<I, Indices, T...>::type& Get() {
- return static_cast<FlatTupleElemBase<FlatTuple, I>*>(this)->value;
- }
+ using FlatTuple::FlatTupleBase::Apply;
+ using FlatTuple::FlatTupleBase::Get;
};
// Utility functions to be called with static_assert to induce deprecation
@@ -1232,9 +1309,25 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
} // namespace internal
} // namespace testing
-#define GTEST_MESSAGE_AT_(file, line, message, result_type) \
- ::testing::internal::AssertHelper(result_type, file, line, message) \
- = ::testing::Message()
+namespace std {
+// Some standard library implementations use `struct tuple_size` and some use
+// `class tuple_size`. Clang warns about the mismatch.
+// https://reviews.llvm.org/D55466
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wmismatched-tags"
+#endif
+template <typename... Ts>
+struct tuple_size<testing::internal::FlatTuple<Ts...>>
+ : std::integral_constant<size_t, sizeof...(Ts)> {};
+#ifdef __clang__
+#pragma clang diagnostic pop
+#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_(message, result_type) \
GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
@@ -1254,127 +1347,214 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
// Suppress MSVC warning 4072 (unreachable code) for the code following
// statement if it returns or throws (or doesn't return or throw in some
// situations).
+// NOTE: The "else" is important to keep this expansion to prevent a top-level
+// "else" from attaching to our "if".
#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
- if (::testing::internal::AlwaysTrue()) { statement; }
-
-#define GTEST_TEST_THROW_(statement, expected_exception, fail) \
- GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
- if (::testing::internal::ConstCharPtr gtest_msg = "") { \
- bool gtest_caught_expected = false; \
- try { \
- GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
- } \
- catch (expected_exception const&) { \
- gtest_caught_expected = true; \
- } \
- catch (...) { \
- gtest_msg.value = \
- "Expected: " #statement " throws an exception of type " \
- #expected_exception ".\n Actual: it throws a different type."; \
- goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
- } \
- if (!gtest_caught_expected) { \
- gtest_msg.value = \
- "Expected: " #statement " throws an exception of type " \
- #expected_exception ".\n Actual: it throws nothing."; \
- goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
- } \
- } else \
- GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
- fail(gtest_msg.value)
-
-#define GTEST_TEST_NO_THROW_(statement, fail) \
- GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
- if (::testing::internal::AlwaysTrue()) { \
- try { \
- GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
- } \
- catch (...) { \
- 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: it throws.")
-
-#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.")
+ if (::testing::internal::AlwaysTrue()) { \
+ statement; \
+ } else /* NOLINT */ \
+ static_assert(true, "") // User must have a semicolon after expansion.
+
+#if GTEST_HAS_EXCEPTIONS
+
+namespace testing {
+namespace internal {
+
+class NeverThrown {
+ public:
+ const char* what() const noexcept {
+ return "this exception should never be thrown";
+ }
+};
+} // namespace internal
+} // namespace testing
+
+#if GTEST_HAS_RTTI
+
+#define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))
+
+#else // GTEST_HAS_RTTI
+
+#define GTEST_EXCEPTION_TYPE_(e) \
+ std::string { "an std::exception-derived error" }
+
+#endif // GTEST_HAS_RTTI
+
+#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
+ catch (typename std::conditional< \
+ std::is_same<typename std::remove_cv<typename std::remove_reference< \
+ expected_exception>::type>::type, \
+ std::exception>::value, \
+ const ::testing::internal::NeverThrown&, const std::exception&>::type \
+ e) { \
+ gtest_msg.value = "Expected: " #statement \
+ " throws an exception of type " #expected_exception \
+ ".\n Actual: it throws "; \
+ gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
+ gtest_msg.value += " with description \""; \
+ gtest_msg.value += e.what(); \
+ gtest_msg.value += "\"."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ }
+
+#else // GTEST_HAS_EXCEPTIONS
+
+#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)
+
+#endif // GTEST_HAS_EXCEPTIONS
+
+#define GTEST_TEST_THROW_(statement, expected_exception, fail) \
+ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
+ if (::testing::internal::TrueWithString gtest_msg{}) { \
+ bool gtest_caught_expected = false; \
+ try { \
+ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
+ } catch (expected_exception const&) { \
+ gtest_caught_expected = true; \
+ } \
+ GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
+ catch (...) { \
+ gtest_msg.value = "Expected: " #statement \
+ " throws an exception of type " #expected_exception \
+ ".\n Actual: it throws a different type."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ } \
+ if (!gtest_caught_expected) { \
+ gtest_msg.value = "Expected: " #statement \
+ " throws an exception of type " #expected_exception \
+ ".\n Actual: it throws nothing."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ } \
+ } else /*NOLINT*/ \
+ GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
+ : fail(gtest_msg.value.c_str())
+
+#if GTEST_HAS_EXCEPTIONS
+
+#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
+ catch (std::exception const& e) { \
+ gtest_msg.value = "it throws "; \
+ gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
+ gtest_msg.value += " with description \""; \
+ gtest_msg.value += e.what(); \
+ gtest_msg.value += "\"."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
+ }
+
+#else // GTEST_HAS_EXCEPTIONS
+
+#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()
+
+#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) { \
+ 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.")
// Implements Boolean test assertions such as EXPECT_TRUE. expression can be
// either a boolean expression or an AssertionResult. text is a textual
-// represenation of expression as it was passed into the EXPECT_TRUE.
+// 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()) { \
- ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
- GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
- if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
+ 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()) { \
+ const ::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.")
+ } \
+ } else /* NOLINT */ \
+ 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)() {} \
- \
- private: \
- virtual void TestBody(); \
- static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
- GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
- test_name)); \
- }; \
- \
- ::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 // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h
index 97533993c0c3..6a81c37fa6af 100644
--- a/googletest/include/gtest/internal/gtest-param-util.h
+++ b/googletest/include/gtest/internal/gtest-param-util.h
@@ -27,36 +27,41 @@
// (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 GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
#include <ctype.h>
#include <cassert>
#include <iterator>
+#include <map>
#include <memory>
+#include <ostream>
#include <set>
+#include <string>
#include <tuple>
+#include <type_traits>
#include <utility>
#include <vector>
+#include "gtest/gtest-printers.h"
+#include "gtest/gtest-test-part.h"
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
-#include "gtest/gtest-printers.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;
};
@@ -82,15 +87,17 @@ 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>.
template <typename T>
class ParamIteratorInterface {
public:
- virtual ~ParamIteratorInterface() {}
+ virtual ~ParamIteratorInterface() = default;
// A pointer to the base generator instance.
// Used only for the purposes of iterator comparison
// to make sure that two iterators belong to the same generator.
@@ -127,8 +134,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;
}
@@ -155,7 +161,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
@@ -165,7 +171,7 @@ class ParamGeneratorInterface {
public:
typedef T ParamType;
- virtual ~ParamGeneratorInterface() {}
+ virtual ~ParamGeneratorInterface() = default;
// Generator interface definition
virtual ParamIteratorInterface<T>* Begin() const = 0;
@@ -177,7 +183,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;
@@ -194,7 +200,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
@@ -205,9 +211,11 @@ 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)) {}
- ~RangeGenerator() override {}
+ : begin_(begin),
+ end_(end),
+ step_(step),
+ end_index_(CalculateEndIndex(begin, end, step)) {}
+ ~RangeGenerator() override = default;
ParamIteratorInterface<T>* Begin() const override {
return new Iterator(this, begin_, 0, step_);
@@ -222,7 +230,7 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
IncrementT step)
: base_(base), value_(value), index_(index), step_(step) {}
- ~Iterator() override {}
+ ~Iterator() override = default;
const ParamGeneratorInterface<T>* BaseGenerator() const override {
return base_;
@@ -249,7 +257,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.
@@ -261,12 +271,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;
}
@@ -281,7 +289,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
@@ -292,7 +299,7 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
template <typename ForwardIterator>
ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
: container_(begin, end) {}
- ~ValuesInIteratorRangeGenerator() override {}
+ ~ValuesInIteratorRangeGenerator() override = default;
ParamIteratorInterface<T>* Begin() const override {
return new Iterator(this, container_.begin());
@@ -309,7 +316,7 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
Iterator(const ParamGeneratorInterface<T>* base,
typename ContainerType::const_iterator iterator)
: base_(base), iterator_(iterator) {}
- ~Iterator() override {}
+ ~Iterator() override = default;
const ParamGeneratorInterface<T>* BaseGenerator() const override {
return base_;
@@ -339,13 +346,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_) {}
@@ -392,8 +399,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();
@@ -402,7 +409,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.
@@ -412,7 +420,7 @@ class ParameterizedTestFactory : public TestFactoryBase {
template <class ParamType>
class TestMetaFactoryBase {
public:
- virtual ~TestMetaFactoryBase() {}
+ virtual ~TestMetaFactoryBase() = default;
virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
};
@@ -431,14 +439,15 @@ class TestMetaFactory
public:
using ParamType = typename TestSuite::ParamType;
- TestMetaFactory() {}
+ TestMetaFactory() = default;
TestFactoryBase* CreateTestFactory(ParamType parameter) override {
return new ParameterizedTestFactory<TestSuite>(parameter);
}
private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
+ TestMetaFactory(const TestMetaFactory&) = delete;
+ TestMetaFactory& operator=(const TestMetaFactory&) = delete;
};
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
@@ -453,11 +462,11 @@ class TestMetaFactory
// and calls RegisterTests() on each of them when asked.
class ParameterizedTestSuiteInfoBase {
public:
- virtual ~ParameterizedTestSuiteInfoBase() {}
+ virtual ~ParameterizedTestSuiteInfoBase() = default;
// Base part of test suite name for display purposes.
virtual const std::string& GetTestSuiteName() const = 0;
- // Test case id to verify identity.
+ // Test suite id to verify identity.
virtual TypeId GetTestSuiteTypeId() const = 0;
// UnitTest class invokes this method to register tests in this
// test suite right before running them in RUN_ALL_TESTS macro.
@@ -469,9 +478,23 @@ 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.
+//
+// Report a the name of a test_suit as safe to ignore
+// as the side effect of construction of this type.
+struct GTEST_API_ MarkAsIgnored {
+ explicit MarkAsIgnored(const char* test_suite);
};
+GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
+ CodeLocation location, bool has_test_p);
+
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
@@ -494,11 +517,11 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
CodeLocation code_location)
: test_suite_name_(name), code_location_(code_location) {}
- // Test case base name for display purposes.
+ // Test suite base name for display purposes.
const std::string& GetTestSuiteName() const override {
return test_suite_name_;
}
- // Test case id to verify identity.
+ // Test suite id to verify identity.
TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
// TEST_P macro uses AddTestPattern() to record information
// about a single test in a LocalTestInfo structure.
@@ -507,9 +530,10 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
// parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
// test suite base name and DoBar is test base name.
void AddTestPattern(const char* test_suite_name, const char* test_base_name,
- TestMetaFactoryBase<ParamType>* meta_factory) {
- tests_.push_back(std::shared_ptr<TestInfo>(
- new TestInfo(test_suite_name, test_base_name, meta_factory)));
+ TestMetaFactoryBase<ParamType>* meta_factory,
+ CodeLocation code_location) {
+ tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(
+ test_suite_name, test_base_name, meta_factory, code_location)));
}
// INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
// about a generator.
@@ -522,17 +546,19 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
return 0; // Return value used only to run this method in namespace scope.
}
// UnitTest class invokes this method to register tests in this test suite
- // test suites right before running tests in RUN_ALL_TESTS macro.
+ // right before running tests in RUN_ALL_TESTS macro.
// This method should not be called more than once on any single
// instance of a ParameterizedTestSuiteInfoBase derived class.
// UnitTest has a guard to prevent from calling this method more than once.
void RegisterTests() override {
+ bool generated_instantiations = false;
+
for (typename TestInfoContainer::iterator test_it = tests_.begin();
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;
@@ -540,7 +566,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;
@@ -549,19 +575,20 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
for (typename ParamGenerator<ParamType>::iterator param_it =
generator.begin();
param_it != generator.end(); ++param_it, ++i) {
+ generated_instantiations = true;
+
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);
@@ -572,63 +599,69 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
MakeAndRegisterTestInfo(
test_suite_name.c_str(), test_name_stream.GetString().c_str(),
nullptr, // No type parameter.
- PrintToString(*param_it).c_str(), code_location_,
+ PrintToString(*param_it).c_str(), test_info->code_location,
GetTestSuiteTypeId(),
SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
test_info->test_meta_factory->CreateTestFactory(*param_it));
} // for param_it
- } // for gen_it
- } // for test_it
- } // RegisterTests
+ } // 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
private:
// LocalTestInfo structure keeps information about a single test registered
// with TEST_P macro.
struct TestInfo {
TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
- TestMetaFactoryBase<ParamType>* a_test_meta_factory)
+ TestMetaFactoryBase<ParamType>* a_test_meta_factory,
+ CodeLocation a_code_location)
: test_suite_base_name(a_test_suite_base_name),
test_base_name(a_test_base_name),
- test_meta_factory(a_test_meta_factory) {}
+ test_meta_factory(a_test_meta_factory),
+ code_location(a_code_location) {}
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;
@@ -639,7 +672,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
@@ -656,7 +691,7 @@ using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
// ParameterizedTestSuiteInfo descriptors.
class ParameterizedTestSuiteRegistry {
public:
- ParameterizedTestSuiteRegistry() {}
+ ParameterizedTestSuiteRegistry() = default;
~ParameterizedTestSuiteRegistry() {
for (auto& test_suite_info : test_suite_infos_) {
delete test_suite_info;
@@ -682,7 +717,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;
}
@@ -714,7 +749,38 @@ 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
+// where as well as which are intatiated. This allows susequently
+// identifying suits that are defined but never used.
+class TypeParameterizedTestSuiteRegistry {
+ public:
+ // Add a suite definition
+ void RegisterTestSuite(const char* test_suite_name,
+ CodeLocation code_location);
+
+ // Add an instantiation of a suit.
+ void RegisterInstantiation(const char* test_suite_name);
+
+ // For each suit repored as defined but not reported as instantiation,
+ // emit a test that reports that fact (configurably, as an error).
+ void CheckForInstantiations();
+
+ private:
+ struct TypeParameterizedTestSuiteInfo {
+ explicit TypeParameterizedTestSuiteInfo(CodeLocation c)
+ : code_location(c), instantiated(false) {}
+
+ CodeLocation code_location;
+ bool instantiated;
+ };
+
+ std::map<std::string, TypeParameterizedTestSuiteInfo> suites_;
};
} // namespace internal
@@ -728,10 +794,12 @@ internal::ParamGenerator<typename Container::value_type> ValuesIn(
namespace internal {
// Used in the Values() function to provide polymorphic capabilities.
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
+
template <typename... Ts>
class ValueArray {
public:
- ValueArray(Ts... v) : v_{std::move(v)...} {}
+ explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
template <typename T>
operator ParamGenerator<T>() const { // NOLINT
@@ -747,6 +815,8 @@ class ValueArray {
FlatTuple<Ts...> v_;
};
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
+
template <typename... T>
class CartesianProductGenerator
: public ParamGeneratorInterface<::std::tuple<T...>> {
@@ -755,7 +825,7 @@ class CartesianProductGenerator
CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
: generators_(g) {}
- ~CartesianProductGenerator() override {}
+ ~CartesianProductGenerator() override = default;
ParamIteratorInterface<ParamType>* Begin() const override {
return new Iterator(this, generators_, false);
@@ -772,14 +842,15 @@ 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()...),
current_(is_end ? end_ : begin_) {
ComputeCurrentValue();
}
- ~IteratorImpl() override {}
+ ~IteratorImpl() override = default;
const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
return base_;
@@ -877,7 +948,79 @@ class CartesianProductHolder {
std::tuple<Gen...> generators_;
};
+template <typename From, typename To>
+class ParamGeneratorConverter : public ParamGeneratorInterface<To> {
+ public:
+ ParamGeneratorConverter(ParamGenerator<From> gen) // NOLINT
+ : generator_(std::move(gen)) {}
+
+ ParamIteratorInterface<To>* Begin() const override {
+ return new Iterator(this, generator_.begin(), generator_.end());
+ }
+ ParamIteratorInterface<To>* End() const override {
+ return new Iterator(this, generator_.end(), generator_.end());
+ }
+
+ private:
+ class Iterator : public ParamIteratorInterface<To> {
+ public:
+ Iterator(const ParamGeneratorInterface<To>* base, ParamIterator<From> it,
+ ParamIterator<From> end)
+ : base_(base), it_(it), end_(end) {
+ if (it_ != end_) value_ = std::make_shared<To>(static_cast<To>(*it_));
+ }
+ ~Iterator() override = default;
+
+ const ParamGeneratorInterface<To>* BaseGenerator() const override {
+ return base_;
+ }
+ void Advance() override {
+ ++it_;
+ if (it_ != end_) value_ = std::make_shared<To>(static_cast<To>(*it_));
+ }
+ ParamIteratorInterface<To>* Clone() const override {
+ return new Iterator(*this);
+ }
+ const To* Current() const override { return value_.get(); }
+ bool Equals(const ParamIteratorInterface<To>& other) const override {
+ // Having the same base generator guarantees that the other
+ // iterator is of the same type and we can downcast.
+ GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
+ << "The program attempted to compare iterators "
+ << "from different generators." << std::endl;
+ const ParamIterator<From> other_it =
+ CheckedDowncastToActualType<const Iterator>(&other)->it_;
+ return it_ == other_it;
+ }
+
+ private:
+ Iterator(const Iterator& other) = default;
+
+ const ParamGeneratorInterface<To>* const base_;
+ ParamIterator<From> it_;
+ ParamIterator<From> end_;
+ std::shared_ptr<To> value_;
+ }; // class ParamGeneratorConverter::Iterator
+
+ ParamGenerator<From> generator_;
+}; // class ParamGeneratorConverter
+
+template <class Gen>
+class ParamConverterGenerator {
+ public:
+ ParamConverterGenerator(ParamGenerator<Gen> g) // NOLINT
+ : generator_(std::move(g)) {}
+
+ template <typename T>
+ operator ParamGenerator<T>() const { // NOLINT
+ return ParamGenerator<T>(new ParamGeneratorConverter<Gen, T>(generator_));
+ }
+
+ private:
+ ParamGenerator<Gen> generator_;
+};
+
} // namespace internal
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
diff --git a/googletest/include/gtest/internal/gtest-port-arch.h b/googletest/include/gtest/internal/gtest-port-arch.h
index cece93dba12d..3162f2b1cbd2 100644
--- a/googletest/include/gtest/internal/gtest-port-arch.h
+++ b/googletest/include/gtest/internal/gtest-port-arch.h
@@ -26,82 +26,97 @@
// 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.
// It is separate from gtest-port.h so that custom/gtest-port.h can include it.
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
// 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
-# 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
+#define GTEST_OS_ESP8266 1
+#elif defined ESP32
+#define GTEST_OS_ESP32 1
+#elif defined(__XTENSA__)
+#define GTEST_OS_XTENSA 1
+#elif defined(__hexagon__)
+#define GTEST_OS_QURT 1
+#elif defined(CPU_QN9090) || defined(CPU_QN9090HN)
+#define GTEST_OS_NXP_QN9090 1
+#elif defined(NRF52)
+#define GTEST_OS_NRF52 1
#endif // __CYGWIN__
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h
index 063fcb1083ba..b887e24edcd0 100644
--- a/googletest/include/gtest/internal/gtest-port.h
+++ b/googletest/include/gtest/internal/gtest-port.h
@@ -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,10 +38,12 @@
// 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 GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
// Environment-describing macros
// -----------------------------
@@ -81,6 +83,8 @@
// GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that
// std::wstring does/doesn't work (Google Test can
// be used where std::wstring is unavailable).
+// GTEST_HAS_FILE_SYSTEM - Define it to 1/0 to indicate whether or not a
+// file system is/isn't available.
// GTEST_HAS_SEH - Define it to 1/0 to indicate whether the
// compiler supports Microsoft's "Structured
// Exception Handling".
@@ -116,6 +120,7 @@
// 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
@@ -156,10 +161,10 @@
// NOT define them.
//
// These macros are public so that portable tests can be written.
-// Such tests typically surround code using a feature with an #if
+// Such tests typically surround code using a feature with an #ifdef
// which controls that code. For example:
//
-// #if GTEST_HAS_DEATH_TEST
+// #ifdef GTEST_HAS_DEATH_TEST
// EXPECT_DEATH(DoSomethingDeadly());
// #endif
//
@@ -167,12 +172,13 @@
// 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_USES_SIMPLE_RE - our own simple regex is used;
// the above RE\b(s) are mutually exclusive.
+// GTEST_HAS_ABSL - Google Test is compiled with Abseil.
// Misc public macros
// ------------------
@@ -190,24 +196,44 @@
// 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 operator=.
-// GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy 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).
// GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
// is suppressed.
+// GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or
+// UniversalPrinter<absl::any> specializations.
+// Always defined to 0 or 1.
+// GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>
+// or
+// UniversalPrinter<absl::optional>
+// specializations. Always defined to 0 or 1.
+// GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
+// Matcher<absl::string_view>
+// specializations. Always defined to 0 or 1.
+// GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or
+// UniversalPrinter<absl::variant>
+// specializations. Always defined to 0 or 1.
+// GTEST_USE_OWN_FLAGFILE_FLAG_ - Always defined to 0 or 1.
+// GTEST_HAS_CXXABI_H_ - Always defined to 0 or 1.
+// GTEST_CAN_STREAM_RESULTS_ - Always defined to 0 or 1.
+// GTEST_HAS_ALT_PATH_SEP_ - Always defined to 0 or 1.
+// GTEST_WIDE_STRING_USES_UTF16_ - Always defined to 0 or 1.
+// GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Always defined to 0 or 1.
+// GTEST_HAS_NOTIFICATION_- Always defined to 0 or 1.
//
// Synchronization:
// Mutex, MutexLock, ThreadLocal, GetThreadCount()
// - 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.
@@ -223,19 +249,16 @@
//
// Integer types:
// TypeWithSize - maps an integer to a int type.
-// Int32, UInt32, Int64, UInt64, TimeInMillis
-// - integers of known sizes.
+// TimeInMillis - integers of known sizes.
// 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:
// GetEnv() - gets the value of an environment variable.
// BoolFromGTestEnv() - parses a bool environment variable.
-// Int32FromGTestEnv() - parses an Int32 environment variable.
+// Int32FromGTestEnv() - parses an int32_t environment variable.
// StringFromGTestEnv() - parses a string environment variable.
//
// Deprecation warnings:
@@ -243,53 +266,84 @@
// deprecated; calling a marked function
// should generate a compiler warning
+// The definition of GTEST_INTERNAL_CPLUSPLUS_LANG comes first because it can
+// potentially be used as an #include guard.
+#if defined(_MSVC_LANG)
+#define GTEST_INTERNAL_CPLUSPLUS_LANG _MSVC_LANG
+#elif defined(__cplusplus)
+#define GTEST_INTERNAL_CPLUSPLUS_LANG __cplusplus
+#endif
+
+#if !defined(GTEST_INTERNAL_CPLUSPLUS_LANG) || \
+ GTEST_INTERNAL_CPLUSPLUS_LANG < 201402L
+#error C++ versions less than C++14 are not supported.
+#endif
+
#include <ctype.h> // for isspace, etc
#include <stddef.h> // for ptrdiff_t
#include <stdio.h>
#include <stdlib.h>
#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 <ostream>
+#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 <algorithm> // NOLINT
-#include <iostream> // NOLINT
-#include <sstream> // NOLINT
-#include <string> // NOLINT
-#include <tuple>
-#include <utility>
-#include <vector> // NOLINT
-
-#include "gtest/internal/gtest-port-arch.h"
#include "gtest/internal/custom/gtest-port.h"
+#include "gtest/internal/gtest-port-arch.h"
+
+#ifndef GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
+#define GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ 0
+#endif
+
+#ifndef GTEST_HAS_NOTIFICATION_
+#define GTEST_HAS_NOTIFICATION_ 0
+#endif
+
+#ifdef 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.
@@ -298,43 +352,39 @@
// /* 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
+#ifdef GTEST_OS_WINDOWS
+#ifndef 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)
+#if defined(GTEST_OS_WINDOWS_MINGW) && !defined(__MINGW64_VERSION_MAJOR)
// MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two
// separate (equivalent) structs, instead of using typedef
typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;
@@ -344,72 +394,68 @@ typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#endif
+#elif defined(GTEST_OS_XTENSA)
+#include <unistd.h>
+// Xtensa toolchains define strcasecmp in the string.h header instead of
+// strings.h. string.h is already included.
#else
// 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
+#ifdef 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
+#ifdef 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 (!GTEST_OS_WINDOWS)
-# endif
+#define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
+#else
+#if !(defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_XTENSA) || \
+ defined(GTEST_OS_QURT))
+#define GTEST_HAS_POSIX_RE 1
+#else
+#define GTEST_HAS_POSIX_RE 0
+#endif
+#endif // GTEST_OS_LINUX_ANDROID
#endif
-#if GTEST_USES_PCRE
-// The appropriate headers have already been included.
-
+// Select the regular expression implementation.
+#ifdef 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
@@ -418,112 +464,117 @@ 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
+#if defined(__EXCEPTIONS) && __EXCEPTIONS && __has_feature(cxx_exceptions)
+#define GTEST_HAS_EXCEPTIONS 1
+#else
+#define GTEST_HAS_EXCEPTIONS 0
+#endif
+#elif defined(__GNUC__) && defined(__EXCEPTIONS) && __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__) && defined(__EXCEPTIONS) && __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
-#if !defined(GTEST_HAS_STD_STRING)
-// Even though we don't use this macro any longer, we keep it in case
-// some clients still depend on it.
-# define GTEST_HAS_STD_STRING 1
-#elif !GTEST_HAS_STD_STRING
-// The user told us that ::std::string isn't available.
-# error "::std::string isn't available."
-#endif // !defined(GTEST_HAS_STD_STRING)
-
#ifndef GTEST_HAS_STD_WSTRING
// The user didn't tell us whether ::std::wstring is available, so we need
// to figure it out.
// Cygwin 1.7 and below doesn't support ::std::wstring.
// Solaris' libc++ doesn't support it either. Android has
// no support for it at least as recent as Froyo (2.2).
-#define GTEST_HAS_STD_WSTRING \
- (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
- GTEST_OS_HAIKU))
-
+#if (!(defined(GTEST_OS_LINUX_ANDROID) || defined(GTEST_OS_CYGWIN) || \
+ defined(GTEST_OS_SOLARIS) || defined(GTEST_OS_HAIKU) || \
+ defined(GTEST_OS_ESP32) || defined(GTEST_OS_ESP8266) || \
+ defined(GTEST_OS_XTENSA) || defined(GTEST_OS_QURT) || \
+ defined(GTEST_OS_NXP_QN9090) || defined(GTEST_OS_NRF52)))
+#define GTEST_HAS_STD_WSTRING 1
+#else
+#define GTEST_HAS_STD_WSTRING 0
+#endif
#endif // GTEST_HAS_STD_WSTRING
+#ifndef GTEST_HAS_FILE_SYSTEM
+// Most platforms support a file system.
+#define GTEST_HAS_FILE_SYSTEM 1
+#endif // GTEST_HAS_FILE_SYSTEM
+
// Determines whether RTTI is available.
#ifndef GTEST_HAS_RTTI
// 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 defined(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.
@@ -533,20 +584,26 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
//
// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
// to your compiler flags.
-#define GTEST_HAS_PTHREAD \
- (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)
+#if (defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || \
+ defined(GTEST_OS_HPUX) || defined(GTEST_OS_QNX) || \
+ defined(GTEST_OS_FREEBSD) || defined(GTEST_OS_NACL) || \
+ defined(GTEST_OS_NETBSD) || defined(GTEST_OS_FUCHSIA) || \
+ defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_GNU_KFREEBSD) || \
+ defined(GTEST_OS_OPENBSD) || defined(GTEST_OS_HAIKU) || \
+ defined(GTEST_OS_GNU_HURD))
+#define GTEST_HAS_PTHREAD 1
+#else
+#define GTEST_HAS_PTHREAD 0
+#endif
#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.
@@ -556,24 +613,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 defined(GTEST_OS_LINUX) && !defined(__ia64__)
+#if defined(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
@@ -581,23 +637,34 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// output correctness and to implement death tests.
#ifndef GTEST_HAS_STREAM_REDIRECTION
// By default, we assume that stream redirection is supported on all
-// platforms except known mobile ones.
-# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
-# define GTEST_HAS_STREAM_REDIRECTION 0
-# else
-# define GTEST_HAS_STREAM_REDIRECTION 1
-# endif // !GTEST_OS_WINDOWS_MOBILE
+// platforms except known mobile / embedded ones. Also, if the port doesn't have
+// a file system, stream redirection is not supported.
+#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \
+ defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \
+ defined(GTEST_OS_XTENSA) || defined(GTEST_OS_QURT) || \
+ !GTEST_HAS_FILE_SYSTEM
+#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.
// pops up a dialog window that cannot be suppressed programmatically.
-#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
- (GTEST_OS_MAC && !GTEST_OS_IOS) || \
- (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
+#if (defined(GTEST_OS_LINUX) || defined(GTEST_OS_CYGWIN) || \
+ defined(GTEST_OS_SOLARIS) || \
+ (defined(GTEST_OS_MAC) && !defined(GTEST_OS_IOS)) || \
+ (defined(GTEST_OS_WINDOWS_DESKTOP) && _MSC_VER) || \
+ defined(GTEST_OS_WINDOWS_MINGW) || defined(GTEST_OS_AIX) || \
+ defined(GTEST_OS_HPUX) || defined(GTEST_OS_OPENBSD) || \
+ defined(GTEST_OS_QNX) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_NETBSD) || defined(GTEST_OS_FUCHSIA) || \
+ defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_GNU_KFREEBSD) || \
+ defined(GTEST_OS_HAIKU) || defined(GTEST_OS_GNU_HURD))
+// Death tests require a file system to work properly.
+#if GTEST_HAS_FILE_SYSTEM
+#define GTEST_HAS_DEATH_TEST 1
+#endif // GTEST_HAS_FILE_SYSTEM
#endif
// Determines whether to support type-driven tests.
@@ -606,18 +673,26 @@ 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.
-#define GTEST_WIDE_STRING_USES_UTF16_ \
- (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2)
+#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_CYGWIN) || \
+ defined(GTEST_OS_AIX) || defined(GTEST_OS_OS2)
+#define GTEST_WIDE_STRING_USES_UTF16_ 1
+#else
+#define GTEST_WIDE_STRING_USES_UTF16_ 0
+#endif
// 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
+#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_GNU_KFREEBSD) || \
+ defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_NETBSD) || defined(GTEST_OS_OPENBSD) || \
+ defined(GTEST_OS_GNU_HURD) || defined(GTEST_OS_MAC)
+#define GTEST_CAN_STREAM_RESULTS_ 1
+#else
+#define GTEST_CAN_STREAM_RESULTS_ 0
#endif
// Defines some utility macros.
@@ -631,72 +706,75 @@ 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
-// prevent the compiler from optimizing away instances that are never
-// used. This is useful when all interesting logic happens inside the
-// c'tor and / or d'tor. Example:
+// GTEST_HAVE_ATTRIBUTE_
//
-// struct Foo {
-// Foo() { ... }
-// } GTEST_ATTRIBUTE_UNUSED_;
+// A function-like feature checking macro that is a wrapper around
+// `__has_attribute`, which is defined by GCC 5+ and Clang and evaluates to a
+// nonzero constant integer if the attribute is supported or 0 if not.
//
-// 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))
-#elif defined(__clang__)
-# if __has_attribute(unused)
-# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
-# endif
+// It evaluates to zero if `__has_attribute` is not defined by the compiler.
+//
+// GCC: https://gcc.gnu.org/gcc-5/changes.html
+// Clang: https://clang.llvm.org/docs/LanguageExtensions.html
+#ifdef __has_attribute
+#define GTEST_HAVE_ATTRIBUTE_(x) __has_attribute(x)
+#else
+#define GTEST_HAVE_ATTRIBUTE_(x) 0
#endif
-#ifndef GTEST_ATTRIBUTE_UNUSED_
-# define GTEST_ATTRIBUTE_UNUSED_
+
+// GTEST_HAVE_FEATURE_
+//
+// A function-like feature checking macro that is a wrapper around
+// `__has_feature`.
+#ifdef __has_feature
+#define GTEST_HAVE_FEATURE_(x) __has_feature(x)
+#else
+#define GTEST_HAVE_FEATURE_(x) 0
+#endif
+
+// Use this annotation after a variable or parameter declaration to tell the
+// compiler the variable/parameter does not have to be used.
+// Example:
+//
+// GTEST_ATTRIBUTE_UNUSED_ int foo = bar();
+#if GTEST_HAVE_ATTRIBUTE_(unused)
+#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused))
+#else
+#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 GTEST_HAVE_ATTRIBUTE_(format) && 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)))
+#elif GTEST_HAVE_ATTRIBUTE_(format)
+#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
+ __attribute__((format(printf, string_index, first_to_check)))
#else
-# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
+#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
#endif
-
-// A macro to disallow operator=
-// This should be used in the private: declarations for a class.
-#define GTEST_DISALLOW_ASSIGN_(type) \
- void 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; \
- GTEST_DISALLOW_ASSIGN_(type)
-
// Tell the compiler to warn about unused return values for functions declared
// with this macro. The macro should be used on function declarations
// following the argument list:
//
// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
-#if defined(__GNUC__) && !defined(COMPILER_ICC)
-# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
+#if GTEST_HAVE_ATTRIBUTE_(warn_unused_result)
+#define GTEST_MUST_USE_RESULT_ __attribute__((warn_unused_result))
#else
-# define GTEST_MUST_USE_RESULT_
-#endif // __GNUC__ && !COMPILER_ICC
+#define GTEST_MUST_USE_RESULT_
+#endif
// MS C++ compiler emits warning when a conditional expression is compile time
// constant. In some contexts this warning is false positive and needs to be
@@ -706,10 +784,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
@@ -717,114 +794,116 @@ 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
#ifndef GTEST_IS_THREADSAFE
-#define GTEST_IS_THREADSAFE \
- (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \
- (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \
- GTEST_HAS_PTHREAD)
+#if (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \
+ (defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \
+ !defined(GTEST_OS_WINDOWS_RT)) || \
+ GTEST_HAS_PTHREAD)
+#define GTEST_IS_THREADSAFE 1
+#endif
#endif // GTEST_IS_THREADSAFE
+#ifdef 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
-#elif __GNUC__ >= 4 || defined(__clang__)
-# define GTEST_API_ __attribute__((visibility ("default")))
+#if GTEST_LINKED_AS_SHARED_LIBRARY
+#define GTEST_API_ __declspec(dllimport)
+#elif GTEST_CREATE_SHARED_LIBRARY
+#define GTEST_API_ __declspec(dllexport)
+#endif
+#elif GTEST_HAVE_ATTRIBUTE_(visibility)
+#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__
+#if GTEST_HAVE_ATTRIBUTE_(noinline)
// 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 GTEST_HAVE_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))
+#elif defined(__GNUC__) && !defined(__NVCOMPILER)
+#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 GTEST_HAVE_ATTRIBUTE_(no_sanitize_memory)
+#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ __attribute__((no_sanitize_memory))
#else
-# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
-#endif // __clang__
+#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
+#endif
// 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 GTEST_HAVE_ATTRIBUTE_(no_sanitize_address)
+#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
+ __attribute__((no_sanitize_address))
#else
-# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
-#endif // __clang__
+#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
+#endif
// 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 GTEST_HAVE_FEATURE_(hwaddress_sanitizer) && \
+ GTEST_HAVE_ATTRIBUTE_(no_sanitize)
+#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \
+ __attribute__((no_sanitize("hwaddress")))
#else
-# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
-#endif // __clang__
+#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
+#endif
// 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 GTEST_HAVE_ATTRIBUTE_(no_sanitize_thread)
+#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ __attribute((no_sanitize_thread))
#else
-# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
-#endif // __clang__
+#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
+#endif
namespace testing {
@@ -841,23 +920,11 @@ using std::tuple_size;
namespace internal {
// A secret type that Google Test users don't know about. It has no
-// definition on purpose. Therefore it's impossible to create a
+// accessible constructors on purpose. Therefore it's impossible to create a
// 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)
-
-// Evaluates to the number of elements in 'array'.
-#define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0]))
+class Secret {
+ Secret(const Secret&) = delete;
+};
// A helper for suppressing warnings on constant condition. It just
// returns 'condition'.
@@ -865,9 +932,34 @@ GTEST_API_ bool IsTrue(bool condition);
// Defines RE.
-#if GTEST_USES_PCRE
-// if used, PCRE is injected by custom/gtest-port.h
-#elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE
+#ifdef 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 defined(GTEST_USES_POSIX_RE) || defined(GTEST_USES_SIMPLE_RE)
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
+/* class A needs to have dll-interface to be used by clients of class B */)
// A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
// Regular Expression syntax.
@@ -884,7 +976,7 @@ class GTEST_API_ RE {
~RE();
// Returns the string representation of the regex.
- const char* pattern() const { return pattern_; }
+ const char* pattern() const { return pattern_.c_str(); }
// FullMatch(str, re) returns true if and only if regular expression re
// matches the entire str.
@@ -902,24 +994,22 @@ class GTEST_API_ RE {
private:
void Init(const char* regex);
- const char* pattern_;
+ std::string pattern_;
bool is_valid_;
-# if GTEST_USES_POSIX_RE
+#ifdef GTEST_USES_POSIX_RE
regex_t full_regex_; // For FullMatch().
regex_t partial_regex_; // For PartialMatch().
-# else // GTEST_USES_SIMPLE_RE
-
- const char* full_pattern_; // For FullMatch();
+#else // GTEST_USES_SIMPLE_RE
-# endif
+ std::string full_pattern_; // For FullMatch();
- GTEST_DISALLOW_ASSIGN_(RE);
+#endif
};
-
-#endif // GTEST_USES_PCRE
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
+#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.
@@ -937,12 +1027,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
@@ -959,14 +1044,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); }
@@ -978,7 +1065,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";
@@ -988,12 +1075,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
@@ -1002,9 +1089,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
@@ -1018,9 +1104,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) \
@@ -1033,7 +1123,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:
//
@@ -1046,48 +1136,9 @@ 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; }
-
-// When you upcast (that is, cast a pointer from type Foo to type
-// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
-// always succeed. When you downcast (that is, cast a pointer from
-// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
-// how do you know the pointer is really of type SubclassOfFoo? It
-// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
-// when you downcast, you should use this macro. In debug mode, we
-// use dynamic_cast<> to double-check the downcast is legal (we die
-// if it's not). In normal mode, we do the efficient static_cast<>
-// instead. Thus, it's important to test in debug mode to make sure
-// the cast is legal!
-// This is the only place in the code we should use dynamic_cast<>.
-// In particular, you SHOULDN'T be using dynamic_cast<> in order to
-// do RTTI (eg code like this:
-// if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
-// if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
-// You should design the code some other way not to need this.
-//
-// 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
- // 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);
- }
-
-#if GTEST_HAS_RTTI
- // RTTI: debug mode only!
- GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr);
-#endif
- return static_cast<To>(f);
+template <typename To>
+inline To ImplicitCast_(To x) {
+ return x;
}
// Downcasts the pointer of type Base to Derived.
@@ -1097,17 +1148,12 @@ inline To DownCast_(From* f) { // so we only accept pointers
// check to enforce this.
template <class Derived, class Base>
Derived* CheckedDowncastToActualType(Base* base) {
+ static_assert(std::is_base_of<Base, Derived>::value,
+ "target type not derived from source type");
#if GTEST_HAS_RTTI
- GTEST_CHECK_(typeid(*base) == typeid(Derived));
-#endif
-
-#if GTEST_HAS_DOWNCAST_
- return ::down_cast<Derived*>(base);
-#elif GTEST_HAS_RTTI
- return dynamic_cast<Derived*>(base); // NOLINT
-#else
- return static_cast<Derived*>(base); // Poor man's downcast.
+ GTEST_CHECK_(base == nullptr || dynamic_cast<Derived*>(base) != nullptr);
#endif
+ return static_cast<Derived*>(base);
}
#if GTEST_HAS_STREAM_REDIRECTION
@@ -1133,7 +1179,7 @@ GTEST_API_ std::string ReadEntireFile(FILE* file);
// All command line arguments.
GTEST_API_ std::vector<std::string> GetArgvs();
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
std::vector<std::string> GetInjectableArgvs();
// Deprecated: pass the args vector by value instead.
@@ -1144,72 +1190,9 @@ void ClearInjectableArgvs();
#endif // GTEST_HAS_DEATH_TEST
// 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);
+#ifdef GTEST_IS_THREADSAFE
+#ifdef GTEST_OS_WINDOWS
// Provides leak-safe Windows kernel handle ownership.
// Used in death tests and in threading support.
class GTEST_API_ AutoHandle {
@@ -1236,8 +1219,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
@@ -1245,23 +1238,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 && !defined(GTEST_OS_WINDOWS_MINGW)
// As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
// Consequently, it cannot select a correct instantiation of ThreadWithParam
@@ -1270,7 +1280,7 @@ class GTEST_API_ Notification {
// problem.
class ThreadWithParamBase {
public:
- virtual ~ThreadWithParamBase() {}
+ virtual ~ThreadWithParamBase() = default;
virtual void Run() = 0;
};
@@ -1337,16 +1347,18 @@ 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 defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \
+ !defined(GTEST_OS_WINDOWS_RT)
// Mutex implements mutex on Windows platforms. It is used in conjunction
// with class MutexLock:
@@ -1400,14 +1412,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
@@ -1416,15 +1429,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;
@@ -1451,7 +1464,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
@@ -1480,7 +1494,7 @@ class GTEST_API_ ThreadWithParamBase {
virtual void Run() = 0;
};
- ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
+ ThreadWithParamBase(Runnable* runnable, Notification* thread_can_start);
virtual ~ThreadWithParamBase();
private:
@@ -1494,30 +1508,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.
@@ -1554,7 +1564,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(); }
@@ -1573,16 +1583,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();
}
@@ -1593,37 +1604,43 @@ 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 {
public:
DefaultValueHolderFactory() {}
- virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); }
+ 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 {
public:
explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
- virtual ValueHolder* MakeNewHolder() const {
+ ValueHolder* MakeNewHolder() const override {
return new ValueHolder(value_);
}
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 {
@@ -1670,8 +1687,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,
@@ -1690,12 +1707,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
@@ -1705,15 +1721,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;
@@ -1724,9 +1740,9 @@ typedef GTestMutexLock MutexLock;
// C-linkage. Therefore it cannot be templatized to access
// ThreadLocal<T>. Hence the need for class
// ThreadLocalValueHolderBase.
-class ThreadLocalValueHolderBase {
+class GTEST_API_ ThreadLocalValueHolderBase {
public:
- virtual ~ThreadLocalValueHolderBase() {}
+ virtual ~ThreadLocalValueHolderBase() = default;
};
// Called by pthread to delete thread-local data stored by
@@ -1770,7 +1786,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() {
@@ -1797,44 +1814,50 @@ class GTEST_API_ ThreadLocal {
class ValueHolderFactory {
public:
- ValueHolderFactory() {}
- virtual ~ValueHolderFactory() {}
+ ValueHolderFactory() = default;
+ virtual ~ValueHolderFactory() = default;
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 {
public:
- DefaultValueHolderFactory() {}
- virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); }
+ DefaultValueHolderFactory() = default;
+ 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 {
public:
explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
- virtual ValueHolder* MakeNewHolder() const {
+ ValueHolder* MakeNewHolder() const override {
return new ValueHolder(value_);
}
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
@@ -1851,10 +1874,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
@@ -1877,6 +1900,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_;
};
@@ -1887,18 +1911,12 @@ class GTEST_API_ ThreadLocal {
// we cannot detect it.
GTEST_API_ size_t GetThreadCount();
-template <bool B>
-using bool_constant = std::integral_constant<bool, B>;
-
-#if GTEST_OS_WINDOWS
-# define GTEST_PATH_SEP_ "\\"
-# define GTEST_HAS_ALT_PATH_SEP_ 1
-// The biggest signed integer type the compiler supports.
-typedef __int64 BiggestInt;
+#ifdef GTEST_OS_WINDOWS
+#define GTEST_PATH_SEP_ "\\"
+#define GTEST_HAS_ALT_PATH_SEP_ 1
#else
-# define GTEST_PATH_SEP_ "/"
-# define GTEST_HAS_ALT_PATH_SEP_ 0
-typedef long long BiggestInt; // NOLINT
+#define GTEST_PATH_SEP_ "/"
+#define GTEST_HAS_ALT_PATH_SEP_ 0
#endif // GTEST_OS_WINDOWS
// Utilities for char.
@@ -1929,6 +1947,19 @@ inline bool IsUpper(char ch) {
inline bool IsXDigit(char ch) {
return isxdigit(static_cast<unsigned char>(ch)) != 0;
}
+#ifdef __cpp_lib_char8_t
+inline bool IsXDigit(char8_t ch) {
+ return isxdigit(static_cast<unsigned char>(ch)) != 0;
+}
+#endif
+inline bool IsXDigit(char16_t ch) {
+ const unsigned char low_byte = static_cast<unsigned char>(ch);
+ return ch == low_byte && isxdigit(low_byte) != 0;
+}
+inline bool IsXDigit(char32_t ch) {
+ const unsigned char low_byte = static_cast<unsigned char>(ch);
+ return ch == low_byte && isxdigit(low_byte) != 0;
+}
inline bool IsXDigit(wchar_t ch) {
const unsigned char low_byte = static_cast<unsigned char>(ch);
return ch == low_byte && isxdigit(low_byte) != 0;
@@ -1943,8 +1974,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;
}
@@ -1956,85 +1986,125 @@ inline std::string StripTrailingSpaces(std::string str) {
namespace posix {
-// Functions with a different name on Windows.
-
-#if GTEST_OS_WINDOWS
+// File system porting.
+#if GTEST_HAS_FILE_SYSTEM
+#ifdef GTEST_OS_WINDOWS
typedef struct _stat StatStruct;
-# ifdef __BORLANDC__
-inline int IsATTY(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
-inline int IsATTY(int /* fd */) { return 0; }
-# else
-inline int IsATTY(int fd) { return _isatty(fd); }
-# 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__
-
-# if GTEST_OS_WINDOWS_MOBILE
+#ifdef 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;
+inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; }
+#endif // GTEST_OS_WINDOWS_MOBILE
+
+#elif defined(GTEST_OS_ESP8266)
+typedef struct stat StatStruct;
+
+inline int FileNo(FILE* file) { return fileno(file); }
+inline int Stat(const char* path, StatStruct* buf) {
+ // stat function not implemented on ESP8266
+ return 0;
}
-# endif // GTEST_OS_WINDOWS_MOBILE
+inline int RmDir(const char* dir) { return rmdir(dir); }
+inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
#else
typedef struct stat StatStruct;
inline int FileNo(FILE* file) { return fileno(file); }
-inline int IsATTY(int fd) { return isatty(fd); }
inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
+#ifdef GTEST_OS_QURT
+// QuRT doesn't support any directory functions, including rmdir
+inline int RmDir(const char*) { return 0; }
+#else
+inline int RmDir(const char* dir) { return rmdir(dir); }
+#endif
+inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
+
+#endif // GTEST_OS_WINDOWS
+#endif // GTEST_HAS_FILE_SYSTEM
+
+// Other functions with a different name on Windows.
+
+#ifdef GTEST_OS_WINDOWS
+
+#ifdef __BORLANDC__
+inline int DoIsATTY(int fd) { return isatty(fd); }
+inline int StrCaseCmp(const char* s1, const char* s2) {
+ return stricmp(s1, s2);
+}
+#else // !__BORLANDC__
+#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_ZOS) || \
+ defined(GTEST_OS_IOS) || defined(GTEST_OS_WINDOWS_PHONE) || \
+ defined(GTEST_OS_WINDOWS_RT) || defined(ESP_PLATFORM)
+inline int DoIsATTY(int /* fd */) { return 0; }
+#else
+inline int DoIsATTY(int fd) { return _isatty(fd); }
+#endif // GTEST_OS_WINDOWS_MOBILE
+inline int StrCaseCmp(const char* s1, const char* s2) {
+ return _stricmp(s1, s2);
+}
+#endif // __BORLANDC__
+
+#else
+
+inline int DoIsATTY(int fd) { return isatty(fd); }
inline int StrCaseCmp(const char* s1, const char* s2) {
return strcasecmp(s1, s2);
}
-inline char* StrDup(const char* src) { return strdup(src); }
-inline int RmDir(const char* dir) { return rmdir(dir); }
-inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
#endif // GTEST_OS_WINDOWS
+inline int IsATTY(int fd) {
+ // DoIsATTY might change errno (for example ENOTTY in case you redirect stdout
+ // to a file on Linux), which is unexpected, so save the previous value, and
+ // restore it after the call.
+ int savedErrno = errno;
+ int isAttyValue = DoIsATTY(fd);
+ errno = savedErrno;
+
+ return isAttyValue;
+}
+
// Functions deprecated by MSVC 8.0.
GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
-inline const char* StrNCpy(char* dest, const char* src, size_t n) {
- return strncpy(dest, src, n);
-}
-
// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
// StrError() aren't needed on Windows CE at this time and thus not
// defined there.
-
-#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
+#if GTEST_HAS_FILE_SYSTEM
+#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_WINDOWS_PHONE) && \
+ !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_ESP8266) && \
+ !defined(GTEST_OS_XTENSA) && !defined(GTEST_OS_QURT)
inline int ChDir(const char* dir) { return chdir(dir); }
#endif
inline FILE* FOpen(const char* path, const char* mode) {
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW)
+ struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
+ std::wstring_convert<wchar_codecvt> converter;
+ 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
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) {
+#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_QURT)
+inline FILE* FReopen(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); }
-#endif
+#endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT
inline int FClose(FILE* fp) { return fclose(fp); }
-#if !GTEST_OS_WINDOWS_MOBILE
+#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_QURT)
inline int Read(int fd, void* buf, unsigned int count) {
return static_cast<int>(read(fd, buf, count));
}
@@ -2042,11 +2112,18 @@ inline int Write(int fd, const void* buf, unsigned int count) {
return static_cast<int>(write(fd, buf, count));
}
inline int Close(int fd) { return close(fd); }
+#endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT
+#endif // GTEST_HAS_FILE_SYSTEM
+
+#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_QURT)
inline const char* StrError(int errnum) { return strerror(errnum); }
-#endif
+#endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT
+
inline const char* GetEnv(const char* name) {
-#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
- // We are on Windows CE, which has no environment variables.
+#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \
+ defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \
+ defined(GTEST_OS_QURT)
+ // We are on an embedded platform, which has no environment variables.
static_cast<void>(name); // To prevent 'unused argument' warning.
return nullptr;
#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
@@ -2061,7 +2138,7 @@ inline const char* GetEnv(const char* name) {
GTEST_DISABLE_MSC_DEPRECATED_POP_()
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// Windows CE has no C library. The abort() function is used in
// several places in Google Test. This implementation provides a reasonable
// imitation of standard behaviour.
@@ -2077,26 +2154,24 @@ GTEST_DISABLE_MSC_DEPRECATED_POP_()
// MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate
// function in order to achieve that. We use macro definition here because
// snprintf is a variadic function.
-#if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE
+#if defined(_MSC_VER) && !defined(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 maximum number a BiggestInt can represent. This definition
-// works no matter BiggestInt is represented in one's complement or
-// two's complement.
+// The biggest signed integer type the compiler supports.
//
-// We cannot rely on numeric_limits in STL, as __int64 and long long
-// are not part of standard C++ and numeric_limits doesn't need to be
-// defined for them.
-const BiggestInt kMaxBiggestInt =
- ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1));
+// long long is guaranteed to be at least 64-bits in C++11.
+using BiggestInt = long long; // NOLINT
+
+// The maximum number a BiggestInt can represent.
+constexpr BiggestInt kMaxBiggestInt = (std::numeric_limits<BiggestInt>::max)();
// This template class serves as a compile-time function from size to
// type. It maps a size in bytes to a primitive type with that
@@ -2121,87 +2196,122 @@ class TypeWithSize {
public:
// This prevents the user from using TypeWithSize<N> with incorrect
// values of N.
- typedef void UInt;
+ using UInt = void;
};
// The specialization for size 4.
template <>
class TypeWithSize<4> {
public:
- // unsigned int has size 4 in both gcc and MSVC.
- //
- // As base/basictypes.h doesn't compile on Windows, we cannot use
- // uint32, uint64, and etc here.
- typedef int Int;
- typedef unsigned int UInt;
+ using Int = std::int32_t;
+ using UInt = std::uint32_t;
};
// The specialization for size 8.
template <>
class TypeWithSize<8> {
public:
-#if GTEST_OS_WINDOWS
- typedef __int64 Int;
- typedef unsigned __int64 UInt;
-#else
- typedef long long Int; // NOLINT
- typedef unsigned long long UInt; // NOLINT
-#endif // GTEST_OS_WINDOWS
+ using Int = std::int64_t;
+ using UInt = std::uint64_t;
};
// Integer types of known sizes.
-typedef TypeWithSize<4>::Int Int32;
-typedef TypeWithSize<4>::UInt UInt32;
-typedef TypeWithSize<8>::Int Int64;
-typedef TypeWithSize<8>::UInt UInt64;
-typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds.
+using TimeInMillis = int64_t; // Represents time in milliseconds.
// Utilities for command line flags and environment variables.
// 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.
+#ifdef 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 ::testing::internal::Int32 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_ ::testing::internal::Int32 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
// to *value and returns true; otherwise leaves *value unchanged and returns
// false.
-bool ParseInt32(const Message& src_text, const char* str, Int32* value);
+GTEST_API_ bool ParseInt32(const Message& src_text, const char* str,
+ int32_t* value);
-// Parses a bool/Int32/string from the environment variable
+// Parses a bool/int32_t/string from the environment variable
// corresponding to the given Google Test flag.
bool BoolFromGTestEnv(const char* flag, bool default_val);
-GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val);
+GTEST_API_ int32_t Int32FromGTestEnv(const char* flag, int32_t default_val);
std::string OutputFlagAlsoCheckEnvVar();
const char* StringFromGTestEnv(const char* flag, const char* default_val);
@@ -2228,4 +2338,144 @@ const char* StringFromGTestEnv(const char* flag, const char* default_val);
#endif // !defined(GTEST_INTERNAL_DEPRECATED)
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
+#ifdef GTEST_HAS_ABSL
+// Always use absl::any for UniversalPrinter<> specializations if googletest
+// is built with absl support.
+#define GTEST_INTERNAL_HAS_ANY 1
+#include "absl/types/any.h"
+namespace testing {
+namespace internal {
+using Any = ::absl::any;
+} // namespace internal
+} // namespace testing
+#else
+#ifdef __has_include
+#if __has_include(<any>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L && \
+ (!defined(_MSC_VER) || GTEST_HAS_RTTI)
+// Otherwise for C++17 and higher use std::any for UniversalPrinter<>
+// specializations.
+#define GTEST_INTERNAL_HAS_ANY 1
+#include <any>
+namespace testing {
+namespace internal {
+using Any = ::std::any;
+} // namespace internal
+} // namespace testing
+// The case where absl is configured NOT to alias std::any is not
+// supported.
+#endif // __has_include(<any>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
+#endif // __has_include
+#endif // GTEST_HAS_ABSL
+
+#ifndef GTEST_INTERNAL_HAS_ANY
+#define GTEST_INTERNAL_HAS_ANY 0
+#endif
+
+#ifdef GTEST_HAS_ABSL
+// Always use absl::optional for UniversalPrinter<> specializations if
+// googletest is built with absl support.
+#define GTEST_INTERNAL_HAS_OPTIONAL 1
+#include "absl/types/optional.h"
+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
+#ifdef __has_include
+#if __has_include(<optional>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
+// Otherwise for C++17 and higher use std::optional for UniversalPrinter<>
+// specializations.
+#define GTEST_INTERNAL_HAS_OPTIONAL 1
+#include <optional>
+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
+// supported.
+#endif // __has_include(<optional>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
+#endif // __has_include
+#endif // GTEST_HAS_ABSL
+
+#ifndef GTEST_INTERNAL_HAS_OPTIONAL
+#define GTEST_INTERNAL_HAS_OPTIONAL 0
+#endif
+
+#ifdef 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
+#include "absl/strings/string_view.h"
+namespace testing {
+namespace internal {
+using StringView = ::absl::string_view;
+} // namespace internal
+} // namespace testing
+#else
+#ifdef __has_include
+#if __has_include(<string_view>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
+// Otherwise for C++17 and higher use std::string_view for Matcher<>
+// specializations.
+#define GTEST_INTERNAL_HAS_STRING_VIEW 1
+#include <string_view>
+namespace testing {
+namespace internal {
+using StringView = ::std::string_view;
+} // namespace internal
+} // namespace testing
+// The case where absl is configured NOT to alias std::string_view is not
+// supported.
+#endif // __has_include(<string_view>) && GTEST_INTERNAL_CPLUSPLUS_LANG >=
+ // 201703L
+#endif // __has_include
+#endif // GTEST_HAS_ABSL
+
+#ifndef GTEST_INTERNAL_HAS_STRING_VIEW
+#define GTEST_INTERNAL_HAS_STRING_VIEW 0
+#endif
+
+#ifdef GTEST_HAS_ABSL
+// Always use absl::variant for UniversalPrinter<> specializations if googletest
+// is built with absl support.
+#define GTEST_INTERNAL_HAS_VARIANT 1
+#include "absl/types/variant.h"
+namespace testing {
+namespace internal {
+template <typename... T>
+using Variant = ::absl::variant<T...>;
+} // namespace internal
+} // namespace testing
+#else
+#ifdef __has_include
+#if __has_include(<variant>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
+// Otherwise for C++17 and higher use std::variant for UniversalPrinter<>
+// specializations.
+#define GTEST_INTERNAL_HAS_VARIANT 1
+#include <variant>
+namespace testing {
+namespace internal {
+template <typename... T>
+using Variant = ::std::variant<T...>;
+} // namespace internal
+} // namespace testing
+// The case where absl is configured NOT to alias std::variant is not supported.
+#endif // __has_include(<variant>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
+#endif // __has_include
+#endif // GTEST_HAS_ABSL
+
+#ifndef GTEST_INTERNAL_HAS_VARIANT
+#define GTEST_INTERNAL_HAS_VARIANT 0
+#endif
+
+#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
+ GTEST_INTERNAL_CPLUSPLUS_LANG < 201703L
+#define GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL 1
+#endif
+
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h
index 82aaa63bf465..7c05b58339f6 100644
--- a/googletest/include/gtest/internal/gtest-string.h
+++ b/googletest/include/gtest/internal/gtest-string.h
@@ -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
@@ -36,17 +36,22 @@
// 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 GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
+#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 <sstream>
#include <string>
#include "gtest/internal/gtest-port.h"
@@ -68,7 +73,7 @@ class GTEST_API_ String {
// memory using malloc().
static const char* CloneCString(const char* c_str);
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
// able to pass strings to Win32 APIs on CE we need to convert them
// to 'Unicode', UTF-16.
@@ -122,8 +127,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.
@@ -142,24 +146,27 @@ 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
+ // Formats an int value to given width with leading zeros.
+ static std::string FormatIntWidthN(int value, int width);
+
// Formats an int value as "%X".
static std::string FormatHexInt(int value);
// Formats an int value as "%X".
- static std::string FormatHexUInt32(UInt32 value);
+ static std::string FormatHexUInt32(uint32_t value);
// Formats a byte as "%02X".
static std::string FormatByte(unsigned char value);
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".
@@ -168,4 +175,4 @@ GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
} // namespace internal
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h
index 3d7542d1fb35..f94cf614ade7 100644
--- a/googletest/include/gtest/internal/gtest-type-util.h
+++ b/googletest/include/gtest/internal/gtest-type-util.h
@@ -1,7 +1,3 @@
-// This file was GENERATED by command:
-// pump.py gtest-type-util.h.pump
-// DO NOT EDIT BY HAND!!!
-
// Copyright 2008 Google Inc.
// All Rights Reserved.
//
@@ -32,27 +28,28 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Type utilities needed for implementing typed and type-parameterized
-// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
-//
-// Currently we support at most 50 types in a list, and at most 50
-// type-parameterized tests in one type-parameterized test suite.
-// Please contact googletestframework@googlegroups.com if you need
-// more.
+// tests.
+
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
-// GOOGLETEST_CM0001 DO NOT DELETE
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
+#include <string>
+#include <type_traits>
+#include <typeinfo>
#include "gtest/internal/gtest-port.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 {
@@ -70,1560 +67,79 @@ inline std::string CanonicalizeForStdLibVersioning(std::string s) {
s.erase(strlen("std"), end - strlen("std"));
}
}
+
+ // Strip redundant spaces in typename to match MSVC
+ // For example, std::pair<int, bool> -> std::pair<int,bool>
+ static const char to_search[] = ", ";
+ static const char replace_str[] = ",";
+ size_t pos = 0;
+ while (true) {
+ // Get the next occurrence from the current position
+ pos = s.find(to_search, pos);
+ if (pos == std::string::npos) {
+ break;
+ }
+ // Replace this occurrence of substring
+ s.replace(pos, strlen(to_search), replace_str);
+ pos += strlen(replace_str);
+ }
return s;
}
-// GetTypeName<T>() returns a human-readable name of type T.
-// NB: This function is also used in Google Mock, so don't move it inside of
-// the typed-test-only section below.
-template <typename T>
-std::string GetTypeName() {
-# if GTEST_HAS_RTTI
-
- const char* const name = typeid(T).name();
-# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
+#if GTEST_HAS_RTTI
+// GetTypeName(const std::type_info&) returns a human-readable name of type T.
+inline std::string GetTypeName(const std::type_info& type) {
+ const char* const name = type.name();
+#if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
int status = 0;
// gcc's implementation of typeid(T).name() mangles the type name,
// so we have to demangle it.
-# if GTEST_HAS_CXXABI_H_
+#if GTEST_HAS_CXXABI_H_
using abi::__cxa_demangle;
-# endif // GTEST_HAS_CXXABI_H_
+#endif // GTEST_HAS_CXXABI_H_
char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
const std::string name_str(status == 0 ? readable_name : name);
free(readable_name);
return CanonicalizeForStdLibVersioning(name_str);
-# else
+#elif defined(_MSC_VER)
+ // Strip struct and class due to differences between
+ // MSVC and other compilers. std::pair<int,bool> is printed as
+ // "struct std::pair<int,bool>" when using MSVC vs "std::pair<int, bool>" with
+ // other compilers.
+ std::string s = name;
+ // Only strip the leading "struct " and "class ", so uses rfind == 0 to
+ // ensure that
+ if (s.rfind("struct ", 0) == 0) {
+ s = s.substr(strlen("struct "));
+ } else if (s.rfind("class ", 0) == 0) {
+ s = s.substr(strlen("class "));
+ }
+ return s;
+#else
return name;
-# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
-
-# else
+#endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
+}
+#endif // GTEST_HAS_RTTI
+// GetTypeName<T>() returns a human-readable name of type T if and only if
+// RTTI is enabled, otherwise it returns a dummy type name.
+// NB: This function is also used in Google Mock, so don't move it inside of
+// the typed-test-only section below.
+template <typename T>
+std::string GetTypeName() {
+#if GTEST_HAS_RTTI
+ return GetTypeName(typeid(T));
+#else
return "<type>";
-
-# endif // GTEST_HAS_RTTI
+#endif // GTEST_HAS_RTTI
}
-#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
-
-// A unique type used as the default value for the arguments of class
-// template Types. This allows us to simulate variadic templates
-// (e.g. Types<int>, Type<int, double>, and etc), which C++ doesn't
-// support directly.
+// A unique type indicating an empty node
struct None {};
-// The following family of struct and struct templates are used to
-// represent type lists. In particular, TypesN<T1, T2, ..., TN>
-// represents a type list with N types (T1, T2, ..., and TN) in it.
-// Except for Types0, every struct in the family has two member types:
-// Head for the first type in the list, and Tail for the rest of the
-// list.
-
-// The empty type list.
-struct Types0 {};
-
-// Type lists of length 1, 2, 3, and so on.
-
-template <typename T1>
-struct Types1 {
- typedef T1 Head;
- typedef Types0 Tail;
-};
-template <typename T1, typename T2>
-struct Types2 {
- typedef T1 Head;
- typedef Types1<T2> Tail;
-};
-
-template <typename T1, typename T2, typename T3>
-struct Types3 {
- typedef T1 Head;
- typedef Types2<T2, T3> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4>
-struct Types4 {
- typedef T1 Head;
- typedef Types3<T2, T3, T4> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5>
-struct Types5 {
- typedef T1 Head;
- typedef Types4<T2, T3, T4, T5> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6>
-struct Types6 {
- typedef T1 Head;
- typedef Types5<T2, T3, T4, T5, T6> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7>
-struct Types7 {
- typedef T1 Head;
- typedef Types6<T2, T3, T4, T5, T6, T7> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8>
-struct Types8 {
- typedef T1 Head;
- typedef Types7<T2, T3, T4, T5, T6, T7, T8> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9>
-struct Types9 {
- typedef T1 Head;
- typedef Types8<T2, T3, T4, T5, T6, T7, T8, T9> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10>
-struct Types10 {
- typedef T1 Head;
- typedef Types9<T2, T3, T4, T5, T6, T7, T8, T9, T10> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11>
-struct Types11 {
- typedef T1 Head;
- typedef Types10<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12>
-struct Types12 {
- typedef T1 Head;
- typedef Types11<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13>
-struct Types13 {
- typedef T1 Head;
- typedef Types12<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14>
-struct Types14 {
- typedef T1 Head;
- typedef Types13<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15>
-struct Types15 {
- typedef T1 Head;
- typedef Types14<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16>
-struct Types16 {
- typedef T1 Head;
- typedef Types15<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17>
-struct Types17 {
- typedef T1 Head;
- typedef Types16<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18>
-struct Types18 {
- typedef T1 Head;
- typedef Types17<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19>
-struct Types19 {
- typedef T1 Head;
- typedef Types18<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20>
-struct Types20 {
- typedef T1 Head;
- typedef Types19<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21>
-struct Types21 {
- typedef T1 Head;
- typedef Types20<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22>
-struct Types22 {
- typedef T1 Head;
- typedef Types21<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23>
-struct Types23 {
- typedef T1 Head;
- typedef Types22<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24>
-struct Types24 {
- typedef T1 Head;
- typedef Types23<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25>
-struct Types25 {
- typedef T1 Head;
- typedef Types24<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26>
-struct Types26 {
- typedef T1 Head;
- typedef Types25<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27>
-struct Types27 {
- typedef T1 Head;
- typedef Types26<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28>
-struct Types28 {
- typedef T1 Head;
- typedef Types27<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29>
-struct Types29 {
- typedef T1 Head;
- typedef Types28<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30>
-struct Types30 {
- typedef T1 Head;
- typedef Types29<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31>
-struct Types31 {
- typedef T1 Head;
- typedef Types30<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32>
-struct Types32 {
- typedef T1 Head;
- typedef Types31<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33>
-struct Types33 {
- typedef T1 Head;
- typedef Types32<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34>
-struct Types34 {
- typedef T1 Head;
- typedef Types33<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35>
-struct Types35 {
- typedef T1 Head;
- typedef Types34<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36>
-struct Types36 {
- typedef T1 Head;
- typedef Types35<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37>
-struct Types37 {
- typedef T1 Head;
- typedef Types36<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38>
-struct Types38 {
- typedef T1 Head;
- typedef Types37<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39>
-struct Types39 {
- typedef T1 Head;
- typedef Types38<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40>
-struct Types40 {
- typedef T1 Head;
- typedef Types39<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41>
-struct Types41 {
- typedef T1 Head;
- typedef Types40<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42>
-struct Types42 {
- typedef T1 Head;
- typedef Types41<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43>
-struct Types43 {
- typedef T1 Head;
- typedef Types42<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
- T43> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44>
-struct Types44 {
- typedef T1 Head;
- typedef Types43<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
- T44> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45>
-struct Types45 {
- typedef T1 Head;
- typedef Types44<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
- T44, T45> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45,
- typename T46>
-struct Types46 {
- typedef T1 Head;
- typedef Types45<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
- T44, T45, T46> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45,
- typename T46, typename T47>
-struct Types47 {
- typedef T1 Head;
- typedef Types46<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
- T44, T45, T46, T47> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45,
- typename T46, typename T47, typename T48>
-struct Types48 {
- typedef T1 Head;
- typedef Types47<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
- T44, T45, T46, T47, T48> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45,
- typename T46, typename T47, typename T48, typename T49>
-struct Types49 {
- typedef T1 Head;
- typedef Types48<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
- T44, T45, T46, T47, T48, T49> Tail;
-};
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45,
- typename T46, typename T47, typename T48, typename T49, typename T50>
-struct Types50 {
- typedef T1 Head;
- typedef Types49<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
- T44, T45, T46, T47, T48, T49, T50> Tail;
-};
-
-
-} // namespace internal
-
-// We don't want to require the users to write TypesN<...> directly,
-// as that would require them to count the length. Types<...> is much
-// easier to write, but generates horrible messages when there is a
-// compiler error, as gcc insists on printing out each template
-// argument, even if it has the default value (this means Types<int>
-// will appear as Types<int, None, None, ..., None> in the compiler
-// errors).
-//
-// Our solution is to combine the best part of the two approaches: a
-// user would write Types<T1, ..., TN>, and Google Test will translate
-// that to TypesN<T1, ..., TN> internally to make error messages
-// readable. The translation is done by the 'type' member of the
-// Types template.
-template <typename T1 = internal::None, typename T2 = internal::None,
- typename T3 = internal::None, typename T4 = internal::None,
- typename T5 = internal::None, typename T6 = internal::None,
- typename T7 = internal::None, typename T8 = internal::None,
- typename T9 = internal::None, typename T10 = internal::None,
- typename T11 = internal::None, typename T12 = internal::None,
- typename T13 = internal::None, typename T14 = internal::None,
- typename T15 = internal::None, typename T16 = internal::None,
- typename T17 = internal::None, typename T18 = internal::None,
- typename T19 = internal::None, typename T20 = internal::None,
- typename T21 = internal::None, typename T22 = internal::None,
- typename T23 = internal::None, typename T24 = internal::None,
- typename T25 = internal::None, typename T26 = internal::None,
- typename T27 = internal::None, typename T28 = internal::None,
- typename T29 = internal::None, typename T30 = internal::None,
- typename T31 = internal::None, typename T32 = internal::None,
- typename T33 = internal::None, typename T34 = internal::None,
- typename T35 = internal::None, typename T36 = internal::None,
- typename T37 = internal::None, typename T38 = internal::None,
- typename T39 = internal::None, typename T40 = internal::None,
- typename T41 = internal::None, typename T42 = internal::None,
- typename T43 = internal::None, typename T44 = internal::None,
- typename T45 = internal::None, typename T46 = internal::None,
- typename T47 = internal::None, typename T48 = internal::None,
- typename T49 = internal::None, typename T50 = internal::None>
-struct Types {
- typedef internal::Types50<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41, T42, T43, T44, T45, T46, T47, T48, T49, T50> type;
-};
-
-template <>
-struct Types<internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types0 type;
-};
-template <typename T1>
-struct Types<T1, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types1<T1> type;
-};
-template <typename T1, typename T2>
-struct Types<T1, T2, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types2<T1, T2> type;
-};
-template <typename T1, typename T2, typename T3>
-struct Types<T1, T2, T3, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None> {
- typedef internal::Types3<T1, T2, T3> type;
-};
-template <typename T1, typename T2, typename T3, typename T4>
-struct Types<T1, T2, T3, T4, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None> {
- typedef internal::Types4<T1, T2, T3, T4> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5>
-struct Types<T1, T2, T3, T4, T5, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None> {
- typedef internal::Types5<T1, T2, T3, T4, T5> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6>
-struct Types<T1, T2, T3, T4, T5, T6, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types6<T1, T2, T3, T4, T5, T6> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7>
-struct Types<T1, T2, T3, T4, T5, T6, T7, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types7<T1, T2, T3, T4, T5, T6, T7> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None> {
- typedef internal::Types8<T1, T2, T3, T4, T5, T6, T7, T8> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None> {
- typedef internal::Types9<T1, T2, T3, T4, T5, T6, T7, T8, T9> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None> {
- typedef internal::Types10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,
- T12> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None> {
- typedef internal::Types14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None> {
- typedef internal::Types15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None> {
- typedef internal::Types19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None> {
- typedef internal::Types20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None> {
- typedef internal::Types21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types23<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types24<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None> {
- typedef internal::Types25<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None> {
- typedef internal::Types26<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25,
- T26> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types27<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types28<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types29<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None> {
- typedef internal::Types30<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None> {
- typedef internal::Types31<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types32<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types33<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types34<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None> {
- typedef internal::Types35<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None> {
- typedef internal::Types36<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None> {
- typedef internal::Types37<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types38<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, T39, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types39<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types40<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39,
- T40> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None, internal::None> {
- typedef internal::Types41<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, internal::None,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None> {
- typedef internal::Types42<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41, T42> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None, internal::None> {
- typedef internal::Types43<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41, T42, T43> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
- internal::None, internal::None, internal::None, internal::None,
- internal::None, internal::None> {
- typedef internal::Types44<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41, T42, T43, T44> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45,
- internal::None, internal::None, internal::None, internal::None,
- internal::None> {
- typedef internal::Types45<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41, T42, T43, T44, T45> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45,
- typename T46>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45,
- T46, internal::None, internal::None, internal::None, internal::None> {
- typedef internal::Types46<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41, T42, T43, T44, T45, T46> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45,
- typename T46, typename T47>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45,
- T46, T47, internal::None, internal::None, internal::None> {
- typedef internal::Types47<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41, T42, T43, T44, T45, T46, T47> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45,
- typename T46, typename T47, typename T48>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45,
- T46, T47, T48, internal::None, internal::None> {
- typedef internal::Types48<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41, T42, T43, T44, T45, T46, T47, T48> type;
-};
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45,
- typename T46, typename T47, typename T48, typename T49>
-struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15,
- T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30,
- T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45,
- T46, T47, T48, T49, internal::None> {
- typedef internal::Types49<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41, T42, T43, T44, T45, T46, T47, T48, T49> type;
-};
-
-namespace internal {
-
-# 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
@@ -1641,1695 +157,64 @@ struct TemplateSel {
};
};
-# define GTEST_BIND_(TmplSel, T) \
- TmplSel::template Bind<T>::type
-
-// A unique struct template used as the default value for the
-// arguments of class template Templates. This allows us to simulate
-// variadic templates (e.g. Templates<int>, Templates<int, double>,
-// and etc), which C++ doesn't support directly.
-template <typename T>
-struct NoneT {};
-
-// The following family of struct and struct templates are used to
-// represent template lists. In particular, TemplatesN<T1, T2, ...,
-// TN> represents a list of N templates (T1, T2, ..., and TN). Except
-// for Templates0, every struct in the family has two member types:
-// Head for the selector of the first template in the list, and Tail
-// for the rest of the list.
-
-// The empty template list.
-struct Templates0 {};
-
-// Template lists of length 1, 2, 3, and so on.
-
-template <GTEST_TEMPLATE_ T1>
-struct Templates1 {
- typedef TemplateSel<T1> Head;
- typedef Templates0 Tail;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2>
-struct Templates2 {
- typedef TemplateSel<T1> Head;
- typedef Templates1<T2> Tail;
-};
+#define GTEST_BIND_(TmplSel, T) TmplSel::template Bind<T>::type
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3>
-struct Templates3 {
- typedef TemplateSel<T1> Head;
- typedef Templates2<T2, T3> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4>
-struct Templates4 {
- typedef TemplateSel<T1> Head;
- typedef Templates3<T2, T3, T4> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5>
-struct Templates5 {
- typedef TemplateSel<T1> Head;
- typedef Templates4<T2, T3, T4, T5> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6>
-struct Templates6 {
- typedef TemplateSel<T1> Head;
- typedef Templates5<T2, T3, T4, T5, T6> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7>
-struct Templates7 {
- typedef TemplateSel<T1> Head;
- typedef Templates6<T2, T3, T4, T5, T6, T7> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8>
-struct Templates8 {
- typedef TemplateSel<T1> Head;
- typedef Templates7<T2, T3, T4, T5, T6, T7, T8> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9>
-struct Templates9 {
- typedef TemplateSel<T1> Head;
- typedef Templates8<T2, T3, T4, T5, T6, T7, T8, T9> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10>
-struct Templates10 {
- typedef TemplateSel<T1> Head;
- typedef Templates9<T2, T3, T4, T5, T6, T7, T8, T9, T10> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11>
-struct Templates11 {
- typedef TemplateSel<T1> Head;
- typedef Templates10<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12>
-struct Templates12 {
- typedef TemplateSel<T1> Head;
- typedef Templates11<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13>
-struct Templates13 {
- typedef TemplateSel<T1> Head;
- typedef Templates12<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14>
-struct Templates14 {
- typedef TemplateSel<T1> Head;
- typedef Templates13<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15>
-struct Templates15 {
- typedef TemplateSel<T1> Head;
- typedef Templates14<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16>
-struct Templates16 {
- typedef TemplateSel<T1> Head;
- typedef Templates15<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17>
-struct Templates17 {
- typedef TemplateSel<T1> Head;
- typedef Templates16<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18>
-struct Templates18 {
- typedef TemplateSel<T1> Head;
- typedef Templates17<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19>
-struct Templates19 {
- typedef TemplateSel<T1> Head;
- typedef Templates18<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20>
-struct Templates20 {
- typedef TemplateSel<T1> Head;
- typedef Templates19<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21>
-struct Templates21 {
- typedef TemplateSel<T1> Head;
- typedef Templates20<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22>
-struct Templates22 {
- typedef TemplateSel<T1> Head;
- typedef Templates21<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23>
-struct Templates23 {
- typedef TemplateSel<T1> Head;
- typedef Templates22<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24>
-struct Templates24 {
- typedef TemplateSel<T1> Head;
- typedef Templates23<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25>
-struct Templates25 {
- typedef TemplateSel<T1> Head;
- typedef Templates24<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26>
-struct Templates26 {
- typedef TemplateSel<T1> Head;
- typedef Templates25<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27>
-struct Templates27 {
- typedef TemplateSel<T1> Head;
- typedef Templates26<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28>
-struct Templates28 {
- typedef TemplateSel<T1> Head;
- typedef Templates27<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29>
-struct Templates29 {
- typedef TemplateSel<T1> Head;
- typedef Templates28<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30>
-struct Templates30 {
- typedef TemplateSel<T1> Head;
- typedef Templates29<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31>
-struct Templates31 {
- typedef TemplateSel<T1> Head;
- typedef Templates30<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32>
-struct Templates32 {
- typedef TemplateSel<T1> Head;
- typedef Templates31<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33>
-struct Templates33 {
- typedef TemplateSel<T1> Head;
- typedef Templates32<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34>
-struct Templates34 {
- typedef TemplateSel<T1> Head;
- typedef Templates33<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35>
-struct Templates35 {
- typedef TemplateSel<T1> Head;
- typedef Templates34<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36>
-struct Templates36 {
- typedef TemplateSel<T1> Head;
- typedef Templates35<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37>
-struct Templates37 {
- typedef TemplateSel<T1> Head;
- typedef Templates36<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38>
-struct Templates38 {
- typedef TemplateSel<T1> Head;
- typedef Templates37<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39>
-struct Templates39 {
- typedef TemplateSel<T1> Head;
- typedef Templates38<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40>
-struct Templates40 {
- typedef TemplateSel<T1> Head;
- typedef Templates39<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41>
-struct Templates41 {
- typedef TemplateSel<T1> Head;
- typedef Templates40<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42>
-struct Templates42 {
- typedef TemplateSel<T1> Head;
- typedef Templates41<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
- T42> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43>
-struct Templates43 {
- typedef TemplateSel<T1> Head;
- typedef Templates42<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
- T43> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44>
-struct Templates44 {
- typedef TemplateSel<T1> Head;
- typedef Templates43<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
- T43, T44> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45>
-struct Templates45 {
- typedef TemplateSel<T1> Head;
- typedef Templates44<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
- T43, T44, T45> Tail;
-};
-
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
- GTEST_TEMPLATE_ T46>
-struct Templates46 {
- typedef TemplateSel<T1> Head;
- typedef Templates45<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
- T43, T44, T45, T46> Tail;
+template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_>
+struct Templates {
+ using Head = TemplateSel<Head_>;
+ using Tail = Templates<Tail_...>;
};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
- GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47>
-struct Templates47 {
- typedef TemplateSel<T1> Head;
- typedef Templates46<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
- T43, T44, T45, T46, T47> Tail;
+template <GTEST_TEMPLATE_ Head_>
+struct Templates<Head_> {
+ using Head = TemplateSel<Head_>;
+ using Tail = None;
};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
- GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48>
-struct Templates48 {
- typedef TemplateSel<T1> Head;
- typedef Templates47<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
- T43, T44, T45, T46, T47, T48> Tail;
+// Tuple-like type lists
+template <typename Head_, typename... Tail_>
+struct Types {
+ using Head = Head_;
+ using Tail = Types<Tail_...>;
};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
- GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48,
- GTEST_TEMPLATE_ T49>
-struct Templates49 {
- typedef TemplateSel<T1> Head;
- typedef Templates48<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
- T43, T44, T45, T46, T47, T48, T49> Tail;
+template <typename Head_>
+struct Types<Head_> {
+ using Head = Head_;
+ using Tail = None;
};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
- GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48,
- GTEST_TEMPLATE_ T49, GTEST_TEMPLATE_ T50>
-struct Templates50 {
- typedef TemplateSel<T1> Head;
- typedef Templates49<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42,
- T43, T44, T45, T46, T47, T48, T49, T50> Tail;
+// Helper metafunctions to tell apart a single type from types
+// generated by ::testing::Types
+template <typename... Ts>
+struct ProxyTypeList {
+ using type = Types<Ts...>;
};
+template <typename>
+struct is_proxy_type_list : std::false_type {};
-// We don't want to require the users to write TemplatesN<...> directly,
-// as that would require them to count the length. Templates<...> is much
-// easier to write, but generates horrible messages when there is a
-// compiler error, as gcc insists on printing out each template
-// argument, even if it has the default value (this means Templates<list>
-// will appear as Templates<list, NoneT, NoneT, ..., NoneT> in the compiler
-// errors).
-//
-// Our solution is to combine the best part of the two approaches: a
-// user would write Templates<T1, ..., TN>, and Google Test will translate
-// that to TemplatesN<T1, ..., TN> internally to make error messages
-// readable. The translation is done by the 'type' member of the
-// Templates template.
-template <GTEST_TEMPLATE_ T1 = NoneT, GTEST_TEMPLATE_ T2 = NoneT,
- GTEST_TEMPLATE_ T3 = NoneT, GTEST_TEMPLATE_ T4 = NoneT,
- GTEST_TEMPLATE_ T5 = NoneT, GTEST_TEMPLATE_ T6 = NoneT,
- GTEST_TEMPLATE_ T7 = NoneT, GTEST_TEMPLATE_ T8 = NoneT,
- GTEST_TEMPLATE_ T9 = NoneT, GTEST_TEMPLATE_ T10 = NoneT,
- GTEST_TEMPLATE_ T11 = NoneT, GTEST_TEMPLATE_ T12 = NoneT,
- GTEST_TEMPLATE_ T13 = NoneT, GTEST_TEMPLATE_ T14 = NoneT,
- GTEST_TEMPLATE_ T15 = NoneT, GTEST_TEMPLATE_ T16 = NoneT,
- GTEST_TEMPLATE_ T17 = NoneT, GTEST_TEMPLATE_ T18 = NoneT,
- GTEST_TEMPLATE_ T19 = NoneT, GTEST_TEMPLATE_ T20 = NoneT,
- GTEST_TEMPLATE_ T21 = NoneT, GTEST_TEMPLATE_ T22 = NoneT,
- GTEST_TEMPLATE_ T23 = NoneT, GTEST_TEMPLATE_ T24 = NoneT,
- GTEST_TEMPLATE_ T25 = NoneT, GTEST_TEMPLATE_ T26 = NoneT,
- GTEST_TEMPLATE_ T27 = NoneT, GTEST_TEMPLATE_ T28 = NoneT,
- GTEST_TEMPLATE_ T29 = NoneT, GTEST_TEMPLATE_ T30 = NoneT,
- GTEST_TEMPLATE_ T31 = NoneT, GTEST_TEMPLATE_ T32 = NoneT,
- GTEST_TEMPLATE_ T33 = NoneT, GTEST_TEMPLATE_ T34 = NoneT,
- GTEST_TEMPLATE_ T35 = NoneT, GTEST_TEMPLATE_ T36 = NoneT,
- GTEST_TEMPLATE_ T37 = NoneT, GTEST_TEMPLATE_ T38 = NoneT,
- GTEST_TEMPLATE_ T39 = NoneT, GTEST_TEMPLATE_ T40 = NoneT,
- GTEST_TEMPLATE_ T41 = NoneT, GTEST_TEMPLATE_ T42 = NoneT,
- GTEST_TEMPLATE_ T43 = NoneT, GTEST_TEMPLATE_ T44 = NoneT,
- GTEST_TEMPLATE_ T45 = NoneT, GTEST_TEMPLATE_ T46 = NoneT,
- GTEST_TEMPLATE_ T47 = NoneT, GTEST_TEMPLATE_ T48 = NoneT,
- GTEST_TEMPLATE_ T49 = NoneT, GTEST_TEMPLATE_ T50 = NoneT>
-struct Templates {
- typedef Templates50<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
- T42, T43, T44, T45, T46, T47, T48, T49, T50> type;
-};
-
-template <>
-struct Templates<NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT> {
- typedef Templates0 type;
-};
-template <GTEST_TEMPLATE_ T1>
-struct Templates<T1, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT> {
- typedef Templates1<T1> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2>
-struct Templates<T1, T2, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT> {
- typedef Templates2<T1, T2> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3>
-struct Templates<T1, T2, T3, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates3<T1, T2, T3> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4>
-struct Templates<T1, T2, T3, T4, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates4<T1, T2, T3, T4> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5>
-struct Templates<T1, T2, T3, T4, T5, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates5<T1, T2, T3, T4, T5> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6>
-struct Templates<T1, T2, T3, T4, T5, T6, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates6<T1, T2, T3, T4, T5, T6> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates7<T1, T2, T3, T4, T5, T6, T7> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates8<T1, T2, T3, T4, T5, T6, T7, T8> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates9<T1, T2, T3, T4, T5, T6, T7, T8, T9> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT> {
- typedef Templates18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT> {
- typedef Templates19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT> {
- typedef Templates20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT> {
- typedef Templates21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT> {
- typedef Templates22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT> {
- typedef Templates23<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT> {
- typedef Templates24<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT> {
- typedef Templates25<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT> {
- typedef Templates26<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT> {
- typedef Templates27<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT> {
- typedef Templates28<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT> {
- typedef Templates29<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates30<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates31<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates32<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates33<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates34<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates35<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates36<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, NoneT, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates37<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, NoneT, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates38<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates39<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, NoneT, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates40<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, NoneT, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates41<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, NoneT,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates42<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
- T42> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates43<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
- T42, T43> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
- NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates44<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
- T42, T43, T44> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
- T45, NoneT, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates45<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
- T42, T43, T44, T45> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
- GTEST_TEMPLATE_ T46>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
- T45, T46, NoneT, NoneT, NoneT, NoneT> {
- typedef Templates46<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
- T42, T43, T44, T45, T46> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
- GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
- T45, T46, T47, NoneT, NoneT, NoneT> {
- typedef Templates47<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
- T42, T43, T44, T45, T46, T47> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
- GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
- T45, T46, T47, T48, NoneT, NoneT> {
- typedef Templates48<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
- T42, T43, T44, T45, T46, T47, T48> type;
-};
-template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3,
- GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6,
- GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9,
- GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12,
- GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15,
- GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18,
- GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21,
- GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24,
- GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27,
- GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30,
- GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33,
- GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36,
- GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39,
- GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42,
- GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45,
- GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48,
- GTEST_TEMPLATE_ T49>
-struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14,
- T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29,
- T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44,
- T45, T46, T47, T48, T49, NoneT> {
- typedef Templates49<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27,
- T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41,
- T42, T43, T44, T45, T46, T47, T48, T49> type;
-};
-
-// The TypeList template makes it possible to use either a single type
-// or a Types<...> list in TYPED_TEST_SUITE() and
-// INSTANTIATE_TYPED_TEST_SUITE_P().
+template <typename... Ts>
+struct is_proxy_type_list<ProxyTypeList<Ts...>> : std::true_type {};
+// Generator which conditionally creates type lists.
+// It recognizes if a requested type list should be created
+// and prevents creating a new type list nested within another one.
template <typename T>
-struct TypeList {
- typedef Types1<T> type;
-};
+struct GenerateTypeList {
+ private:
+ using proxy = typename std::conditional<is_proxy_type_list<T>::value, T,
+ ProxyTypeList<T>>::type;
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9, typename T10,
- typename T11, typename T12, typename T13, typename T14, typename T15,
- typename T16, typename T17, typename T18, typename T19, typename T20,
- typename T21, typename T22, typename T23, typename T24, typename T25,
- typename T26, typename T27, typename T28, typename T29, typename T30,
- typename T31, typename T32, typename T33, typename T34, typename T35,
- typename T36, typename T37, typename T38, typename T39, typename T40,
- typename T41, typename T42, typename T43, typename T44, typename T45,
- typename T46, typename T47, typename T48, typename T49, typename T50>
-struct TypeList<Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13,
- T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28,
- T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43,
- T44, T45, T46, T47, T48, T49, T50> > {
- typedef typename Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,
- T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
- T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40,
- T41, T42, T43, T44, T45, T46, T47, T48, T49, T50>::type type;
+ public:
+ using type = typename proxy::type;
};
-#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
-
} // namespace internal
+
+template <typename... Ts>
+using Types = internal::ProxyTypeList<Ts...>;
+
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
diff --git a/googletest/include/gtest/internal/gtest-type-util.h.pump b/googletest/include/gtest/internal/gtest-type-util.h.pump
deleted file mode 100644
index 5e31b7b3206b..000000000000
--- a/googletest/include/gtest/internal/gtest-type-util.h.pump
+++ /dev/null
@@ -1,302 +0,0 @@
-$$ -*- mode: c++; -*-
-$var n = 50 $$ Maximum length of type lists we want to support.
-// Copyright 2008 Google Inc.
-// All Rights Reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-
-// Type utilities needed for implementing typed and type-parameterized
-// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
-//
-// Currently we support at most $n types in a list, and at most $n
-// type-parameterized tests in one type-parameterized test suite.
-// Please contact googletestframework@googlegroups.com if you need
-// more.
-
-// GOOGLETEST_CM0001 DO NOT DELETE
-
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
-
-#include "gtest/internal/gtest-port.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_
-
-namespace testing {
-namespace internal {
-
-// Canonicalizes a given name with respect to the Standard C++ Library.
-// This handles removing the inline namespace within `std` that is
-// used by various standard libraries (e.g., `std::__1`). Names outside
-// of namespace std are returned unmodified.
-inline std::string CanonicalizeForStdLibVersioning(std::string s) {
- static const char prefix[] = "std::__";
- if (s.compare(0, strlen(prefix), prefix) == 0) {
- std::string::size_type end = s.find("::", strlen(prefix));
- if (end != s.npos) {
- // Erase everything between the initial `std` and the second `::`.
- s.erase(strlen("std"), end - strlen("std"));
- }
- }
- return s;
-}
-
-// GetTypeName<T>() returns a human-readable name of type T.
-// NB: This function is also used in Google Mock, so don't move it inside of
-// the typed-test-only section below.
-template <typename T>
-std::string GetTypeName() {
-# if GTEST_HAS_RTTI
-
- const char* const name = typeid(T).name();
-# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
- int status = 0;
- // gcc's implementation of typeid(T).name() mangles the type name,
- // so we have to demangle it.
-# if GTEST_HAS_CXXABI_H_
- using abi::__cxa_demangle;
-# endif // GTEST_HAS_CXXABI_H_
- char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
- const std::string name_str(status == 0 ? readable_name : name);
- free(readable_name);
- return CanonicalizeForStdLibVersioning(name_str);
-# else
- return name;
-# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
-
-# else
-
- return "<type>";
-
-# endif // GTEST_HAS_RTTI
-}
-
-#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
-
-// A unique type used as the default value for the arguments of class
-// template Types. This allows us to simulate variadic templates
-// (e.g. Types<int>, Type<int, double>, and etc), which C++ doesn't
-// support directly.
-struct None {};
-
-// The following family of struct and struct templates are used to
-// represent type lists. In particular, TypesN<T1, T2, ..., TN>
-// represents a type list with N types (T1, T2, ..., and TN) in it.
-// Except for Types0, every struct in the family has two member types:
-// Head for the first type in the list, and Tail for the rest of the
-// list.
-
-// The empty type list.
-struct Types0 {};
-
-// Type lists of length 1, 2, 3, and so on.
-
-template <typename T1>
-struct Types1 {
- typedef T1 Head;
- typedef Types0 Tail;
-};
-
-$range i 2..n
-
-$for i [[
-$range j 1..i
-$range k 2..i
-template <$for j, [[typename T$j]]>
-struct Types$i {
- typedef T1 Head;
- typedef Types$(i-1)<$for k, [[T$k]]> Tail;
-};
-
-
-]]
-
-} // namespace internal
-
-// We don't want to require the users to write TypesN<...> directly,
-// as that would require them to count the length. Types<...> is much
-// easier to write, but generates horrible messages when there is a
-// compiler error, as gcc insists on printing out each template
-// argument, even if it has the default value (this means Types<int>
-// will appear as Types<int, None, None, ..., None> in the compiler
-// errors).
-//
-// Our solution is to combine the best part of the two approaches: a
-// user would write Types<T1, ..., TN>, and Google Test will translate
-// that to TypesN<T1, ..., TN> internally to make error messages
-// readable. The translation is done by the 'type' member of the
-// Types template.
-
-$range i 1..n
-template <$for i, [[typename T$i = internal::None]]>
-struct Types {
- typedef internal::Types$n<$for i, [[T$i]]> type;
-};
-
-template <>
-struct Types<$for i, [[internal::None]]> {
- typedef internal::Types0 type;
-};
-
-$range i 1..n-1
-$for i [[
-$range j 1..i
-$range k i+1..n
-template <$for j, [[typename T$j]]>
-struct Types<$for j, [[T$j]]$for k[[, internal::None]]> {
- typedef internal::Types$i<$for j, [[T$j]]> type;
-};
-
-]]
-
-namespace internal {
-
-# 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
-// parameter, as a type. TemplateSel<Tmpl>::Bind<T>::type is defined
-// as the type Tmpl<T>. This allows us to actually instantiate the
-// template "selected" by TemplateSel<Tmpl>.
-//
-// This trick is necessary for simulating typedef for class templates,
-// which C++ doesn't support directly.
-template <GTEST_TEMPLATE_ Tmpl>
-struct TemplateSel {
- template <typename T>
- struct Bind {
- typedef Tmpl<T> type;
- };
-};
-
-# define GTEST_BIND_(TmplSel, T) \
- TmplSel::template Bind<T>::type
-
-// A unique struct template used as the default value for the
-// arguments of class template Templates. This allows us to simulate
-// variadic templates (e.g. Templates<int>, Templates<int, double>,
-// and etc), which C++ doesn't support directly.
-template <typename T>
-struct NoneT {};
-
-// The following family of struct and struct templates are used to
-// represent template lists. In particular, TemplatesN<T1, T2, ...,
-// TN> represents a list of N templates (T1, T2, ..., and TN). Except
-// for Templates0, every struct in the family has two member types:
-// Head for the selector of the first template in the list, and Tail
-// for the rest of the list.
-
-// The empty template list.
-struct Templates0 {};
-
-// Template lists of length 1, 2, 3, and so on.
-
-template <GTEST_TEMPLATE_ T1>
-struct Templates1 {
- typedef TemplateSel<T1> Head;
- typedef Templates0 Tail;
-};
-
-$range i 2..n
-
-$for i [[
-$range j 1..i
-$range k 2..i
-template <$for j, [[GTEST_TEMPLATE_ T$j]]>
-struct Templates$i {
- typedef TemplateSel<T1> Head;
- typedef Templates$(i-1)<$for k, [[T$k]]> Tail;
-};
-
-
-]]
-
-// We don't want to require the users to write TemplatesN<...> directly,
-// as that would require them to count the length. Templates<...> is much
-// easier to write, but generates horrible messages when there is a
-// compiler error, as gcc insists on printing out each template
-// argument, even if it has the default value (this means Templates<list>
-// will appear as Templates<list, NoneT, NoneT, ..., NoneT> in the compiler
-// errors).
-//
-// Our solution is to combine the best part of the two approaches: a
-// user would write Templates<T1, ..., TN>, and Google Test will translate
-// that to TemplatesN<T1, ..., TN> internally to make error messages
-// readable. The translation is done by the 'type' member of the
-// Templates template.
-
-$range i 1..n
-template <$for i, [[GTEST_TEMPLATE_ T$i = NoneT]]>
-struct Templates {
- typedef Templates$n<$for i, [[T$i]]> type;
-};
-
-template <>
-struct Templates<$for i, [[NoneT]]> {
- typedef Templates0 type;
-};
-
-$range i 1..n-1
-$for i [[
-$range j 1..i
-$range k i+1..n
-template <$for j, [[GTEST_TEMPLATE_ T$j]]>
-struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> {
- typedef Templates$i<$for j, [[T$j]]> type;
-};
-
-]]
-
-// The TypeList template makes it possible to use either a single type
-// or a Types<...> list in TYPED_TEST_SUITE() and
-// INSTANTIATE_TYPED_TEST_SUITE_P().
-
-template <typename T>
-struct TypeList {
- typedef Types1<T> type;
-};
-
-
-$range i 1..n
-template <$for i, [[typename T$i]]>
-struct TypeList<Types<$for i, [[T$i]]> > {
- typedef typename Types<$for i, [[T$i]]>::type type;
-};
-
-#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
-
-} // namespace internal
-} // namespace testing
-
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
diff --git a/googletest/samples/prime_tables.h b/googletest/samples/prime_tables.h
index 72539bf14a23..14c016adce1b 100644
--- a/googletest/samples/prime_tables.h
+++ b/googletest/samples/prime_tables.h
@@ -27,21 +27,19 @@
// (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.
-#ifndef GTEST_SAMPLES_PRIME_TABLES_H_
-#define GTEST_SAMPLES_PRIME_TABLES_H_
+#ifndef GOOGLETEST_SAMPLES_PRIME_TABLES_H_
+#define GOOGLETEST_SAMPLES_PRIME_TABLES_H_
#include <algorithm>
// The prime table interface.
class PrimeTable {
public:
- virtual ~PrimeTable() {}
+ virtual ~PrimeTable() = default;
// Returns true if and only if n is a prime number.
virtual bool IsPrime(int n) const = 0;
@@ -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;
}
@@ -66,11 +64,11 @@ class OnTheFlyPrimeTable : public PrimeTable {
}
int GetNextPrime(int p) const override {
- for (int n = p + 1; n > 0; n++) {
+ if (p < 0) return -1;
+
+ for (int n = p + 1;; n++) {
if (IsPrime(n)) return n;
}
-
- return -1;
}
};
@@ -80,8 +78,9 @@ class PreCalculatedPrimeTable : public PrimeTable {
public:
// 'max' specifies the maximum number the prime table holds.
explicit PreCalculatedPrimeTable(int max)
- : is_prime_size_(max + 1), is_prime_(new bool[max + 1]) {
- CalculatePrimesUpTo(max);
+ : is_prime_size_(std::max(1, max + 1)),
+ is_prime_(new bool[static_cast<size_t>(is_prime_size_)]) {
+ CalculatePrimesUpTo(is_prime_size_ - 1);
}
~PreCalculatedPrimeTable() override { delete[] is_prime_; }
@@ -104,13 +103,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;
}
}
@@ -123,4 +122,4 @@ class PreCalculatedPrimeTable : public PrimeTable {
void operator=(const PreCalculatedPrimeTable& rhs);
};
-#endif // GTEST_SAMPLES_PRIME_TABLES_H_
+#endif // GOOGLETEST_SAMPLES_PRIME_TABLES_H_
diff --git a/googletest/samples/sample1.cc b/googletest/samples/sample1.cc
index 1d4275979ff6..80b69f415c80 100644
--- a/googletest/samples/sample1.cc
+++ b/googletest/samples/sample1.cc
@@ -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.
diff --git a/googletest/samples/sample1.h b/googletest/samples/sample1.h
index 12e49deafa2c..ba392cfbd266 100644
--- a/googletest/samples/sample1.h
+++ b/googletest/samples/sample1.h
@@ -29,8 +29,8 @@
// A sample program demonstrating using Google C++ testing framework.
-#ifndef GTEST_SAMPLES_SAMPLE1_H_
-#define GTEST_SAMPLES_SAMPLE1_H_
+#ifndef GOOGLETEST_SAMPLES_SAMPLE1_H_
+#define GOOGLETEST_SAMPLES_SAMPLE1_H_
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
int Factorial(int n);
@@ -38,4 +38,4 @@ int Factorial(int n);
// Returns true if and only if n is a prime number.
bool IsPrime(int n);
-#endif // GTEST_SAMPLES_SAMPLE1_H_
+#endif // GOOGLETEST_SAMPLES_SAMPLE1_H_
diff --git a/googletest/samples/sample10_unittest.cc b/googletest/samples/sample10_unittest.cc
index 36cdac2279ae..2107954932b6 100644
--- a/googletest/samples/sample10_unittest.cc
+++ b/googletest/samples/sample10_unittest.cc
@@ -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.
@@ -39,7 +38,6 @@ using ::testing::InitGoogleTest;
using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
-using ::testing::TestPartResult;
using ::testing::UnitTest;
namespace {
@@ -104,14 +102,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
diff --git a/googletest/samples/sample1_unittest.cc b/googletest/samples/sample1_unittest.cc
index cb08b61a59a9..60f2770ca0e7 100644
--- a/googletest/samples/sample1_unittest.cc
+++ b/googletest/samples/sample1_unittest.cc
@@ -34,14 +34,15 @@
//
// 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.
diff --git a/googletest/samples/sample2.cc b/googletest/samples/sample2.cc
index d8e8723965a1..be7c4c9949f8 100644
--- a/googletest/samples/sample2.cc
+++ b/googletest/samples/sample2.cc
@@ -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;
diff --git a/googletest/samples/sample2.h b/googletest/samples/sample2.h
index e9a5a7050b7d..15a1ce7781a9 100644
--- a/googletest/samples/sample2.h
+++ b/googletest/samples/sample2.h
@@ -29,12 +29,11 @@
// A sample program demonstrating using Google C++ testing framework.
-#ifndef GTEST_SAMPLES_SAMPLE2_H_
-#define GTEST_SAMPLES_SAMPLE2_H_
+#ifndef GOOGLETEST_SAMPLES_SAMPLE2_H_
+#define GOOGLETEST_SAMPLES_SAMPLE2_H_
#include <string.h>
-
// A simple string class.
class MyString {
private:
@@ -77,5 +76,4 @@ class MyString {
void Set(const char* c_string);
};
-
-#endif // GTEST_SAMPLES_SAMPLE2_H_
+#endif // GOOGLETEST_SAMPLES_SAMPLE2_H_
diff --git a/googletest/samples/sample2_unittest.cc b/googletest/samples/sample2_unittest.cc
index 41e31c1767de..cd734f943a08 100644
--- a/googletest/samples/sample2_unittest.cc
+++ b/googletest/samples/sample2_unittest.cc
@@ -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.
diff --git a/googletest/samples/sample3-inl.h b/googletest/samples/sample3-inl.h
index 80ba6b923480..bc3ffb9c4093 100644
--- a/googletest/samples/sample3-inl.h
+++ b/googletest/samples/sample3-inl.h
@@ -29,12 +29,11 @@
// A sample program demonstrating using Google C++ testing framework.
-#ifndef GTEST_SAMPLES_SAMPLE3_INL_H_
-#define GTEST_SAMPLES_SAMPLE3_INL_H_
+#ifndef GOOGLETEST_SAMPLES_SAMPLE3_INL_H_
+#define GOOGLETEST_SAMPLES_SAMPLE3_INL_H_
#include <stddef.h>
-
// Queue is a simple queue implemented as a singled-linked list.
//
// The element type must support copy constructor.
@@ -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 // GTEST_SAMPLES_SAMPLE3_INL_H_
+#endif // GOOGLETEST_SAMPLES_SAMPLE3_INL_H_
diff --git a/googletest/samples/sample3_unittest.cc b/googletest/samples/sample3_unittest.cc
index b19416d53c95..71609c6a0986 100644
--- a/googletest/samples/sample3_unittest.cc
+++ b/googletest/samples/sample3_unittest.cc
@@ -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();
diff --git a/googletest/samples/sample4.cc b/googletest/samples/sample4.cc
index b0ee6093b4a2..489c89b0d34b 100644
--- a/googletest/samples/sample4.cc
+++ b/googletest/samples/sample4.cc
@@ -29,26 +29,22 @@
// 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_); }
diff --git a/googletest/samples/sample4.h b/googletest/samples/sample4.h
index e256f4064fe9..0c4ed92e738b 100644
--- a/googletest/samples/sample4.h
+++ b/googletest/samples/sample4.h
@@ -28,8 +28,8 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework.
-#ifndef GTEST_SAMPLES_SAMPLE4_H_
-#define GTEST_SAMPLES_SAMPLE4_H_
+#ifndef GOOGLETEST_SAMPLES_SAMPLE4_H_
+#define GOOGLETEST_SAMPLES_SAMPLE4_H_
// A simple monotonic counter.
class Counter {
@@ -50,4 +50,4 @@ class Counter {
void Print() const;
};
-#endif // GTEST_SAMPLES_SAMPLE4_H_
+#endif // GOOGLETEST_SAMPLES_SAMPLE4_H_
diff --git a/googletest/samples/sample4_unittest.cc b/googletest/samples/sample4_unittest.cc
index d5144c0d00f5..fb9973fe666e 100644
--- a/googletest/samples/sample4_unittest.cc
+++ b/googletest/samples/sample4_unittest.cc
@@ -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 {
diff --git a/googletest/samples/sample5_unittest.cc b/googletest/samples/sample5_unittest.cc
index 0a21dd215770..cc8c0f012e96 100644
--- a/googletest/samples/sample5_unittest.cc
+++ b/googletest/samples/sample5_unittest.cc
@@ -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.
//
@@ -45,9 +44,10 @@
#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) {
diff --git a/googletest/samples/sample6_unittest.cc b/googletest/samples/sample6_unittest.cc
index 0266e27e589e..cf576f0a5354 100644
--- a/googletest/samples/sample6_unittest.cc
+++ b/googletest/samples/sample6_unittest.cc
@@ -27,13 +27,11 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
// 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
@@ -73,8 +71,6 @@ class PrimeTableTest : public testing::Test {
PrimeTable* const table_;
};
-#if GTEST_HAS_TYPED_TEST
-
using testing::Types;
// Google Test offers two ways for reusing tests for different types.
@@ -134,10 +130,6 @@ TYPED_TEST(PrimeTableTest, CanGetNextPrime) {
// in the type list specified in TYPED_TEST_SUITE. Sit back and be
// happy that you don't have to define them multiple times.
-#endif // GTEST_HAS_TYPED_TEST
-
-#if GTEST_HAS_TYPED_TEST_P
-
using testing::Types;
// Sometimes, however, you don't yet know all the types that you want
@@ -157,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
@@ -220,5 +211,4 @@ INSTANTIATE_TYPED_TEST_SUITE_P(OnTheFlyAndPreCalculated, // Instance name
PrimeTableTest2, // Test case name
PrimeTableImplementations); // Type list
-#endif // GTEST_HAS_TYPED_TEST_P
} // namespace
diff --git a/googletest/samples/sample7_unittest.cc b/googletest/samples/sample7_unittest.cc
index e0efc29e4a2a..3ad22cab8d12 100644
--- a/googletest/samples/sample7_unittest.cc
+++ b/googletest/samples/sample7_unittest.cc
@@ -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() {
diff --git a/googletest/samples/sample8_unittest.cc b/googletest/samples/sample8_unittest.cc
index 10488b0ea450..4df81df0c032 100644
--- a/googletest/samples/sample8_unittest.cc
+++ b/googletest/samples/sample8_unittest.cc
@@ -27,14 +27,14 @@
// (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 <tuple>
+#include "prime_tables.h"
#include "gtest/gtest.h"
namespace {
@@ -79,10 +79,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
diff --git a/googletest/samples/sample9_unittest.cc b/googletest/samples/sample9_unittest.cc
index e502d08d73e7..0a2f0970d927 100644
--- a/googletest/samples/sample9_unittest.cc
+++ b/googletest/samples/sample9_unittest.cc
@@ -26,10 +26,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.
-
// 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>
@@ -38,7 +37,6 @@
using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest;
using ::testing::Test;
-using ::testing::TestCase;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
using ::testing::TestPartResult;
@@ -59,29 +57,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 +93,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 +142,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/common.py b/googletest/scripts/common.py
deleted file mode 100644
index 3c0347a75bdf..000000000000
--- a/googletest/scripts/common.py
+++ /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
index d0dd464fe8b5..000000000000
--- a/googletest/scripts/fuse_gtest_files.py
+++ /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
index b43efdf41e5c..000000000000
--- a/googletest/scripts/gen_gtest_pred_impl.py
+++ /dev/null
@@ -1,730 +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.
-
-#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 " << 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 to circumvent a bug in
-// gcc 2.95.3, which sometimes has problem with the above template
-// function.
-bool PredFunction%(n)sInt(%(int_vs)s) {
- return %(v_sum)s > 0;
-}
-bool PredFunction%(n)sBool(%(Bool_vs)s) {
- return %(v_sum)s > 0;
-}
-""" % DEFS)
-
- tests += """
-// A %(arity)s predicate functor.
-struct PredFunctor%(n)s {
- template <%(types)s>
- bool operator()(""" % DEFS
-
- tests += Iter(n, 'const T%s& v%s', sep=""",
- """)
-
- tests += """) {
- return %(v_sum)s > 0;
- }
-};
-""" % DEFS
-
- tests += """
-// A %(arity)s predicate-formatter function.
-template <%(types)s>
-testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS
-
- tests += Iter(n, 'const char* e%s', sep=""",
- """)
-
- tests += Iter(n, """,
- const T%s& v%s""")
-
- tests += """) {
- if (PredFunction%(n)s(%(vs)s))
- return testing::AssertionSuccess();
-
- 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:
- virtual void SetUp() {
- expected_to_finish_ = true;
- finished_ = false;""" % DEFS
-
- tests += """
- """ + Iter(n, 'n%s_ = ') + """0;
- }
-"""
-
- tests += """
- virtual void TearDown() {
- // Verifies that each of the predicate's arguments was evaluated
- // exactly once."""
-
- tests += ''.join(["""
- EXPECT_EQ(1, n%s_) <<
- "The predicate assertion didn't evaluate argument %s "
- "exactly once.";""" % (i, i + 1) for i in OneTo(n)])
-
- tests += """
-
- // Verifies that the control flow in the test function is expected.
- if (expected_to_finish_ && !finished_) {
- FAIL() << "The predicate assertion unexpactedly aborted the test.";
- } else if (!expected_to_finish_ && finished_) {
- FAIL() << "The failed predicate assertion didn't abort the test "
- "as expected.";
- }
- }
-
- // true iff the test function is expected to run to finish.
- static bool expected_to_finish_;
-
- // true iff the test function did run to finish.
- static bool finished_;
-""" % DEFS
-
- tests += Iter(n, """
- static int n%s_;""")
-
- tests += """
-};
-
-bool Predicate%(n)sTest::expected_to_finish_;
-bool Predicate%(n)sTest::finished_;
-""" % DEFS
-
- tests += Iter(n, """int Predicate%%(n)sTest::n%s_;
-""") % DEFS
-
- tests += """
-typedef Predicate%(n)sTest EXPECT_PRED_FORMAT%(n)sTest;
-typedef Predicate%(n)sTest ASSERT_PRED_FORMAT%(n)sTest;
-typedef Predicate%(n)sTest EXPECT_PRED%(n)sTest;
-typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest;
-""" % DEFS
-
- def GenTest(use_format, use_assert, expect_failure,
- use_functor, use_user_type):
- """Returns the test for a predicate assertion macro.
-
- Args:
- use_format: true iff the assertion is a *_PRED_FORMAT*.
- use_assert: true iff the assertion is a ASSERT_*.
- expect_failure: true iff the assertion is expected to fail.
- use_functor: true iff the first argument of the assertion is
- a functor (as opposed to a function)
- use_user_type: true iff the predicate functor/function takes
- argument(s) of a user-defined type.
-
- Example:
-
- GenTest(1, 0, 0, 1, 0) returns a test that tests the behavior
- of a successful EXPECT_PRED_FORMATn() that takes a functor
- whose arguments have built-in types."""
-
- if use_assert:
- assrt = 'ASSERT' # 'assert' is reserved, so we cannot use
- # that identifier here.
- else:
- assrt = 'EXPECT'
-
- assertion = assrt + '_PRED'
-
- if use_format:
- pred_format = 'PredFormat'
- assertion += '_FORMAT'
- else:
- pred_format = 'Pred'
-
- assertion += '%(n)s' % DEFS
-
- if use_functor:
- pred_format_type = 'functor'
- pred_format += 'Functor%(n)s()'
- else:
- pred_format_type = 'function'
- pred_format += 'Function%(n)s'
- if not use_format:
- if use_user_type:
- pred_format += 'Bool'
- else:
- pred_format += 'Int'
-
- test_name = pred_format_type.title()
-
- if use_user_type:
- arg_type = 'user-defined type (Bool)'
- test_name += 'OnUserType'
- if expect_failure:
- arg = 'Bool(n%s_++)'
- else:
- arg = 'Bool(++n%s_)'
- else:
- arg_type = 'built-in type (int)'
- test_name += 'OnBuiltInType'
- if expect_failure:
- arg = 'n%s_++'
- else:
- arg = '++n%s_'
-
- if expect_failure:
- successful_or_failed = 'failed'
- expected_or_not = 'expected.'
- test_name += 'Failure'
- else:
- successful_or_failed = 'successful'
- expected_or_not = 'UNEXPECTED!'
- test_name += 'Success'
-
- # A map that defines the values used in the test template.
- defs = DEFS.copy()
- defs.update({
- 'assert' : assrt,
- 'assertion' : assertion,
- 'test_name' : test_name,
- 'pf_type' : pred_format_type,
- 'pf' : pred_format,
- 'arg_type' : arg_type,
- 'arg' : arg,
- 'successful' : successful_or_failed,
- 'expected' : expected_or_not,
- })
-
- test = """
-// Tests a %(successful)s %(assertion)s where the
-// predicate-formatter is a %(pf_type)s on a %(arg_type)s.
-TEST_F(%(assertion)sTest, %(test_name)s) {""" % defs
-
- indent = (len(assertion) + 3)*' '
- extra_indent = ''
-
- if expect_failure:
- extra_indent = ' '
- if use_assert:
- test += """
- expected_to_finish_ = false;
- EXPECT_FATAL_FAILURE({ // NOLINT"""
- else:
- test += """
- EXPECT_NONFATAL_FAILURE({ // NOLINT"""
-
- test += '\n' + extra_indent + """ %(assertion)s(%(pf)s""" % defs
-
- test = test % defs
- test += Iter(n, ',\n' + indent + extra_indent + '%(arg)s' % defs)
- test += ');\n' + extra_indent + ' finished_ = true;\n'
-
- if expect_failure:
- test += ' }, "");\n'
-
- test += '}\n'
- return test
-
- # Generates tests for all 2**6 = 64 combinations.
- tests += ''.join([GenTest(use_format, use_assert, expect_failure,
- use_functor, use_user_type)
- for use_format in [0, 1]
- for use_assert in [0, 1]
- for expect_failure in [0, 1]
- for use_functor in [0, 1]
- for use_user_type in [0, 1]
- ])
-
- return tests
-
-
-def UnitTestPostamble():
- """Returns the postamble for the tests."""
-
- return ''
-
-
-def GenerateUnitTest(n):
- """Returns the tests for up-to n-ary predicate assertions."""
-
- GenerateFile(UNIT_TEST,
- UnitTestPreamble()
- + ''.join([TestsForArity(i) for i in OneTo(n)])
- + UnitTestPostamble())
-
-
-def _Main():
- """The entry point of the script. Generates the header file and its
- unit test."""
-
- if len(sys.argv) != 2:
- print __doc__
- print 'Author: ' + __author__
- sys.exit(1)
-
- n = int(sys.argv[1])
- GenerateHeader(n)
- GenerateUnitTest(n)
-
-
-if __name__ == '__main__':
- _Main()
diff --git a/googletest/scripts/gtest-config.in b/googletest/scripts/gtest-config.in
deleted file mode 100755
index 780f8432efcc..000000000000
--- a/googletest/scripts/gtest-config.in
+++ /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/pump.py b/googletest/scripts/pump.py
deleted file mode 100755
index 5efb653c207d..000000000000
--- a/googletest/scripts/pump.py
+++ /dev/null
@@ -1,855 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2008, Google Inc.
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""pump v0.2.0 - Pretty Useful for Meta Programming.
-
-A tool for preprocessor meta programming. Useful for generating
-repetitive boilerplate code. Especially useful for writing C++
-classes, functions, macros, and templates that need to work with
-various number of arguments.
-
-USAGE:
- pump.py SOURCE_FILE
-
-EXAMPLES:
- pump.py foo.cc.pump
- Converts foo.cc.pump to foo.cc.
-
-GRAMMAR:
- CODE ::= ATOMIC_CODE*
- ATOMIC_CODE ::= $var ID = EXPRESSION
- | $var ID = [[ CODE ]]
- | $range ID EXPRESSION..EXPRESSION
- | $for ID SEPARATOR [[ CODE ]]
- | $($)
- | $ID
- | $(EXPRESSION)
- | $if EXPRESSION [[ CODE ]] ELSE_BRANCH
- | [[ CODE ]]
- | RAW_CODE
- SEPARATOR ::= RAW_CODE | EMPTY
- ELSE_BRANCH ::= $else [[ CODE ]]
- | $elif EXPRESSION [[ CODE ]] ELSE_BRANCH
- | EMPTY
- EXPRESSION has Python syntax.
-"""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-import os
-import re
-import sys
-
-
-TOKEN_TABLE = [
- (re.compile(r'\$var\s+'), '$var'),
- (re.compile(r'\$elif\s+'), '$elif'),
- (re.compile(r'\$else\s+'), '$else'),
- (re.compile(r'\$for\s+'), '$for'),
- (re.compile(r'\$if\s+'), '$if'),
- (re.compile(r'\$range\s+'), '$range'),
- (re.compile(r'\$[_A-Za-z]\w*'), '$id'),
- (re.compile(r'\$\(\$\)'), '$($)'),
- (re.compile(r'\$'), '$'),
- (re.compile(r'\[\[\n?'), '[['),
- (re.compile(r'\]\]\n?'), ']]'),
- ]
-
-
-class Cursor:
- """Represents a position (line and column) in a text file."""
-
- def __init__(self, line=-1, column=-1):
- self.line = line
- self.column = column
-
- def __eq__(self, rhs):
- return self.line == rhs.line and self.column == rhs.column
-
- def __ne__(self, rhs):
- return not self == rhs
-
- def __lt__(self, rhs):
- return self.line < rhs.line or (
- self.line == rhs.line and self.column < rhs.column)
-
- def __le__(self, rhs):
- return self < rhs or self == rhs
-
- def __gt__(self, rhs):
- return rhs < self
-
- def __ge__(self, rhs):
- return rhs <= self
-
- def __str__(self):
- if self == Eof():
- return 'EOF'
- else:
- return '%s(%s)' % (self.line + 1, self.column)
-
- def __add__(self, offset):
- return Cursor(self.line, self.column + offset)
-
- def __sub__(self, offset):
- return Cursor(self.line, self.column - offset)
-
- def Clone(self):
- """Returns a copy of self."""
-
- return Cursor(self.line, self.column)
-
-
-# Special cursor to indicate the end-of-file.
-def Eof():
- """Returns the special cursor to denote the end-of-file."""
- return Cursor(-1, -1)
-
-
-class Token:
- """Represents a token in a Pump source file."""
-
- def __init__(self, start=None, end=None, value=None, token_type=None):
- if start is None:
- self.start = Eof()
- else:
- self.start = start
- if end is None:
- self.end = Eof()
- else:
- self.end = end
- self.value = value
- self.token_type = token_type
-
- def __str__(self):
- return 'Token @%s: \'%s\' type=%s' % (
- self.start, self.value, self.token_type)
-
- def Clone(self):
- """Returns a copy of self."""
-
- return Token(self.start.Clone(), self.end.Clone(), self.value,
- self.token_type)
-
-
-def StartsWith(lines, pos, string):
- """Returns True iff the given position in lines starts with 'string'."""
-
- return lines[pos.line][pos.column:].startswith(string)
-
-
-def FindFirstInLine(line, token_table):
- best_match_start = -1
- for (regex, token_type) in token_table:
- m = regex.search(line)
- if m:
- # We found regex in lines
- if best_match_start < 0 or m.start() < best_match_start:
- best_match_start = m.start()
- best_match_length = m.end() - m.start()
- best_match_token_type = token_type
-
- if best_match_start < 0:
- return None
-
- return (best_match_start, best_match_length, best_match_token_type)
-
-
-def FindFirst(lines, token_table, cursor):
- """Finds the first occurrence of any string in strings in lines."""
-
- start = cursor.Clone()
- cur_line_number = cursor.line
- for line in lines[start.line:]:
- if cur_line_number == start.line:
- line = line[start.column:]
- m = FindFirstInLine(line, token_table)
- if m:
- # We found a regex in line.
- (start_column, length, token_type) = m
- if cur_line_number == start.line:
- start_column += start.column
- found_start = Cursor(cur_line_number, start_column)
- found_end = found_start + length
- return MakeToken(lines, found_start, found_end, token_type)
- cur_line_number += 1
- # We failed to find str in lines
- return None
-
-
-def SubString(lines, start, end):
- """Returns a substring in lines."""
-
- if end == Eof():
- end = Cursor(len(lines) - 1, len(lines[-1]))
-
- if start >= end:
- return ''
-
- if start.line == end.line:
- return lines[start.line][start.column:end.column]
-
- result_lines = ([lines[start.line][start.column:]] +
- lines[start.line + 1:end.line] +
- [lines[end.line][:end.column]])
- return ''.join(result_lines)
-
-
-def StripMetaComments(str):
- """Strip meta comments from each line in the given string."""
-
- # First, completely remove lines containing nothing but a meta
- # comment, including the trailing \n.
- str = re.sub(r'^\s*\$\$.*\n', '', str)
-
- # Then, remove meta comments from contentful lines.
- return re.sub(r'\s*\$\$.*', '', str)
-
-
-def MakeToken(lines, start, end, token_type):
- """Creates a new instance of Token."""
-
- return Token(start, end, SubString(lines, start, end), token_type)
-
-
-def ParseToken(lines, pos, regex, token_type):
- line = lines[pos.line][pos.column:]
- m = regex.search(line)
- if m and not m.start():
- return MakeToken(lines, pos, pos + m.end(), token_type)
- else:
- print 'ERROR: %s expected at %s.' % (token_type, pos)
- sys.exit(1)
-
-
-ID_REGEX = re.compile(r'[_A-Za-z]\w*')
-EQ_REGEX = re.compile(r'=')
-REST_OF_LINE_REGEX = re.compile(r'.*?(?=$|\$\$)')
-OPTIONAL_WHITE_SPACES_REGEX = re.compile(r'\s*')
-WHITE_SPACE_REGEX = re.compile(r'\s')
-DOT_DOT_REGEX = re.compile(r'\.\.')
-
-
-def Skip(lines, pos, regex):
- line = lines[pos.line][pos.column:]
- m = re.search(regex, line)
- if m and not m.start():
- return pos + m.end()
- else:
- return pos
-
-
-def SkipUntil(lines, pos, regex, token_type):
- line = lines[pos.line][pos.column:]
- m = re.search(regex, line)
- if m:
- return pos + m.start()
- else:
- print ('ERROR: %s expected on line %s after column %s.' %
- (token_type, pos.line + 1, pos.column))
- sys.exit(1)
-
-
-def ParseExpTokenInParens(lines, pos):
- def ParseInParens(pos):
- pos = Skip(lines, pos, OPTIONAL_WHITE_SPACES_REGEX)
- pos = Skip(lines, pos, r'\(')
- pos = Parse(pos)
- pos = Skip(lines, pos, r'\)')
- return pos
-
- def Parse(pos):
- pos = SkipUntil(lines, pos, r'\(|\)', ')')
- if SubString(lines, pos, pos + 1) == '(':
- pos = Parse(pos + 1)
- pos = Skip(lines, pos, r'\)')
- return Parse(pos)
- else:
- return pos
-
- start = pos.Clone()
- pos = ParseInParens(pos)
- return MakeToken(lines, start, pos, 'exp')
-
-
-def RStripNewLineFromToken(token):
- if token.value.endswith('\n'):
- return Token(token.start, token.end, token.value[:-1], token.token_type)
- else:
- return token
-
-
-def TokenizeLines(lines, pos):
- while True:
- found = FindFirst(lines, TOKEN_TABLE, pos)
- if not found:
- yield MakeToken(lines, pos, Eof(), 'code')
- return
-
- if found.start == pos:
- prev_token = None
- prev_token_rstripped = None
- else:
- prev_token = MakeToken(lines, pos, found.start, 'code')
- prev_token_rstripped = RStripNewLineFromToken(prev_token)
-
- if found.token_type == '$var':
- if prev_token_rstripped:
- yield prev_token_rstripped
- yield found
- id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
- yield id_token
- pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX)
-
- eq_token = ParseToken(lines, pos, EQ_REGEX, '=')
- yield eq_token
- pos = Skip(lines, eq_token.end, r'\s*')
-
- if SubString(lines, pos, pos + 2) != '[[':
- exp_token = ParseToken(lines, pos, REST_OF_LINE_REGEX, 'exp')
- yield exp_token
- pos = Cursor(exp_token.end.line + 1, 0)
- elif found.token_type == '$for':
- if prev_token_rstripped:
- yield prev_token_rstripped
- yield found
- id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
- yield id_token
- pos = Skip(lines, id_token.end, WHITE_SPACE_REGEX)
- elif found.token_type == '$range':
- if prev_token_rstripped:
- yield prev_token_rstripped
- yield found
- id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
- yield id_token
- pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX)
-
- dots_pos = SkipUntil(lines, pos, DOT_DOT_REGEX, '..')
- yield MakeToken(lines, pos, dots_pos, 'exp')
- yield MakeToken(lines, dots_pos, dots_pos + 2, '..')
- pos = dots_pos + 2
- new_pos = Cursor(pos.line + 1, 0)
- yield MakeToken(lines, pos, new_pos, 'exp')
- pos = new_pos
- elif found.token_type == '$':
- if prev_token:
- yield prev_token
- yield found
- exp_token = ParseExpTokenInParens(lines, found.end)
- yield exp_token
- pos = exp_token.end
- elif (found.token_type == ']]' or found.token_type == '$if' or
- found.token_type == '$elif' or found.token_type == '$else'):
- if prev_token_rstripped:
- yield prev_token_rstripped
- yield found
- pos = found.end
- else:
- if prev_token:
- yield prev_token
- yield found
- pos = found.end
-
-
-def Tokenize(s):
- """A generator that yields the tokens in the given string."""
- if s != '':
- lines = s.splitlines(True)
- for token in TokenizeLines(lines, Cursor(0, 0)):
- yield token
-
-
-class CodeNode:
- def __init__(self, atomic_code_list=None):
- self.atomic_code = atomic_code_list
-
-
-class VarNode:
- def __init__(self, identifier=None, atomic_code=None):
- self.identifier = identifier
- self.atomic_code = atomic_code
-
-
-class RangeNode:
- def __init__(self, identifier=None, exp1=None, exp2=None):
- self.identifier = identifier
- self.exp1 = exp1
- self.exp2 = exp2
-
-
-class ForNode:
- def __init__(self, identifier=None, sep=None, code=None):
- self.identifier = identifier
- self.sep = sep
- self.code = code
-
-
-class ElseNode:
- def __init__(self, else_branch=None):
- self.else_branch = else_branch
-
-
-class IfNode:
- def __init__(self, exp=None, then_branch=None, else_branch=None):
- self.exp = exp
- self.then_branch = then_branch
- self.else_branch = else_branch
-
-
-class RawCodeNode:
- def __init__(self, token=None):
- self.raw_code = token
-
-
-class LiteralDollarNode:
- def __init__(self, token):
- self.token = token
-
-
-class ExpNode:
- def __init__(self, token, python_exp):
- self.token = token
- self.python_exp = python_exp
-
-
-def PopFront(a_list):
- head = a_list[0]
- a_list[:1] = []
- return head
-
-
-def PushFront(a_list, elem):
- a_list[:0] = [elem]
-
-
-def PopToken(a_list, token_type=None):
- token = PopFront(a_list)
- if token_type is not None and token.token_type != token_type:
- print 'ERROR: %s expected at %s' % (token_type, token.start)
- print 'ERROR: %s found instead' % (token,)
- sys.exit(1)
-
- return token
-
-
-def PeekToken(a_list):
- if not a_list:
- return None
-
- return a_list[0]
-
-
-def ParseExpNode(token):
- python_exp = re.sub(r'([_A-Za-z]\w*)', r'self.GetValue("\1")', token.value)
- return ExpNode(token, python_exp)
-
-
-def ParseElseNode(tokens):
- def Pop(token_type=None):
- return PopToken(tokens, token_type)
-
- next = PeekToken(tokens)
- if not next:
- return None
- if next.token_type == '$else':
- Pop('$else')
- Pop('[[')
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- return code_node
- elif next.token_type == '$elif':
- Pop('$elif')
- exp = Pop('code')
- Pop('[[')
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- inner_else_node = ParseElseNode(tokens)
- return CodeNode([IfNode(ParseExpNode(exp), code_node, inner_else_node)])
- elif not next.value.strip():
- Pop('code')
- return ParseElseNode(tokens)
- else:
- return None
-
-
-def ParseAtomicCodeNode(tokens):
- def Pop(token_type=None):
- return PopToken(tokens, token_type)
-
- head = PopFront(tokens)
- t = head.token_type
- if t == 'code':
- return RawCodeNode(head)
- elif t == '$var':
- id_token = Pop('id')
- Pop('=')
- next = PeekToken(tokens)
- if next.token_type == 'exp':
- exp_token = Pop()
- return VarNode(id_token, ParseExpNode(exp_token))
- Pop('[[')
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- return VarNode(id_token, code_node)
- elif t == '$for':
- id_token = Pop('id')
- next_token = PeekToken(tokens)
- if next_token.token_type == 'code':
- sep_token = next_token
- Pop('code')
- else:
- sep_token = None
- Pop('[[')
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- return ForNode(id_token, sep_token, code_node)
- elif t == '$if':
- exp_token = Pop('code')
- Pop('[[')
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- else_node = ParseElseNode(tokens)
- return IfNode(ParseExpNode(exp_token), code_node, else_node)
- elif t == '$range':
- id_token = Pop('id')
- exp1_token = Pop('exp')
- Pop('..')
- exp2_token = Pop('exp')
- return RangeNode(id_token, ParseExpNode(exp1_token),
- ParseExpNode(exp2_token))
- elif t == '$id':
- return ParseExpNode(Token(head.start + 1, head.end, head.value[1:], 'id'))
- elif t == '$($)':
- return LiteralDollarNode(head)
- elif t == '$':
- exp_token = Pop('exp')
- return ParseExpNode(exp_token)
- elif t == '[[':
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- return code_node
- else:
- PushFront(tokens, head)
- return None
-
-
-def ParseCodeNode(tokens):
- atomic_code_list = []
- while True:
- if not tokens:
- break
- atomic_code_node = ParseAtomicCodeNode(tokens)
- if atomic_code_node:
- atomic_code_list.append(atomic_code_node)
- else:
- break
- return CodeNode(atomic_code_list)
-
-
-def ParseToAST(pump_src_text):
- """Convert the given Pump source text into an AST."""
- tokens = list(Tokenize(pump_src_text))
- code_node = ParseCodeNode(tokens)
- return code_node
-
-
-class Env:
- def __init__(self):
- self.variables = []
- self.ranges = []
-
- def Clone(self):
- clone = Env()
- clone.variables = self.variables[:]
- clone.ranges = self.ranges[:]
- return clone
-
- def PushVariable(self, var, value):
- # If value looks like an int, store it as an int.
- try:
- int_value = int(value)
- if ('%s' % int_value) == value:
- value = int_value
- except Exception:
- pass
- self.variables[:0] = [(var, value)]
-
- def PopVariable(self):
- self.variables[:1] = []
-
- def PushRange(self, var, lower, upper):
- self.ranges[:0] = [(var, lower, upper)]
-
- def PopRange(self):
- self.ranges[:1] = []
-
- def GetValue(self, identifier):
- for (var, value) in self.variables:
- if identifier == var:
- return value
-
- print 'ERROR: meta variable %s is undefined.' % (identifier,)
- sys.exit(1)
-
- def EvalExp(self, exp):
- try:
- result = eval(exp.python_exp)
- except Exception, e:
- print 'ERROR: caught exception %s: %s' % (e.__class__.__name__, e)
- print ('ERROR: failed to evaluate meta expression %s at %s' %
- (exp.python_exp, exp.token.start))
- sys.exit(1)
- return result
-
- def GetRange(self, identifier):
- for (var, lower, upper) in self.ranges:
- if identifier == var:
- return (lower, upper)
-
- print 'ERROR: range %s is undefined.' % (identifier,)
- sys.exit(1)
-
-
-class Output:
- def __init__(self):
- self.string = ''
-
- def GetLastLine(self):
- index = self.string.rfind('\n')
- if index < 0:
- return ''
-
- return self.string[index + 1:]
-
- def Append(self, s):
- self.string += s
-
-
-def RunAtomicCode(env, node, output):
- if isinstance(node, VarNode):
- identifier = node.identifier.value.strip()
- result = Output()
- RunAtomicCode(env.Clone(), node.atomic_code, result)
- value = result.string
- env.PushVariable(identifier, value)
- elif isinstance(node, RangeNode):
- identifier = node.identifier.value.strip()
- lower = int(env.EvalExp(node.exp1))
- upper = int(env.EvalExp(node.exp2))
- env.PushRange(identifier, lower, upper)
- elif isinstance(node, ForNode):
- identifier = node.identifier.value.strip()
- if node.sep is None:
- sep = ''
- else:
- sep = node.sep.value
- (lower, upper) = env.GetRange(identifier)
- for i in range(lower, upper + 1):
- new_env = env.Clone()
- new_env.PushVariable(identifier, i)
- RunCode(new_env, node.code, output)
- if i != upper:
- output.Append(sep)
- elif isinstance(node, RawCodeNode):
- output.Append(node.raw_code.value)
- elif isinstance(node, IfNode):
- cond = env.EvalExp(node.exp)
- if cond:
- RunCode(env.Clone(), node.then_branch, output)
- elif node.else_branch is not None:
- RunCode(env.Clone(), node.else_branch, output)
- elif isinstance(node, ExpNode):
- value = env.EvalExp(node)
- output.Append('%s' % (value,))
- elif isinstance(node, LiteralDollarNode):
- output.Append('$')
- elif isinstance(node, CodeNode):
- RunCode(env.Clone(), node, output)
- else:
- print 'BAD'
- print node
- sys.exit(1)
-
-
-def RunCode(env, code_node, output):
- for atomic_code in code_node.atomic_code:
- RunAtomicCode(env, atomic_code, output)
-
-
-def IsSingleLineComment(cur_line):
- return '//' in cur_line
-
-
-def IsInPreprocessorDirective(prev_lines, cur_line):
- if cur_line.lstrip().startswith('#'):
- return True
- return prev_lines and prev_lines[-1].endswith('\\')
-
-
-def WrapComment(line, output):
- loc = line.find('//')
- before_comment = line[:loc].rstrip()
- if before_comment == '':
- indent = loc
- else:
- output.append(before_comment)
- indent = len(before_comment) - len(before_comment.lstrip())
- prefix = indent*' ' + '// '
- max_len = 80 - len(prefix)
- comment = line[loc + 2:].strip()
- segs = [seg for seg in re.split(r'(\w+\W*)', comment) if seg != '']
- cur_line = ''
- for seg in segs:
- if len((cur_line + seg).rstrip()) < max_len:
- cur_line += seg
- else:
- if cur_line.strip() != '':
- output.append(prefix + cur_line.rstrip())
- cur_line = seg.lstrip()
- if cur_line.strip() != '':
- output.append(prefix + cur_line.strip())
-
-
-def WrapCode(line, line_concat, output):
- indent = len(line) - len(line.lstrip())
- prefix = indent*' ' # Prefix of the current line
- max_len = 80 - indent - len(line_concat) # Maximum length of the current line
- new_prefix = prefix + 4*' ' # Prefix of a continuation line
- new_max_len = max_len - 4 # Maximum length of a continuation line
- # Prefers to wrap a line after a ',' or ';'.
- segs = [seg for seg in re.split(r'([^,;]+[,;]?)', line.strip()) if seg != '']
- cur_line = '' # The current line without leading spaces.
- for seg in segs:
- # If the line is still too long, wrap at a space.
- while cur_line == '' and len(seg.strip()) > max_len:
- seg = seg.lstrip()
- split_at = seg.rfind(' ', 0, max_len)
- output.append(prefix + seg[:split_at].strip() + line_concat)
- seg = seg[split_at + 1:]
- prefix = new_prefix
- max_len = new_max_len
-
- if len((cur_line + seg).rstrip()) < max_len:
- cur_line = (cur_line + seg).lstrip()
- else:
- output.append(prefix + cur_line.rstrip() + line_concat)
- prefix = new_prefix
- max_len = new_max_len
- cur_line = seg.lstrip()
- if cur_line.strip() != '':
- output.append(prefix + cur_line.strip())
-
-
-def WrapPreprocessorDirective(line, output):
- WrapCode(line, ' \\', output)
-
-
-def WrapPlainCode(line, output):
- WrapCode(line, '', output)
-
-
-def IsMultiLineIWYUPragma(line):
- return re.search(r'/\* IWYU pragma: ', line)
-
-
-def IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
- return (re.match(r'^#(ifndef|define|endif\s*//)\s*[\w_]+\s*$', line) or
- re.match(r'^#include\s', line) or
- # Don't break IWYU pragmas, either; that causes iwyu.py problems.
- re.search(r'// IWYU pragma: ', line))
-
-
-def WrapLongLine(line, output):
- line = line.rstrip()
- if len(line) <= 80:
- output.append(line)
- elif IsSingleLineComment(line):
- if IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
- # The style guide made an exception to allow long header guard lines,
- # includes and IWYU pragmas.
- output.append(line)
- else:
- WrapComment(line, output)
- elif IsInPreprocessorDirective(output, line):
- if IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
- # The style guide made an exception to allow long header guard lines,
- # includes and IWYU pragmas.
- output.append(line)
- else:
- WrapPreprocessorDirective(line, output)
- elif IsMultiLineIWYUPragma(line):
- output.append(line)
- else:
- WrapPlainCode(line, output)
-
-
-def BeautifyCode(string):
- lines = string.splitlines()
- output = []
- for line in lines:
- WrapLongLine(line, output)
- output2 = [line.rstrip() for line in output]
- return '\n'.join(output2) + '\n'
-
-
-def ConvertFromPumpSource(src_text):
- """Return the text generated from the given Pump source text."""
- ast = ParseToAST(StripMetaComments(src_text))
- output = Output()
- RunCode(Env(), ast, output)
- return BeautifyCode(output.string)
-
-
-def main(argv):
- if len(argv) == 1:
- print __doc__
- sys.exit(1)
-
- file_path = argv[-1]
- output_str = ConvertFromPumpSource(file(file_path, 'r').read())
- if file_path.endswith('.pump'):
- output_file_path = file_path[:-5]
- else:
- output_file_path = '-'
- if output_file_path == '-':
- print output_str,
- else:
- output_file = file(output_file_path, 'w')
- output_file.write('// This file was GENERATED by command:\n')
- output_file.write('// %s %s\n' %
- (os.path.basename(__file__), os.path.basename(file_path)))
- output_file.write('// DO NOT EDIT BY HAND!!!\n\n')
- output_file.write(output_str)
- output_file.close()
-
-
-if __name__ == '__main__':
- main(sys.argv)
diff --git a/googletest/scripts/release_docs.py b/googletest/scripts/release_docs.py
deleted file mode 100755
index 1291347f674a..000000000000
--- a/googletest/scripts/release_docs.py
+++ /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 documenation 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/test/Makefile b/googletest/scripts/test/Makefile
deleted file mode 100644
index cdff584637b7..000000000000
--- a/googletest/scripts/test/Makefile
+++ /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
index c852e4c91e06..000000000000
--- a/googletest/scripts/upload.py
+++ /dev/null
@@ -1,1387 +0,0 @@
-#!/usr/bin/env python
-#
-# 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.
-
-"""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
index be19ae80911c..000000000000
--- a/googletest/scripts/upload_gtest.py
+++ /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()
diff --git a/googletest/src/gtest-all.cc b/googletest/src/gtest-all.cc
index ad292905cf38..2a70ed88c784 100644
--- a/googletest/src/gtest-all.cc
+++ b/googletest/src/gtest-all.cc
@@ -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
index 000000000000..39989216741a
--- /dev/null
+++ b/googletest/src/gtest-assertion-result.cc
@@ -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_ != 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_ != 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
diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc
index da09a1cfc23a..0eb6e38b2a96 100644
--- a/googletest/src/gtest-death-test.cc
+++ b/googletest/src/gtest-death-test.cc
@@ -32,51 +32,56 @@
#include "gtest/gtest-death-test.h"
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <string>
#include <utility>
+#include <vector>
-#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
+#ifdef GTEST_HAS_DEATH_TEST
+
+#ifdef GTEST_OS_MAC
+#include <crt_externs.h>
+#endif // GTEST_OS_MAC
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+
+#ifdef GTEST_OS_LINUX
+#include <signal.h>
+#endif // GTEST_OS_LINUX
+
+#include <stdarg.h>
+
+#ifdef GTEST_OS_WINDOWS
+#include <windows.h>
+#else
+#include <sys/mman.h>
+#include <sys/wait.h>
+#endif // GTEST_OS_WINDOWS
+
+#ifdef GTEST_OS_QNX
+#include <spawn.h>
+#endif // GTEST_OS_QNX
+
+#ifdef 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
@@ -95,9 +100,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 "
@@ -106,7 +114,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 "
@@ -116,7 +124,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 "
@@ -125,17 +132,18 @@ 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
-#if GTEST_HAS_DEATH_TEST
+namespace testing {
+
+#ifdef GTEST_HAS_DEATH_TEST
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 !defined(GTEST_OS_WINDOWS) && !defined(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
@@ -143,16 +151,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 defined(GTEST_OS_WINDOWS) || defined(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
@@ -161,40 +169,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 defined(GTEST_OS_WINDOWS) || defined(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 !defined(GTEST_OS_WINDOWS) && !defined(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 {
@@ -205,23 +211,23 @@ namespace internal {
static std::string ExitSummary(int exit_code) {
Message m;
-# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#if defined(GTEST_OS_WINDOWS) || defined(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();
}
@@ -232,7 +238,7 @@ bool ExitedUnsuccessfully(int exit_status) {
return !ExitedWithCode(0)(exit_status);
}
-# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#if !defined(GTEST_OS_WINDOWS) && !defined(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
@@ -247,13 +253,13 @@ static std::string DeathTestThreadWarning(size_t thread_count) {
msg << "detected " << thread_count << " threads.";
}
msg << " See "
- "https://github.com/google/googletest/blob/master/googletest/docs/"
+ "https://github.com/google/googletest/blob/main/docs/"
"advanced.md#death-tests-and-threads"
<< " for more explanation and suggested solutions, especially if"
<< " 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';
@@ -261,7 +267,7 @@ static const char kDeathTestReturned = 'R';
static const char kDeathTestThrew = 'T';
static const char kDeathTestInternalError = 'I';
-#if GTEST_OS_FUCHSIA
+#ifdef GTEST_OS_FUCHSIA
// File descriptor used for the pipe in the child process.
static const int kFuchsiaReadPipeFd = 3;
@@ -282,7 +288,7 @@ enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
// message is propagated back to the parent process. Otherwise, the
// message is simply printed to stderr. In either case, the program
// then exits with status 1.
-static void DeathTestAbort(const std::string& message) {
+[[noreturn]] static void DeathTestAbort(const std::string& message) {
// On a POSIX system, this function may be called from a threadsafe-style
// death test child process, which operates on a very small stack. Use
// the heap for any additional non-minuscule memory requirements.
@@ -303,14 +309,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
@@ -320,23 +326,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
@@ -369,8 +375,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");
}
}
@@ -499,9 +506,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.
@@ -511,9 +516,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.,
@@ -532,7 +537,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) {
@@ -567,8 +572,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();
@@ -579,15 +583,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) {
@@ -604,7 +611,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:
@@ -617,7 +625,21 @@ bool DeathTestImpl::Passed(bool status_ok) {
return success;
}
-# if GTEST_OS_WINDOWS
+#ifndef GTEST_OS_WINDOWS
+// Note: The return value points into args, so the return value's lifetime is
+// bound to that of args.
+static std::unique_ptr<char*[]> CreateArgvFromArgs(
+ std::vector<std::string>& args) {
+ auto result = std::make_unique<char*[]>(args.size() + 1);
+ for (size_t i = 0; i < args.size(); ++i) {
+ result[i] = &args[i][0];
+ }
+ result[args.size()] = nullptr; // extra null terminator
+ return result;
+}
+#endif
+
+#ifdef 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
@@ -678,14 +700,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:
@@ -706,9 +726,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);
@@ -741,12 +760,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,
@@ -755,27 +774,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("");
@@ -795,8 +813,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.
@@ -808,7 +826,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
return OVERSEE_TEST;
}
-# elif GTEST_OS_FUCHSIA
+#elif defined(GTEST_OS_FUCHSIA)
class FuchsiaDeathTest : public DeathTestImpl {
public:
@@ -836,41 +854,6 @@ class FuchsiaDeathTest : public DeathTestImpl {
zx::socket stderr_socket_;
};
-// Utility class for accumulating command-line arguments.
-class Arguments {
- public:
- Arguments() { args_.push_back(nullptr); }
-
- ~Arguments() {
- for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
- ++i) {
- free(*i);
- }
- }
- void AddArgument(const char* argument) {
- args_.insert(args_.end() - 1, posix::StrDup(argument));
- }
-
- template <typename Str>
- void AddArguments(const ::std::vector<Str>& arguments) {
- for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
- i != arguments.end();
- ++i) {
- args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
- }
- }
- char* const* Argv() {
- return &args_[0];
- }
-
- int size() {
- return args_.size() - 1;
- }
-
- private:
- std::vector<char*> args_;
-};
-
// Waits for the child in a death test to exit, returning its exit
// status, or 0 if no child process exists. As a side effect, sets the
// outcome data member.
@@ -879,8 +862,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;
@@ -889,19 +871,18 @@ 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, ZX_WAIT_ASYNC_ONCE);
+ 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.
status_zx = stderr_socket_.wait_async(
- port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
- ZX_WAIT_ASYNC_ONCE);
+ port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
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, ZX_WAIT_ASYNC_ONCE);
+ 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 +912,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) {
@@ -941,8 +922,7 @@ int FuchsiaDeathTest::Wait() {
} else {
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
status_zx = stderr_socket_.wait_async(
- port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
- ZX_WAIT_ASYNC_ONCE);
+ port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
}
} else {
@@ -955,12 +935,12 @@ int FuchsiaDeathTest::Wait() {
ReadAndInterpretStatusByte();
zx_info_process_t buffer;
- status_zx = child_process_.get_info(
- ZX_INFO_PROCESS, &buffer, sizeof(buffer), nullptr, nullptr);
+ status_zx = child_process_.get_info(ZX_INFO_PROCESS, &buffer, sizeof(buffer),
+ nullptr, nullptr);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
- GTEST_DEATH_TEST_CHECK_(buffer.exited);
- set_status(buffer.return_code);
+ GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED);
+ set_status(static_cast<int>(buffer.return_code));
return status();
}
@@ -988,17 +968,16 @@ 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);
- Arguments args;
- args.AddArguments(GetInjectableArgvs());
- args.AddArgument(filter_flag.c_str());
- args.AddArgument(internal_flag.c_str());
+ "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::vector<std::string> args = GetInjectableArgvs();
+ args.push_back(filter_flag);
+ args.push_back(internal_flag);
// Build the pipe for communication with the child.
zx_status_t status;
@@ -1017,8 +996,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 =
@@ -1035,35 +1013,38 @@ 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);
+ // Note: The test component must have `fuchsia.process.Launcher` declared
+ // in its manifest. (Fuchsia integration tests require creating a
+ // "Fuchsia Test Component" which contains a "Fuchsia Component Manifest")
+ // Launching processes is a privileged operation in Fuchsia, and the
+ // declaration indicates that the ability is required for the component.
+ std::unique_ptr<char*[]> argv = CreateArgvFromArgs(args);
+ status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, argv[0], argv.get(),
+ 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.
@@ -1094,8 +1075,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();
@@ -1148,7 +1128,7 @@ DeathTest::TestRole NoExecDeathTest::AssumeRole() {
LogToStderr();
// Event forwarding to the listeners of event listener API mush be shut
// down in death test subprocesses.
- GetUnitTestImpl()->listeners()->SuppressEventForwarding();
+ GetUnitTestImpl()->listeners()->SuppressEventForwarding(true);
g_in_fast_death_test_child = true;
return EXECUTE_TEST;
} else {
@@ -1174,11 +1154,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.
@@ -1187,37 +1167,6 @@ class ExecDeathTest : public ForkingDeathTest {
const int line_;
};
-// Utility class for accumulating command-line arguments.
-class Arguments {
- public:
- Arguments() { args_.push_back(nullptr); }
-
- ~Arguments() {
- for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
- ++i) {
- free(*i);
- }
- }
- void AddArgument(const char* argument) {
- args_.insert(args_.end() - 1, posix::StrDup(argument));
- }
-
- template <typename Str>
- void AddArguments(const ::std::vector<Str>& arguments) {
- for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
- i != arguments.end();
- ++i) {
- args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
- }
- }
- char* const* Argv() {
- return &args_[0];
- }
-
- private:
- std::vector<char*> args_;
-};
-
// A struct that encompasses the arguments to the child process of a
// threadsafe-style death test process.
struct ExecDeathTestArgs {
@@ -1225,21 +1174,9 @@ struct ExecDeathTestArgs {
int close_fd; // File descriptor to close; the read end of a pipe
};
-# if GTEST_OS_MAC
-inline char** GetEnviron() {
- // When Google Test is built as a framework on MacOS X, the environ variable
- // is unavailable. Apple's documentation (man environ) recommends using
- // _NSGetEnviron() instead.
- return *_NSGetEnviron();
-}
-# else
-// Some POSIX platforms expect you to declare environ. extern "C" makes
-// it reside in the global namespace.
+#ifdef GTEST_OS_QNX
extern "C" char** environ;
-inline char** GetEnviron() { return environ; }
-# endif // GTEST_OS_MAC
-
-# if !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.
@@ -1254,25 +1191,24 @@ 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;
}
- // We can safely call execve() as it's a direct system call. We
+ // We can safely call execv() as it's almost a direct system call. We
// cannot use execvp() as it's a libc function and thus potentially
- // unsafe. Since execve() doesn't search the PATH, the user must
+ // unsafe. Since execv() doesn't search the PATH, the user must
// invoke the test program via a valid path that contains at least
// one path separator.
- execve(args->argv[0], args->argv, GetEnviron());
- DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
- original_dir + " failed: " +
- GetLastErrnoDescription());
+ execv(args->argv[0], args->argv);
+ DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +
+ 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
@@ -1284,24 +1220,29 @@ static int ExecDeathTestChildMain(void* child_arg) {
// correct answer.
static void StackLowerThanAddress(const void* ptr,
bool* result) GTEST_NO_INLINE_;
+// Make sure sanitizers do not tamper with the stack here.
+// Ideally, we want to use `__builtin_frame_address` instead of a local variable
+// address with sanitizer disabled, but it does not work when the
+// compiler optimizes the stack frame out, which happens on PowerPC targets.
// HWAddressSanitizer add a random tag to the MSB of the local variable address,
// making comparison result unpredictable.
+GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
static void StackLowerThanAddress(const void* ptr, bool* result) {
- int dummy;
- *result = (&dummy < ptr);
+ int dummy = 0;
+ *result = std::less<const void*>()(&dummy, ptr);
}
// Make sure AddressSanitizer does not tamper with the stack here.
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
static bool StackGrowsDown() {
- int dummy;
+ int dummy = 0;
bool result;
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
@@ -1311,10 +1252,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
+#ifdef GTEST_OS_QNX
// Obtains the current directory and sets it to be closed in the child
// process.
const int cwd_fd = open(".", O_RDONLY);
@@ -1327,26 +1268,25 @@ 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, GetEnviron());
+ child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);
// Restores the current working directory.
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
+#ifdef 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.
@@ -1355,16 +1295,16 @@ 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();
- const auto stack_size = static_cast<size_t>(getpagesize());
+ const auto stack_size = static_cast<size_t>(getpagesize() * 2);
// MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,
MAP_ANON | MAP_PRIVATE, -1, 0);
@@ -1379,7 +1319,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);
@@ -1388,19 +1328,18 @@ 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);
+ _exit(ExecDeathTestChildMain(&args));
}
-# endif // GTEST_OS_QNX
-# if GTEST_OS_LINUX
+#endif // GTEST_OS_QNX
+#ifdef 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;
@@ -1429,17 +1368,16 @@ 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]);
- Arguments args;
- args.AddArguments(GetArgvsForDeathTestChildProcess());
- args.AddArgument(filter_flag.c_str());
- args.AddArgument(internal_flag.c_str());
+ "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]);
+ std::vector<std::string> args = GetArgvsForDeathTestChildProcess();
+ args.push_back(filter_flag);
+ args.push_back(internal_flag);
DeathTest::set_last_death_test_message("");
@@ -1448,7 +1386,8 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
// is necessary.
FlushInfoLog();
- const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
+ std::unique_ptr<char*[]> argv = CreateArgvFromArgs(args);
+ const pid_t child_pid = ExecDeathTestSpawnChild(argv.get(), pipe_fd[0]);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
set_child_pid(child_pid);
set_read_fd(pipe_fd[0]);
@@ -1456,7 +1395,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
@@ -1470,15 +1409,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;
}
@@ -1489,50 +1428,50 @@ bool DefaultDeathTestFactory::Create(const char* statement,
}
}
-# if GTEST_OS_WINDOWS
+#ifdef 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 defined(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
+#ifdef 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));
@@ -1540,8 +1479,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
@@ -1563,9 +1501,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) +
@@ -1587,61 +1523,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).empty()) 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
+#ifdef 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 defined(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);
}
diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc
index bd7b99ff03e4..513e947f5703 100644
--- a/googletest/src/gtest-filepath.cc
+++ b/googletest/src/gtest-filepath.cc
@@ -30,35 +30,42 @@
#include "gtest/internal/gtest-filepath.h"
#include <stdlib.h>
-#include "gtest/internal/gtest-port.h"
+
+#include <iterator>
+#include <string>
+
#include "gtest/gtest-message.h"
+#include "gtest/internal/gtest-port.h"
-#if GTEST_OS_WINDOWS_MOBILE
-# include <windows.h>
-#elif GTEST_OS_WINDOWS
-# include <direct.h>
-# include <io.h>
+#ifdef GTEST_OS_WINDOWS_MOBILE
+#include <windows.h>
+#elif defined(GTEST_OS_WINDOWS)
+#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
+#ifdef GTEST_OS_WINDOWS
+#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
+#if GTEST_HAS_FILE_SYSTEM
+
namespace testing {
namespace internal {
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// On Windows, '\\' is the standard path separator, but many tools and the
// Windows API also accept '/' as an alternate path separator. Unless otherwise
// noted, a file path can contain either kind of path separators, or a mixture
@@ -66,16 +73,16 @@ namespace internal {
const char kPathSeparator = '\\';
const char kAlternatePathSeparator = '/';
const char kAlternatePathSeparatorString[] = "/";
-# if GTEST_OS_WINDOWS_MOBILE
+#ifdef 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[] = "./";
@@ -92,23 +99,26 @@ static bool IsPathSeparator(char c) {
// Returns the current working directory, or "" if unsuccessful.
FilePath FilePath::GetCurrentDir() {
-#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
- GTEST_OS_WINDOWS_RT || ARDUINO || defined(ESP_PLATFORM)
+#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \
+ defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \
+ defined(GTEST_OS_ESP32) || defined(GTEST_OS_XTENSA) || \
+ defined(GTEST_OS_QURT) || defined(GTEST_OS_NXP_QN9090) || \
+ defined(GTEST_OS_NRF52)
// These platforms do not have a current directory, so we just return
// something reasonable.
return FilePath(kCurrentDirectoryString);
-#elif GTEST_OS_WINDOWS
- char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
+#elif defined(GTEST_OS_WINDOWS)
+ 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
+#ifdef 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
}
@@ -120,8 +130,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;
}
@@ -142,6 +152,44 @@ const char* FilePath::FindLastPathSeparator() const {
return last_sep;
}
+size_t FilePath::CalculateRootLength() const {
+ const auto& path = pathname_;
+ auto s = path.begin();
+ auto end = path.end();
+#ifdef GTEST_OS_WINDOWS
+ if (end - s >= 2 && s[1] == ':' && (end - s == 2 || IsPathSeparator(s[2])) &&
+ (('A' <= s[0] && s[0] <= 'Z') || ('a' <= s[0] && s[0] <= 'z'))) {
+ // A typical absolute path like "C:\Windows" or "D:"
+ s += 2;
+ if (s != end) {
+ ++s;
+ }
+ } else if (end - s >= 3 && IsPathSeparator(*s) && IsPathSeparator(*(s + 1)) &&
+ !IsPathSeparator(*(s + 2))) {
+ // Move past the "\\" prefix in a UNC path like "\\Server\Share\Folder"
+ s += 2;
+ // Skip 2 components and their following separators ("Server\" and "Share\")
+ for (int i = 0; i < 2; ++i) {
+ while (s != end) {
+ bool stop = IsPathSeparator(*s);
+ ++s;
+ if (stop) {
+ break;
+ }
+ }
+ }
+ } else if (s != end && IsPathSeparator(*s)) {
+ // A drive-rooted path like "\Windows"
+ ++s;
+ }
+#else
+ if (s != end && IsPathSeparator(*s)) {
+ ++s;
+ }
+#endif
+ return static_cast<size_t>(s - path.begin());
+}
+
// Returns a copy of the FilePath with the directory part removed.
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
@@ -177,15 +225,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));
}
@@ -194,8 +241,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());
}
@@ -203,13 +249,13 @@ FilePath FilePath::ConcatPaths(const FilePath& directory,
// Returns true if pathname describes something findable in the file-system,
// either a file, directory, or whatever.
bool FilePath::FileOrDirectoryExists() const {
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef 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;
+ posix::StatStruct file_stat{};
return posix::Stat(pathname_.c_str(), &file_stat) == 0;
#endif // GTEST_OS_WINDOWS_MOBILE
}
@@ -218,55 +264,42 @@ bool FilePath::FileOrDirectoryExists() const {
// that exists.
bool FilePath::DirectoryExists() const {
bool result = false;
-#if GTEST_OS_WINDOWS
+#ifdef 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
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef 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);
+ posix::StatStruct file_stat{};
+ result =
+ posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
#endif // GTEST_OS_WINDOWS_MOBILE
return result;
}
// Returns true if pathname describes a root directory. (Windows has one
-// root directory per disk drive.)
+// root directory per disk drive. UNC share roots are also included.)
bool FilePath::IsRootDirectory() const {
-#if GTEST_OS_WINDOWS
- return pathname_.length() == 3 && IsAbsolutePath();
-#else
- return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
-#endif
+ size_t root_length = CalculateRootLength();
+ return root_length > 0 && root_length == pathname_.size() &&
+ IsPathSeparator(pathname_[root_length - 1]);
}
// Returns true if pathname describes an absolute path.
-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]);
-#else
- return IsPathSeparator(name[0]);
-#endif
-}
+bool FilePath::IsAbsolutePath() const { return CalculateRootLength() > 0; }
// Returns a pathname for a file that does not currently exist. The pathname
// will be directory/base_name.extension or
@@ -316,13 +349,18 @@ bool FilePath::CreateDirectoriesRecursively() const {
// directory for any reason, including if the parent directory does not
// exist. Not named "CreateDirectory" because that's a macro on Windows.
bool FilePath::CreateFolder() const {
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
- delete [] unicode;
-#elif GTEST_OS_WINDOWS
+ delete[] unicode;
+#elif defined(GTEST_OS_WINDOWS)
int result = _mkdir(pathname_.c_str());
+#elif defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \
+ defined(GTEST_OS_QURT) || defined(GTEST_OS_NXP_QN9090) || \
+ defined(GTEST_OS_NRF52)
+ // do nothing
+ int result = 0;
#else
int result = mkdir(pathname_.c_str(), 0777);
#endif // GTEST_OS_WINDOWS_MOBILE
@@ -337,43 +375,40 @@ 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.
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
// redundancies that might be in a pathname involving "." or "..".
+// Note that "\\Host\Share" does not contain a redundancy on Windows!
void FilePath::Normalize() {
- if (pathname_.c_str() == nullptr) {
- pathname_ = "";
- return;
+ auto out = pathname_.begin();
+
+ auto i = pathname_.cbegin();
+#ifdef GTEST_OS_WINDOWS
+ // UNC paths are treated specially
+ if (pathname_.end() - i >= 3 && IsPathSeparator(*i) &&
+ IsPathSeparator(*(i + 1)) && !IsPathSeparator(*(i + 2))) {
+ *(out++) = kPathSeparator;
+ *(out++) = kPathSeparator;
}
- const char* src = pathname_.c_str();
- char* const dest = new char[pathname_.length() + 1];
- char* dest_ptr = dest;
- memset(dest_ptr, 0, pathname_.length() + 1);
-
- while (*src != '\0') {
- *dest_ptr = *src;
- if (!IsPathSeparator(*src)) {
- src++;
- } else {
-#if GTEST_HAS_ALT_PATH_SEP_
- if (*dest_ptr == kAlternatePathSeparator) {
- *dest_ptr = kPathSeparator;
- }
#endif
- while (IsPathSeparator(*src))
- src++;
+ while (i != pathname_.end()) {
+ const char character = *i;
+ if (!IsPathSeparator(character)) {
+ *(out++) = character;
+ } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
+ *(out++) = kPathSeparator;
}
- dest_ptr++;
+ ++i;
}
- *dest_ptr = '\0';
- pathname_ = dest;
- delete[] dest;
+
+ pathname_.erase(out, pathname_.end());
}
} // namespace internal
} // namespace testing
+
+#endif // GTEST_HAS_FILE_SYSTEM
diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h
index 8ed70daab094..5b7fcbd06509 100644
--- a/googletest/src/gtest-internal-inl.h
+++ b/googletest/src/gtest-internal-inl.h
@@ -31,40 +31,40 @@
// This file contains purely Google Test's internal implementation. Please
// DO NOT #INCLUDE IT IN A USER PROGRAM.
-#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
-#define GTEST_SRC_GTEST_INTERNAL_INL_H_
+#ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
+#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 <string.h> // For memmove.
#include <algorithm>
+#include <cstdint>
#include <memory>
+#include <set>
#include <string>
#include <vector>
#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
+#ifdef 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
@@ -72,30 +72,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 kFilterFlag[] = "filter";
-const char kListTestsFlag[] = "list_tests";
-const char kOutputFlag[] = "output";
-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;
@@ -109,7 +92,8 @@ GTEST_API_ TimeInMillis GetTimeInMillis();
// Returns true if and only if Google Test should use colors in the output.
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
-// Formats the given time in milliseconds as seconds.
+// Formats the given time in milliseconds as seconds. If the input is an exact N
+// seconds, the output has a trailing decimal point (e.g., "N." instead of "N").
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
// Converts the given time in milliseconds to a date string in the ISO 8601
@@ -122,21 +106,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* 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 random_seed_flag) {
- const unsigned int raw_seed = (random_seed_flag == 0) ?
- static_cast<unsigned int>(GetTimeInMillis()) :
- static_cast<unsigned int>(random_seed_flag);
+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);
// 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;
}
@@ -157,46 +141,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);
- filter_ = GTEST_FLAG(filter);
- internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
- list_tests_ = GTEST_FLAG(list_tests);
- output_ = GTEST_FLAG(output);
- 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(internal_run_death_test) = internal_run_death_test_;
- GTEST_FLAG(list_tests) = list_tests_;
- GTEST_FLAG(output) = output_;
- 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:
@@ -207,19 +199,22 @@ class GTestFlagSaver {
std::string color_;
std::string death_test_style_;
bool death_test_use_fork_;
+ bool fail_fast_;
std::string filter_;
std::string internal_run_death_test_;
bool list_tests_;
std::string output_;
+ bool brief_;
bool print_time_;
bool print_utf8_;
- internal::Int32 random_seed_;
- internal::Int32 repeat_;
+ int32_t random_seed_;
+ int32_t repeat_;
+ bool recreate_environments_when_repeating_;
bool shuffle_;
- internal::Int32 stack_trace_depth_;
+ int32_t stack_trace_depth_;
std::string stream_result_to_;
bool throw_on_failure_;
-} GTEST_ATTRIBUTE_UNUSED_;
+};
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
// code_point parameter is of type UInt32 because wchar_t may not be
@@ -227,7 +222,7 @@ class GTestFlagSaver {
// If the code_point is not a valid Unicode code point
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
// to "(Invalid Unicode 0xXXXXXXXX)".
-GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
+GTEST_API_ std::string CodePointToUtf8(uint32_t code_point);
// Converts a wide string to a narrow string in UTF-8 encoding.
// The wide string is assumed to have the following encoding:
@@ -260,17 +255,17 @@ GTEST_API_ bool ShouldShard(const char* total_shards_str,
const char* shard_index_str,
bool in_subprocess_for_death_test);
-// Parses the environment variable var as an Int32. If it is unset,
-// returns default_val. If it is not an Int32, prints an error and
+// Parses the environment variable var as a 32-bit integer. If it is unset,
+// returns default_val. If it is not a 32-bit integer, prints an error and
// and aborts.
-GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
+GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
// Given the total number of shards, the shard index, and the test id,
// 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.
@@ -281,9 +276,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;
}
@@ -323,7 +317,7 @@ void ShuffleRange(internal::Random* random, int begin, int end,
const int last_in_range = begin + range_width - 1;
const int selected =
begin +
- static_cast<int>(random->Generate(static_cast<UInt32>(range_width)));
+ static_cast<int>(random->Generate(static_cast<uint32_t>(range_width)));
std::swap((*v)[static_cast<size_t>(selected)],
(*v)[static_cast<size_t>(last_in_range)]);
}
@@ -385,25 +379,18 @@ class GTEST_API_ UnitTestOptions {
// Functions for processing the gtest_filter flag.
- // Returns true if and only if the wildcard pattern matches the string.
- // The first ':' or '\0' character in pattern marks the end of it.
- //
- // This recursive algorithm isn't very efficient, but is clear and
- // works well enough for matching test names, which are short.
- static bool PatternMatchesString(const char *pattern, const char *str);
-
// Returns true if and only if the user-specified filter matches the test
// suite name and the test name.
static bool FilterMatchesTest(const std::string& test_suite_name,
const std::string& test_name);
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Function for supporting the gtest_catch_exception flag.
- // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
- // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
+ // Returns EXCEPTION_EXECUTE_HANDLER if given SEH exception was handled, or
+ // EXCEPTION_CONTINUE_SEARCH otherwise.
// This function is useful as an __except condition.
- static int GTestShouldProcessSEH(DWORD exception_code);
+ static int GTestProcessSEH(DWORD seh_code, const char* location);
#endif // GTEST_OS_WINDOWS
// Returns true if "name" matches the ':' separated list of glob-style
@@ -411,15 +398,17 @@ class GTEST_API_ UnitTestOptions {
static bool MatchesFilter(const std::string& name, const char* filter);
};
+#if GTEST_HAS_FILE_SYSTEM
// Returns the current application's name, removing directory path if that
// is present. Used by UnitTestOptions::GetOutputFile.
GTEST_API_ FilePath GetCurrentExecutableName();
+#endif // GTEST_HAS_FILE_SYSTEM
// The role interface for getting the OS stack trace as a string.
class OsStackTraceGetterInterface {
public:
- OsStackTraceGetterInterface() {}
- virtual ~OsStackTraceGetterInterface() {}
+ OsStackTraceGetterInterface() = default;
+ virtual ~OsStackTraceGetterInterface() = default;
// Returns the current OS stack trace as an std::string. Parameters:
//
@@ -439,19 +428,21 @@ 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.
class OsStackTraceGetter : public OsStackTraceGetterInterface {
public:
- OsStackTraceGetter() {}
+ OsStackTraceGetter() = default;
std::string CurrentStackTrace(int max_depth, int skip_count) override;
void UponLeavingGTest() override;
private:
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
Mutex mutex_; // Protects all internal state.
// We save the stack frame below the frame that calls user code.
@@ -461,7 +452,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.
@@ -474,7 +466,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
@@ -484,7 +476,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
@@ -500,7 +495,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
@@ -513,9 +511,9 @@ class GTEST_API_ UnitTestImpl {
virtual ~UnitTestImpl();
// There are two different ways to register your own TestPartResultReporter.
- // You can register your own repoter to listen either only for test results
+ // You can register your own reporter to listen either only for test results
// from the current thread or for results from all threads.
- // By default, each per-thread test result repoter just passes a new
+ // By default, each per-thread test result reporter just passes a new
// TestPartResult to the global test result reporter, which registers the
// test part result for the currently running test.
@@ -638,7 +636,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.
@@ -646,10 +645,10 @@ class GTEST_API_ UnitTestImpl {
// Arguments:
//
// test_suite_name: name of the test suite
- // type_param: the name of the test's type parameter, or NULL if
- // this is not a typed or a type-parameterized test.
- // set_up_tc: pointer to the function that sets up the test suite
- // tear_down_tc: pointer to the function that tears down the test suite
+ // type_param: the name of the test's type parameter, or NULL if
+ // this is not a typed or a type-parameterized test.
+ // set_up_tc: pointer to the function that sets up the test suite
+ // tear_down_tc: pointer to the function that tears down the test suite
TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc);
@@ -673,6 +672,7 @@ class GTEST_API_ UnitTestImpl {
void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc,
TestInfo* test_info) {
+#if GTEST_HAS_FILE_SYSTEM
// In order to support thread-safe death tests, we need to
// remember the original working directory when the test program
// was first invoked. We cannot do this in RUN_ALL_TESTS(), as
@@ -685,6 +685,7 @@ class GTEST_API_ UnitTestImpl {
GTEST_CHECK_(!original_working_dir_.IsEmpty())
<< "Failed to get the current working directory.";
}
+#endif // GTEST_HAS_FILE_SYSTEM
GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
set_up_tc, tear_down_tc)
@@ -697,6 +698,17 @@ class GTEST_API_ UnitTestImpl {
return parameterized_test_registry_;
}
+ std::set<std::string>* ignored_parameterized_test_suites() {
+ return &ignored_parameterized_test_suites_;
+ }
+
+ // Returns TypeParameterizedTestSuiteRegistry object used to keep track of
+ // type-parameterized tests and instantiations of them.
+ internal::TypeParameterizedTestSuiteRegistry&
+ type_parameterized_test_registry() {
+ return type_parameterized_test_registry_;
+ }
+
// Sets the TestSuite object for the test that's currently running.
void set_current_test_suite(TestSuite* a_current_test_suite) {
current_test_suite_ = a_current_test_suite;
@@ -729,9 +741,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
@@ -739,10 +749,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
@@ -771,7 +778,7 @@ class GTEST_API_ UnitTestImpl {
return gtest_trace_stack_.get();
}
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
void InitDeathTestSubprocessControlInfo() {
internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
}
@@ -837,9 +844,11 @@ class GTEST_API_ UnitTestImpl {
// The UnitTest object that owns this implementation object.
UnitTest* const parent_;
+#if GTEST_HAS_FILE_SYSTEM
// The working directory when the first TEST() or TEST_F() was
// executed.
internal::FilePath original_working_dir_;
+#endif // GTEST_HAS_FILE_SYSTEM
// The default test part result reporters.
DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
@@ -847,7 +856,7 @@ class GTEST_API_ UnitTestImpl {
default_per_thread_test_part_result_reporter_;
// Points to (but doesn't own) the global test part result reporter.
- TestPartResultReporterInterface* global_test_part_result_repoter_;
+ TestPartResultReporterInterface* global_test_part_result_reporter_;
// Protects read and write access to global_test_part_result_reporter_.
internal::Mutex global_test_part_result_reporter_mutex_;
@@ -873,6 +882,12 @@ class GTEST_API_ UnitTestImpl {
// ParameterizedTestRegistry object used to register value-parameterized
// tests.
internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
+ internal::TypeParameterizedTestSuiteRegistry
+ type_parameterized_test_registry_;
+
+ // The set holding the name of parameterized
+ // test suites that may go uninstantiated.
+ std::set<std::string> ignored_parameterized_test_suites_;
// Indicates whether RegisterParameterizedTests() has been called already.
bool parameterized_tests_registered_;
@@ -928,7 +943,7 @@ class GTEST_API_ UnitTestImpl {
// How long the test took to run, in milliseconds.
TimeInMillis elapsed_time_;
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
// The decomposed components of the gtest_internal_run_death_test flag,
// parsed when RUN_ALL_TESTS is called.
std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
@@ -942,7 +957,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
@@ -951,7 +967,7 @@ inline UnitTestImpl* GetUnitTestImpl() {
return UnitTest::GetInstance()->impl();
}
-#if GTEST_USES_SIMPLE_RE
+#ifdef GTEST_USES_SIMPLE_RE
// Internal helper functions for implementing the simple regular
// expression matcher.
@@ -965,8 +981,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
@@ -976,7 +993,7 @@ GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
// Returns the message describing the last system error, regardless of the
// platform.
@@ -999,20 +1016,9 @@ bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
char* end;
// BiggestConvertible is the largest integer type that system-provided
// string-to-number conversion routines can return.
+ using BiggestConvertible = unsigned long long; // NOLINT
-# if GTEST_OS_WINDOWS && !defined(__GNUC__)
-
- // MSVC and C++ Builder define __int64 instead of the standard long long.
- typedef unsigned __int64 BiggestConvertible;
- const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
-
-# else
-
- typedef unsigned long long BiggestConvertible; // NOLINT
- const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
-
-# endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
-
+ const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); // NOLINT
const bool parse_success = *end == '\0' && errno == 0;
GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
@@ -1058,7 +1064,7 @@ class StreamingListener : public EmptyTestEventListener {
// Abstract base class for writing strings to a socket.
class AbstractSocketWriter {
public:
- virtual ~AbstractSocketWriter() {}
+ virtual ~AbstractSocketWriter() = default;
// Sends a string to the socket.
virtual void Send(const std::string& message) = 0;
@@ -1079,8 +1085,7 @@ class StreamingListener : public EmptyTestEventListener {
}
~SocketWriter() override {
- if (sockfd_ != -1)
- CloseConnection();
+ if (sockfd_ != -1) CloseConnection();
}
// Sends a string to the socket.
@@ -1090,9 +1095,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_;
}
}
@@ -1113,7 +1117,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".
@@ -1125,7 +1130,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");
@@ -1148,22 +1155,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 compatibilty
- void OnTestCaseStart(const TestCase& test_case) override {
- SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
+ // "case" for compatibility
+ 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 compatibilty
- void OnTestCaseEnd(const TestCase& test_case) override {
- SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
- "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
+ // "case" for compatibility
+ void OnTestSuiteEnd(const TestSuite& test_suite) override {
+ SendLn("event=TestCaseEnd&passed=" + FormatBool(test_suite.Passed()) +
+ "&elapsed_time=" + StreamableToString(test_suite.elapsed_time()) +
"ms");
}
@@ -1173,8 +1180,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");
}
@@ -1198,7 +1204,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_
@@ -1208,4 +1215,4 @@ class StreamingListener : public EmptyTestEventListener {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
-#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
+#endif // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
diff --git a/googletest/src/gtest-matchers.cc b/googletest/src/gtest-matchers.cc
index 7d2fb6851ec4..7e3bcc0cff38 100644
--- a/googletest/src/gtest-matchers.cc
+++ b/googletest/src/gtest-matchers.cc
@@ -32,12 +32,13 @@
// 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
@@ -58,40 +59,40 @@ Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
// s.
Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
-#if GTEST_HAS_ABSL
-// Constructs a matcher that matches a const absl::string_view& whose value is
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+// Constructs a matcher that matches a const StringView& whose value is
// equal to s.
-Matcher<const absl::string_view&>::Matcher(const std::string& s) {
+Matcher<const internal::StringView&>::Matcher(const std::string& s) {
*this = Eq(s);
}
-// Constructs a matcher that matches a const absl::string_view& whose value is
+// Constructs a matcher that matches a const StringView& whose value is
// equal to s.
-Matcher<const absl::string_view&>::Matcher(const char* s) {
+Matcher<const internal::StringView&>::Matcher(const char* s) {
*this = Eq(std::string(s));
}
-// Constructs a matcher that matches a const absl::string_view& whose value is
+// Constructs a matcher that matches a const StringView& whose value is
// equal to s.
-Matcher<const absl::string_view&>::Matcher(absl::string_view s) {
+Matcher<const internal::StringView&>::Matcher(internal::StringView s) {
*this = Eq(std::string(s));
}
-// Constructs a matcher that matches a absl::string_view whose value is equal to
+// Constructs a matcher that matches a StringView whose value is equal to
// s.
-Matcher<absl::string_view>::Matcher(const std::string& s) { *this = Eq(s); }
+Matcher<internal::StringView>::Matcher(const std::string& s) { *this = Eq(s); }
-// Constructs a matcher that matches a absl::string_view whose value is equal to
+// Constructs a matcher that matches a StringView whose value is equal to
// s.
-Matcher<absl::string_view>::Matcher(const char* s) {
+Matcher<internal::StringView>::Matcher(const char* s) {
*this = Eq(std::string(s));
}
-// Constructs a matcher that matches a absl::string_view whose value is equal to
+// Constructs a matcher that matches a StringView whose value is equal to
// s.
-Matcher<absl::string_view>::Matcher(absl::string_view s) {
+Matcher<internal::StringView>::Matcher(internal::StringView s) {
*this = Eq(std::string(s));
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
} // namespace testing
diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc
index fc5ba6becc55..2aaf2bcc26c1 100644
--- a/googletest/src/gtest-port.cc
+++ b/googletest/src/gtest-port.cc
@@ -27,60 +27,68 @@
// (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>
+#include <ostream>
+#include <string>
+#include <utility>
+#include <vector>
+
+#ifdef GTEST_OS_WINDOWS
+#include <io.h>
+#include <sys/stat.h>
+#include <windows.h>
-#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 <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>
+#ifdef GTEST_OS_MAC
+#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
+#if defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD) || \
+ defined(GTEST_OS_OPENBSD)
+#include <sys/sysctl.h>
+#if defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_GNU_KFREEBSD)
+#include <sys/user.h>
+#endif
#endif
-#if GTEST_OS_QNX
-# include <devctl.h>
-# include <fcntl.h>
-# include <sys/procfs.h>
+#ifdef GTEST_OS_QNX
+#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>
+#ifdef GTEST_OS_AIX
+#include <procinfo.h>
+#include <sys/types.h>
#endif // GTEST_OS_AIX
-#if GTEST_OS_FUCHSIA
-# include <zircon/process.h>
-# include <zircon/syscalls.h>
+#ifdef GTEST_OS_FUCHSIA
+#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"
@@ -88,16 +96,7 @@
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 defined(GTEST_OS_LINUX) || defined(GTEST_OS_GNU_HURD)
namespace {
template <typename T>
@@ -120,7 +119,7 @@ size_t GetThreadCount() {
return ReadProcFileField<size_t>(filename, 19);
}
-#elif GTEST_OS_MAC
+#elif defined(GTEST_OS_MAC)
size_t GetThreadCount() {
const task_t task = mach_task_self();
@@ -130,8 +129,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 {
@@ -139,20 +137,20 @@ size_t GetThreadCount() {
}
}
-#elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
- GTEST_OS_NETBSD
+#elif defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD)
-#if GTEST_OS_NETBSD
+#ifdef GTEST_OS_NETBSD
#undef KERN_PROC
#define KERN_PROC KERN_PROC2
#define kinfo_proc kinfo_proc2
#endif
-#if GTEST_OS_DRAGONFLY
+#ifdef GTEST_OS_DRAGONFLY
#define KP_NLWP(kp) (kp.kp_nthreads)
-#elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
+#elif defined(GTEST_OS_FREEBSD) || defined(GTEST_OS_GNU_KFREEBSD)
#define KP_NLWP(kp) (kp.ki_numthreads)
-#elif GTEST_OS_NETBSD
+#elif defined(GTEST_OS_NETBSD)
#define KP_NLWP(kp) (kp.p_nlwps)
#endif
@@ -164,7 +162,7 @@ size_t GetThreadCount() {
KERN_PROC,
KERN_PROC_PID,
getpid(),
-#if GTEST_OS_NETBSD
+#ifdef GTEST_OS_NETBSD
sizeof(struct kinfo_proc),
1,
#endif
@@ -177,18 +175,18 @@ size_t GetThreadCount() {
}
return static_cast<size_t>(KP_NLWP(info));
}
-#elif GTEST_OS_OPENBSD
+#elif defined(GTEST_OS_OPENBSD)
// Returns the number of threads running in the process, or 0 to indicate that
// 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]);
@@ -197,24 +195,24 @@ size_t GetThreadCount() {
if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
return 0;
}
- mib[5] = size / mib[4];
+
+ mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4]));
// populate array of structs
- struct kinfo_proc info[mib[5]];
- if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
+ std::vector<struct kinfo_proc> info(mib[5]);
+ if (sysctl(mib, miblen, info.data(), &size, NULL, 0)) {
return 0;
}
// exclude empty members
- int nthreads = 0;
- for (int i = 0; i < size / mib[4]; i++) {
- if (info[i].p_tid != -1)
- nthreads++;
+ 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++;
}
return nthreads;
}
-#elif GTEST_OS_QNX
+#elif defined(GTEST_OS_QNX)
// Returns the number of threads running in the process, or 0 to indicate that
// we cannot detect it.
@@ -234,7 +232,7 @@ size_t GetThreadCount() {
}
}
-#elif GTEST_OS_AIX
+#elif defined(GTEST_OS_AIX)
size_t GetThreadCount() {
struct procentry64 entry;
@@ -247,18 +245,14 @@ size_t GetThreadCount() {
}
}
-#elif GTEST_OS_FUCHSIA
+#elif defined(GTEST_OS_FUCHSIA)
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 {
@@ -276,29 +270,17 @@ size_t GetThreadCount() {
#endif // GTEST_OS_LINUX
-#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
+#if defined(GTEST_IS_THREADSAFE) && defined(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.
@@ -310,7 +292,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.";
}
}
@@ -320,23 +302,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),
@@ -389,25 +354,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
@@ -433,15 +398,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.
@@ -486,9 +449,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_;
@@ -506,20 +467,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(Runnable* runnable,
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)
@@ -536,6 +495,9 @@ class ThreadLocalRegistryImpl {
// Returns a value that can be used to identify the thread from other threads.
static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
const ThreadLocalBase* thread_local_instance) {
+#ifdef _MSC_VER
+ MemoryIsNotDeallocated memory_is_not_deallocated;
+#endif // _MSC_VER
DWORD current_thread = ::GetCurrentThreadId();
MutexLock lock(&mutex_);
ThreadIdToThreadLocals* const thread_to_thread_locals =
@@ -543,8 +505,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;
@@ -572,9 +536,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);
@@ -604,9 +567,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);
@@ -632,9 +594,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.
@@ -645,7 +606,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,
@@ -659,8 +621,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;
@@ -683,23 +644,24 @@ class ThreadLocalRegistryImpl {
static Mutex thread_map_mutex_;
};
-Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
-Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
+Mutex ThreadLocalRegistryImpl::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);
}
#endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
-#if GTEST_USES_POSIX_RE
+#ifdef GTEST_USES_POSIX_RE
// Implements RE. Currently only needed for death tests.
@@ -712,7 +674,6 @@ RE::~RE() {
regfree(&partial_regex_);
regfree(&full_regex_);
}
- free(const_cast<char*>(pattern_));
}
// Returns true if and only if regular expression re matches the entire str.
@@ -734,7 +695,7 @@ bool RE::PartialMatch(const char* str, const RE& re) {
// Initializes an RE from its string representation.
void RE::Init(const char* regex) {
- pattern_ = posix::StrDup(regex);
+ pattern_ = regex;
// Reserves enough bytes to hold the regular expression used for a
// full match.
@@ -762,7 +723,7 @@ void RE::Init(const char* regex) {
delete[] full_pattern;
}
-#elif GTEST_USES_SIMPLE_RE
+#elif defined(GTEST_USES_SIMPLE_RE)
// Returns true if and only if ch appears anywhere in str (excluding the
// terminating '\0' character).
@@ -781,7 +742,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.
@@ -794,17 +755,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;
}
@@ -815,7 +787,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;
@@ -857,12 +830,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;
}
@@ -880,12 +853,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.
@@ -898,8 +869,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;
}
@@ -913,25 +883,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);
}
}
@@ -946,40 +914,37 @@ 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;
}
// Implements the RE class.
-RE::~RE() {
- free(const_cast<char*>(pattern_));
- free(const_cast<char*>(full_pattern_));
-}
+RE::~RE() = default;
// Returns true if and only if regular expression re matches the entire str.
bool RE::FullMatch(const char* str, const RE& re) {
- return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
+ return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_.c_str(), str);
}
// Returns true if and only if regular expression re matches a substring of
// str (including str itself).
bool RE::PartialMatch(const char* str, const RE& re) {
- return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
+ return re.is_valid_ && MatchRegexAnywhere(re.pattern_.c_str(), str);
}
// Initializes an RE from its string representation.
void RE::Init(const char* regex) {
- pattern_ = full_pattern_ = nullptr;
+ full_pattern_.clear();
+ pattern_.clear();
+
if (regex != nullptr) {
- pattern_ = posix::StrDup(regex);
+ pattern_ = regex;
}
is_valid_ = ValidateRegex(regex);
@@ -988,25 +953,19 @@ void RE::Init(const char* regex) {
return;
}
- const size_t len = strlen(regex);
// Reserves enough bytes to hold the regular expression used for a
- // full match: we need space to prepend a '^', append a '$', and
- // terminate the string with '\0'.
- char* buffer = static_cast<char*>(malloc(len + 3));
- full_pattern_ = buffer;
-
- if (*regex != '^')
- *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
+ // full match: we need space to prepend a '^' and append a '$'.
+ full_pattern_.reserve(pattern_.size() + 2);
- // We don't use snprintf or strncpy, as they trigger a warning when
- // compiled with VC++ 8.0.
- memcpy(buffer, regex, len);
- buffer += len;
+ if (pattern_.empty() || pattern_.front() != '^') {
+ full_pattern_.push_back('^'); // Makes sure full_pattern_ starts with '^'.
+ }
- if (len == 0 || regex[len - 1] != '$')
- *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
+ full_pattern_.append(pattern_);
- *buffer = '\0';
+ if (pattern_.empty() || pattern_.back() != '$') {
+ full_pattern_.push_back('$'); // Makes sure full_pattern_ ends with '$'.
+ }
}
#endif // GTEST_USES_POSIX_RE
@@ -1033,8 +992,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)
@@ -1045,12 +1004,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.
@@ -1073,27 +1033,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
+#ifdef 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 the /tmp directory
- // instead. We use /tmp on most systems, and /sdcard on Android.
- // That's because Android doesn't have /tmp.
-# if GTEST_OS_LINUX_ANDROID
+ // directory, so we create the temporary file in a temporary directory.
+ std::string name_template;
+
+#ifdef 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,
@@ -1105,26 +1064,53 @@ class CapturedStream {
// The location /data/local/tmp is directly accessible from native code.
// '/sdcard' and other variants cannot be relied on, as they are not
// guaranteed to be mounted, or may have a delay in mounting.
- char name_template[] = "/data/local/tmp/gtest_captured_stream.XXXXXX";
-# else
- char name_template[] = "/tmp/captured_stream.XXXXXX";
-# endif // GTEST_OS_LINUX_ANDROID
- const int captured_fd = mkstemp(name_template);
+ name_template = "/data/local/tmp/";
+#elif defined(GTEST_OS_IOS)
+ char user_temp_dir[PATH_MAX + 1];
+
+ // Documented alternative to NSTemporaryDirectory() (for obtaining creating
+ // a temporary directory) at
+ // https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW10
+ //
+ // _CS_DARWIN_USER_TEMP_DIR (as well as _CS_DARWIN_USER_CACHE_DIR) is not
+ // documented in the confstr() man page at
+ // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/confstr.3.html#//apple_ref/doc/man/3/confstr
+ // but are still available, according to the WebKit patches at
+ // https://trac.webkit.org/changeset/262004/webkit
+ // https://trac.webkit.org/changeset/263705/webkit
+ //
+ // The confstr() implementation falls back to getenv("TMPDIR"). See
+ // https://opensource.apple.com/source/Libc/Libc-1439.100.3/gen/confstr.c.auto.html
+ ::confstr(_CS_DARWIN_USER_TEMP_DIR, user_temp_dir, sizeof(user_temp_dir));
+
+ name_template = user_temp_dir;
+ if (name_template.back() != GTEST_PATH_SEP_[0])
+ name_template.push_back(GTEST_PATH_SEP_[0]);
+#else
+ name_template = "/tmp/";
+#endif
+ name_template.append("gtest_captured_stream.XXXXXX");
+
+ // mkstemp() modifies the string bytes in place, and does not go beyond the
+ // string's length. This results in well-defined behavior in C++17.
+ //
+ // The const_cast is needed below C++17. The constraints on std::string
+ // implementations in C++11 and above make assumption behind the const_cast
+ // fairly safe.
+ const int captured_fd = ::mkstemp(const_cast<char*>(name_template.data()));
if (captured_fd == -1) {
GTEST_LOG_(WARNING)
<< "Failed to create tmp file " << name_template
<< " for test; does the test have access to the /tmp directory?";
}
- filename_ = name_template;
-# endif // GTEST_OS_WINDOWS
+ filename_ = std::move(name_template);
+#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) {
@@ -1151,7 +1137,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_()
@@ -1179,6 +1166,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);
@@ -1201,10 +1197,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));
@@ -1222,7 +1214,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);
@@ -1232,7 +1225,7 @@ std::string ReadEntireFile(FILE* file) {
return content;
}
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
static const std::vector<std::string>* g_injected_test_argvs =
nullptr; // Owned.
@@ -1259,7 +1252,7 @@ void ClearInjectableArgvs() {
}
#endif // GTEST_HAS_DEATH_TEST
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
namespace posix {
void Abort() {
DebugBreak();
@@ -1286,7 +1279,7 @@ static std::string FlagToEnvVar(const char* flag) {
// Parses 'str' for a 32-bit signed integer. If successful, writes
// the result to *value and returns true; otherwise leaves *value
// unchanged and returns false.
-bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
+bool ParseInt32(const Message& src_text, const char* str, int32_t* value) {
// Parses the environment variable as a decimal integer.
char* end = nullptr;
const long long_value = strtol(str, &end, 10); // NOLINT
@@ -1303,14 +1296,14 @@ bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
return false;
}
- // Is the parsed value in the range of an Int32?
- const Int32 result = static_cast<Int32>(long_value);
+ // Is the parsed value in the range of an int32_t?
+ const auto result = static_cast<int32_t>(long_value);
if (long_value == LONG_MAX || long_value == LONG_MIN ||
// The parsed value overflows as a long. (strtol() returns
// LONG_MAX or LONG_MIN when the input overflows.)
result != long_value
- // The parsed value overflows as an Int32.
- ) {
+ // The parsed value overflows as an int32_t.
+ ) {
Message msg;
msg << "WARNING: " << src_text
<< " is expected to be a 32-bit integer, but actually"
@@ -1342,7 +1335,7 @@ bool BoolFromGTestEnv(const char* flag, bool default_value) {
// Reads and returns a 32-bit integer stored in the environment
// variable corresponding to the given flag; if it isn't set or
// doesn't represent a valid 32-bit integer, returns default_value.
-Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
+int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
#if defined(GTEST_GET_INT32_FROM_ENV_)
return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
#else
@@ -1353,9 +1346,9 @@ Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
return default_value;
}
- Int32 result = default_value;
- if (!ParseInt32(Message() << "Environment variable " << env_var,
- string_value, &result)) {
+ int32_t result = default_value;
+ if (!ParseInt32(Message() << "Environment variable " << env_var, string_value,
+ &result)) {
printf("The default value %s is used.\n",
(Message() << default_value).GetString().c_str());
fflush(stdout);
@@ -1374,7 +1367,7 @@ Int32 Int32FromGTestEnv(const char* flag, Int32 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) {
diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc
index 3337be312ea4..e3acecba8e4d 100644
--- a/googletest/src/gtest-printers.cc
+++ b/googletest/src/gtest-printers.cc
@@ -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
@@ -42,11 +41,18 @@
// defines Foo.
#include "gtest/gtest-printers.h"
+
#include <stdio.h>
+
#include <cctype>
+#include <cstdint>
#include <cwchar>
+#include <iomanip>
+#include <ios>
#include <ostream> // NOLINT
#include <string>
+#include <type_traits>
+
#include "gtest/internal/gtest-port.h"
#include "src/gtest-internal-inl.h"
@@ -96,15 +102,25 @@ 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 << ">";
}
+// Helpers for widening a character to char32_t. Since the standard does not
+// specify if char / wchar_t is signed or unsigned, it is important to first
+// convert it to the unsigned type of the same width before widening it to
+// char32_t.
+template <typename CharType>
+char32_t ToChar32(CharType in) {
+ return static_cast<char32_t>(
+ static_cast<typename std::make_unsigned<CharType>::type>(in));
+}
+
} // namespace
-namespace internal2 {
+namespace internal {
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
// given object. The delegation simplifies the implementation, which
@@ -116,36 +132,25 @@ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
PrintBytesInObjectToImpl(obj_bytes, count, os);
}
-} // namespace internal2
-
-namespace internal {
-
// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
// - 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
// Windows Mobile.
-inline bool IsPrintableAscii(wchar_t c) {
- return 0x20 <= c && c <= 0x7E;
-}
+inline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }
-// Prints a wide or narrow char c as a character literal without the
-// quotes, escaping it when necessary; returns how c was formatted.
-// The template argument UnsignedChar is the unsigned version of Char,
-// which is the type of c.
-template <typename UnsignedChar, typename Char>
+// Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a
+// character literal without the quotes, escaping it when necessary; returns how
+// c was formatted.
+template <typename Char>
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
- wchar_t w_c = static_cast<wchar_t>(c);
- switch (w_c) {
+ const char32_t u_c = ToChar32(c);
+ switch (u_c) {
case L'\0':
*os << "\\0";
break;
@@ -177,13 +182,12 @@ static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
*os << "\\v";
break;
default:
- if (IsPrintableAscii(w_c)) {
+ if (IsPrintableAscii(u_c)) {
*os << static_cast<char>(c);
return kAsIs;
} else {
ostream::fmtflags flags = os->flags();
- *os << "\\x" << std::hex << std::uppercase
- << static_cast<int>(static_cast<UnsignedChar>(c));
+ *os << "\\x" << std::hex << std::uppercase << static_cast<int>(u_c);
os->flags(flags);
return kHexEscape;
}
@@ -191,9 +195,9 @@ static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
return kSpecialEscape;
}
-// Prints a wchar_t c as if it's part of a string literal, escaping it when
+// Prints a char32_t c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
-static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
+static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
switch (c) {
case L'\'':
*os << "'";
@@ -202,33 +206,60 @@ static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
*os << "\\\"";
return kSpecialEscape;
default:
- return PrintAsCharLiteralTo<wchar_t>(c, os);
+ return PrintAsCharLiteralTo(c, os);
}
}
+static const char* GetCharWidthPrefix(char) { return ""; }
+
+static const char* GetCharWidthPrefix(signed char) { return ""; }
+
+static const char* GetCharWidthPrefix(unsigned char) { return ""; }
+
+#ifdef __cpp_lib_char8_t
+static const char* GetCharWidthPrefix(char8_t) { return "u8"; }
+#endif
+
+static const char* GetCharWidthPrefix(char16_t) { return "u"; }
+
+static const char* GetCharWidthPrefix(char32_t) { return "U"; }
+
+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.
static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
- return PrintAsStringLiteralTo(
- static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
+ return PrintAsStringLiteralTo(ToChar32(c), os);
+}
+
+#ifdef __cpp_lib_char8_t
+static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
+ return PrintAsStringLiteralTo(ToChar32(c), os);
+}
+#endif
+
+static CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {
+ return PrintAsStringLiteralTo(ToChar32(c), os);
+}
+
+static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
+ return PrintAsStringLiteralTo(ToChar32(c), os);
}
-// Prints a wide or narrow character c and its code. '\0' is printed
-// as "'\\0'", other unprintable characters are also properly escaped
-// using the standard C++ escape sequence. The template argument
-// UnsignedChar is the unsigned version of Char, which is the type of c.
-template <typename UnsignedChar, typename Char>
+// Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)
+// and its code. '\0' is printed as "'\\0'", other unprintable characters are
+// also properly escaped using the standard C++ escape sequence.
+template <typename Char>
void PrintCharAndCodeTo(Char c, ostream* os) {
// First, print c as a literal in the most readable form we can find.
- *os << ((sizeof(c) > 1) ? "L'" : "'");
- const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
+ *os << GetCharWidthPrefix(c) << "'";
+ const CharFormat format = PrintAsCharLiteralTo(c, os);
*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,
@@ -242,32 +273,75 @@ void PrintCharAndCodeTo(Char c, ostream* os) {
*os << ")";
}
-void PrintTo(unsigned char c, ::std::ostream* os) {
- PrintCharAndCodeTo<unsigned char>(c, os);
-}
-void PrintTo(signed char c, ::std::ostream* os) {
- PrintCharAndCodeTo<unsigned char>(c, os);
-}
+void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
+void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
// Prints a wchar_t as a symbol if it is printable or as its internal
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
-void PrintTo(wchar_t wc, ostream* os) {
- PrintCharAndCodeTo<wchar_t>(wc, os);
+void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }
+
+// TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.
+void PrintTo(char32_t c, ::std::ostream* os) {
+ *os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4)
+ << 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 = static_cast<char>('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 or wchar_t.
+// 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) {
- const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
- *os << kQuoteBegin;
+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;
CharFormat print_format = kAsIs;
for (size_t index = 0; index < len; ++index) {
@@ -276,7 +350,7 @@ static CharFormat PrintCharsAsStringTo(
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
- *os << "\" " << kQuoteBegin;
+ *os << "\" " << quote_prefix << "\"";
}
is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
// Remember if any characters required hex escaping.
@@ -291,12 +365,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'.
@@ -322,22 +395,57 @@ void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
UniversalPrintCharArray(begin, len, os);
}
+#ifdef __cpp_lib_char8_t
+// Prints a (const) char8_t array of 'len' elements, starting at address
+// 'begin'.
+void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
+ UniversalPrintCharArray(begin, len, os);
+}
+#endif
+
+// Prints a (const) char16_t array of 'len' elements, starting at address
+// 'begin'.
+void UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {
+ UniversalPrintCharArray(begin, len, os);
+}
+
+// Prints a (const) char32_t array of 'len' elements, starting at address
+// 'begin'.
+void UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {
+ UniversalPrintCharArray(begin, len, os);
+}
+
// Prints a (const) wchar_t array of 'len' elements, starting at address
// 'begin'.
void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
UniversalPrintCharArray(begin, len, os);
}
-// Prints the given C string to the ostream.
-void PrintTo(const char* s, ostream* os) {
+namespace {
+
+// Prints a null-terminated C-style string to the ostream.
+template <typename Char>
+void PrintCStringTo(const Char* s, ostream* os) {
if (s == nullptr) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
- PrintCharsAsStringTo(s, strlen(s), os);
+ PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os);
}
}
+} // anonymous namespace
+
+void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }
+
+#ifdef __cpp_lib_char8_t
+void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
+#endif
+
+void PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }
+
+void PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }
+
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
@@ -346,41 +454,34 @@ void PrintTo(const char* s, ostream* os) {
// wchar_t is implemented as a native type.
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
// Prints the given wide C string to the ostream.
-void PrintTo(const wchar_t* s, ostream* os) {
- if (s == nullptr) {
- *os << "NULL";
- } else {
- *os << ImplicitCast_<const void*>(s) << " pointing to ";
- PrintCharsAsStringTo(s, wcslen(s), os);
- }
-}
+void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
#endif // wchar_t is native
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++];
@@ -393,15 +494,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) &&
@@ -425,12 +524,26 @@ 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);
}
}
}
+#ifdef __cpp_lib_char8_t
+void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
+ PrintCharsAsStringTo(s.data(), s.size(), os);
+}
+#endif
+
+void PrintU16StringTo(const ::std::u16string& s, ostream* os) {
+ PrintCharsAsStringTo(s.data(), s.size(), os);
+}
+
+void PrintU32StringTo(const ::std::u32string& s, ostream* os) {
+ PrintCharsAsStringTo(s.data(), s.size(), os);
+}
+
#if GTEST_HAS_STD_WSTRING
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
diff --git a/googletest/src/gtest-test-part.cc b/googletest/src/gtest-test-part.cc
index 178317a6bcdb..6f8ddd7c485c 100644
--- a/googletest/src/gtest-test-part.cc
+++ b/googletest/src/gtest-test-part.cc
@@ -31,12 +31,15 @@
// The Google C++ Testing and Mocking Framework (Google Test)
#include "gtest/gtest-test-part.h"
+
+#include <ostream>
+#include <string>
+
+#include "gtest/internal/gtest-port.h"
#include "src/gtest-internal-inl.h"
namespace testing {
-using internal::GetUnitTestImpl;
-
// Gets the summary of the failure message by omitting the stack trace
// in it.
std::string TestPartResult::ExtractSummary(const char* message) {
@@ -46,14 +49,14 @@ std::string TestPartResult::ExtractSummary(const char* message) {
// Prints a TestPartResult object.
std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
- return os << 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")
+ 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")
<< ":\n"
<< result.message() << std::endl;
}
@@ -82,8 +85,8 @@ namespace internal {
HasNewFatalFailureHelper::HasNewFatalFailureHelper()
: has_new_fatal_failure_(false),
- original_reporter_(GetUnitTestImpl()->
- GetTestPartResultReporterForCurrentThread()) {
+ original_reporter_(
+ GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) {
GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
}
@@ -94,8 +97,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);
}
diff --git a/googletest/src/gtest-typed-test.cc b/googletest/src/gtest-typed-test.cc
index 8677caf732b4..b251c09deb80 100644
--- a/googletest/src/gtest-typed-test.cc
+++ b/googletest/src/gtest-typed-test.cc
@@ -27,21 +27,21 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
#include "gtest/gtest-typed-test.h"
+#include <set>
+#include <string>
+#include <vector>
+
#include "gtest/gtest.h"
namespace testing {
namespace internal {
-#if GTEST_HAS_TYPED_TEST_P
-
// 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;
}
@@ -58,7 +58,10 @@ static std::vector<std::string> SplitIntoTestNames(const char* src) {
// registered_tests_; returns registered_tests if successful, or
// aborts the program otherwise.
const char* TypedTestSuitePState::VerifyRegisteredTestNames(
- const char* file, int line, const char* registered_tests) {
+ const char* test_suite_name, const char* file, int line,
+ const char* registered_tests) {
+ RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line));
+
typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
registered_ = true;
@@ -75,17 +78,7 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames(
continue;
}
- bool found = false;
- for (RegisteredTestIter it = registered_tests_.begin();
- it != registered_tests_.end();
- ++it) {
- if (name == it->first) {
- found = true;
- break;
- }
- }
-
- if (found) {
+ if (registered_tests_.count(name) != 0) {
tests.insert(name);
} else {
errors << "No test named " << name
@@ -94,15 +87,14 @@ 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";
}
}
const std::string& errors_str = errors.GetString();
- if (errors_str != "") {
+ if (!errors_str.empty()) {
fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
errors_str.c_str());
fflush(stderr);
@@ -112,7 +104,5 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames(
return registered_tests;
}
-#endif // GTEST_HAS_TYPED_TEST_P
-
} // namespace internal
} // namespace testing
diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc
index 69f25e6890e5..30a5cc3f83a7 100644
--- a/googletest/src/gtest.cc
+++ b/googletest/src/gtest.cc
@@ -31,11 +31,8 @@
// 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 <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
@@ -44,100 +41,126 @@
#include <wctype.h>
#include <algorithm>
+#include <chrono> // NOLINT
+#include <cmath>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <initializer_list>
#include <iomanip>
+#include <ios>
+#include <iostream>
+#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <ostream> // NOLINT
+#include <set>
#include <sstream>
+#include <unordered_set>
+#include <utility>
#include <vector>
-#if GTEST_OS_LINUX
+#include "gtest/gtest-assertion-result.h"
+#include "gtest/gtest-spi.h"
+#include "gtest/internal/custom/gtest.h"
+#include "gtest/internal/gtest-port.h"
-# define GTEST_HAS_GETTIMEOFDAY_ 1
+#ifdef 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
-#elif GTEST_OS_ZOS
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-# include <sys/time.h> // NOLINT
+#include <string>
+
+#elif defined(GTEST_OS_ZOS)
+#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.
+#elif defined(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.
+#elif defined(GTEST_OS_WINDOWS) // We are on Windows proper.
-# include <windows.h> // NOLINT
-# undef min
+#include <windows.h> // NOLINT
+#undef min
-# include <crtdbg.h> // NOLINT
-# include <debugapi.h> // NOLINT
-# include <io.h> // NOLINT
-# include <sys/timeb.h> // NOLINT
-# include <sys/types.h> // NOLINT
-# include <sys/stat.h> // NOLINT
+#ifdef _MSC_VER
+#include <crtdbg.h> // NOLINT
+#endif
-# if GTEST_OS_WINDOWS_MINGW
-// MinGW has gettimeofday() but not _ftime64().
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-# include <sys/time.h> // NOLINT
-# endif // GTEST_OS_WINDOWS_MINGW
+#include <io.h> // NOLINT
+#include <sys/stat.h> // NOLINT
+#include <sys/timeb.h> // NOLINT
+#include <sys/types.h> // NOLINT
-#else
+#ifdef GTEST_OS_WINDOWS_MINGW
+#include <sys/time.h> // NOLINT
+#endif // GTEST_OS_WINDOWS_MINGW
-// Assume other platforms have gettimeofday().
-# define GTEST_HAS_GETTIMEOFDAY_ 1
+#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
+#ifdef GTEST_OS_WINDOWS
+#define vsnprintf _vsnprintf
#endif // GTEST_OS_WINDOWS
-#if GTEST_OS_MAC
+#ifdef GTEST_OS_MAC
#ifndef GTEST_OS_IOS
#include <crt_externs.h>
#endif
#endif
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
+#include "absl/container/flat_hash_set.h"
#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"
+#include "absl/strings/string_view.h"
+#include "absl/strings/strip.h"
#endif // GTEST_HAS_ABSL
+// Checks builtin compiler feature |x| while avoiding an extra layer of #ifdefs
+// at the callsite.
+#if defined(__has_builtin)
+#define GTEST_HAS_BUILTIN(x) __has_builtin(x)
+#else
+#define GTEST_HAS_BUILTIN(x) 0
+#endif // defined(__has_builtin)
+
namespace testing {
using internal::CountIf;
@@ -181,7 +204,8 @@ const char kStackTraceMarker[] = "\nStack trace:\n";
// is specified on the command line.
bool g_help_flag = false;
-// Utilty function to Open File for Writing
+#if GTEST_HAS_FILE_SYSTEM
+// Utility function to Open File for Writing
static FILE* OpenFileForWriting(const std::string& output_file) {
FILE* fileout = nullptr;
FilePath output_file_path(output_file);
@@ -195,6 +219,7 @@ static FILE* OpenFileForWriting(const std::string& output_file) {
}
return fileout;
}
+#endif // GTEST_HAS_FILE_SYSTEM
} // namespace internal
@@ -209,24 +234,44 @@ static const char* GetDefaultFilter() {
return kUniversalFilter;
}
+// Bazel passes in the argument to '--test_runner_fail_fast' via the
+// TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
+static bool GetDefaultFailFast() {
+ const char* const testbridge_test_runner_fail_fast =
+ internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
+ if (testbridge_test_runner_fail_fast != nullptr) {
+ return strcmp(testbridge_test_runner_fail_fast, "1") == 0;
+ }
+ return false;
+}
+
+} // namespace testing
+
+GTEST_DEFINE_bool_(
+ 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 "
@@ -234,7 +279,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 "
@@ -243,13 +289,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
@@ -258,8 +305,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. "
@@ -269,74 +316,93 @@ GTEST_DEFINE_string_(
"executable's name and, if necessary, made unique by adding "
"digits.");
-GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
+GTEST_DEFINE_bool_(
+ brief, testing::internal::BoolFromGTestEnv("brief", false),
+ "True if only test failures should be displayed in text output.");
+
+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 {
+const uint32_t Random::kMaxRange;
+
// Generates a random number from [0, range), using a Linear
// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
// than kMaxRange.
-UInt32 Random::Generate(UInt32 range) {
+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>(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 << ").";
@@ -350,7 +416,7 @@ UInt32 Random::Generate(UInt32 range) {
// GTestIsInitialized() returns true if and only if the user has initialized
// Google Test. Useful for catching the user mistake of not initializing
// Google Test before calling RUN_ALL_TESTS().
-static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
+static bool GTestIsInitialized() { return !GetArgvs().empty(); }
// Iterates over a vector of TestSuites, keeping a running sum of the
// results of calling a given int-returning method on each.
@@ -381,26 +447,175 @@ 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 synthetic test case is
+// inserted to report ether an error or a log message.
+//
+// This configuration bit will likely be removed at some point.
+constexpr bool kErrorOnUninstantiatedParameterizedTest = true;
+constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;
+
+// A test that fails at a given file/line location with a given message.
+class FailureTest : public Test {
+ public:
+ explicit FailureTest(const CodeLocation& loc, std::string error_message,
+ bool as_error)
+ : loc_(loc),
+ error_message_(std::move(error_message)),
+ as_error_(as_error) {}
+
+ void TestBody() override {
+ if (as_error_) {
+ AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
+ loc_.line, "") = Message() << error_message_;
+ } else {
+ std::cout << error_message_ << std::endl;
+ }
+ }
+
+ private:
+ const CodeLocation loc_;
+ const std::string error_message_;
+ const bool as_error_;
+};
+
+} // namespace
+
+std::set<std::string>* GetIgnoredParameterizedTestSuites() {
+ return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
+}
+
+// Add a given test_suit to the list of them allow to go un-instantiated.
+MarkAsIgnored::MarkAsIgnored(const char* test_suite) {
+ GetIgnoredParameterizedTestSuites()->insert(test_suite);
+}
+
+// If this parameterized test suite has no instantiations (and that
+// has not been marked as okay), emit a test case reporting that.
+void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
+ bool has_test_p) {
+ const auto& ignored = *GetIgnoredParameterizedTestSuites();
+ if (ignored.find(name) != ignored.end()) return;
+
+ const char kMissingInstantiation[] = //
+ " is defined via TEST_P, but never instantiated. None of the test cases "
+ "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
+ "ones provided expand to nothing."
+ "\n\n"
+ "Ideally, TEST_P definitions should only ever be included as part of "
+ "binaries that intend to use them. (As opposed to, for example, being "
+ "placed in a library that may be linked in to get other utilities.)";
+
+ const char kMissingTestCase[] = //
+ " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
+ "defined via TEST_P . No test cases will run."
+ "\n\n"
+ "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
+ "code that always depend on code that provides TEST_P. Failing to do "
+ "so is often an indication of dead code, e.g. the last TEST_P was "
+ "removed but the rest got left behind.";
+
+ std::string message =
+ "Parameterized test suite " + name +
+ (has_test_p ? kMissingInstantiation : kMissingTestCase) +
+ "\n\n"
+ "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 + ");";
+
+ std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
+ RegisterTest( //
+ "GoogleTestVerification", full_name.c_str(),
+ nullptr, // No type parameter.
+ nullptr, // No value parameter.
+ location.file.c_str(), location.line, [message, location] {
+ return new FailureTest(location, message,
+ kErrorOnUninstantiatedParameterizedTest);
+ });
+}
+
+void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
+ CodeLocation code_location) {
+ GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
+ test_suite_name, code_location);
+}
+
+void RegisterTypeParameterizedTestSuiteInstantiation(const char* 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));
+}
+
+void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
+ const char* test_suite_name) {
+ auto it = suites_.find(std::string(test_suite_name));
+ if (it != suites_.end()) {
+ it->second.instantiated = true;
+ } else {
+ GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '"
+ << test_suite_name << "'";
+ }
+}
+
+void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
+ const auto& ignored = *GetIgnoredParameterizedTestSuites();
+ for (const auto& testcase : suites_) {
+ if (testcase.second.instantiated) continue;
+ if (ignored.find(testcase.first) != ignored.end()) continue;
+
+ std::string message =
+ "Type parameterized test suite " + testcase.first +
+ " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
+ "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
+ "\n\n"
+ "Ideally, TYPED_TEST_P definitions should only ever be included as "
+ "part of binaries that intend to use them. (As opposed to, for "
+ "example, being placed in a library that may be linked in to get other "
+ "utilities.)"
+ "\n\n"
+ "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(" +
+ testcase.first + ");";
+
+ std::string full_name =
+ "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">";
+ RegisterTest( //
+ "GoogleTestVerification", full_name.c_str(),
+ nullptr, // No type parameter.
+ nullptr, // No value parameter.
+ testcase.second.code_location.file.c_str(),
+ testcase.second.code_location.line, [message, testcase] {
+ return new FailureTest(testcase.second.code_location, message,
+ kErrorOnUninstantiatedTypeParameterizedTest);
+ });
+ }
}
// A copy of all command line arguments. Set by InitGoogleTest().
@@ -417,12 +632,13 @@ static ::std::vector<std::string> g_argvs;
#endif // defined(GTEST_CUSTOM_GET_ARGVS_)
}
+#if GTEST_HAS_FILE_SYSTEM
// Returns the current application's name, removing directory path if that
// is present.
FilePath GetCurrentExecutableName() {
FilePath result;
-#if GTEST_OS_WINDOWS || GTEST_OS_OS2
+#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2)
result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
#else
result.Set(FilePath(GetArgvs()[0]));
@@ -430,12 +646,14 @@ FilePath GetCurrentExecutableName() {
return result.RemoveDirectoryName();
}
+#endif // GTEST_HAS_FILE_SYSTEM
// Functions for processing the gtest_output flag.
// 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)
@@ -443,22 +661,23 @@ std::string UnitTestOptions::GetOutputFormat() {
static_cast<size_t>(colon - gtest_output_flag));
}
+#if GTEST_HAS_FILE_SYSTEM
// 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())
@@ -466,96 +685,196 @@ 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(),
GetOutputFormat().c_str()));
return result.string();
}
+#endif // GTEST_HAS_FILE_SYSTEM
-// Returns true if and only if the wildcard pattern matches the string.
-// The first ':' or '\0' character in pattern marks the end of it.
+// Returns true if and only if the wildcard pattern matches the string. Each
+// pattern consists of regular characters, single-character wildcards (?), and
+// multi-character wildcards (*).
//
-// This recursive algorithm isn't very efficient, but is clear and
-// works well enough for matching test names, which are short.
-bool UnitTestOptions::PatternMatchesString(const char *pattern,
- const char *str) {
- switch (*pattern) {
- case '\0':
- case ':': // Either ':' or '\0' marks the end of the pattern.
- return *str == '\0';
- case '?': // Matches any single character.
- return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
- case '*': // Matches any string (possibly empty) of characters.
- return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
- PatternMatchesString(pattern + 1, str);
- default: // Non-special character. Matches itself.
- return *pattern == *str &&
- PatternMatchesString(pattern + 1, str + 1);
- }
-}
-
-bool UnitTestOptions::MatchesFilter(
- const std::string& name, const char* filter) {
- const char *cur_pattern = filter;
- for (;;) {
- if (PatternMatchesString(cur_pattern, name.c_str())) {
- return true;
+// This function implements a linear-time string globbing algorithm based on
+// https://research.swtch.com/glob.
+static bool PatternMatchesString(const std::string& name_str,
+ const char* pattern, const char* pattern_end) {
+ const char* name = name_str.c_str();
+ const char* const name_begin = name;
+ const char* const name_end = name + name_str.size();
+
+ const char* pattern_next = pattern;
+ const char* name_next = name;
+
+ while (pattern < pattern_end || name < name_end) {
+ if (pattern < pattern_end) {
+ switch (*pattern) {
+ default: // Match an ordinary character.
+ if (name < name_end && *name == *pattern) {
+ ++pattern;
+ ++name;
+ continue;
+ }
+ break;
+ case '?': // Match any single character.
+ if (name < name_end) {
+ ++pattern;
+ ++name;
+ continue;
+ }
+ break;
+ case '*':
+ // Match zero or more characters. Start by skipping over the wildcard
+ // and matching zero characters from name. If that fails, restart and
+ // match one more character than the last attempt.
+ pattern_next = pattern;
+ name_next = name + 1;
+ ++pattern;
+ continue;
+ }
}
+ // Failed to match a character. Restart if possible.
+ if (name_begin < name_next && name_next <= name_end) {
+ pattern = pattern_next;
+ name = name_next;
+ continue;
+ }
+ return false;
+ }
+ return true;
+}
- // Finds the next pattern in the filter.
- cur_pattern = strchr(cur_pattern, ':');
+namespace {
- // Returns if no more pattern can be found.
- if (cur_pattern == nullptr) {
- return false;
+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_;
+};
+
+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);
}
+ }
+
+ // 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);
+ }
- // Skips the pattern separater (the ':' character).
- cur_pattern++;
+ // 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
-// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
-// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
-// This function is useful as an __except condition.
-int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
+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 << ".";
+ return message.GetString();
+}
+
+int UnitTestOptions::GTestProcessSEH(DWORD seh_code, const char* location) {
// Google Test should handle a SEH exception if:
// 1. the user wants it to, AND
- // 2. this is not a breakpoint exception, AND
+ // 2. this is not a breakpoint exception or stack overflow, AND
// 3. this is not a C++ exception (VC++ implements them via SEH,
// apparently).
//
@@ -563,16 +882,20 @@ int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
// (see http://support.microsoft.com/kb/185294 for more information).
const DWORD kCxxExceptionCode = 0xe06d7363;
- bool should_handle = true;
+ if (!GTEST_FLAG_GET(catch_exceptions) || seh_code == kCxxExceptionCode ||
+ seh_code == EXCEPTION_BREAKPOINT ||
+ seh_code == EXCEPTION_STACK_OVERFLOW) {
+ return EXCEPTION_CONTINUE_SEARCH; // Don't handle these exceptions
+ }
- if (!GTEST_FLAG(catch_exceptions))
- should_handle = false;
- else if (exception_code == EXCEPTION_BREAKPOINT)
- should_handle = false;
- else if (exception_code == kCxxExceptionCode)
- should_handle = false;
+ internal::ReportFailureInUnknownLocation(
+ TestPartResult::kFatalFailure,
+ FormatSehExceptionMessage(seh_code, location) +
+ "\n"
+ "Stack trace:\n" +
+ ::testing::internal::GetCurrentOsStackTraceExceptTop(1));
- return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
+ return EXCEPTION_EXECUTE_HANDLER;
}
#endif // GTEST_HAS_SEH
@@ -583,8 +906,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();
}
@@ -593,8 +915,7 @@ ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
// results.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
InterceptMode intercept_mode, TestPartResultArray* result)
- : intercept_mode_(intercept_mode),
- result_(result) {
+ : intercept_mode_(intercept_mode), result_(result) {
Init();
}
@@ -638,9 +959,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().
@@ -655,9 +974,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"
@@ -676,10 +995,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();
@@ -702,7 +1021,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) {
@@ -711,7 +1031,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) {
@@ -722,14 +1043,14 @@ void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
TestPartResultReporterInterface*
UnitTestImpl::GetGlobalTestPartResultReporter() {
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
- return global_test_part_result_repoter_;
+ return global_test_part_result_reporter_;
}
// Sets the global test part result reporter.
void UnitTestImpl::SetGlobalTestPartResultReporter(
TestPartResultReporterInterface* reporter) {
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
- global_test_part_result_repoter_ = reporter;
+ global_test_part_result_reporter_ = reporter;
}
// Returns the test part result reporter for the current thread.
@@ -818,58 +1139,50 @@ 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
}
-// Returns the current time in milliseconds.
-TimeInMillis GetTimeInMillis() {
-#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
- // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
- // http://analogous.blogspot.com/2005/04/epoch.html
- const TimeInMillis kJavaEpochToWinFileTimeDelta =
- static_cast<TimeInMillis>(116444736UL) * 100000UL;
- const DWORD kTenthMicrosInMilliSecond = 10000;
-
- SYSTEMTIME now_systime;
- FILETIME now_filetime;
- ULARGE_INTEGER now_int64;
- GetSystemTime(&now_systime);
- if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
- now_int64.LowPart = now_filetime.dwLowDateTime;
- now_int64.HighPart = now_filetime.dwHighDateTime;
- now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
- kJavaEpochToWinFileTimeDelta;
- return now_int64.QuadPart;
- }
- return 0;
-#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
- __timeb64 now;
-
- // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
- // (deprecated function) there.
- GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
- _ftime64(&now);
- GTEST_DISABLE_MSC_DEPRECATED_POP_()
-
- return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
-#elif GTEST_HAS_GETTIMEOFDAY_
- struct timeval now;
- gettimeofday(&now, nullptr);
- return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
+// A helper class for measuring elapsed times.
+class Timer {
+ public:
+ Timer() : start_(clock::now()) {}
+
+ // Return time elapsed in milliseconds since the timer was created.
+ TimeInMillis Elapsed() {
+ return std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() -
+ start_)
+ .count();
+ }
+
+ private:
+ // Fall back to the system_clock when building with newlib on a system
+ // without a monotonic clock.
+#if defined(_NEWLIB_VERSION) && !defined(CLOCK_MONOTONIC)
+ using clock = std::chrono::system_clock;
#else
-# error "Don't know how to get the current time on your system."
+ using clock = std::chrono::steady_clock;
#endif
+ clock::time_point start_;
+};
+
+// Returns a timestamp as milliseconds since the epoch. Note this time may jump
+// around subject to adjustments by the system, to measure elapsed time use
+// Timer instead.
+TimeInMillis GetTimeInMillis() {
+ return std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::system_clock::now() -
+ std::chrono::system_clock::from_time_t(0))
+ .count();
}
// Utilities
// class String.
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// Creates a UTF-16 wide string from the given ANSI string, allocating
// memory using new. The caller is responsible for deleting the return
// value using delete[]. Returns the wide string, or NULL if the
@@ -880,8 +1193,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;
}
@@ -890,7 +1202,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);
@@ -909,7 +1221,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;
@@ -923,11 +1235,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++;
@@ -969,17 +1280,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;
}
@@ -991,44 +1302,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 {
@@ -1320,8 +1593,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;
@@ -1338,10 +1610,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);
@@ -1353,45 +1623,61 @@ 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();
+ // Find the value which is closest to zero.
+ const double min_abs = std::min(fabs(val1), fabs(val2));
+ // Find the distance to the next double from that value.
+ const double epsilon =
+ nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
+ // Detect the case where abs_error is so small that EXPECT_NEAR is
+ // effectively the same as EXPECT_EQUAL, and give an informative error
+ // message so that the situation can be more easily understood without
+ // requiring exotic floating-point knowledge.
+ // Don't do an epsilon check if abs_error is zero because that implies
+ // that an equality check was actually intended.
+ if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
+ abs_error < epsilon) {
+ return AssertionFailure()
+ << "The difference between " << expr1 << " and " << expr2 << " is "
+ << diff << ", where\n"
+ << expr1 << " evaluates to " << val1 << ",\n"
+ << expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter "
+ << abs_error_expr << " evaluates to " << abs_error
+ << " which is smaller than the minimum distance between doubles for "
+ "numbers of this magnitude which is "
+ << epsilon
+ << ", thus making this EXPECT_NEAR check equivalent to "
+ "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();
@@ -1416,138 +1702,76 @@ 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);
}
namespace internal {
-// The helper function for {ASSERT|EXPECT}_EQ with int or enum
-// arguments.
-AssertionResult CmpHelperEQ(const char* lhs_expression,
- const char* rhs_expression,
- BiggestInt lhs,
- BiggestInt rhs) {
- if (lhs == rhs) {
- return AssertionSuccess();
- }
-
- return EqFailure(lhs_expression,
- rhs_expression,
- FormatForComparisonFailureMessage(lhs, rhs),
- FormatForComparisonFailureMessage(rhs, lhs),
- false);
-}
-
-// A macro for implementing the helper functions needed to implement
-// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
-// just to avoid copy-and-paste of similar code.
-#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
-AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
- BiggestInt val1, BiggestInt val2) {\
- if (val1 op val2) {\
- return AssertionSuccess();\
- } else {\
- return AssertionFailure() \
- << "Expected: (" << expr1 << ") " #op " (" << expr2\
- << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
- << " vs " << FormatForComparisonFailureMessage(val2, val1);\
- }\
-}
-
-// Implements the helper function for {ASSERT|EXPECT}_NE with int or
-// enum arguments.
-GTEST_IMPL_CMP_HELPER_(NE, !=)
-// Implements the helper function for {ASSERT|EXPECT}_LE with int or
-// enum arguments.
-GTEST_IMPL_CMP_HELPER_(LE, <=)
-// Implements the helper function for {ASSERT|EXPECT}_LT with int or
-// enum arguments.
-GTEST_IMPL_CMP_HELPER_(LT, < )
-// Implements the helper function for {ASSERT|EXPECT}_GE with int or
-// enum arguments.
-GTEST_IMPL_CMP_HELPER_(GE, >=)
-// Implements the helper function for {ASSERT|EXPECT}_GT with int or
-// enum arguments.
-GTEST_IMPL_CMP_HELPER_(GT, > )
-
-#undef GTEST_IMPL_CMP_HELPER_
-
// 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 << "\"";
}
}
@@ -1575,8 +1799,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;
}
@@ -1585,21 +1808,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
@@ -1608,100 +1832,99 @@ 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
namespace internal {
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
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 defined(GTEST_OS_WINDOWS_MOBILE) || defined(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
@@ -1735,33 +1958,35 @@ 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.
-const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(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.
-const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
+constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;
// The maximum code-point a three-byte UTF-8 sequence can represent.
-const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(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.
-const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(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
// shifted to the right by n bits.
-inline UInt32 ChopLowBits(UInt32* bits, int n) {
- const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
+inline uint32_t ChopLowBits(uint32_t* bits, int n) {
+ const uint32_t low_bits = *bits & ((static_cast<uint32_t>(1) << n) - 1);
*bits >>= n;
return low_bits;
}
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
-// code_point parameter is of type UInt32 because wchar_t may not be
+// code_point parameter is of type uint32_t because wchar_t may not be
// wide enough to contain a code point.
// If the code_point is not a valid Unicode code point
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
// to "(Invalid Unicode 0xXXXXXXXX)".
-std::string CodePointToUtf8(UInt32 code_point) {
+std::string CodePointToUtf8(uint32_t code_point) {
if (code_point > kMaxCodePoint4) {
return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")";
}
@@ -1769,7 +1994,7 @@ std::string CodePointToUtf8(UInt32 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
@@ -1797,16 +2022,16 @@ std::string CodePointToUtf8(UInt32 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.
-inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
- wchar_t second) {
- const auto first_u = static_cast<UInt32>(first);
- const auto second_u = static_cast<UInt32>(second);
- const UInt32 mask = (1 << 10) - 1;
+inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,
+ wchar_t second) {
+ const auto first_u = static_cast<uint32_t>(first);
+ const auto second_u = static_cast<uint32_t>(second);
+ const uint32_t mask = (1 << 10) - 1;
return (sizeof(wchar_t) == 2)
? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
:
@@ -1829,21 +2054,20 @@ inline UInt32 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) {
- UInt32 unicode_code_point;
+ uint32_t unicode_code_point;
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>(str[i]);
+ unicode_code_point = static_cast<uint32_t>(str[i]);
}
stream << CodePointToUtf8(unicode_code_point);
@@ -1853,7 +2077,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);
@@ -1865,7 +2089,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;
@@ -1875,33 +2099,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
@@ -1910,7 +2128,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;
@@ -1934,9 +2152,9 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
if (rhs == nullptr) return false;
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
return _wcsicmp(lhs, rhs) == 0;
-#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
+#elif defined(GTEST_OS_LINUX) && !defined(GTEST_OS_LINUX_ANDROID)
return wcscasecmp(lhs, rhs) == 0;
#else
// Android, Mac OS X and Cygwin don't define wcscasecmp.
@@ -1952,8 +2170,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) &&
@@ -1963,13 +2181,18 @@ bool String::EndsWithCaseInsensitive(
// Formats an int value as "%02d".
std::string String::FormatIntWidth2(int value) {
+ return FormatIntWidthN(value, 2);
+}
+
+// Formats an int value to given width with leading zeros.
+std::string String::FormatIntWidthN(int value, int width) {
std::stringstream ss;
- ss << std::setfill('0') << std::setw(2) << value;
+ ss << std::setfill('0') << std::setw(width) << value;
return ss.str();
}
// Formats an int value as "%X".
-std::string String::FormatHexUInt32(UInt32 value) {
+std::string String::FormatHexUInt32(uint32_t value) {
std::stringstream ss;
ss << std::hex << std::uppercase << value;
return ss.str();
@@ -1977,7 +2200,7 @@ std::string String::FormatHexUInt32(UInt32 value) {
// Formats an int value as "%X".
std::string String::FormatHexInt(int value) {
- return FormatHexUInt32(static_cast<UInt32>(value));
+ return FormatHexUInt32(static_cast<uint32_t>(value));
}
// Formats a byte as "%02X".
@@ -2016,7 +2239,9 @@ std::string AppendUserMessage(const std::string& gtest_msg,
if (user_msg_string.empty()) {
return gtest_msg;
}
-
+ if (gtest_msg.empty()) {
+ return user_msg_string;
+ }
return gtest_msg + "\n" + user_msg_string;
}
@@ -2029,15 +2254,13 @@ TestResult::TestResult()
: death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
// D'tor.
-TestResult::~TestResult() {
-}
+TestResult::~TestResult() = default;
// 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));
}
@@ -2045,15 +2268,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) {
@@ -2068,7 +2288,7 @@ void TestResult::RecordProperty(const std::string& xml_element,
if (!ValidateTestProperty(xml_element, test_property)) {
return;
}
- internal::MutexLock lock(&test_properites_mutex_);
+ internal::MutexLock lock(&test_properties_mutex_);
const std::vector<TestProperty>::iterator property_with_matching_key =
std::find_if(test_properties_.begin(), test_properties_.end(),
internal::TestPropertyKeyIs(test_property.key()));
@@ -2082,25 +2302,19 @@ 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.
static const char* const kReservedTestSuiteAttributes[] = {
- "disabled", "errors", "failures", "name", "tests", "time", "timestamp"};
+ "disabled", "errors", "failures", "name",
+ "tests", "time", "timestamp", "skipped"};
// 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")
@@ -2128,7 +2342,9 @@ static std::vector<std::string> GetReservedAttributesForElement(
return std::vector<std::string>();
}
+#if GTEST_HAS_FILE_SYSTEM
// TODO(jdesprez): Merge the two getReserved attributes once skip is improved
+// This function is only used when file systems are enabled.
static std::vector<std::string> GetReservedOutputAttributesForElement(
const std::string& xml_element) {
if (xml_element == "testsuites") {
@@ -2143,6 +2359,7 @@ static std::vector<std::string> GetReservedOutputAttributesForElement(
// This code is unreachable but some compilers may not realizes that.
return std::vector<std::string>();
}
+#endif
static std::string FormatWordList(const std::vector<std::string>& words) {
Message word_list;
@@ -2162,7 +2379,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_ << ")";
@@ -2200,8 +2417,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;
}
@@ -2242,40 +2458,28 @@ 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() = default;
// 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) {
UnitTest::GetInstance()->RecordProperty(key, value);
}
-// Allows user supplied key value pairs to be recorded for later output.
-void Test::RecordProperty(const std::string& key, int value) {
- Message value_message;
- value_message << value;
- RecordProperty(key, value_message.GetString().c_str());
-}
-
namespace internal {
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
@@ -2358,23 +2562,6 @@ bool Test::HasSameFixtureClass() {
return true;
}
-#if GTEST_HAS_SEH
-
-// Adds an "exception thrown" fatal failure to the current test. This
-// function returns its result via an output parameter pointer because VC++
-// prohibits creation of objects with destructors on stack in functions
-// using __try (see error C2712).
-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 << ".";
-
- return new std::string(message.GetString());
-}
-
-#endif // GTEST_HAS_SEH
-
namespace internal {
#if GTEST_HAS_EXCEPTIONS
@@ -2411,21 +2598,13 @@ 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)();
- } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
- GetExceptionCode())) {
- // 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);
- internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
- *exception_message);
- delete exception_message;
+ } __except (internal::UnitTestOptions::GTestProcessSEH( // NOLINT
+ GetExceptionCode(), location)) {
return static_cast<Result>(0);
}
#else
@@ -2438,8 +2617,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
@@ -2449,7 +2628,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.
@@ -2505,16 +2684,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.
@@ -2524,8 +2703,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.
@@ -2544,7 +2724,8 @@ TestInfo::TestInfo(const std::string& a_test_suite_name,
internal::TypeId fixture_class_id,
internal::TestFactoryBase* factory)
: test_suite_name_(a_test_suite_name),
- name_(a_name),
+ // begin()/end() is MSVC 17.3.3 ASAN crash workaround (GitHub issue #3997)
+ name_(a_name.begin(), a_name.end()),
type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
location_(a_code_location),
@@ -2552,6 +2733,7 @@ TestInfo::TestInfo(const std::string& a_test_suite_name,
should_run_(false),
is_disabled_(false),
matches_filter_(false),
+ is_in_another_shard_(false),
factory_(factory),
result_() {}
@@ -2565,7 +2747,7 @@ namespace internal {
//
// Arguments:
//
-// test_suite_name: name of the test suite
+// test_suite_name: name of the test suite
// name: name of the test
// type_param: the name of the test's type parameter, or NULL if
// this is not a typed or a type-parameterized test.
@@ -2607,38 +2789,6 @@ void ReportInvalidTestSuiteType(const char* test_suite_name,
code_location.line)
<< " " << errors.GetString();
}
-} // namespace internal
-
-namespace {
-
-// A predicate that checks the test name of a TestInfo against a known
-// value.
-//
-// This is used for implementation of the TestSuite class only. We put
-// it in the anonymous namespace to prevent polluting the outer
-// namespace.
-//
-// TestNameIs is copyable.
-class TestNameIs {
- public:
- // Constructor.
- //
- // TestNameIs has NO default constructor.
- 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 {
- return test_info && test_info->name() == name_;
- }
-
- private:
- std::string name_;
-};
-
-} // namespace
-
-namespace internal {
// This method expands all parameterized tests registered with macros TEST_P
// and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
@@ -2646,6 +2796,7 @@ namespace internal {
void UnitTestImpl::RegisterParameterizedTests() {
if (!parameterized_tests_registered_) {
parameterized_test_registry_.RegisterTests();
+ type_parameterized_test_registry_.CheckForInstantiations();
parameterized_tests_registered_ = true;
}
}
@@ -2655,19 +2806,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);
-
- const TimeInMillis start = internal::GetTimeInMillis();
-
+ result_.set_start_timestamp(internal::GetTimeInMillis());
+ internal::Timer timer;
impl->os_stack_trace_getter()->UponLeavingGTest();
// Creates the test object.
@@ -2691,8 +2843,7 @@ void TestInfo::Run() {
test, &Test::DeleteSelf_, "the test fixture's destructor");
}
- result_.set_start_timestamp(start);
- result_.set_elapsed_time(internal::GetTimeInMillis() - start);
+ result_.set_elapsed_time(timer.Elapsed());
// Notifies the unit test event listener that a test has just finished.
repeater->OnTestEnd(*this);
@@ -2702,6 +2853,28 @@ void TestInfo::Run() {
impl->set_current_test_info(nullptr);
}
+// Skip and records a skipped test result for this object.
+void TestInfo::Skip() {
+ if (!should_run_) return;
+
+ 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);
+
+ const TestPartResult test_part_result =
+ TestPartResult(TestPartResult::kSkip, this->file(), this->line(), "");
+ impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
+ test_part_result);
+
+ // Notifies the unit test event listener that a test has just finished.
+ repeater->OnTestEnd(*this);
+ impl->set_current_test_info(nullptr);
+}
+
// class TestSuite
// Gets the number of successful tests in this test suite.
@@ -2748,7 +2921,7 @@ int TestSuite::total_test_count() const {
//
// Arguments:
//
-// name: name of the test suite
+// a_name: name of the test suite
// a_type_param: the name of the test suite's type parameter, or NULL if
// this is not a typed or a type-parameterized test suite.
// set_up_tc: pointer to the function that sets up the test suite
@@ -2800,22 +2973,56 @@ void TestSuite::Run() {
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
+ // Ensure our tests are in a deterministic order.
+ //
+ // We do this by sorting lexicographically on (file, line number), providing
+ // an order matching what the user can see in the source code.
+ //
+ // In the common case the line number comparison shouldn't be necessary,
+ // because the registrations made by the TEST macro are executed in order
+ // within a translation unit. But this is not true of the manual registration
+ // API, and in more exotic scenarios a single file may be part of multiple
+ // translation units.
+ std::stable_sort(test_info_list_.begin(), test_info_list_.end(),
+ [](const TestInfo* const a, const TestInfo* const b) {
+ if (const int result = std::strcmp(a->file(), b->file())) {
+ return result < 0;
+ }
+
+ return a->line() < b->line();
+ });
+
// Call both legacy and the new API
repeater->OnTestSuiteStart(*this);
// Legacy API is deprecated but still available
-#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
repeater->OnTestCaseStart(*this);
-#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
+ const bool skip_all =
+ ad_hoc_test_result().Failed() || ad_hoc_test_result().Skipped();
+
start_timestamp_ = internal::GetTimeInMillis();
+ internal::Timer timer;
for (int i = 0; i < total_test_count(); i++) {
- GetMutableTestInfo(i)->Run();
+ 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();
+ }
+ break;
+ }
}
- elapsed_time_ = internal::GetTimeInMillis() - start_timestamp_;
+ elapsed_time_ = timer.Elapsed();
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
@@ -2824,9 +3031,39 @@ void TestSuite::Run() {
// Call both legacy and the new API
repeater->OnTestSuiteEnd(*this);
// Legacy API is deprecated but still available
-#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
repeater->OnTestCaseEnd(*this);
-#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+
+ impl->set_current_test_suite(nullptr);
+}
+
+// Skips all tests under this TestSuite.
+void TestSuite::Skip() {
+ if (!should_run_) return;
+
+ internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
+ impl->set_current_test_suite(this);
+
+ TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
+
+ // Call both legacy and the new API
+ repeater->OnTestSuiteStart(*this);
+// Legacy API is deprecated but still available
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+ repeater->OnTestCaseStart(*this);
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+
+ for (int i = 0; i < total_test_count(); i++) {
+ GetMutableTestInfo(i)->Skip();
+ }
+
+ // Call both legacy and the new API
+ repeater->OnTestSuiteEnd(*this);
+ // Legacy API is deprecated but still available
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+ repeater->OnTestCaseEnd(*this);
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
impl->set_current_test_suite(nullptr);
}
@@ -2854,11 +3091,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.
@@ -2875,10 +3111,10 @@ 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";
+ return "Skipped\n";
case TestPartResult::kSuccess:
return "Success";
@@ -2895,28 +3131,32 @@ static const char * TestPartResultTypeToString(TestPartResult::Type type) {
}
namespace internal {
+namespace {
+enum class GTestColor { kDefault, kRed, kGreen, kYellow };
+} // namespace
// 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
// following statements add the test part result message to the Output
// window such that the user can double-click on it to jump to the
// corresponding source code location; otherwise they do nothing.
-#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE)
// We don't call OutputDebugString*() on Windows Mobile, as printing
// to stdout is done by OutputDebugString() there already - we don't
// want the same message printed twice.
@@ -2926,16 +3166,21 @@ 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 defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \
+ !defined(GTEST_OS_WINDOWS_PHONE) && !defined(GTEST_OS_WINDOWS_RT) && \
+ !defined(GTEST_OS_WINDOWS_MINGW)
// Returns the character attribute for the given color.
static WORD GetColorAttribute(GTestColor color) {
switch (color) {
- case COLOR_RED: return FOREGROUND_RED;
- case COLOR_GREEN: return FOREGROUND_GREEN;
- case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
- default: return 0;
+ case GTestColor::kRed:
+ return FOREGROUND_RED;
+ case GTestColor::kGreen:
+ return FOREGROUND_GREEN;
+ case GTestColor::kYellow:
+ return FOREGROUND_RED | FOREGROUND_GREEN;
+ default:
+ return 0;
}
}
@@ -2972,13 +3217,16 @@ static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
#else
-// Returns the ANSI color code for the given color. COLOR_DEFAULT is
+// Returns the ANSI color code for the given color. GTestColor::kDefault is
// an invalid input.
static const char* GetAnsiColorCode(GTestColor color) {
switch (color) {
- case COLOR_RED: return "1";
- case COLOR_GREEN: return "2";
- case COLOR_YELLOW: return "3";
+ case GTestColor::kRed:
+ return "1";
+ case GTestColor::kGreen:
+ return "2";
+ case GTestColor::kYellow:
+ return "3";
default:
return nullptr;
}
@@ -2988,10 +3236,11 @@ 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
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW)
// On Windows the TERM variable is usually not set, but the
// console there does support colors.
return stdout_is_tty;
@@ -2999,25 +3248,23 @@ bool ShouldUseColor(bool stdout_is_tty) {
// On non-Windows platforms, we rely on the TERM variable.
const char* const term = posix::GetEnv("TERM");
const bool term_supports_color =
- String::CStringEquals(term, "xterm") ||
- String::CStringEquals(term, "xterm-color") ||
- String::CStringEquals(term, "xterm-256color") ||
- String::CStringEquals(term, "screen") ||
- String::CStringEquals(term, "screen-256color") ||
- String::CStringEquals(term, "tmux") ||
- String::CStringEquals(term, "tmux-256color") ||
- String::CStringEquals(term, "rxvt-unicode") ||
- String::CStringEquals(term, "rxvt-unicode-256color") ||
- String::CStringEquals(term, "linux") ||
- String::CStringEquals(term, "cygwin");
+ term != nullptr && (String::CStringEquals(term, "xterm") ||
+ String::CStringEquals(term, "xterm-color") ||
+ String::CStringEquals(term, "xterm-kitty") ||
+ String::CStringEquals(term, "screen") ||
+ String::CStringEquals(term, "tmux") ||
+ String::CStringEquals(term, "rxvt-unicode") ||
+ String::CStringEquals(term, "linux") ||
+ String::CStringEquals(term, "cygwin") ||
+ String::EndsWithCaseInsensitive(term, "-256color"));
return stdout_is_tty && term_supports_color;
#endif // GTEST_OS_WINDOWS
}
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.
@@ -3027,18 +3274,20 @@ bool ShouldUseColor(bool stdout_is_tty) {
// cannot simply emit special characters and have the terminal change colors.
// This routine must actually emit the characters rather than return a string
// that would be colored when printed, as can be done on Linux.
-void ColoredPrintf(GTestColor color, const char* fmt, ...) {
+
+GTEST_ATTRIBUTE_PRINTF_(2, 3)
+static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
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 =
+#if GTEST_HAS_FILE_SYSTEM
ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
- const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
-#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
+#else
+ false;
+#endif // GTEST_HAS_FILE_SYSTEM
+
+ const bool use_color = in_color_mode && (color != GTestColor::kDefault);
if (!use_color) {
vprintf(fmt, args);
@@ -3046,8 +3295,9 @@ 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 defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \
+ !defined(GTEST_OS_WINDOWS_PHONE) && !defined(GTEST_OS_WINDOWS_RT) && \
+ !defined(GTEST_OS_WINDOWS_MINGW)
const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
// Gets the current text color.
@@ -3101,7 +3351,7 @@ static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
// Class PrettyUnitTestResultPrinter is copyable.
class PrettyUnitTestResultPrinter : public TestEventListener {
public:
- PrettyUnitTestResultPrinter() {}
+ PrettyUnitTestResultPrinter() = default;
static void PrintTestName(const char* test_suite, const char* test) {
printf("%s.%s", test_suite, test);
}
@@ -3118,6 +3368,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;
@@ -3134,39 +3385,40 @@ class PrettyUnitTestResultPrinter : public TestEventListener {
private:
static void PrintFailedTests(const UnitTest& unit_test);
+ static void PrintFailedTestSuites(const UnitTest& unit_test);
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.
if (!String::CStringEquals(filter, kUniversalFilter)) {
- ColoredPrintf(COLOR_YELLOW,
- "Note: %s filter = %s\n", GTEST_NAME_, filter);
+ ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_,
+ filter);
}
if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
- const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
- ColoredPrintf(COLOR_YELLOW,
- "Note: This is test shard %d of %s.\n",
+ const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
+ ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n",
static_cast<int>(shard_index) + 1,
internal::posix::GetEnv(kTestTotalShards));
}
- if (GTEST_FLAG(shuffle)) {
- ColoredPrintf(COLOR_YELLOW,
+ if (GTEST_FLAG_GET(shuffle)) {
+ ColoredPrintf(GTestColor::kYellow,
"Note: Randomizing tests' orders with a seed of %d .\n",
unit_test.random_seed());
}
- ColoredPrintf(COLOR_GREEN, "[==========] ");
+ ColoredPrintf(GTestColor::kGreen, "[==========] ");
printf("Running %s from %s.\n",
FormatTestCount(unit_test.test_to_run_count()).c_str(),
FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
@@ -3175,7 +3427,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart(
void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
const UnitTest& /*unit_test*/) {
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("Global test environment set-up.\n");
fflush(stdout);
}
@@ -3184,7 +3436,7 @@ void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
const std::string counts =
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s", counts.c_str(), test_case.name());
if (test_case.type_param() == nullptr) {
printf("\n");
@@ -3198,7 +3450,7 @@ void PrettyUnitTestResultPrinter::OnTestSuiteStart(
const TestSuite& test_suite) {
const std::string counts =
FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s", counts.c_str(), test_suite.name());
if (test_suite.type_param() == nullptr) {
printf("\n");
@@ -3210,7 +3462,14 @@ void PrettyUnitTestResultPrinter::OnTestSuiteStart(
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
- ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ RUN ] ");
+ PrintTestName(test_info.test_suite_name(), test_info.name());
+ printf("\n");
+ 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);
@@ -3220,9 +3479,7 @@ void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
void PrettyUnitTestResultPrinter::OnTestPartResult(
const TestPartResult& result) {
switch (result.type()) {
- // If the test part succeeded, or was skipped,
- // we don't need to do anything.
- case TestPartResult::kSkip:
+ // If the test part succeeded, we don't need to do anything.
case TestPartResult::kSuccess:
return;
default:
@@ -3235,19 +3492,19 @@ void PrettyUnitTestResultPrinter::OnTestPartResult(
void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
if (test_info.result()->Passed()) {
- ColoredPrintf(COLOR_GREEN, "[ OK ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ OK ] ");
} else if (test_info.result()->Skipped()) {
- ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
} else {
- ColoredPrintf(COLOR_RED, "[ FAILED ] ");
+ 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");
}
@@ -3256,22 +3513,22 @@ 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");
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
internal::StreamableToString(test_case.elapsed_time()).c_str());
fflush(stdout);
}
#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");
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
internal::StreamableToString(test_suite.elapsed_time()).c_str());
fflush(stdout);
@@ -3280,7 +3537,7 @@ void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
const UnitTest& /*unit_test*/) {
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("Global test environment tear-down\n");
fflush(stdout);
}
@@ -3288,9 +3545,8 @@ void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
// Internal helper for printing the list of failed tests.
void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
const int failed_test_count = unit_test.failed_test_count();
- if (failed_test_count == 0) {
- return;
- }
+ ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
+ printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
const TestSuite& test_suite = *unit_test.GetTestSuite(i);
@@ -3302,12 +3558,36 @@ void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
if (!test_info.should_run() || !test_info.result()->Failed()) {
continue;
}
- ColoredPrintf(COLOR_RED, "[ FAILED ] ");
+ ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
printf("%s.%s", test_suite.name(), test_info.name());
PrintFullTestCommentIfPresent(test_info);
printf("\n");
}
}
+ printf("\n%2d FAILED %s\n", failed_test_count,
+ failed_test_count == 1 ? "TEST" : "TESTS");
+}
+
+// Internal helper for printing the list of test suite failures not covered by
+// PrintFailedTests.
+void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
+ const UnitTest& unit_test) {
+ int suite_failure_count = 0;
+ for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
+ const TestSuite& test_suite = *unit_test.GetTestSuite(i);
+ if (!test_suite.should_run()) {
+ continue;
+ }
+ if (test_suite.ad_hoc_test_result().Failed()) {
+ ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
+ printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
+ ++suite_failure_count;
+ }
+ }
+ if (suite_failure_count > 0) {
+ printf("\n%2d FAILED TEST %s\n", suite_failure_count,
+ suite_failure_count == 1 ? "SUITE" : "SUITES");
+ }
}
// Internal helper for printing the list of skipped tests.
@@ -3327,7 +3607,7 @@ void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
if (!test_info.should_run() || !test_info.result()->Skipped()) {
continue;
}
- ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
printf("%s.%s", test_suite.name(), test_info.name());
printf("\n");
}
@@ -3336,44 +3616,37 @@ void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
int /*iteration*/) {
- ColoredPrintf(COLOR_GREEN, "[==========] ");
+ ColoredPrintf(GTestColor::kGreen, "[==========] ");
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());
}
printf("\n");
- ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
const int skipped_test_count = unit_test.skipped_test_count();
if (skipped_test_count > 0) {
- ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
PrintSkippedTests(unit_test);
}
- int num_failures = unit_test.failed_test_count();
if (!unit_test.Passed()) {
- const int failed_test_count = unit_test.failed_test_count();
- ColoredPrintf(COLOR_RED, "[ FAILED ] ");
- printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
PrintFailedTests(unit_test);
- printf("\n%2d FAILED %s\n", num_failures,
- num_failures == 1 ? "TEST" : "TESTS");
+ PrintFailedTestSuites(unit_test);
}
int num_disabled = unit_test.reportable_disabled_test_count();
- if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
- if (!num_failures) {
+ 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.
}
- ColoredPrintf(COLOR_YELLOW,
- " YOU HAVE %d DISABLED %s\n\n",
- num_disabled,
- num_disabled == 1 ? "TEST" : "TESTS");
+ ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
+ num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
}
// Ensure that Google Test output is printed before, e.g., heapchecker output.
fflush(stdout);
@@ -3381,6 +3654,111 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
// End PrettyUnitTestResultPrinter
+// This class implements the TestEventListener interface.
+//
+// Class BriefUnitTestResultPrinter is copyable.
+class BriefUnitTestResultPrinter : public TestEventListener {
+ public:
+ BriefUnitTestResultPrinter() = default;
+ static void PrintTestName(const char* test_suite, const char* test) {
+ printf("%s.%s", test_suite, test);
+ }
+
+ // The following methods override what's in the TestEventListener class.
+ void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
+ void OnTestIterationStart(const UnitTest& /*unit_test*/,
+ int /*iteration*/) override {}
+ void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
+ void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+ void OnTestCaseStart(const TestCase& /*test_case*/) override {}
+#else
+ void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
+#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;
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+ void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
+#else
+ void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+
+ void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
+ void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
+ void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
+ void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
+};
+
+// Called after an assertion failure.
+void BriefUnitTestResultPrinter::OnTestPartResult(
+ const TestPartResult& result) {
+ switch (result.type()) {
+ // If the test part succeeded, we don't need to do anything.
+ case TestPartResult::kSuccess:
+ return;
+ default:
+ // Print failure message from the assertion
+ // (e.g. expected this and got that).
+ PrintTestPartResult(result);
+ fflush(stdout);
+ }
+}
+
+void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
+ if (test_info.result()->Failed()) {
+ ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
+ PrintTestName(test_info.test_suite_name(), test_info.name());
+ PrintFullTestCommentIfPresent(test_info);
+
+ if (GTEST_FLAG_GET(print_time)) {
+ printf(" (%s ms)\n",
+ internal::StreamableToString(test_info.result()->elapsed_time())
+ .c_str());
+ } else {
+ printf("\n");
+ }
+ fflush(stdout);
+ }
+}
+
+void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
+ int /*iteration*/) {
+ ColoredPrintf(GTestColor::kGreen, "[==========] ");
+ 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_GET(print_time)) {
+ printf(" (%s ms total)",
+ internal::StreamableToString(unit_test.elapsed_time()).c_str());
+ }
+ printf("\n");
+ ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
+ printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
+
+ const int skipped_test_count = unit_test.skipped_test_count();
+ if (skipped_test_count > 0) {
+ ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
+ printf("%s.\n", FormatTestCount(skipped_test_count).c_str());
+ }
+
+ int num_disabled = unit_test.reportable_disabled_test_count();
+ 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.
+ }
+ ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
+ num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
+ }
+ // Ensure that Google Test output is printed before, e.g., heapchecker output.
+ fflush(stdout);
+}
+
+// End BriefUnitTestResultPrinter
+
// class TestEventRepeater
//
// This class forwards events to other event listeners.
@@ -3388,7 +3766,7 @@ class TestEventRepeater : public TestEventListener {
public:
TestEventRepeater() : forwarding_enabled_(true) {}
~TestEventRepeater() override;
- void Append(TestEventListener *listener);
+ void Append(TestEventListener* listener);
TestEventListener* Release(TestEventListener* listener);
// Controls whether events will be forwarded to listeners_. Set to false
@@ -3396,27 +3774,28 @@ class TestEventRepeater : public TestEventListener {
bool forwarding_enabled() const { return forwarding_enabled_; }
void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
- void OnTestProgramStart(const UnitTest& unit_test) override;
+ void OnTestProgramStart(const UnitTest& parameter) override;
void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
- void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
- void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
+ void OnEnvironmentsSetUpStart(const UnitTest& parameter) override;
+ void OnEnvironmentsSetUpEnd(const UnitTest& parameter) override;
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void OnTestCaseStart(const TestSuite& parameter) override;
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void OnTestSuiteStart(const TestSuite& parameter) override;
- void OnTestStart(const TestInfo& test_info) override;
- void OnTestPartResult(const TestPartResult& result) override;
- void OnTestEnd(const TestInfo& test_info) override;
+ void OnTestStart(const TestInfo& parameter) override;
+ void OnTestDisabled(const TestInfo& parameter) override;
+ void OnTestPartResult(const TestPartResult& parameter) override;
+ void OnTestEnd(const TestInfo& parameter) override;
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void OnTestCaseEnd(const TestCase& parameter) override;
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void OnTestSuiteEnd(const TestSuite& parameter) override;
- void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
- void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
+ void OnEnvironmentsTearDownStart(const UnitTest& parameter) override;
+ void OnEnvironmentsTearDownEnd(const UnitTest& parameter) override;
void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
- void OnTestProgramEnd(const UnitTest& unit_test) override;
+ void OnTestProgramEnd(const UnitTest& parameter) override;
private:
// Controls whether events will be forwarded to listeners_. Set to false
@@ -3425,18 +3804,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(TestEventListener* listener) {
listeners_.push_back(listener);
}
-TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
+TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
for (size_t i = 0; i < listeners_.size(); ++i) {
if (listeners_[i] == listener) {
listeners_.erase(listeners_.begin() + static_cast<int>(i));
@@ -3449,14 +3829,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) \
@@ -3476,6 +3856,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)
@@ -3511,6 +3892,7 @@ void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
// End TestEventRepeater
+#if GTEST_HAS_FILE_SYSTEM
// This class generates an XML output file.
class XmlUnitTestResultPrinter : public EmptyTestEventListener {
public:
@@ -3526,12 +3908,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;
}
@@ -3564,6 +3947,16 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener {
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
+ // Streams a test suite XML stanza containing the given test result.
+ //
+ // Requires: result.Failed()
+ static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
+ const TestResult& result);
+
+ // Streams an XML representation of a TestResult object.
+ static void OutputXmlTestResult(::std::ostream* stream,
+ const TestResult& result);
+
// Streams an XML representation of a TestInfo object.
static void OutputXmlTestInfo(::std::ostream* stream,
const char* test_suite_name,
@@ -3591,7 +3984,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.
@@ -3631,8 +4025,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) {
@@ -3660,8 +4054,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
@@ -3682,7 +4077,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;
@@ -3690,7 +4085,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:
//
@@ -3708,6 +4102,13 @@ std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
// Formats the given time in milliseconds as seconds.
std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
::std::stringstream ss;
+ // For the exact N seconds, makes sure output has a trailing decimal point.
+ // Sets precision so that we won't have many trailing zeros (e.g., 300 ms
+ // will be just 0.3, 410 ms 0.41, and so on)
+ ss << std::fixed
+ << std::setprecision(
+ ms % 1000 == 0 ? 0 : (ms % 100 == 0 ? 1 : (ms % 10 == 0 ? 2 : 3)))
+ << std::showpoint;
ss << (static_cast<double>(ms) * 1e-3);
return ss.str();
}
@@ -3722,6 +4123,10 @@ static bool PortableLocaltime(time_t seconds, struct tm* out) {
if (tm_ptr == nullptr) return false;
*out = *tm_ptr;
return true;
+#elif defined(__STDC_LIB_EXT1__)
+ // Uses localtime_s when available as localtime_r is only available from
+ // C23 standard.
+ return localtime_s(&seconds, out) != nullptr;
#else
return localtime_r(&seconds, out) != nullptr;
#endif
@@ -3733,13 +4138,14 @@ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
struct tm time_struct;
if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
return "";
- // YYYY-MM-DDThh:mm:ss
+ // 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::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.
@@ -3750,8 +4156,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 {
@@ -3763,21 +4169,56 @@ 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
<< ">.";
*stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
}
+// Streams a test suite XML stanza containing the given test result.
+void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
+ ::std::ostream* stream, const TestResult& result) {
+ // Output the boilerplate for a minimal test suite with one test.
+ *stream << " <testsuite";
+ OutputXmlAttribute(stream, "testsuite", "name", "NonTestSuiteFailure");
+ OutputXmlAttribute(stream, "testsuite", "tests", "1");
+ OutputXmlAttribute(stream, "testsuite", "failures", "1");
+ OutputXmlAttribute(stream, "testsuite", "disabled", "0");
+ OutputXmlAttribute(stream, "testsuite", "skipped", "0");
+ OutputXmlAttribute(stream, "testsuite", "errors", "0");
+ OutputXmlAttribute(stream, "testsuite", "time",
+ FormatTimeInMillisAsSeconds(result.elapsed_time()));
+ OutputXmlAttribute(
+ stream, "testsuite", "timestamp",
+ FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
+ *stream << ">";
+
+ // Output the boilerplate for a minimal test case with a single test.
+ *stream << " <testcase";
+ OutputXmlAttribute(stream, "testcase", "name", "");
+ OutputXmlAttribute(stream, "testcase", "status", "run");
+ OutputXmlAttribute(stream, "testcase", "result", "completed");
+ OutputXmlAttribute(stream, "testcase", "classname", "");
+ OutputXmlAttribute(stream, "testcase", "time",
+ FormatTimeInMillisAsSeconds(result.elapsed_time()));
+ OutputXmlAttribute(
+ stream, "testcase", "timestamp",
+ FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
+
+ // Output the actual test result.
+ OutputXmlTestResult(stream, result);
+
+ // Complete the test suite.
+ *stream << " </testsuite>\n";
+}
+
// Prints an XML representation of a TestInfo object.
void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
const char* test_suite_name,
@@ -3800,10 +4241,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;
}
@@ -3821,30 +4263,48 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
+ OutputXmlTestResult(stream, result);
+}
+
+void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
+ const TestResult& result) {
int failures = 0;
+ int skips = 0;
for (int i = 0; i < result.total_part_count(); ++i) {
const TestPartResult& part = result.GetTestPartResult(i);
if (part.failed()) {
- if (++failures == 1) {
+ if (++failures == 1 && skips == 0) {
*stream << ">\n";
}
const std::string location =
internal::FormatCompilerIndependentFileLocation(part.file_name(),
part.line_number());
const std::string summary = location + "\n" + part.summary();
- *stream << " <failure message=\""
- << EscapeXmlAttribute(summary.c_str())
+ *stream << " <failure message=\"" << EscapeXmlAttribute(summary)
<< "\" type=\"\">";
const std::string detail = location + "\n" + part.message();
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
*stream << "</failure>\n";
+ } else if (part.skipped()) {
+ if (++skips == 1 && failures == 0) {
+ *stream << ">\n";
+ }
+ const std::string location =
+ internal::FormatCompilerIndependentFileLocation(part.file_name(),
+ part.line_number());
+ const std::string summary = location + "\n" + part.summary();
+ *stream << " <skipped message=\""
+ << EscapeXmlAttribute(summary.c_str()) << "\">";
+ const std::string detail = location + "\n" + part.message();
+ OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
+ *stream << "</skipped>\n";
}
}
- if (failures == 0 && result.test_property_count() == 0) {
+ if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
*stream << " />\n";
} else {
- if (failures == 0) {
+ if (failures == 0 && skips == 0) {
*stream << ">\n";
}
OutputXmlTestProperties(stream, result);
@@ -3860,13 +4320,17 @@ 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(
stream, kTestsuite, "disabled",
StreamableToString(test_suite.reportable_disabled_test_count()));
+ OutputXmlAttribute(stream, kTestsuite, "skipped",
+ StreamableToString(test_suite.skipped_test_count()));
+
OutputXmlAttribute(stream, kTestsuite, "errors", "0");
+
OutputXmlAttribute(stream, kTestsuite, "time",
FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
OutputXmlAttribute(
@@ -3904,7 +4368,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()));
}
@@ -3917,6 +4381,13 @@ void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
}
+
+ // If there was a test failure outside of one of the test suites (like in a
+ // test environment) include that in the output.
+ if (unit_test.ad_hoc_test_result().Failed()) {
+ OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
+ }
+
*stream << "</" << kTestsuites << ">\n";
}
@@ -3950,7 +4421,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();
}
@@ -3964,19 +4435,21 @@ 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
+#endif // GTEST_HAS_FILE_SYSTEM
+#if GTEST_HAS_FILE_SYSTEM
// This class generates an JSON output file.
class JsonUnitTestResultPrinter : public EmptyTestEventListener {
public:
@@ -3996,16 +4469,22 @@ 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.
+ //
+ // Requires: result.Failed()
+ static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
+ const TestResult& result);
+
+ // Streams a JSON representation of a TestResult object.
+ static void OutputJsonTestResult(::std::ostream* stream,
+ const TestResult& result);
// Streams a JSON representation of a TestInfo object.
static void OutputJsonTestInfo(::std::ostream* stream,
@@ -4028,7 +4507,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.
@@ -4040,7 +4521,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);
@@ -4106,55 +4587,90 @@ 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.
+void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
+ ::std::ostream* stream, const TestResult& result) {
+ // Output the boilerplate for a new test suite.
+ *stream << Indent(4) << "{\n";
+ OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6));
+ OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6));
+ 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));
+ OutputJsonKey(stream, "testsuite", "errors", 0, Indent(6));
+ OutputJsonKey(stream, "testsuite", "time",
+ FormatTimeInMillisAsDuration(result.elapsed_time()),
+ Indent(6));
+ OutputJsonKey(stream, "testsuite", "timestamp",
+ FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
+ Indent(6));
+ }
+ *stream << Indent(6) << "\"testsuite\": [\n";
+
+ // Output the boilerplate for a new test case.
+ *stream << Indent(8) << "{\n";
+ OutputJsonKey(stream, "testcase", "name", "", Indent(10));
+ OutputJsonKey(stream, "testcase", "status", "RUN", Indent(10));
+ OutputJsonKey(stream, "testcase", "result", "COMPLETED", Indent(10));
+ OutputJsonKey(stream, "testcase", "timestamp",
+ FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
+ Indent(10));
+ OutputJsonKey(stream, "testcase", "time",
+ FormatTimeInMillisAsDuration(result.elapsed_time()),
+ Indent(10));
+ OutputJsonKey(stream, "testcase", "classname", "", Indent(10), false);
+ *stream << TestPropertiesAsJson(result, Indent(10));
+
+ // Output the actual test result.
+ OutputJsonTestResult(stream, result);
+
+ // Finish the test suite.
+ *stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}";
}
// Prints a JSON representation of a TestInfo object.
@@ -4176,11 +4692,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",
@@ -4199,13 +4718,22 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
false);
*stream << TestPropertiesAsJson(result, kIndent);
+ OutputJsonTestResult(stream, result);
+}
+
+void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
+ const TestResult& result) {
+ const std::string kIndent = Indent(10);
+
int failures = 0;
for (int i = 0; i < result.total_part_count(); ++i) {
const TestPartResult& part = result.GetTestPartResult(i);
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(),
@@ -4218,8 +4746,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
}
}
- if (failures > 0)
- *stream << "\n" << kIndent << "]";
+ if (failures > 0) *stream << "\n" << kIndent << "]";
*stream << "\n" << Indent(8) << "}";
}
@@ -4233,7 +4760,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",
@@ -4280,7 +4807,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);
}
@@ -4309,7 +4836,18 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
}
}
- *stream << "\n" << kIndent << "]\n" << "}\n";
+ // If there was a test failure outside of one of the test suites (like in a
+ // test environment) include that in the output.
+ if (unit_test.ad_hoc_test_result().Failed()) {
+ if (comma) {
+ *stream << ",\n";
+ }
+ OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
+ }
+
+ *stream << "\n"
+ << kIndent << "]\n"
+ << "}\n";
}
void JsonUnitTestResultPrinter::PrintJsonTestList(
@@ -4344,13 +4882,15 @@ 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();
}
// End JsonUnitTestResultPrinter
+#endif // GTEST_HAS_FILE_SYSTEM
#if GTEST_CAN_STREAM_RESULTS_
@@ -4368,7 +4908,8 @@ std::string StreamingListener::UrlEncode(const char* str) {
case '=':
case '&':
case '\n':
- result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
+ result.push_back('%');
+ result.append(String::FormatByte(static_cast<unsigned char>(ch)));
break;
default:
result.push_back(ch);
@@ -4384,14 +4925,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);
@@ -4400,8 +4941,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) {
@@ -4429,7 +4970,7 @@ const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
GTEST_LOCK_EXCLUDED_(mutex_) {
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
std::string result;
if (max_depth <= 0) {
@@ -4451,7 +4992,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;
@@ -4470,7 +5011,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 "";
@@ -4478,7 +5019,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
}
void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
void* caller_frame = nullptr;
if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
caller_frame = nullptr;
@@ -4489,25 +5030,27 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
#endif // GTEST_HAS_ABSL
}
+#ifdef GTEST_HAS_DEATH_TEST
// A helper class that creates the premature-exit file in its
// constructor and deletes the file in its destructor.
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);
}
}
~ScopedPrematureExitFile() {
+#ifndef GTEST_OS_ESP8266
if (!premature_exit_filepath_.empty()) {
int retval = remove(premature_exit_filepath_.c_str());
if (retval) {
@@ -4516,13 +5059,16 @@ class ScopedPrematureExitFile {
<< retval;
}
}
+#endif
}
private:
const std::string premature_exit_filepath_;
- GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
+ ScopedPrematureExitFile(const ScopedPrematureExitFile&) = delete;
+ ScopedPrematureExitFile& operator=(const ScopedPrematureExitFile&) = delete;
};
+#endif // GTEST_HAS_DEATH_TEST
} // namespace internal
@@ -4594,8 +5140,8 @@ bool TestEventListeners::EventForwardingEnabled() const {
return repeater_->forwarding_enabled();
}
-void TestEventListeners::SuppressEventForwarding() {
- repeater_->set_forwarding_enabled(false);
+void TestEventListeners::SuppressEventForwarding(bool suppress) {
+ repeater_->set_forwarding_enabled(!suppress);
}
// class UnitTest
@@ -4695,7 +5241,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.
@@ -4738,9 +5284,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
@@ -4765,34 +5309,36 @@ 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;
internal::MutexLock lock(&mutex_);
- if (impl_->gtest_trace_stack().size() > 0) {
+ if (!impl_->gtest_trace_stack().empty()) {
msg << "\n" << GTEST_NAME_ << " trace:";
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;
}
}
if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
msg << internal::kStackTraceMarker << os_stack_trace;
+ } else {
+ msg << "\n";
}
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) {
@@ -4801,8 +5347,9 @@ 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_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
+ if (GTEST_FLAG_GET(break_on_failure)) {
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \
+ !defined(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
// the --gtest_catch_exceptions flags are specified.
@@ -4812,13 +5359,17 @@ void UnitTest::AddTestPartResult(
(defined(__x86_64__) || defined(__i386__)))
// with clang/gcc we can achieve the same effect on x86 by invoking int3
asm("int3");
+#elif GTEST_HAS_BUILTIN(__builtin_trap)
+ __builtin_trap();
+#elif defined(SIGTRAP)
+ raise(SIGTRAP);
#else
// Dereference nullptr through a volatile pointer to prevent the compiler
// from removing. We use this rather than abort() or __builtin_trap() for
// 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
@@ -4846,8 +5397,9 @@ void UnitTest::RecordProperty(const std::string& key,
// We don't protect this under mutex_, as we only support calling it
// from the main thread.
int UnitTest::Run() {
+#ifdef GTEST_HAS_DEATH_TEST
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:
@@ -4874,41 +5426,45 @@ int UnitTest::Run() {
in_death_test_child_process
? nullptr
: internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
+#else
+ const bool in_death_test_child_process = false;
+#endif // GTEST_HAS_DEATH_TEST
// 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
+#ifdef GTEST_OS_WINDOWS
// Either the user wants Google Test to catch exceptions thrown by the
// tests or this is executing in the context of death test child
// 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 !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_WINDOWS_PHONE) && \
+ !defined(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) || defined(GTEST_OS_WINDOWS_MINGW)) && \
+ !defined(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) && !defined(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.
-# endif
// In debug mode, the Windows CRT can crash with an assertion over invalid
// input (e.g. passing an invalid file descriptor). The default handling
@@ -4919,20 +5475,26 @@ int UnitTest::Run() {
_CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
(void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
}
+#endif
}
+#else
+ (void)in_death_test_child_process; // Needed inside the #if block above
#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;
}
+#if GTEST_HAS_FILE_SYSTEM
// Returns the working directory when the first TEST() or TEST_F() was
// executed.
const char* UnitTest::original_working_dir() const {
return impl_->original_working_dir_.c_str();
}
+#endif // GTEST_HAS_FILE_SYSTEM
// Returns the TestSuite object for the test that's currently running,
// or NULL if no test is running.
@@ -4970,14 +5532,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.
@@ -4988,8 +5546,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();
}
@@ -5001,7 +5558,7 @@ UnitTestImpl::UnitTestImpl(UnitTest* parent)
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
default_global_test_part_result_reporter_(this),
default_per_thread_test_part_result_reporter_(this),
- GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
+ GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_reporter_(
&default_global_test_part_result_reporter_),
per_thread_test_part_result_reporter_(
&default_per_thread_test_part_result_reporter_),
@@ -5017,7 +5574,7 @@ UnitTestImpl::UnitTestImpl(UnitTest* parent)
random_(0), // Will be reseeded before first use.
start_timestamp_(0),
elapsed_time_(0),
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
death_test_factory_(new DefaultDeathTestFactory),
#endif
// Will be overridden by the flag before first use.
@@ -5057,12 +5614,12 @@ void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
test_result->RecordProperty(xml_element, test_property);
}
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
// Disables event forwarding if the control is currently in a death test
// subprocess. Must not be called before InitGoogleTest.
void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
- if (internal_run_death_test_flag_.get() != nullptr)
- listeners()->SuppressEventForwarding();
+ if (internal_run_death_test_flag_ != nullptr)
+ listeners()->SuppressEventForwarding(true);
}
#endif // GTEST_HAS_DEATH_TEST
@@ -5070,28 +5627,35 @@ void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
// UnitTestOptions. Must not be called before InitGoogleTest.
void UnitTestImpl::ConfigureXmlOutput() {
const std::string& output_format = UnitTestOptions::GetOutputFormat();
+#if GTEST_HAS_FILE_SYSTEM
if (output_format == "xml") {
listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
} else if (output_format == "json") {
listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
- } else if (output_format != "") {
+ } else if (!output_format.empty()) {
GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
<< output_format << "\" ignored.";
}
+#else
+ if (!output_format.empty()) {
+ GTEST_LOG_(ERROR) << "ERROR: alternative output formats require "
+ << "GTEST_HAS_FILE_SYSTEM to be enabled";
+ }
+#endif // GTEST_HAS_FILE_SYSTEM
}
#if GTEST_CAN_STREAM_RESULTS_
// 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.";
@@ -5115,7 +5679,7 @@ void UnitTestImpl::PostFlagParsingInit() {
listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo();
SuppressTestEventsIfInSubprocess();
#endif // GTEST_HAS_DEATH_TEST
@@ -5129,13 +5693,17 @@ void UnitTestImpl::PostFlagParsingInit() {
// to shut down the default XML output before invoking RUN_ALL_TESTS.
ConfigureXmlOutput();
+ if (GTEST_FLAG_GET(brief)) {
+ listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);
+ }
+
#if GTEST_CAN_STREAM_RESULTS_
// Configures listeners for streaming test results to the specified server.
ConfigureStreamingOutput();
#endif // GTEST_CAN_STREAM_RESULTS_
-#if GTEST_HAS_ABSL
- if (GTEST_FLAG(install_failure_signal_handler)) {
+#ifdef GTEST_HAS_ABSL
+ if (GTEST_FLAG_GET(install_failure_signal_handler)) {
absl::FailureSignalHandlerOptions options;
absl::InstallFailureSignalHandler(options);
}
@@ -5174,10 +5742,10 @@ class TestSuiteNameIs {
// Arguments:
//
// test_suite_name: name of the test suite
-// type_param: the name of the test suite's type parameter, or NULL if
-// this is not a typed or a type-parameterized test suite.
-// set_up_tc: pointer to the function that sets up the test suite
-// tear_down_tc: pointer to the function that tears down the test suite
+// type_param: the name of the test suite's type parameter, or NULL if
+// this is not a typed or a type-parameterized test suite.
+// set_up_tc: pointer to the function that sets up the test suite
+// tear_down_tc: pointer to the function that tears down the test suite
TestSuite* UnitTestImpl::GetTestSuite(
const char* test_suite_name, const char* type_param,
internal::SetUpTestSuiteFunc set_up_tc,
@@ -5193,9 +5761,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
@@ -5232,30 +5800,30 @@ 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.
PostFlagParsingInit();
+#if GTEST_HAS_FILE_SYSTEM
// Even if sharding is not on, test runners may want to use the
// GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
// protocol.
internal::WriteToShardStatusFileIfNeeded();
+#endif // GTEST_HAS_FILE_SYSTEM
// True if and only if we are in a subprocess for running a thread-safe-style
// death test.
bool in_subprocess_for_death_test = false;
-#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_)
+#ifdef GTEST_HAS_DEATH_TEST
+ in_subprocess_for_death_test = (internal_run_death_test_flag_ != nullptr);
+#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,
@@ -5263,19 +5831,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;
@@ -5287,19 +5854,31 @@ 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().
ClearNonAdHocTestResult();
- const TimeInMillis start = GetTimeInMillis();
+ Timer timer;
// Shuffles test suites and tests if requested.
- if (has_tests_to_run && GTEST_FLAG(shuffle)) {
- random()->Reseed(static_cast<UInt32>(random_seed_));
+ 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
// in the event.
@@ -5311,10 +5890,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.
@@ -5336,17 +5918,36 @@ bool UnitTestImpl::RunAllTests() {
for (int test_index = 0; test_index < total_test_suite_count();
test_index++) {
GetMutableSuiteCase(test_index)->Run();
+ 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();
+ }
+ break;
+ }
+ }
+ } else if (Test::HasFatalFailure()) {
+ // If there was a fatal failure during the global setup then we know we
+ // aren't going to run any tests. Explicitly mark all of the tests as
+ // skipped to make this obvious in the output.
+ for (int test_index = 0; test_index < total_test_suite_count();
+ test_index++) {
+ GetMutableSuiteCase(test_index)->Skip();
}
}
- // 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_ = GetTimeInMillis() - start;
+ elapsed_time_ = timer.Elapsed();
// Tells the unit test event listener that the tests have just finished.
repeater->OnTestIterationEnd(*parent_, i);
@@ -5364,7 +5965,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_);
}
@@ -5374,21 +5975,18 @@ bool UnitTestImpl::RunAllTests() {
if (!gtest_is_initialized_before_run_all_tests) {
ColoredPrintf(
- COLOR_RED,
+ GTestColor::kRed,
"\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
"This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
"() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
" will start to enforce the valid usage. "
"Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
-#if GTEST_FOR_GOOGLE_
- ColoredPrintf(COLOR_RED,
- "For more details, see http://wiki/Main/ValidGUnitMain.\n");
-#endif // GTEST_FOR_GOOGLE_
}
return !failed;
}
+#if GTEST_HAS_FILE_SYSTEM
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
// if the variable is present. If a file already exists at this location, this
// function will write over it. If the variable is present, but the file cannot
@@ -5398,7 +5996,7 @@ void WriteToShardStatusFileIfNeeded() {
if (test_shard_file != nullptr) {
FILE* const file = posix::FOpen(test_shard_file, "w");
if (file == nullptr) {
- ColoredPrintf(COLOR_RED,
+ ColoredPrintf(GTestColor::kRed,
"Could not write to the test shard status file \"%s\" "
"specified by the %s environment variable.\n",
test_shard_file, kTestShardStatusFile);
@@ -5408,6 +6006,7 @@ void WriteToShardStatusFileIfNeeded() {
fclose(file);
}
}
+#endif // GTEST_HAS_FILE_SYSTEM
// Checks whether sharding is enabled by examining the relevant
// environment variable values. If the variables are present,
@@ -5415,41 +6014,40 @@ 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;
}
- const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
- const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
+ const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1);
+ const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1);
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";
- ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
+ 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";
- ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
+ << "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";
- ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
+ 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);
}
@@ -5460,13 +6058,13 @@ bool ShouldShard(const char* total_shards_env,
// Parses the environment variable var as an Int32. If it is unset,
// returns default_val. If it is not an Int32, prints an error
// and aborts.
-Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
+int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) {
const char* str_val = posix::GetEnv(var);
if (str_val == nullptr) {
return default_val;
}
- Int32 result;
+ int32_t result;
if (!ParseInt32(Message() << "The value of environment variable " << var,
str_val, &result)) {
exit(EXIT_FAILURE);
@@ -5487,14 +6085,19 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
// each TestSuite and TestInfo object.
// If shard_tests == true, further filters tests based on sharding
// variables in the environment - see
-// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
+// https://github.com/google/googletest/blob/main/docs/advanced.md
// . Returns the number of tests that should run.
int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
- const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
- Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
- const Int32 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
@@ -5510,18 +6113,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 =
@@ -5596,6 +6198,7 @@ void UnitTestImpl::ListTestsMatchingFilter() {
}
}
fflush(stdout);
+#if GTEST_HAS_FILE_SYSTEM
const std::string& output_format = UnitTestOptions::GetOutputFormat();
if (output_format == "xml" || output_format == "json") {
FILE* fileout = OpenFileForWriting(
@@ -5613,6 +6216,7 @@ void UnitTestImpl::ListTestsMatchingFilter() {
fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
fclose(fileout);
}
+#endif // GTEST_HAS_FILE_SYSTEM
}
// Sets the OS stack trace getter.
@@ -5690,8 +6294,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(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);
@@ -5701,7 +6305,7 @@ std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
// suppress unreachable code warnings.
namespace {
class ClassUniqueToAlwaysTrue {};
-}
+} // namespace
bool IsTrue(bool condition) { return condition; }
@@ -5709,8 +6313,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;
}
@@ -5732,13 +6335,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;
@@ -5769,9 +6373,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;
@@ -5781,32 +6385,30 @@ static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
return true;
}
-// Parses a string for an Int32 flag, in the form of
-// "--flag=value".
+// Parses a string for an int32_t flag, in the form of "--flag=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* 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".
+// Parses a string for a string flag, in the form of "--flag=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;
@@ -5823,8 +6425,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) ||
@@ -5841,7 +6442,7 @@ static bool HasGoogleTestFlagPrefix(const char* str) {
// @D changes to the default terminal text color.
//
static void PrintColorEncoded(const char* str) {
- GTestColor color = COLOR_DEFAULT; // The current color.
+ GTestColor color = GTestColor::kDefault; // The current color.
// Conceptually, we split the string into segments divided by escape
// sequences. Then we print one segment at a time. At the end of
@@ -5861,13 +6462,13 @@ static void PrintColorEncoded(const char* str) {
if (ch == '@') {
ColoredPrintf(color, "@");
} else if (ch == 'D') {
- color = COLOR_DEFAULT;
+ color = GTestColor::kDefault;
} else if (ch == 'R') {
- color = COLOR_RED;
+ color = GTestColor::kRed;
} else if (ch == 'G') {
- color = COLOR_GREEN;
+ color = GTestColor::kGreen;
} else if (ch == 'Y') {
- color = COLOR_YELLOW;
+ color = GTestColor::kYellow;
} else {
--str;
}
@@ -5875,105 +6476,140 @@ static void PrintColorEncoded(const char* str) {
}
static const char kColorEncodedHelpMessage[] =
-"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
-"following command line flags to control its behavior:\n"
-"\n"
-"Test Selection:\n"
-" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
-" List the names of all tests instead of running them. The name of\n"
-" TEST(Foo, Bar) is \"Foo.Bar\".\n"
-" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
+ "This program contains tests written using " GTEST_NAME_
+ ". You can use the\n"
+ "following command line flags to control its behavior:\n"
+ "\n"
+ "Test Selection:\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "list_tests@D\n"
+ " List the names of all tests instead of running them. The name of\n"
+ " TEST(Foo, Bar) is \"Foo.Bar\".\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "filter=@YPOSITIVE_PATTERNS"
"[@G-@YNEGATIVE_PATTERNS]@D\n"
-" Run only the tests whose name matches one of the positive patterns but\n"
-" none of the negative patterns. '?' matches any single character; '*'\n"
-" matches any substring; ':' separates two patterns.\n"
-" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
-" Run all disabled tests too.\n"
-"\n"
-"Test Execution:\n"
-" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
-" Run the tests repeatedly; use a negative count to repeat forever.\n"
-" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
-" Randomize tests' orders on every iteration.\n"
-" @G--" GTEST_FLAG_PREFIX_ "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"
-"\n"
-"Test Output:\n"
-" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
-" Enable/disable colored output. The default is @Gauto@D.\n"
-" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
-" Don't print the elapsed time of each test.\n"
-" @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
- GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
-" 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_
-" @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_
-"\n"
-"Assertion Behavior:\n"
-# 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
-" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
-" Turn assertion failures into debugger break-points.\n"
-" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
-" Turn assertion failures into C++ exceptions for use by an external\n"
-" test framework.\n"
-" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
-" Do not report exceptions as test failures. Instead, allow them\n"
-" to crash the program or throw a pop-up (on Windows).\n"
-"\n"
-"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
+ " Run only the tests whose name matches one of the positive patterns "
+ "but\n"
+ " none of the negative patterns. '?' matches any single character; "
+ "'*'\n"
+ " matches any substring; ':' separates two patterns.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "also_run_disabled_tests@D\n"
+ " Run all disabled tests too.\n"
+ "\n"
+ "Test Execution:\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "repeat=@Y[COUNT]@D\n"
+ " Run the tests repeatedly; use a negative count to repeat forever.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "shuffle@D\n"
+ " Randomize tests' orders on every iteration.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "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_
+ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
+ " Enable/disable colored output. The default is @Gauto@D.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "brief=1@D\n"
+ " Only print test failures.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "print_time=0@D\n"
+ " Don't print the elapsed time of each test.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
+ "@Y|@G:@YFILE_PATH]@D\n"
+ " 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_
+ " @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_
+ "\n"
+ "Assertion Behavior:\n"
+#if defined(GTEST_HAS_DEATH_TEST) && !defined(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
+ " @G--" GTEST_FLAG_PREFIX_
+ "break_on_failure@D\n"
+ " Turn assertion failures into debugger break-points.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "throw_on_failure@D\n"
+ " Turn assertion failures into C++ exceptions for use by an external\n"
+ " test framework.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "catch_exceptions=0@D\n"
+ " Do not report exceptions as test failures. Instead, allow them\n"
+ " to crash the program or throw a pop-up (on Windows).\n"
+ "\n"
+ "Except for @G--" GTEST_FLAG_PREFIX_
+ "list_tests@D, you can alternatively set "
"the corresponding\n"
-"environment variable of a flag (all letters in upper-case). For example, to\n"
-"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
+ "environment variable of a flag (all letters in upper-case). For example, "
+ "to\n"
+ "disable colored text output, you can either specify "
+ "@G--" GTEST_FLAG_PREFIX_
"color=no@D or set\n"
-"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
-"\n"
-"For more information, please read the " GTEST_NAME_ " documentation at\n"
-"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
-"(not one in your own code or tests), please report it to\n"
-"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
+ "the @G" GTEST_FLAG_PREFIX_UPPER_
+ "COLOR@D environment variable to @Gno@D.\n"
+ "\n"
+ "For more information, please read the " GTEST_NAME_
+ " documentation at\n"
+ "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
+ "\n"
+ "(not one in your own code or tests), please report it to\n"
+ "@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)) ||
- 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, 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_
+#if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
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));
@@ -5981,38 +6617,34 @@ 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_
+#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
// Parses the command line for Google Test flags, without initializing
// other parts of Google Test. The type parameter CharType can be
// 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));
+#if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
+ } 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)) {
+#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
+ } 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;
@@ -6045,14 +6677,68 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
}
// Parses the command line for Google Test flags, without initializing
-// other parts of Google Test.
+// other parts of Google Test. This function updates argc and argv by removing
+// flags that are known to GoogleTest (including other user flags defined using
+// ABSL_FLAG if GoogleTest is built with GTEST_USE_ABSL). Other arguments
+// remain in place. Unrecognized flags are not reported and do not cause the
+// program to exit.
void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
+#ifdef GTEST_HAS_ABSL
+ if (*argc <= 0) return;
+
+ std::vector<char*> positional_args;
+ std::vector<absl::UnrecognizedFlag> unrecognized_flags;
+ absl::ParseAbseilFlagsOnly(*argc, argv, positional_args, unrecognized_flags);
+ absl::flat_hash_set<absl::string_view> unrecognized;
+ for (const auto& flag : unrecognized_flags) {
+ unrecognized.insert(flag.flag_name);
+ }
+ absl::flat_hash_set<char*> positional;
+ for (const auto& arg : positional_args) {
+ positional.insert(arg);
+ }
+
+ int out_pos = 1;
+ int in_pos = 1;
+ for (; in_pos < *argc; ++in_pos) {
+ char* arg = argv[in_pos];
+ absl::string_view arg_str(arg);
+ if (absl::ConsumePrefix(&arg_str, "--")) {
+ // Flag-like argument. If the flag was unrecognized, keep it.
+ // If it was a GoogleTest flag, remove it.
+ if (unrecognized.contains(arg_str)) {
+ argv[out_pos++] = argv[in_pos];
+ continue;
+ }
+ }
+
+ if (arg_str.empty()) {
+ ++in_pos;
+ break; // '--' indicates that the rest of the arguments are positional
+ }
+
+ // Probably a positional argument. If it is in fact positional, keep it.
+ // If it was a value for the flag argument, remove it.
+ if (positional.contains(arg)) {
+ argv[out_pos++] = arg;
+ }
+ }
+
+ // The rest are positional args for sure.
+ while (in_pos < *argc) {
+ argv[out_pos++] = argv[in_pos++];
+ }
+
+ *argc = out_pos;
+ argv[out_pos] = nullptr;
+#else
ParseGoogleTestFlagsOnlyImpl(argc, argv);
+#endif
// Fix the value of *_NSGetArgc() on macOS, but if and only if
// *_NSGetArgv() == argv
// Only applicable to char** version of argv
-#if GTEST_OS_MAC
+#ifdef GTEST_OS_MAC
#ifndef GTEST_OS_IOS
if (*_NSGetArgv() == argv) {
*_NSGetArgc() = *argc;
@@ -6080,8 +6766,14 @@ void InitGoogleTestImpl(int* argc, CharType** argv) {
g_argvs.push_back(StreamableToString(argv[i]));
}
-#if GTEST_HAS_ABSL
+#ifdef 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);
@@ -6102,7 +6794,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_)
}
@@ -6112,7 +6804,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_)
}
@@ -6128,32 +6820,70 @@ 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_) || \
+ !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
+// Returns the value of the first environment variable that is set and contains
+// a non-empty string. If there are none, returns the "fallback" string. Adds
+// the director-separator character as a suffix if not provided in the
+// environment variable value.
+static std::string GetDirFromEnv(
+ 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 defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE)
+ return GetDirFromEnv({"TEST_TMPDIR", "TEMP"}, "\\temp\\", '\\');
+#elif defined(GTEST_OS_LINUX_ANDROID)
+ return GetDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/data/local/tmp/", '/');
+#else
+ return GetDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/tmp/", '/');
+#endif
+}
+
+#if GTEST_HAS_FILE_SYSTEM && !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
+// Returns the directory path (including terminating separator) of the current
+// executable as derived from argv[0].
+static std::string GetCurrentExecutableDirectory() {
+ internal::FilePath argv_0(internal::GetArgvs()[0]);
+ return argv_0.RemoveFileName().string();
+}
#endif
-#if 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_LINUX_ANDROID
- return "/sdcard/";
+#if GTEST_HAS_FILE_SYSTEM
+std::string SrcDir() {
+#if defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
+ return GTEST_CUSTOM_SRCDIR_FUNCTION_();
+#elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE)
+ return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
+ '\\');
+#elif defined(GTEST_OS_LINUX_ANDROID)
+ return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
+ '/');
#else
- return "/tmp/";
-#endif // GTEST_OS_WINDOWS_MOBILE
+ return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
+ '/');
+#endif
}
+#endif
// Class ScopedTrace
@@ -6169,8 +6899,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();
}
diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc
index f6e1dd96fb3b..8141caf4ca08 100644
--- a/googletest/src/gtest_main.cc
+++ b/googletest/src/gtest_main.cc
@@ -28,16 +28,35 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cstdio>
+
#include "gtest/gtest.h"
-#ifdef ARDUINO
-void setup() {
- testing::InitGoogleTest();
-}
+#if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) || \
+ (defined(GTEST_OS_NRF52) && defined(ARDUINO))
+// Arduino-like platforms: program entry points are setup/loop instead of main.
+
+#ifdef GTEST_OS_ESP8266
+extern "C" {
+#endif
+
+void setup() { testing::InitGoogleTest(); }
void loop() { RUN_ALL_TESTS(); }
+#ifdef GTEST_OS_ESP8266
+}
+#endif
+
+#elif defined(GTEST_OS_QURT)
+// QuRT: program entry point is main, but argc/argv are unusable.
+
+GTEST_API_ int main() {
+ printf("Running main() from %s\n", __FILE__);
+ testing::InitGoogleTest();
+ return RUN_ALL_TESTS();
+}
#else
+// Normal platforms: program entry point is main, argc/argv are initialized.
GTEST_API_ int main(int argc, char **argv) {
printf("Running main() from %s\n", __FILE__);
diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel
index 156d5d4b423c..1890b6ff9ed9 100644
--- a/googletest/test/BUILD.bazel
+++ b/googletest/test/BUILD.bazel
@@ -28,15 +28,14 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
-# Author: misterg@google.com (Gennadiy Civil)
-#
# Bazel BUILD for The Google C++ Testing Framework (Google Test)
-load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
load("@rules_python//python:defs.bzl", "py_library", "py_test")
licenses(["notice"])
+package(default_visibility = ["//:__subpackages__"])
+
#on windows exclude gtest-tuple.h
cc_test(
name = "gtest_all_test",
@@ -56,15 +55,20 @@ cc_test(
"gtest-listener_test.cc",
"gtest-unittest-api_test.cc",
"googletest-param-test-test.cc",
+ "googletest-param-test2-test.cc",
"googletest-catch-exceptions-test_.cc",
"googletest-color-test_.cc",
"googletest-env-var-test_.cc",
+ "googletest-failfast-unittest_.cc",
"googletest-filter-unittest_.cc",
+ "googletest-global-environment-unittest_.cc",
"googletest-break-on-failure-unittest_.cc",
"googletest-listener-test.cc",
+ "googletest-message-test.cc",
"googletest-output-test_.cc",
"googletest-list-tests-unittest_.cc",
"googletest-shuffle-test_.cc",
+ "googletest-setuptestsuite-test_.cc",
"googletest-uninitialized-test_.cc",
"googletest-death-test_ex_test.cc",
"googletest-param-test-test",
@@ -79,6 +83,10 @@ cc_test(
copts = select({
"//:windows": ["-DGTEST_USE_OWN_TR1_TUPLE=0"],
"//conditions:default": ["-DGTEST_USE_OWN_TR1_TUPLE=1"],
+ }) + select({
+ # Ensure MSVC treats source files as UTF-8 encoded.
+ "//:msvc_compiler": ["-utf-8"],
+ "//conditions:default": [],
}),
includes = [
"googletest",
@@ -87,6 +95,7 @@ cc_test(
"googletest/test",
],
linkopts = select({
+ "//:qnx": [],
"//:windows": [],
"//conditions:default": ["-pthread"],
}),
@@ -142,7 +151,6 @@ cc_test(
name = "gtest_unittest",
size = "small",
srcs = ["gtest_unittest.cc"],
- args = ["--heap_check=strict"],
shard_count = 2,
deps = ["//:gtest_main"],
)
@@ -153,6 +161,7 @@ py_library(
name = "gtest_test_utils",
testonly = 1,
srcs = ["gtest_test_utils.py"],
+ imports = ["."],
)
cc_binary(
@@ -166,6 +175,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"],
)
@@ -223,6 +236,21 @@ py_test(
)
cc_binary(
+ name = "googletest-failfast-unittest_",
+ testonly = 1,
+ srcs = ["googletest-failfast-unittest_.cc"],
+ deps = ["//:gtest"],
+)
+
+py_test(
+ name = "googletest-failfast-unittest",
+ size = "medium",
+ srcs = ["googletest-failfast-unittest.py"],
+ data = [":googletest-failfast-unittest_"],
+ deps = [":gtest_test_utils"],
+)
+
+cc_binary(
name = "googletest-filter-unittest_",
testonly = 1,
srcs = ["googletest-filter-unittest_.cc"],
@@ -238,6 +266,21 @@ py_test(
)
cc_binary(
+ name = "googletest-global-environment-unittest_",
+ testonly = 1,
+ srcs = ["googletest-global-environment-unittest_.cc"],
+ deps = ["//:gtest"],
+)
+
+py_test(
+ name = "googletest-global-environment-unittest",
+ size = "medium",
+ srcs = ["googletest-global-environment-unittest.py"],
+ data = [":googletest-global-environment-unittest_"],
+ deps = [":gtest_test_utils"],
+)
+
+cc_binary(
name = "googletest-break-on-failure-unittest_",
testonly = 1,
srcs = ["googletest-break-on-failure-unittest_.cc"],
@@ -296,6 +339,14 @@ cc_test(
)
py_test(
+ name = "gtest_skip_check_output_test",
+ size = "small",
+ srcs = ["gtest_skip_check_output_test.py"],
+ data = [":gtest_skip_test"],
+ deps = [":gtest_test_utils"],
+)
+
+py_test(
name = "gtest_skip_environment_check_output_test",
size = "small",
srcs = ["gtest_skip_environment_check_output_test.py"],
@@ -416,6 +467,21 @@ py_test(
)
cc_binary(
+ name = "googletest-setuptestsuite-test_",
+ testonly = 1,
+ srcs = ["googletest-setuptestsuite-test_.cc"],
+ deps = ["//:gtest_main"],
+)
+
+py_test(
+ name = "googletest-setuptestsuite-test",
+ size = "medium",
+ srcs = ["googletest-setuptestsuite-test.py"],
+ data = [":googletest-setuptestsuite-test_"],
+ deps = [":gtest_test_utils"],
+)
+
+cc_binary(
name = "googletest-uninitialized-test_",
testonly = 1,
srcs = ["googletest-uninitialized-test_.cc"],
@@ -509,6 +575,10 @@ py_test(
size = "small",
srcs = ["googletest-param-test-invalid-name1-test.py"],
data = [":googletest-param-test-invalid-name1-test_"],
+ tags = [
+ "no_test_msvc2015",
+ "no_test_msvc2017",
+ ],
deps = [":gtest_test_utils"],
)
@@ -517,5 +587,9 @@ py_test(
size = "small",
srcs = ["googletest-param-test-invalid-name2-test.py"],
data = [":googletest-param-test-invalid-name2-test_"],
+ tags = [
+ "no_test_msvc2015",
+ "no_test_msvc2017",
+ ],
deps = [":gtest_test_utils"],
)
diff --git a/googletest/test/googletest-break-on-failure-unittest.py b/googletest/test/googletest-break-on-failure-unittest.py
index a5dfbc693b43..e314b5ccdbf6 100755
--- a/googletest/test/googletest-break-on-failure-unittest.py
+++ b/googletest/test/googletest-break-on-failure-unittest.py
@@ -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.
@@ -59,7 +59,8 @@ CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS'
# Path to the googletest-break-on-failure-unittest_ program.
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
- 'googletest-break-on-failure-unittest_')
+ 'googletest-break-on-failure-unittest_'
+)
environ = gtest_test_utils.environ
@@ -87,22 +88,26 @@ def Run(command):
class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):
- """Tests using the GTEST_BREAK_ON_FAILURE environment variable or
+ """Unit test for Google Test's break-on-failure mode.
+
+ Tests using the GTEST_BREAK_ON_FAILURE environment variable or
the --gtest_break_on_failure flag to turn assertion failures into
segmentation faults.
"""
def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault):
- """Runs googletest-break-on-failure-unittest_ and verifies that it does
+ """Runs googletest-break-on-failure-unittest_ and verifies its behavior.
+
+ Runs googletest-break-on-failure-unittest_ and verifies that it does
(or does not) have a seg-fault.
Args:
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
- variable; None if the variable should be unset.
- flag_value: value of the --gtest_break_on_failure flag;
- None if the flag should not be present.
- expect_seg_fault: 1 if the program is expected to generate a seg-fault;
- 0 otherwise.
+ variable; None if the variable should be unset.
+ flag_value: value of the --gtest_break_on_failure flag; None if the
+ flag should not be present.
+ expect_seg_fault: 1 if the program is expected to generate a seg-fault; 0
+ otherwise.
"""
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value)
@@ -132,74 +137,56 @@ class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None)
- msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' %
- (BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command),
- should_or_not))
- self.assert_(has_seg_fault == expect_seg_fault, msg)
+ msg = 'when %s%s, an assertion failure in "%s" %s cause a seg-fault.' % (
+ BREAK_ON_FAILURE_ENV_VAR,
+ env_var_value_msg,
+ ' '.join(command),
+ should_or_not,
+ )
+ self.assertTrue(has_seg_fault == expect_seg_fault, msg)
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
- self.RunAndVerify(env_var_value=None,
- flag_value=None,
- expect_seg_fault=0)
+ self.RunAndVerify(env_var_value=None, flag_value=None, expect_seg_fault=0)
def testEnvVar(self):
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable."""
- self.RunAndVerify(env_var_value='0',
- flag_value=None,
- expect_seg_fault=0)
- self.RunAndVerify(env_var_value='1',
- flag_value=None,
- expect_seg_fault=1)
+ self.RunAndVerify(env_var_value='0', flag_value=None, expect_seg_fault=0)
+ self.RunAndVerify(env_var_value='1', flag_value=None, expect_seg_fault=1)
def testFlag(self):
"""Tests using the --gtest_break_on_failure flag."""
- self.RunAndVerify(env_var_value=None,
- flag_value='0',
- expect_seg_fault=0)
- self.RunAndVerify(env_var_value=None,
- flag_value='1',
- expect_seg_fault=1)
+ self.RunAndVerify(env_var_value=None, flag_value='0', expect_seg_fault=0)
+ self.RunAndVerify(env_var_value=None, flag_value='1', expect_seg_fault=1)
def testFlagOverridesEnvVar(self):
"""Tests that the flag overrides the environment variable."""
- self.RunAndVerify(env_var_value='0',
- flag_value='0',
- expect_seg_fault=0)
- self.RunAndVerify(env_var_value='0',
- flag_value='1',
- expect_seg_fault=1)
- self.RunAndVerify(env_var_value='1',
- flag_value='0',
- expect_seg_fault=0)
- self.RunAndVerify(env_var_value='1',
- flag_value='1',
- expect_seg_fault=1)
+ self.RunAndVerify(env_var_value='0', flag_value='0', expect_seg_fault=0)
+ self.RunAndVerify(env_var_value='0', flag_value='1', expect_seg_fault=1)
+ self.RunAndVerify(env_var_value='1', flag_value='0', expect_seg_fault=0)
+ self.RunAndVerify(env_var_value='1', flag_value='1', expect_seg_fault=1)
def testBreakOnFailureOverridesThrowOnFailure(self):
"""Tests that gtest_break_on_failure overrides gtest_throw_on_failure."""
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1')
try:
- self.RunAndVerify(env_var_value=None,
- flag_value='1',
- expect_seg_fault=1)
+ self.RunAndVerify(env_var_value=None, flag_value='1', expect_seg_fault=1)
finally:
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None)
if IS_WINDOWS:
+
def testCatchExceptionsDoesNotInterfere(self):
"""Tests that gtest_catch_exceptions doesn't interfere."""
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1')
try:
- self.RunAndVerify(env_var_value='1',
- flag_value='1',
- expect_seg_fault=1)
+ self.RunAndVerify(env_var_value='1', flag_value='1', expect_seg_fault=1)
finally:
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None)
diff --git a/googletest/test/googletest-break-on-failure-unittest_.cc b/googletest/test/googletest-break-on-failure-unittest_.cc
index f84957a2d03b..337e34c33017 100644
--- a/googletest/test/googletest-break-on-failure-unittest_.cc
+++ b/googletest/test/googletest-break-on-failure-unittest_.cc
@@ -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
@@ -40,35 +39,33 @@
#include "gtest/gtest.h"
-#if GTEST_OS_WINDOWS
-# include <windows.h>
-# include <stdlib.h>
+#ifdef GTEST_OS_WINDOWS
+#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
+#if GTEST_HAS_SEH && !defined(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) {
-#if GTEST_OS_WINDOWS
+int main(int argc, char** argv) {
+#ifdef 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 && !defined(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);
diff --git a/googletest/test/googletest-catch-exceptions-test.py b/googletest/test/googletest-catch-exceptions-test.py
index 94a5b33f2305..180e18de0f9b 100755
--- a/googletest/test/googletest-catch-exceptions-test.py
+++ b/googletest/test/googletest-catch-exceptions-test.py
@@ -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_'
@@ -46,12 +46,14 @@ FILTER_FLAG = FLAG_PREFIX + 'filter'
# Path to the googletest-catch-exceptions-ex-test_ binary, compiled with
# exceptions enabled.
EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath(
- 'googletest-catch-exceptions-ex-test_')
+ 'googletest-catch-exceptions-ex-test_'
+)
# Path to the googletest-catch-exceptions-test_ binary, compiled with
# exceptions disabled.
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
- 'googletest-catch-exceptions-no-ex-test_')
+ 'googletest-catch-exceptions-no-ex-test_'
+)
environ = gtest_test_utils.environ
SetEnvVar = gtest_test_utils.SetEnvVar
@@ -64,7 +66,8 @@ SetEnvVar = gtest_test_utils.SetEnvVar
SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
TEST_LIST = gtest_test_utils.Subprocess(
- [EXE_PATH, LIST_TESTS_FLAG], env=environ).output
+ [EXE_PATH, LIST_TESTS_FLAG], env=environ
+).output
SUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST
@@ -72,33 +75,47 @@ if SUPPORTS_SEH_EXCEPTIONS:
BINARY_OUTPUT = gtest_test_utils.Subprocess([EXE_PATH], env=environ).output
EX_BINARY_OUTPUT = gtest_test_utils.Subprocess(
- [EX_EXE_PATH], env=environ).output
+ [EX_EXE_PATH], env=environ
+).output
# The tests.
if SUPPORTS_SEH_EXCEPTIONS:
- # pylint:disable-msg=C6302
+
class CatchSehExceptionsTest(gtest_test_utils.TestCase):
"""Tests exception-catching behavior."""
-
def TestSehExceptions(self, test_output):
- self.assert_('SEH exception with code 0x2a thrown '
- 'in the test fixture\'s constructor'
- in test_output)
- self.assert_('SEH exception with code 0x2a thrown '
- 'in the test fixture\'s destructor'
- in test_output)
- self.assert_('SEH exception with code 0x2a thrown in SetUpTestSuite()'
- in test_output)
- self.assert_('SEH exception with code 0x2a thrown in TearDownTestSuite()'
- in test_output)
- self.assert_('SEH exception with code 0x2a thrown in SetUp()'
- in test_output)
- self.assert_('SEH exception with code 0x2a thrown in TearDown()'
- in test_output)
- self.assert_('SEH exception with code 0x2a thrown in the test body'
- in test_output)
+ self.assertIn(
+ (
+ 'SEH exception with code 0x2a thrown '
+ "in the test fixture's constructor"
+ ),
+ test_output,
+ )
+ self.assertIn(
+ (
+ 'SEH exception with code 0x2a thrown '
+ "in the test fixture's destructor"
+ ),
+ test_output,
+ )
+ self.assertIn(
+ 'SEH exception with code 0x2a thrown in SetUpTestSuite()', test_output
+ )
+ self.assertIn(
+ 'SEH exception with code 0x2a thrown in TearDownTestSuite()',
+ test_output,
+ )
+ self.assertIn(
+ 'SEH exception with code 0x2a thrown in SetUp()', test_output
+ )
+ self.assertIn(
+ 'SEH exception with code 0x2a thrown in TearDown()', test_output
+ )
+ self.assertIn(
+ 'SEH exception with code 0x2a thrown in the test body', test_output
+ )
def testCatchesSehExceptionsWithCxxExceptionsEnabled(self):
self.TestSehExceptions(EX_BINARY_OUTPUT)
@@ -110,126 +127,188 @@ if SUPPORTS_SEH_EXCEPTIONS:
class CatchCxxExceptionsTest(gtest_test_utils.TestCase):
"""Tests C++ exception-catching behavior.
- Tests in this test case verify that:
- * C++ exceptions are caught and logged as C++ (not SEH) exceptions
- * Exception thrown affect the remainder of the test work flow in the
- expected manner.
+ Tests in this test case verify that:
+ * C++ exceptions are caught and logged as C++ (not SEH) exceptions
+ * Exception thrown affect the remainder of the test work flow in the
+ expected manner.
"""
def testCatchesCxxExceptionsInFixtureConstructor(self):
self.assertTrue(
'C++ exception with description '
'"Standard C++ exception" thrown '
- 'in the test fixture\'s constructor' in EX_BINARY_OUTPUT,
- EX_BINARY_OUTPUT)
- self.assert_('unexpected' not in EX_BINARY_OUTPUT,
- 'This failure belongs in this test only if '
- '"CxxExceptionInConstructorTest" (no quotes) '
- 'appears on the same line as words "called unexpectedly"')
-
- if ('CxxExceptionInDestructorTest.ThrowsExceptionInDestructor' in
- EX_BINARY_OUTPUT):
+ "in the test fixture's constructor"
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
+ self.assertTrue(
+ 'unexpected' not in EX_BINARY_OUTPUT,
+ (
+ 'This failure belongs in this test only if '
+ '"CxxExceptionInConstructorTest" (no quotes) '
+ 'appears on the same line as words "called unexpectedly"'
+ ),
+ )
+
+ if (
+ 'CxxExceptionInDestructorTest.ThrowsExceptionInDestructor'
+ in EX_BINARY_OUTPUT
+ ):
def testCatchesCxxExceptionsInFixtureDestructor(self):
self.assertTrue(
'C++ exception with description '
'"Standard C++ exception" thrown '
- 'in the test fixture\'s destructor' in EX_BINARY_OUTPUT,
- EX_BINARY_OUTPUT)
+ "in the test fixture's destructor"
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
'CxxExceptionInDestructorTest::TearDownTestSuite() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
def testCatchesCxxExceptionsInSetUpTestCase(self):
self.assertTrue(
'C++ exception with description "Standard C++ exception"'
- ' thrown in SetUpTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
- self.assertTrue(
- 'CxxExceptionInConstructorTest::TearDownTestSuite() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ ' thrown in SetUpTestSuite()'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInSetUpTestSuiteTest constructor '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
- self.assertTrue(
- 'CxxExceptionInSetUpTestSuiteTest destructor '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
- self.assertTrue(
- 'CxxExceptionInSetUpTestSuiteTest::SetUp() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
- self.assertTrue(
- 'CxxExceptionInSetUpTestSuiteTest::TearDown() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
- self.assertTrue(
- 'CxxExceptionInSetUpTestSuiteTest test body '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInConstructorTest::TearDownTestSuite() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
+ self.assertFalse(
+ 'CxxExceptionInSetUpTestSuiteTest constructor called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
+ self.assertFalse(
+ 'CxxExceptionInSetUpTestSuiteTest destructor called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
+ self.assertFalse(
+ 'CxxExceptionInSetUpTestSuiteTest::SetUp() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
+ self.assertFalse(
+ 'CxxExceptionInSetUpTestSuiteTest::TearDown() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
+ self.assertFalse(
+ 'CxxExceptionInSetUpTestSuiteTest test body called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
def testCatchesCxxExceptionsInTearDownTestCase(self):
self.assertTrue(
'C++ exception with description "Standard C++ exception"'
- ' thrown in TearDownTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ ' thrown in TearDownTestSuite()'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
def testCatchesCxxExceptionsInSetUp(self):
self.assertTrue(
'C++ exception with description "Standard C++ exception"'
- ' thrown in SetUp()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ ' thrown in SetUp()'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
+ self.assertTrue(
+ 'CxxExceptionInSetUpTest::TearDownTestSuite() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInSetUpTest::TearDownTestSuite() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInSetUpTest destructor called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInSetUpTest destructor '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInSetUpTest::TearDown() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInSetUpTest::TearDown() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
- self.assert_('unexpected' not in EX_BINARY_OUTPUT,
- 'This failure belongs in this test only if '
- '"CxxExceptionInSetUpTest" (no quotes) '
- 'appears on the same line as words "called unexpectedly"')
+ 'unexpected' not in EX_BINARY_OUTPUT,
+ (
+ 'This failure belongs in this test only if '
+ '"CxxExceptionInSetUpTest" (no quotes) '
+ 'appears on the same line as words "called unexpectedly"'
+ ),
+ )
def testCatchesCxxExceptionsInTearDown(self):
self.assertTrue(
'C++ exception with description "Standard C++ exception"'
- ' thrown in TearDown()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ ' thrown in TearDown()'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInTearDownTest::TearDownTestSuite() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInTearDownTest::TearDownTestSuite() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInTearDownTest destructor '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInTearDownTest destructor called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
def testCatchesCxxExceptionsInTestBody(self):
self.assertTrue(
'C++ exception with description "Standard C++ exception"'
- ' thrown in the test body' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ ' thrown in the test body'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInTestBodyTest::TearDownTestSuite() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInTestBodyTest::TearDownTestSuite() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInTestBodyTest destructor '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInTestBodyTest destructor called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInTestBodyTest::TearDown() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInTestBodyTest::TearDown() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
def testCatchesNonStdCxxExceptions(self):
self.assertTrue(
'Unknown C++ exception thrown in the test body' in EX_BINARY_OUTPUT,
- EX_BINARY_OUTPUT)
+ EX_BINARY_OUTPUT,
+ )
def testUnhandledCxxExceptionsAbortTheProgram(self):
# Filters out SEH exception tests on Windows. Unhandled SEH exceptions
# cause tests to show pop-up windows there.
- FITLER_OUT_SEH_TESTS_FLAG = FILTER_FLAG + '=-*Seh*'
+ filter_out_seh_tests_flag = FILTER_FLAG + '=-*Seh*'
# By default, Google Test doesn't catch the exceptions.
uncaught_exceptions_ex_binary_output = gtest_test_utils.Subprocess(
- [EX_EXE_PATH,
- NO_CATCH_EXCEPTIONS_FLAG,
- FITLER_OUT_SEH_TESTS_FLAG],
- env=environ).output
-
- self.assert_('Unhandled C++ exception terminating the program'
- in uncaught_exceptions_ex_binary_output)
- self.assert_('unexpected' not in uncaught_exceptions_ex_binary_output)
+ [EX_EXE_PATH, NO_CATCH_EXCEPTIONS_FLAG, filter_out_seh_tests_flag],
+ env=environ,
+ ).output
+
+ self.assertIn(
+ 'Unhandled C++ exception terminating the program',
+ uncaught_exceptions_ex_binary_output,
+ )
+ self.assertNotIn('unexpected', uncaught_exceptions_ex_binary_output)
if __name__ == '__main__':
diff --git a/googletest/test/googletest-catch-exceptions-test_.cc b/googletest/test/googletest-catch-exceptions-test_.cc
index 8c127d40b11d..3c8f4f4b790c 100644
--- a/googletest/test/googletest-catch-exceptions-test_.cc
+++ b/googletest/test/googletest-catch-exceptions-test_.cc
@@ -32,18 +32,18 @@
// 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
diff --git a/googletest/test/googletest-color-test.py b/googletest/test/googletest-color-test.py
index f3b7c9990bcf..8926a48155b2 100755
--- a/googletest/test/googletest-color-test.py
+++ b/googletest/test/googletest-color-test.py
@@ -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'
@@ -65,62 +65,64 @@ def UsesColor(term, color_env_var, color_flag):
class GTestColorTest(gtest_test_utils.TestCase):
+
def testNoEnvVarNoFlag(self):
"""Tests the case when there's neither GTEST_COLOR nor --gtest_color."""
if not IS_WINDOWS:
- self.assert_(not UsesColor('dumb', None, None))
- self.assert_(not UsesColor('emacs', None, None))
- self.assert_(not UsesColor('xterm-mono', None, None))
- self.assert_(not UsesColor('unknown', None, None))
- self.assert_(not UsesColor(None, None, None))
- self.assert_(UsesColor('linux', None, None))
- self.assert_(UsesColor('cygwin', None, None))
- self.assert_(UsesColor('xterm', None, None))
- self.assert_(UsesColor('xterm-color', None, None))
- self.assert_(UsesColor('xterm-256color', None, None))
+ self.assertTrue(not UsesColor('dumb', None, None))
+ self.assertTrue(not UsesColor('emacs', None, None))
+ self.assertTrue(not UsesColor('xterm-mono', None, None))
+ self.assertTrue(not UsesColor('unknown', None, None))
+ self.assertTrue(not UsesColor(None, None, None))
+ self.assertTrue(UsesColor('linux', None, None))
+ self.assertTrue(UsesColor('cygwin', None, None))
+ self.assertTrue(UsesColor('xterm', None, None))
+ self.assertTrue(UsesColor('xterm-color', None, None))
+ self.assertTrue(UsesColor('xterm-kitty', None, None))
+ self.assertTrue(UsesColor('xterm-256color', None, None))
def testFlagOnly(self):
"""Tests the case when there's --gtest_color but not GTEST_COLOR."""
- self.assert_(not UsesColor('dumb', None, 'no'))
- self.assert_(not UsesColor('xterm-color', None, 'no'))
+ self.assertTrue(not UsesColor('dumb', None, 'no'))
+ self.assertTrue(not UsesColor('xterm-color', None, 'no'))
if not IS_WINDOWS:
- self.assert_(not UsesColor('emacs', None, 'auto'))
- self.assert_(UsesColor('xterm', None, 'auto'))
- self.assert_(UsesColor('dumb', None, 'yes'))
- self.assert_(UsesColor('xterm', None, 'yes'))
+ self.assertTrue(not UsesColor('emacs', None, 'auto'))
+ self.assertTrue(UsesColor('xterm', None, 'auto'))
+ self.assertTrue(UsesColor('dumb', None, 'yes'))
+ self.assertTrue(UsesColor('xterm', None, 'yes'))
def testEnvVarOnly(self):
"""Tests the case when there's GTEST_COLOR but not --gtest_color."""
- self.assert_(not UsesColor('dumb', 'no', None))
- self.assert_(not UsesColor('xterm-color', 'no', None))
+ self.assertTrue(not UsesColor('dumb', 'no', None))
+ self.assertTrue(not UsesColor('xterm-color', 'no', None))
if not IS_WINDOWS:
- self.assert_(not UsesColor('dumb', 'auto', None))
- self.assert_(UsesColor('xterm-color', 'auto', None))
- self.assert_(UsesColor('dumb', 'yes', None))
- self.assert_(UsesColor('xterm-color', 'yes', None))
+ self.assertTrue(not UsesColor('dumb', 'auto', None))
+ self.assertTrue(UsesColor('xterm-color', 'auto', None))
+ self.assertTrue(UsesColor('dumb', 'yes', None))
+ self.assertTrue(UsesColor('xterm-color', 'yes', None))
def testEnvVarAndFlag(self):
"""Tests the case when there are both GTEST_COLOR and --gtest_color."""
- self.assert_(not UsesColor('xterm-color', 'no', 'no'))
- self.assert_(UsesColor('dumb', 'no', 'yes'))
- self.assert_(UsesColor('xterm-color', 'no', 'auto'))
+ self.assertTrue(not UsesColor('xterm-color', 'no', 'no'))
+ self.assertTrue(UsesColor('dumb', 'no', 'yes'))
+ self.assertTrue(UsesColor('xterm-color', 'no', 'auto'))
def testAliasesOfYesAndNo(self):
"""Tests using aliases in specifying --gtest_color."""
- self.assert_(UsesColor('dumb', None, 'true'))
- self.assert_(UsesColor('dumb', None, 'YES'))
- self.assert_(UsesColor('dumb', None, 'T'))
- self.assert_(UsesColor('dumb', None, '1'))
+ self.assertTrue(UsesColor('dumb', None, 'true'))
+ self.assertTrue(UsesColor('dumb', None, 'YES'))
+ self.assertTrue(UsesColor('dumb', None, 'T'))
+ self.assertTrue(UsesColor('dumb', None, '1'))
- self.assert_(not UsesColor('xterm', None, 'f'))
- self.assert_(not UsesColor('xterm', None, 'false'))
- self.assert_(not UsesColor('xterm', None, '0'))
- self.assert_(not UsesColor('xterm', None, 'unknown'))
+ self.assertTrue(not UsesColor('xterm', None, 'f'))
+ self.assertTrue(not UsesColor('xterm', None, 'false'))
+ self.assertTrue(not UsesColor('xterm', None, '0'))
+ self.assertTrue(not UsesColor('xterm', None, 'unknown'))
if __name__ == '__main__':
diff --git a/googletest/test/googletest-color-test_.cc b/googletest/test/googletest-color-test_.cc
index 220a3a00548f..55657b7262b6 100644
--- a/googletest/test/googletest-color-test_.cc
+++ b/googletest/test/googletest-color-test_.cc
@@ -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);
diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc
index cba906ccd861..4cc81b723e4a 100644
--- a/googletest/test/googletest-death-test-test.cc
+++ b/googletest/test/googletest-death-test-test.cc
@@ -31,34 +31,36 @@
// Tests for death tests.
#include "gtest/gtest-death-test.h"
-
#include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h"
using testing::internal::AlwaysFalse;
using testing::internal::AlwaysTrue;
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
+
+#ifdef 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
-# 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
+#include <limits.h>
+#include <signal.h>
+#include <stdio.h>
-# include <limits.h>
-# include <signal.h>
-# include <stdio.h>
+#include <string>
+#include <vector>
-# if GTEST_OS_LINUX
-# include <sys/time.h>
-# endif // GTEST_OS_LINUX
+#ifdef 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 +92,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 +119,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 +139,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 +154,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 +173,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 +194,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
+#ifdef GTEST_OS_WINDOWS
// Death in dbg due to Windows CRT assertion failure, not opt.
int DieInCRTDebugElse12(int* sideeffect) {
@@ -224,7 +223,7 @@ int DieInCRTDebugElse12(int* sideeffect) {
#endif // GTEST_OS_WINDOWS
-# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
// Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) {
@@ -237,7 +236,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 +269,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,8 +295,15 @@ 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__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement.
@@ -313,31 +319,16 @@ 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())
;
else
EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
}
-
-# if GTEST_USES_PCRE
-
-void DieWithEmbeddedNul() {
- fprintf(stderr, "Hello%cmy null world.\n", '\0');
- fflush(stderr);
- _exit(1);
-}
-
-// Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
-// message has a NUL character in it.
-TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
- EXPECT_DEATH(DieWithEmbeddedNul(), "my null world");
- ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
-}
-
-# endif // GTEST_USES_PCRE
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
// Tests that death test macros expand to code which interacts well with switch
// statements.
@@ -347,12 +338,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_()
}
@@ -360,14 +351,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");
}
@@ -377,7 +368,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), "");
@@ -386,22 +377,25 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
ASSERT_DEATH(_exit(1), "");
}
-# if GTEST_OS_LINUX
-void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
+#ifdef GTEST_OS_LINUX
+void SigprofAction(int, siginfo_t*, void*) { /* no op */
+}
// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
void SetSigprofActionAndTimer() {
- struct itimerval timer;
- timer.it_interval.tv_sec = 0;
- timer.it_interval.tv_usec = 1;
- timer.it_value = timer.it_interval;
- ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
struct sigaction signal_action;
memset(&signal_action, 0, sizeof(signal_action));
sigemptyset(&signal_action.sa_mask);
signal_action.sa_sigaction = SigprofAction;
signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, nullptr));
+ // timer comes second, to avoid SIGPROF premature delivery, as suggested at
+ // https://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html
+ struct itimerval timer;
+ timer.it_interval.tv_sec = 0;
+ timer.it_interval.tv_usec = 1;
+ timer.it_value = timer.it_interval;
+ ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
}
// Disables ITIMER_PROF timer and ignores SIGPROF signal.
@@ -420,7 +414,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;
@@ -429,37 +423,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), "");
@@ -469,23 +463,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), "");
@@ -493,7 +485,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) {
@@ -515,16 +507,12 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
const testing::internal::RE regex(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex);
-# if !GTEST_USES_PCRE
-
const ::std::string regex_std_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_std_str);
// This one is tricky; a temporary pointer into another temporary. Reference
// lifetime extension of the pointer is not sufficient.
EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str());
-
-# endif // !GTEST_USES_PCRE
}
// Tests that a non-void function can be used in a death test.
@@ -539,9 +527,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) {
@@ -552,25 +538,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()
@@ -584,19 +573,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);
}
@@ -641,52 +631,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
+#ifdef 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:
@@ -701,20 +675,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;
@@ -722,18 +696,21 @@ void ExpectDebugDeathHelper(bool* aborted) {
*aborted = false;
}
-# if GTEST_OS_WINDOWS
+#ifdef 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.
@@ -824,83 +801,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
+#ifdef 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 !defined(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"
@@ -908,7 +888,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"),
@@ -919,7 +899,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");
}
@@ -933,8 +913,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_; }
@@ -976,17 +956,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_;
@@ -1011,7 +989,6 @@ class MockDeathTest : public DeathTest {
const bool passed_;
};
-
// MockDeathTestFactory constructor.
MockDeathTestFactory::MockDeathTestFactory()
: create_(true),
@@ -1021,13 +998,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;
@@ -1040,7 +1014,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.
@@ -1080,10 +1053,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;
+ },
+ "");
}
};
@@ -1168,8 +1143,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());
@@ -1185,12 +1159,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
@@ -1202,7 +1180,7 @@ TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
EXPECT_STREQ("", GetLastErrnoDescription().c_str());
}
-# if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
TEST(AutoHandleTest, AutoHandleWorks) {
HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
ASSERT_NE(INVALID_HANDLE_VALUE, handle);
@@ -1227,15 +1205,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
+#ifdef 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>.
@@ -1326,11 +1304,11 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
EXPECT_EQ(123, char_result);
}
-# if GTEST_OS_WINDOWS
+#ifdef 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.
@@ -1346,23 +1324,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) {
@@ -1374,7 +1356,11 @@ void DieWithMessage(const char* message) {
TEST(MatcherDeathTest, DoesNotBreakBareRegexMatching) {
// googletest tests this, of course; here we ensure that including googlemock
// has not broken it.
+#ifdef GTEST_USES_POSIX_RE
EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I d[aeiou]e");
+#else
+ EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I di?e");
+#endif
}
TEST(MatcherDeathTest, MonomorphicMatcherMatches) {
@@ -1462,6 +1448,13 @@ TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
namespace {
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement.
@@ -1479,14 +1472,16 @@ 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
else
EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
// Tests that conditional death test macros expand to code which interacts
// well with switch statements.
@@ -1496,21 +1491,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
diff --git a/googletest/test/googletest-death-test_ex_test.cc b/googletest/test/googletest-death-test_ex_test.cc
index 7ea5b9468e3b..34d55013b665 100644
--- a/googletest/test/googletest-death-test_ex_test.cc
+++ b/googletest/test/googletest-death-test_ex_test.cc
@@ -33,17 +33,17 @@
#include "gtest/gtest-death-test.h"
#include "gtest/gtest.h"
-#if GTEST_HAS_DEATH_TEST
+#ifdef 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,13 +53,13 @@ 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");
}
}
class TestException : public std::exception {
public:
- const char* what() const throw() override { return "exceptional message"; }
+ const char* what() const noexcept override { return "exceptional message"; }
};
TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
@@ -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();
}
diff --git a/googletest/test/googletest-env-var-test.py b/googletest/test/googletest-env-var-test.py
index 2f0e406afcfc..24d8edbbff80 100755
--- a/googletest/test/googletest-env-var-test.py
+++ b/googletest/test/googletest-env-var-test.py
@@ -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'
@@ -85,9 +85,12 @@ class GTestEnvVarTest(gtest_test_utils.TestCase):
TestFlag('break_on_failure', '1', '0')
TestFlag('color', 'yes', 'auto')
+ SetEnvVar('TESTBRIDGE_TEST_RUNNER_FAIL_FAST', None) # For 'fail_fast' test
+ TestFlag('fail_fast', '1', '0')
TestFlag('filter', 'FooTest.Bar', '*')
SetEnvVar('XML_OUTPUT_FILE', None) # For 'output' test
TestFlag('output', 'xml:tmp/foo.xml', '')
+ TestFlag('brief', '1', '0')
TestFlag('print_time', '0', '1')
TestFlag('repeat', '999', '1')
TestFlag('throw_on_failure', '1', '0')
@@ -98,7 +101,6 @@ class GTestEnvVarTest(gtest_test_utils.TestCase):
TestFlag('death_test_use_fork', '1', '0')
TestFlag('stack_trace_depth', '0', '100')
-
def testXmlOutputFile(self):
"""Tests that $XML_OUTPUT_FILE affects the output flag."""
@@ -113,5 +115,6 @@ class GTestEnvVarTest(gtest_test_utils.TestCase):
SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml')
AssertEq('xml:tmp/foo.xml', GetFlag('output'))
+
if __name__ == '__main__':
gtest_test_utils.Main()
diff --git a/googletest/test/googletest-env-var-test_.cc b/googletest/test/googletest-env-var-test_.cc
index fd2aa82f74fa..365337508027 100644
--- a/googletest/test/googletest-env-var-test_.cc
+++ b/googletest/test/googletest-env-var-test_.cc
@@ -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,62 +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_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_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;
}
diff --git a/googletest/test/googletest-failfast-unittest.py b/googletest/test/googletest-failfast-unittest.py
new file mode 100755
index 000000000000..cdbce0c5d762
--- /dev/null
+++ b/googletest/test/googletest-failfast-unittest.py
@@ -0,0 +1,461 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google Inc. All Rights Reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Unit test for Google Test fail_fast.
+
+A user can specify if a Google Test program should continue test execution
+after a test failure via the GTEST_FAIL_FAST environment variable or the
+--gtest_fail_fast flag. The default value of the flag can also be changed
+by Bazel fail fast environment variable TESTBRIDGE_TEST_RUNNER_FAIL_FAST.
+
+This script tests such functionality by invoking googletest-failfast-unittest_
+(a program written with Google Test) with different environments and command
+line flags.
+"""
+
+import os
+from googletest.test import gtest_test_utils
+
+# Constants.
+
+# Bazel testbridge environment variable for fail fast
+BAZEL_FAIL_FAST_ENV_VAR = 'TESTBRIDGE_TEST_RUNNER_FAIL_FAST'
+
+# The environment variable for specifying fail fast.
+FAIL_FAST_ENV_VAR = 'GTEST_FAIL_FAST'
+
+# The command line flag for specifying fail fast.
+FAIL_FAST_FLAG = 'gtest_fail_fast'
+
+# The command line flag to run disabled tests.
+RUN_DISABLED_FLAG = 'gtest_also_run_disabled_tests'
+
+# The command line flag for specifying a filter.
+FILTER_FLAG = 'gtest_filter'
+
+# Command to run the googletest-failfast-unittest_ program.
+COMMAND = gtest_test_utils.GetTestExecutablePath(
+ 'googletest-failfast-unittest_'
+)
+
+# The command line flag to tell Google Test to output the list of tests it
+# will run.
+LIST_TESTS_FLAG = '--gtest_list_tests'
+
+# Indicates whether Google Test supports death tests.
+SUPPORTS_DEATH_TESTS = (
+ 'HasDeathTest'
+ in gtest_test_utils.Subprocess([COMMAND, LIST_TESTS_FLAG]).output
+)
+
+# Utilities.
+
+environ = os.environ.copy()
+
+
+def SetEnvVar(env_var, value):
+ """Sets the env variable to 'value'; unsets it when 'value' is None."""
+
+ if value is not None:
+ environ[env_var] = value
+ elif env_var in environ:
+ del environ[env_var]
+
+
+def RunAndReturnOutput(test_suite=None, fail_fast=None, run_disabled=False):
+ """Runs the test program and returns its output."""
+
+ args = []
+ xml_path = os.path.join(
+ gtest_test_utils.GetTempDir(), '.GTestFailFastUnitTest.xml'
+ )
+ args += ['--gtest_output=xml:' + xml_path]
+ if fail_fast is not None:
+ if isinstance(fail_fast, str):
+ args += ['--%s=%s' % (FAIL_FAST_FLAG, fail_fast)]
+ elif fail_fast:
+ args += ['--%s' % FAIL_FAST_FLAG]
+ else:
+ args += ['--no%s' % FAIL_FAST_FLAG]
+ if test_suite:
+ args += ['--%s=%s.*' % (FILTER_FLAG, test_suite)]
+ if run_disabled:
+ args += ['--%s' % RUN_DISABLED_FLAG]
+ txt_out = gtest_test_utils.Subprocess([COMMAND] + args, env=environ).output
+ with open(xml_path) as xml_file:
+ return txt_out, xml_file.read()
+
+
+# The unit test.
+class GTestFailFastUnitTest(gtest_test_utils.TestCase):
+ """Tests the env variable or the command line flag for fail_fast."""
+
+ def testDefaultBehavior(self):
+ """Tests the behavior of not specifying the fail_fast."""
+
+ txt, _ = RunAndReturnOutput()
+ self.assertIn('22 FAILED TEST', txt)
+
+ def testGoogletestFlag(self):
+ txt, _ = RunAndReturnOutput(test_suite='HasSimpleTest', fail_fast=True)
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+
+ txt, _ = RunAndReturnOutput(test_suite='HasSimpleTest', fail_fast=False)
+ self.assertIn('4 FAILED TEST', txt)
+ self.assertNotIn('[ SKIPPED ]', txt)
+
+ def testGoogletestEnvVar(self):
+ """Tests the behavior of specifying fail_fast via Googletest env var."""
+
+ try:
+ SetEnvVar(FAIL_FAST_ENV_VAR, '1')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+
+ SetEnvVar(FAIL_FAST_ENV_VAR, '0')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('4 FAILED TEST', txt)
+ self.assertNotIn('[ SKIPPED ]', txt)
+ finally:
+ SetEnvVar(FAIL_FAST_ENV_VAR, None)
+
+ def testBazelEnvVar(self):
+ """Tests the behavior of specifying fail_fast via Bazel testbridge."""
+
+ try:
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '1')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '0')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('4 FAILED TEST', txt)
+ self.assertNotIn('[ SKIPPED ]', txt)
+ finally:
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, None)
+
+ def testFlagOverridesEnvVar(self):
+ """Tests precedence of flag over env var."""
+
+ try:
+ SetEnvVar(FAIL_FAST_ENV_VAR, '0')
+ txt, _ = RunAndReturnOutput('HasSimpleTest', True)
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+ finally:
+ SetEnvVar(FAIL_FAST_ENV_VAR, None)
+
+ def testGoogletestEnvVarOverridesBazelEnvVar(self):
+ """Tests that the Googletest native env var over Bazel testbridge."""
+
+ try:
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '0')
+ SetEnvVar(FAIL_FAST_ENV_VAR, '1')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+ finally:
+ SetEnvVar(FAIL_FAST_ENV_VAR, None)
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, None)
+
+ def testEventListener(self):
+ txt, _ = RunAndReturnOutput(test_suite='HasSkipTest', fail_fast=True)
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+ for expected_count, callback in [
+ (1, 'OnTestSuiteStart'),
+ (5, 'OnTestStart'),
+ (5, 'OnTestEnd'),
+ (5, 'OnTestPartResult'),
+ (1, 'OnTestSuiteEnd'),
+ ]:
+ self.assertEqual(
+ expected_count,
+ txt.count(callback),
+ 'Expected %d calls to callback %s match count on output: %s '
+ % (expected_count, callback, txt),
+ )
+
+ txt, _ = RunAndReturnOutput(test_suite='HasSkipTest', fail_fast=False)
+ self.assertIn('3 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 1 test', txt)
+ for expected_count, callback in [
+ (1, 'OnTestSuiteStart'),
+ (5, 'OnTestStart'),
+ (5, 'OnTestEnd'),
+ (5, 'OnTestPartResult'),
+ (1, 'OnTestSuiteEnd'),
+ ]:
+ self.assertEqual(
+ expected_count,
+ txt.count(callback),
+ 'Expected %d calls to callback %s match count on output: %s '
+ % (expected_count, callback, txt),
+ )
+
+ def assertXmlResultCount(self, result, count, xml):
+ self.assertEqual(
+ count,
+ xml.count('result="%s"' % result),
+ 'Expected \'result="%s"\' match count of %s: %s '
+ % (result, count, xml),
+ )
+
+ def assertXmlStatusCount(self, status, count, xml):
+ self.assertEqual(
+ count,
+ xml.count('status="%s"' % status),
+ 'Expected \'status="%s"\' match count of %s: %s '
+ % (status, count, xml),
+ )
+
+ def assertFailFastXmlAndTxtOutput(
+ self,
+ fail_fast,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False,
+ ):
+ """Assert XML and text output of a test execution."""
+
+ txt, xml = RunAndReturnOutput(test_suite, fail_fast, run_disabled)
+ if failure_count > 0:
+ self.assertIn('%s FAILED TEST' % failure_count, txt)
+ if suppressed_count > 0:
+ self.assertIn('%s DISABLED TEST' % suppressed_count, txt)
+ if skipped_count > 0:
+ self.assertIn('[ SKIPPED ] %s tests' % skipped_count, txt)
+ self.assertXmlStatusCount(
+ 'run', passed_count + failure_count + skipped_count, xml
+ )
+ self.assertXmlStatusCount('notrun', suppressed_count, xml)
+ self.assertXmlResultCount('completed', passed_count + failure_count, xml)
+ self.assertXmlResultCount('skipped', skipped_count, xml)
+ self.assertXmlResultCount('suppressed', suppressed_count, xml)
+
+ def assertFailFastBehavior(
+ self,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False,
+ ):
+ """Assert --fail_fast via flag."""
+
+ for fail_fast in ('true', '1', 't', True):
+ self.assertFailFastXmlAndTxtOutput(
+ fail_fast,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled,
+ )
+
+ def assertNotFailFastBehavior(
+ self,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False,
+ ):
+ """Assert --nofail_fast via flag."""
+
+ for fail_fast in ('false', '0', 'f', False):
+ self.assertFailFastXmlAndTxtOutput(
+ fail_fast,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled,
+ )
+
+ def testFlag_HasFixtureTest(self):
+ """Tests the behavior of fail_fast and TEST_F."""
+ self.assertFailFastBehavior(
+ test_suite='HasFixtureTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0,
+ )
+ self.assertNotFailFastBehavior(
+ test_suite='HasFixtureTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0,
+ )
+
+ def testFlag_HasSimpleTest(self):
+ """Tests the behavior of fail_fast and TEST."""
+ self.assertFailFastBehavior(
+ test_suite='HasSimpleTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0,
+ )
+ self.assertNotFailFastBehavior(
+ test_suite='HasSimpleTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0,
+ )
+
+ def testFlag_HasParametersTest(self):
+ """Tests the behavior of fail_fast and TEST_P."""
+ self.assertFailFastBehavior(
+ test_suite='HasParametersSuite/HasParametersTest',
+ passed_count=0,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0,
+ )
+ self.assertNotFailFastBehavior(
+ test_suite='HasParametersSuite/HasParametersTest',
+ passed_count=0,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0,
+ )
+
+ def testFlag_HasDisabledTest(self):
+ """Tests the behavior of fail_fast and Disabled test cases."""
+ self.assertFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=2,
+ suppressed_count=1,
+ run_disabled=False,
+ )
+ self.assertNotFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=3,
+ skipped_count=0,
+ suppressed_count=1,
+ run_disabled=False,
+ )
+
+ def testFlag_HasDisabledRunDisabledTest(self):
+ """Tests the behavior of fail_fast and Disabled test cases enabled."""
+ self.assertFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0,
+ run_disabled=True,
+ )
+ self.assertNotFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0,
+ run_disabled=True,
+ )
+
+ def testFlag_HasDisabledSuiteTest(self):
+ """Tests the behavior of fail_fast and Disabled test suites."""
+ self.assertFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=0,
+ failure_count=0,
+ skipped_count=0,
+ suppressed_count=5,
+ run_disabled=False,
+ )
+ self.assertNotFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=0,
+ failure_count=0,
+ skipped_count=0,
+ suppressed_count=5,
+ run_disabled=False,
+ )
+
+ def testFlag_HasDisabledSuiteRunDisabledTest(self):
+ """Tests the behavior of fail_fast and Disabled test suites enabled."""
+ self.assertFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0,
+ run_disabled=True,
+ )
+ self.assertNotFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0,
+ run_disabled=True,
+ )
+
+ if SUPPORTS_DEATH_TESTS:
+
+ def testFlag_HasDeathTest(self):
+ """Tests the behavior of fail_fast and death tests."""
+ self.assertFailFastBehavior(
+ test_suite='HasDeathTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0,
+ )
+ self.assertNotFailFastBehavior(
+ test_suite='HasDeathTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0,
+ )
+
+
+if __name__ == '__main__':
+ gtest_test_utils.Main()
diff --git a/googletest/test/googletest-failfast-unittest_.cc b/googletest/test/googletest-failfast-unittest_.cc
new file mode 100644
index 000000000000..3bd05a8eb293
--- /dev/null
+++ b/googletest/test/googletest-failfast-unittest_.cc
@@ -0,0 +1,166 @@
+// Copyright 2005, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Unit test for Google Test test filters.
+//
+// A user can specify which test(s) in a Google Test program to run via
+// either the GTEST_FILTER environment variable or the --gtest_filter
+// flag. This is used for testing such functionality.
+//
+// The program will be invoked from a Python unit test. Don't run it
+// directly.
+
+#include "gtest/gtest.h"
+
+namespace {
+
+// Test HasFixtureTest.
+
+class HasFixtureTest : public testing::Test {};
+
+TEST_F(HasFixtureTest, Test0) {}
+
+TEST_F(HasFixtureTest, Test1) { FAIL() << "Expected failure."; }
+
+TEST_F(HasFixtureTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST_F(HasFixtureTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST_F(HasFixtureTest, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasSimpleTest.
+
+TEST(HasSimpleTest, Test0) {}
+
+TEST(HasSimpleTest, Test1) { FAIL() << "Expected failure."; }
+
+TEST(HasSimpleTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST(HasSimpleTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST(HasSimpleTest, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasDisabledTest.
+
+TEST(HasDisabledTest, Test0) {}
+
+TEST(HasDisabledTest, DISABLED_Test1) { FAIL() << "Expected failure."; }
+
+TEST(HasDisabledTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST(HasDisabledTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST(HasDisabledTest, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasDeathTest
+
+TEST(HasDeathTest, Test0) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); }
+
+TEST(HasDeathTest, Test1) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+TEST(HasDeathTest, Test2) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+TEST(HasDeathTest, Test3) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+TEST(HasDeathTest, Test4) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+// Test DISABLED_HasDisabledSuite
+
+TEST(DISABLED_HasDisabledSuite, Test0) {}
+
+TEST(DISABLED_HasDisabledSuite, Test1) { FAIL() << "Expected failure."; }
+
+TEST(DISABLED_HasDisabledSuite, Test2) { FAIL() << "Expected failure."; }
+
+TEST(DISABLED_HasDisabledSuite, Test3) { FAIL() << "Expected failure."; }
+
+TEST(DISABLED_HasDisabledSuite, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasParametersTest
+
+class HasParametersTest : public testing::TestWithParam<int> {};
+
+TEST_P(HasParametersTest, Test1) { FAIL() << "Expected failure."; }
+
+TEST_P(HasParametersTest, Test2) { FAIL() << "Expected failure."; }
+
+INSTANTIATE_TEST_SUITE_P(HasParametersSuite, HasParametersTest,
+ testing::Values(1, 2));
+
+class MyTestListener : public ::testing::EmptyTestEventListener {
+ void OnTestSuiteStart(const ::testing::TestSuite& test_suite) override {
+ printf("We are in OnTestSuiteStart of %s.\n", test_suite.name());
+ }
+
+ void OnTestStart(const ::testing::TestInfo& test_info) override {
+ printf("We are in OnTestStart of %s.%s.\n", test_info.test_suite_name(),
+ test_info.name());
+ }
+
+ void OnTestPartResult(
+ const ::testing::TestPartResult& test_part_result) override {
+ printf("We are in OnTestPartResult %s:%d.\n", test_part_result.file_name(),
+ test_part_result.line_number());
+ }
+
+ void OnTestEnd(const ::testing::TestInfo& test_info) override {
+ printf("We are in OnTestEnd of %s.%s.\n", test_info.test_suite_name(),
+ test_info.name());
+ }
+
+ void OnTestSuiteEnd(const ::testing::TestSuite& test_suite) override {
+ printf("We are in OnTestSuiteEnd of %s.\n", test_suite.name());
+ }
+};
+
+TEST(HasSkipTest, Test0) { SUCCEED() << "Expected success."; }
+
+TEST(HasSkipTest, Test1) { GTEST_SKIP() << "Expected skip."; }
+
+TEST(HasSkipTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST(HasSkipTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST(HasSkipTest, Test4) { FAIL() << "Expected failure."; }
+
+} // namespace
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ ::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener());
+ return RUN_ALL_TESTS();
+}
diff --git a/googletest/test/googletest-filepath-test.cc b/googletest/test/googletest-filepath-test.cc
index aafad36f3fef..3e9c79f037be 100644
--- a/googletest/test/googletest-filepath-test.cc
+++ b/googletest/test/googletest-filepath-test.cc
@@ -35,36 +35,38 @@
// This file is #included from gtest-internal.h.
// Do not #include this file anywhere else!
-#include "gtest/internal/gtest-filepath.h"
+#include <string>
+
#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
-#elif GTEST_OS_WINDOWS
-# include <direct.h> // NOLINT
-#endif // GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
+#include <windows.h> // NOLINT
+#elif defined(GTEST_OS_WINDOWS)
+#include <direct.h> // NOLINT
+#endif // GTEST_OS_WINDOWS_MOBILE
namespace testing {
namespace internal {
namespace {
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// Windows CE doesn't have the remove C function.
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 +80,18 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) {
const FilePath cwd = FilePath::GetCurrentDir();
posix::ChDir(original_dir.c_str());
-# if GTEST_OS_WINDOWS || GTEST_OS_OS2
+#if defined(GTEST_OS_WINDOWS) || defined(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 +114,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_
@@ -171,7 +174,7 @@ TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileNameForAlternateSeparator) {
// RemoveFileName "" -> "./"
TEST(RemoveFileNameTest, EmptyName) {
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// On Windows CE, we use the root as the current directory.
EXPECT_EQ(GTEST_PATH_SEP_, FilePath("").RemoveFileName().string());
#else
@@ -182,7 +185,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 +197,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 +239,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 +286,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 +296,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 +308,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 +333,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 +345,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.
+#ifdef 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] = ':';
@@ -366,7 +369,7 @@ TEST(DirectoryTest, RootDirectoryExists) {
#endif // GTEST_OS_WINDOWS
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
TEST(DirectoryTest, RootOfWrongDriveDoesNotExists) {
const int saved_drive_ = _getdrive();
// Find a drive that doesn't exist. Start with 'Z' to avoid common ones.
@@ -384,7 +387,7 @@ TEST(DirectoryTest, RootOfWrongDriveDoesNotExists) {
}
#endif // GTEST_OS_WINDOWS
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
// Windows CE _does_ consider an empty directory to exist.
TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {
EXPECT_FALSE(FilePath("").DirectoryExists());
@@ -392,13 +395,13 @@ TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {
#endif // !GTEST_OS_WINDOWS_MOBILE
TEST(DirectoryTest, CurrentDirectoryExists) {
-#if GTEST_OS_WINDOWS // We are on Windows.
-# ifndef _WIN32_CE // Windows CE doesn't have a current directory.
+#ifdef GTEST_OS_WINDOWS // We are on Windows.
+#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 +409,40 @@ 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());
+#ifdef GTEST_OS_WINDOWS
+ EXPECT_EQ(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar",
+ FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
+#else
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());
+#endif
+ EXPECT_EQ(
+ GTEST_PATH_SEP_ "bar",
+ FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
}
// "foo/" == foo//" == "foo///"
-TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
- EXPECT_EQ("foo" GTEST_PATH_SEP_,
- FilePath("foo" GTEST_PATH_SEP_).string());
+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_ 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 +451,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 +485,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());
@@ -508,12 +515,12 @@ class DirectoryCreationTest : public Test {
}
// Strings representing a directory and a file, with identical paths
- // except for the trailing separator character that distinquishes
+ // except for the trailing separator character that distinguishes
// 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 +537,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 +547,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());
@@ -613,20 +620,25 @@ TEST(FilePathTest, IsDirectory) {
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());
+#ifdef GTEST_OS_WINDOWS
+ 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());
+ EXPECT_TRUE(FilePath("d:/Windows").IsAbsolutePath());
+ EXPECT_TRUE(FilePath("\\\\Host\\Share").IsAbsolutePath());
+ EXPECT_TRUE(FilePath("\\\\Host\\Share\\Folder").IsAbsolutePath());
#else
EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
- .IsAbsolutePath());
+ .IsAbsolutePath());
#endif // GTEST_OS_WINDOWS
}
TEST(FilePathTest, IsRootDirectory) {
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
EXPECT_TRUE(FilePath("a:\\").IsRootDirectory());
EXPECT_TRUE(FilePath("Z:/").IsRootDirectory());
EXPECT_TRUE(FilePath("e://").IsRootDirectory());
@@ -635,6 +647,16 @@ TEST(FilePathTest, IsRootDirectory) {
EXPECT_FALSE(FilePath("b:a").IsRootDirectory());
EXPECT_FALSE(FilePath("8:/").IsRootDirectory());
EXPECT_FALSE(FilePath("c|/").IsRootDirectory());
+ EXPECT_TRUE(FilePath("c:/").IsRootDirectory());
+ EXPECT_FALSE(FilePath("d:/Windows").IsRootDirectory());
+
+ // This is for backward compatibility, since callers (even in this library)
+ // have assumed IsRootDirectory() implies a trailing directory separator.
+ EXPECT_FALSE(FilePath("\\\\Host\\Share").IsRootDirectory());
+
+ EXPECT_TRUE(FilePath("\\\\Host\\Share\\").IsRootDirectory());
+ EXPECT_FALSE(FilePath("\\\\Host\\Share\\.").IsRootDirectory());
+ EXPECT_FALSE(FilePath("\\\\Host\\Share\\C$\\").IsRootDirectory());
#else
EXPECT_TRUE(FilePath("/").IsRootDirectory());
EXPECT_TRUE(FilePath("//").IsRootDirectory());
diff --git a/googletest/test/googletest-filter-unittest.py b/googletest/test/googletest-filter-unittest.py
index 6b32f2d21997..f1f3c7a513be 100755
--- a/googletest/test/googletest-filter-unittest.py
+++ b/googletest/test/googletest-filter-unittest.py
@@ -42,12 +42,13 @@ we test that here also.
import os
import re
+
try:
from sets import Set as set # For Python 2.3 compatibility
except ImportError:
pass
import sys
-import gtest_test_utils
+from googletest.test import gtest_test_utils
# Constants.
@@ -60,7 +61,8 @@ CAN_PASS_EMPTY_ENV = False
if sys.executable:
os.environ['EMPTY_VAR'] = ''
child = gtest_test_utils.Subprocess(
- [sys.executable, '-c', 'import os; print(\'EMPTY_VAR\' in os.environ)'])
+ [sys.executable, '-c', "import os; print('EMPTY_VAR' in os.environ)"]
+ )
CAN_PASS_EMPTY_ENV = eval(child.output)
@@ -75,8 +77,8 @@ if sys.executable:
os.environ['UNSET_VAR'] = 'X'
del os.environ['UNSET_VAR']
child = gtest_test_utils.Subprocess(
- [sys.executable, '-c', 'import os; print(\'UNSET_VAR\' not in os.environ)'
- ])
+ [sys.executable, '-c', "import os; print('UNSET_VAR' not in os.environ)"]
+ )
CAN_UNSET_ENV = eval(child.output)
@@ -84,7 +86,7 @@ if sys.executable:
# make sense on platforms that cannot pass empty env variables (Win32)
# and on platforms that cannot unset variables (since we cannot tell
# the difference between "" and NULL -- Borland and Solaris < 5.10)
-CAN_TEST_EMPTY_FILTER = (CAN_PASS_EMPTY_ENV and CAN_UNSET_ENV)
+CAN_TEST_EMPTY_FILTER = CAN_PASS_EMPTY_ENV and CAN_UNSET_ENV
# The environment variable for specifying the test filters.
@@ -113,13 +115,18 @@ 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'
# Indicates whether Google Test supports death tests.
-SUPPORTS_DEATH_TESTS = 'HasDeathTest' in gtest_test_utils.Subprocess(
- [COMMAND, LIST_TESTS_FLAG]).output
+SUPPORTS_DEATH_TESTS = (
+ 'HasDeathTest'
+ in gtest_test_utils.Subprocess([COMMAND, LIST_TESTS_FLAG]).output
+)
# Full names of all tests in googletest-filter-unittests_.
PARAM_TESTS = [
@@ -131,7 +138,7 @@ PARAM_TESTS = [
'SeqQ/ParamTest.TestX/1',
'SeqQ/ParamTest.TestY/0',
'SeqQ/ParamTest.TestY/1',
- ]
+]
DISABLED_TESTS = [
'BarTest.DISABLED_TestFour',
@@ -140,29 +147,31 @@ DISABLED_TESTS = [
'DISABLED_FoobarTest.Test1',
'DISABLED_FoobarTest.DISABLED_Test2',
'DISABLED_FoobarbazTest.TestA',
- ]
+]
if SUPPORTS_DEATH_TESTS:
DEATH_TESTS = [
- 'HasDeathTest.Test1',
- 'HasDeathTest.Test2',
- ]
+ 'HasDeathTest.Test1',
+ 'HasDeathTest.Test2',
+ ]
else:
DEATH_TESTS = []
# All the non-disabled tests.
-ACTIVE_TESTS = [
- 'FooTest.Abc',
- 'FooTest.Xyz',
-
- 'BarTest.TestOne',
- 'BarTest.TestTwo',
- 'BarTest.TestThree',
-
- 'BazTest.TestOne',
- 'BazTest.TestA',
- 'BazTest.TestB',
- ] + DEATH_TESTS + PARAM_TESTS
+ACTIVE_TESTS = (
+ [
+ 'FooTest.Abc',
+ 'FooTest.Xyz',
+ 'BarTest.TestOne',
+ 'BarTest.TestTwo',
+ 'BarTest.TestThree',
+ 'BazTest.TestOne',
+ 'BazTest.TestA',
+ 'BazTest.TestB',
+ ]
+ + DEATH_TESTS
+ + PARAM_TESTS
+)
param_tests_present = None
@@ -180,14 +189,15 @@ def SetEnvVar(env_var, value):
del environ[env_var]
-def RunAndReturnOutput(args = None):
+def RunAndReturnOutput(args=None):
"""Runs the test program and returns its output."""
- return gtest_test_utils.Subprocess([COMMAND] + (args or []),
- env=environ).output
+ return gtest_test_utils.Subprocess(
+ [COMMAND] + (args or []), env=environ
+ ).output
-def RunAndExtractTestList(args = None):
+def RunAndExtractTestList(args=None):
"""Runs the test program and returns its exit code and a list of tests run."""
p = gtest_test_utils.Subprocess([COMMAND] + (args or []), env=environ)
@@ -206,6 +216,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:
@@ -220,10 +241,13 @@ def InvokeWithModifiedEnv(extra_env, function, *args, **kwargs):
def RunWithSharding(total_shards, shard_index, command):
"""Runs a test program shard and returns exit code and a list of tests run."""
- extra_env = {SHARD_INDEX_ENV_VAR: str(shard_index),
- TOTAL_SHARDS_ENV_VAR: str(total_shards)}
+ extra_env = {
+ SHARD_INDEX_ENV_VAR: str(shard_index),
+ TOTAL_SHARDS_ENV_VAR: str(total_shards),
+ }
return InvokeWithModifiedEnv(extra_env, RunAndExtractTestList, command)
+
# The unit test.
@@ -236,10 +260,10 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
"""Asserts that two sets are equal."""
for elem in lhs:
- self.assert_(elem in rhs, '%s in %s' % (elem, rhs))
+ self.assertTrue(elem in rhs, '%s in %s' % (elem, rhs))
for elem in rhs:
- self.assert_(elem in lhs, '%s in %s' % (elem, lhs))
+ self.assertTrue(elem in lhs, '%s in %s' % (elem, lhs))
def AssertPartitionIsValid(self, set_var, list_of_sets):
"""Asserts that list_of_sets is a valid partition of set_var."""
@@ -271,13 +295,13 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
# into a process using the environment variable. However, we can still
# test the case when the variable is not supplied (i.e., gtest_filter is
# None).
- # pylint: disable-msg=C6403
+ # pylint: disable=g-explicit-bool-comparison
if CAN_TEST_EMPTY_FILTER or gtest_filter != '':
SetEnvVar(FILTER_ENV_VAR, gtest_filter)
tests_run = RunAndExtractTestList()[0]
SetEnvVar(FILTER_ENV_VAR, None)
self.AssertSetEqual(tests_run, tests_to_run)
- # pylint: enable-msg=C6403
+ # pylint: enable=g-explicit-bool-comparison
# Next, tests using the command line flag.
@@ -289,8 +313,14 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
tests_run = RunAndExtractTestList(args)[0]
self.AssertSetEqual(tests_run, tests_to_run)
- def RunAndVerifyWithSharding(self, gtest_filter, total_shards, tests_to_run,
- args=None, check_exit_0=False):
+ def RunAndVerifyWithSharding(
+ self,
+ gtest_filter,
+ total_shards,
+ tests_to_run,
+ args=None,
+ check_exit_0=False,
+ ):
"""Checks that binary runs correct tests for the given filter and shard.
Runs all shards of googletest-filter-unittest_ with the given filter, and
@@ -302,9 +332,9 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
gtest_filter: A filter to apply to the tests.
total_shards: A total number of shards to split test run into.
tests_to_run: A set of tests expected to run.
- args : Arguments to pass to the to the test binary.
- check_exit_0: When set to a true value, make sure that all shards
- return 0.
+ args: Arguments to pass to the to the test binary.
+ check_exit_0: When set to a true value, make sure that all shards return
+ 0.
"""
tests_to_run = self.AdjustForParameterizedTests(tests_to_run)
@@ -314,7 +344,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
# into a process using the environment variable. However, we can still
# test the case when the variable is not supplied (i.e., gtest_filter is
# None).
- # pylint: disable-msg=C6403
+ # pylint: disable=g-explicit-bool-comparison
if CAN_TEST_EMPTY_FILTER or gtest_filter != '':
SetEnvVar(FILTER_ENV_VAR, gtest_filter)
partition = []
@@ -326,7 +356,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
self.AssertPartitionIsValid(tests_to_run, partition)
SetEnvVar(FILTER_ENV_VAR, None)
- # pylint: enable-msg=C6403
+ # pylint: enable=g-explicit-bool-comparison
def RunAndVerifyAllowingDisabled(self, gtest_filter, tests_to_run):
"""Checks that the binary runs correct set of tests for the given filter.
@@ -358,8 +388,9 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
global param_tests_present
if param_tests_present is None:
- param_tests_present = PARAM_TEST_REGEX.search(
- RunAndReturnOutput()) is not None
+ param_tests_present = (
+ PARAM_TEST_REGEX.search(RunAndReturnOutput()) is not None
+ )
def testDefaultBehavior(self):
"""Tests the behavior of not specifying the filter."""
@@ -411,8 +442,9 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
BAZ_TESTS = ['BazTest.TestOne', 'BazTest.TestA', 'BazTest.TestB']
self.RunAndVerify('BazTest.*', BAZ_TESTS)
- self.RunAndVerifyAllowingDisabled('BazTest.*',
- BAZ_TESTS + ['BazTest.DISABLED_TestC'])
+ self.RunAndVerifyAllowingDisabled(
+ 'BazTest.*', BAZ_TESTS + ['BazTest.DISABLED_TestC']
+ )
def testFilterByTest(self):
"""Tests filtering by test name."""
@@ -423,38 +455,50 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
"""Select only the disabled tests to run."""
self.RunAndVerify('DISABLED_FoobarTest.Test1', [])
- self.RunAndVerifyAllowingDisabled('DISABLED_FoobarTest.Test1',
- ['DISABLED_FoobarTest.Test1'])
+ self.RunAndVerifyAllowingDisabled(
+ 'DISABLED_FoobarTest.Test1', ['DISABLED_FoobarTest.Test1']
+ )
self.RunAndVerify('*DISABLED_*', [])
self.RunAndVerifyAllowingDisabled('*DISABLED_*', DISABLED_TESTS)
self.RunAndVerify('*.DISABLED_*', [])
- self.RunAndVerifyAllowingDisabled('*.DISABLED_*', [
- 'BarTest.DISABLED_TestFour',
- 'BarTest.DISABLED_TestFive',
- 'BazTest.DISABLED_TestC',
- 'DISABLED_FoobarTest.DISABLED_Test2',
- ])
+ self.RunAndVerifyAllowingDisabled(
+ '*.DISABLED_*',
+ [
+ 'BarTest.DISABLED_TestFour',
+ 'BarTest.DISABLED_TestFive',
+ 'BazTest.DISABLED_TestC',
+ 'DISABLED_FoobarTest.DISABLED_Test2',
+ ],
+ )
self.RunAndVerify('DISABLED_*', [])
- self.RunAndVerifyAllowingDisabled('DISABLED_*', [
- 'DISABLED_FoobarTest.Test1',
- 'DISABLED_FoobarTest.DISABLED_Test2',
- 'DISABLED_FoobarbazTest.TestA',
- ])
+ self.RunAndVerifyAllowingDisabled(
+ 'DISABLED_*',
+ [
+ 'DISABLED_FoobarTest.Test1',
+ 'DISABLED_FoobarTest.DISABLED_Test2',
+ 'DISABLED_FoobarbazTest.TestA',
+ ],
+ )
def testWildcardInTestCaseName(self):
"""Tests using wildcard in the test case name."""
- self.RunAndVerify('*a*.*', [
- 'BarTest.TestOne',
- 'BarTest.TestTwo',
- 'BarTest.TestThree',
-
- 'BazTest.TestOne',
- 'BazTest.TestA',
- 'BazTest.TestB', ] + DEATH_TESTS + PARAM_TESTS)
+ self.RunAndVerify(
+ '*a*.*',
+ [
+ 'BarTest.TestOne',
+ 'BarTest.TestTwo',
+ 'BarTest.TestThree',
+ 'BazTest.TestOne',
+ 'BazTest.TestA',
+ 'BazTest.TestB',
+ ]
+ + DEATH_TESTS
+ + PARAM_TESTS,
+ )
def testWildcardInTestName(self):
"""Tests using wildcard in the test name."""
@@ -464,23 +508,27 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
def testFilterWithoutDot(self):
"""Tests a filter that has no '.' in it."""
- self.RunAndVerify('*z*', [
- 'FooTest.Xyz',
-
- 'BazTest.TestOne',
- 'BazTest.TestA',
- 'BazTest.TestB',
- ])
+ self.RunAndVerify(
+ '*z*',
+ [
+ 'FooTest.Xyz',
+ 'BazTest.TestOne',
+ 'BazTest.TestA',
+ 'BazTest.TestB',
+ ],
+ )
def testTwoPatterns(self):
"""Tests filters that consist of two patterns."""
- self.RunAndVerify('Foo*.*:*A*', [
- 'FooTest.Abc',
- 'FooTest.Xyz',
-
- 'BazTest.TestA',
- ])
+ self.RunAndVerify(
+ 'Foo*.*:*A*',
+ [
+ 'FooTest.Abc',
+ 'FooTest.Xyz',
+ 'BazTest.TestA',
+ ],
+ )
# An empty pattern + a non-empty one
self.RunAndVerify(':*A*', ['FooTest.Abc', 'BazTest.TestA'])
@@ -488,83 +536,109 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
def testThreePatterns(self):
"""Tests filters that consist of three patterns."""
- self.RunAndVerify('*oo*:*A*:*One', [
- 'FooTest.Abc',
- 'FooTest.Xyz',
-
- 'BarTest.TestOne',
-
- 'BazTest.TestOne',
- 'BazTest.TestA',
- ])
+ self.RunAndVerify(
+ '*oo*:*A*:*One',
+ [
+ 'FooTest.Abc',
+ 'FooTest.Xyz',
+ 'BarTest.TestOne',
+ 'BazTest.TestOne',
+ 'BazTest.TestA',
+ ],
+ )
# The 2nd pattern is empty.
- self.RunAndVerify('*oo*::*One', [
- 'FooTest.Abc',
- 'FooTest.Xyz',
-
- 'BarTest.TestOne',
-
- 'BazTest.TestOne',
- ])
+ self.RunAndVerify(
+ '*oo*::*One',
+ [
+ 'FooTest.Abc',
+ 'FooTest.Xyz',
+ 'BarTest.TestOne',
+ 'BazTest.TestOne',
+ ],
+ )
# The last 2 patterns are empty.
- self.RunAndVerify('*oo*::', [
- 'FooTest.Abc',
- 'FooTest.Xyz',
- ])
+ self.RunAndVerify(
+ '*oo*::',
+ [
+ 'FooTest.Abc',
+ 'FooTest.Xyz',
+ ],
+ )
def testNegativeFilters(self):
- self.RunAndVerify('*-BazTest.TestOne', [
- 'FooTest.Abc',
- 'FooTest.Xyz',
-
- 'BarTest.TestOne',
- 'BarTest.TestTwo',
- 'BarTest.TestThree',
-
- 'BazTest.TestA',
- 'BazTest.TestB',
- ] + DEATH_TESTS + PARAM_TESTS)
-
- self.RunAndVerify('*-FooTest.Abc:BazTest.*', [
- 'FooTest.Xyz',
-
- 'BarTest.TestOne',
- 'BarTest.TestTwo',
- 'BarTest.TestThree',
- ] + DEATH_TESTS + PARAM_TESTS)
-
- self.RunAndVerify('BarTest.*-BarTest.TestOne', [
- 'BarTest.TestTwo',
- 'BarTest.TestThree',
- ])
+ self.RunAndVerify(
+ '*-BazTest.TestOne',
+ [
+ 'FooTest.Abc',
+ 'FooTest.Xyz',
+ 'BarTest.TestOne',
+ 'BarTest.TestTwo',
+ 'BarTest.TestThree',
+ 'BazTest.TestA',
+ 'BazTest.TestB',
+ ]
+ + DEATH_TESTS
+ + PARAM_TESTS,
+ )
+
+ self.RunAndVerify(
+ '*-FooTest.Abc:BazTest.*',
+ [
+ 'FooTest.Xyz',
+ 'BarTest.TestOne',
+ 'BarTest.TestTwo',
+ 'BarTest.TestThree',
+ ]
+ + DEATH_TESTS
+ + PARAM_TESTS,
+ )
+
+ self.RunAndVerify(
+ 'BarTest.*-BarTest.TestOne',
+ [
+ 'BarTest.TestTwo',
+ 'BarTest.TestThree',
+ ],
+ )
# Tests without leading '*'.
- self.RunAndVerify('-FooTest.Abc:FooTest.Xyz:BazTest.*', [
- 'BarTest.TestOne',
- 'BarTest.TestTwo',
- 'BarTest.TestThree',
- ] + DEATH_TESTS + PARAM_TESTS)
+ self.RunAndVerify(
+ '-FooTest.Abc:FooTest.Xyz:BazTest.*',
+ [
+ 'BarTest.TestOne',
+ 'BarTest.TestTwo',
+ 'BarTest.TestThree',
+ ]
+ + DEATH_TESTS
+ + PARAM_TESTS,
+ )
# Value parameterized tests.
self.RunAndVerify('*/*', PARAM_TESTS)
# Value parameterized tests filtering by the sequence name.
- self.RunAndVerify('SeqP/*', [
- 'SeqP/ParamTest.TestX/0',
- 'SeqP/ParamTest.TestX/1',
- 'SeqP/ParamTest.TestY/0',
- 'SeqP/ParamTest.TestY/1',
- ])
+ self.RunAndVerify(
+ 'SeqP/*',
+ [
+ 'SeqP/ParamTest.TestX/0',
+ 'SeqP/ParamTest.TestX/1',
+ 'SeqP/ParamTest.TestY/0',
+ 'SeqP/ParamTest.TestY/1',
+ ],
+ )
# Value parameterized tests filtering by the test name.
- self.RunAndVerify('*/0', [
- 'SeqP/ParamTest.TestX/0',
- 'SeqP/ParamTest.TestY/0',
- 'SeqQ/ParamTest.TestX/0',
- 'SeqQ/ParamTest.TestY/0',
- ])
+ self.RunAndVerify(
+ '*/0',
+ [
+ 'SeqP/ParamTest.TestX/0',
+ 'SeqP/ParamTest.TestY/0',
+ 'SeqQ/ParamTest.TestX/0',
+ 'SeqQ/ParamTest.TestY/0',
+ ],
+ )
def testFlagOverridesEnvVar(self):
"""Tests that the filter flag overrides the filtering env. variable."""
@@ -579,41 +653,70 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
def testShardStatusFileIsCreated(self):
"""Tests that the shard file is created if specified in the environment."""
- shard_status_file = os.path.join(gtest_test_utils.GetTempDir(),
- 'shard_status_file')
- self.assert_(not os.path.exists(shard_status_file))
+ shard_status_file = os.path.join(
+ gtest_test_utils.GetTempDir(), 'shard_status_file'
+ )
+ self.assertTrue(not os.path.exists(shard_status_file))
extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file}
try:
InvokeWithModifiedEnv(extra_env, RunAndReturnOutput)
finally:
- self.assert_(os.path.exists(shard_status_file))
+ self.assertTrue(os.path.exists(shard_status_file))
os.remove(shard_status_file)
def testShardStatusFileIsCreatedWithListTests(self):
"""Tests that the shard file is created with the "list_tests" flag."""
- shard_status_file = os.path.join(gtest_test_utils.GetTempDir(),
- 'shard_status_file2')
- self.assert_(not os.path.exists(shard_status_file))
+ shard_status_file = os.path.join(
+ gtest_test_utils.GetTempDir(), 'shard_status_file2'
+ )
+ self.assertTrue(not os.path.exists(shard_status_file))
extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file}
try:
- output = InvokeWithModifiedEnv(extra_env,
- RunAndReturnOutput,
- [LIST_TESTS_FLAG])
+ output = InvokeWithModifiedEnv(
+ extra_env, RunAndReturnOutput, [LIST_TESTS_FLAG]
+ )
finally:
# This assertion ensures that Google Test enumerated the tests as
# opposed to running them.
- self.assert_('[==========]' not in output,
- 'Unexpected output during test enumeration.\n'
- 'Please ensure that LIST_TESTS_FLAG is assigned the\n'
- 'correct flag value for listing Google Test tests.')
-
- self.assert_(os.path.exists(shard_status_file))
+ self.assertTrue(
+ '[==========]' not in output,
+ (
+ 'Unexpected output during test enumeration.\n'
+ 'Please ensure that LIST_TESTS_FLAG is assigned the\n'
+ 'correct flag value for listing Google Test tests.'
+ ),
+ )
+
+ self.assertTrue(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."""
@@ -621,19 +724,23 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
expected_tests = [
'HasDeathTest.Test1',
'HasDeathTest.Test2',
-
'SeqP/ParamTest.TestX/0',
'SeqP/ParamTest.TestX/1',
'SeqP/ParamTest.TestY/0',
'SeqP/ParamTest.TestY/1',
- ]
-
- for flag in ['--gtest_death_test_style=threadsafe',
- '--gtest_death_test_style=fast']:
- self.RunAndVerifyWithSharding(gtest_filter, 3, expected_tests,
- check_exit_0=True, args=[flag])
- self.RunAndVerifyWithSharding(gtest_filter, 5, expected_tests,
- check_exit_0=True, args=[flag])
+ ]
+
+ for flag in [
+ '--gtest_death_test_style=threadsafe',
+ '--gtest_death_test_style=fast',
+ ]:
+ self.RunAndVerifyWithSharding(
+ gtest_filter, 3, expected_tests, check_exit_0=True, args=[flag]
+ )
+ self.RunAndVerifyWithSharding(
+ gtest_filter, 5, expected_tests, check_exit_0=True, args=[flag]
+ )
+
if __name__ == '__main__':
gtest_test_utils.Main()
diff --git a/googletest/test/googletest-filter-unittest_.cc b/googletest/test/googletest-filter-unittest_.cc
index d30ec9c78b56..bc7aa5940837 100644
--- a/googletest/test/googletest-filter-unittest_.cc
+++ b/googletest/test/googletest-filter-unittest_.cc
@@ -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));
diff --git a/googletest/test/googletest-global-environment-unittest.py b/googletest/test/googletest-global-environment-unittest.py
new file mode 100644
index 000000000000..bd73a2e1d888
--- /dev/null
+++ b/googletest/test/googletest-global-environment-unittest.py
@@ -0,0 +1,141 @@
+# Copyright 2021 Google Inc. All Rights Reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+"""Unit test for Google Test's global test environment behavior.
+
+A user can specify a global test environment via
+testing::AddGlobalTestEnvironment. Failures in the global environment should
+result in all unit tests being skipped.
+
+This script tests such functionality by invoking
+googletest-global-environment-unittest_ (a program written with Google Test).
+"""
+
+import re
+from googletest.test import gtest_test_utils
+
+
+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_'
+ )
+ ]
+ + (args or [])
+ ).output
+
+
+class GTestGlobalEnvironmentUnitTest(gtest_test_utils.TestCase):
+ """Tests global test environment failures."""
+
+ def testEnvironmentSetUpFails(self):
+ """Tests the behavior of not specifying the fail_fast."""
+
+ # Run the test.
+ txt = RunAndReturnOutput()
+
+ # We should see the text of the global environment setup error.
+ self.assertIn('Canned environment setup error', txt)
+
+ # Our test should have been skipped due to the error, and not treated as a
+ # pass.
+ self.assertIn('[ SKIPPED ] 1 test', txt)
+ self.assertIn('[ PASSED ] 0 tests', txt)
+
+ # 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()
diff --git a/googletest/test/googletest-global-environment-unittest_.cc b/googletest/test/googletest-global-environment-unittest_.cc
new file mode 100644
index 000000000000..f401b2fac25d
--- /dev/null
+++ b/googletest/test/googletest-global-environment-unittest_.cc
@@ -0,0 +1,58 @@
+// Copyright 2005, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Unit test for Google Test global test environments.
+//
+// The program will be invoked from a Python unit test. Don't run it
+// directly.
+
+#include "gtest/gtest.h"
+
+namespace {
+
+// An environment that always fails in its SetUp method.
+class FailingEnvironment final : public ::testing::Environment {
+ public:
+ void SetUp() override { FAIL() << "Canned environment setup error"; }
+};
+
+// Register the environment.
+auto* const g_environment_ =
+ ::testing::AddGlobalTestEnvironment(new FailingEnvironment);
+
+// A test that doesn't actually run.
+TEST(SomeTest, DoesFoo) { FAIL() << "Unexpected call"; }
+
+} // namespace
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/googletest/test/googletest-json-outfiles-test.py b/googletest/test/googletest-json-outfiles-test.py
index 8ef47b8f9746..5626004ed732 100644
--- a/googletest/test/googletest-json-outfiles-test.py
+++ b/googletest/test/googletest-json-outfiles-test.py
@@ -32,97 +32,82 @@
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_'
GTEST_OUTPUT_2_TEST = 'gtest_xml_outfile2_test_'
EXPECTED_1 = {
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'name':
- u'AllTests',
- u'testsuites': [{
- u'name':
- u'PropertyOne',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'TestSomeProperties',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'PropertyOne',
- u'SetUpProp': u'1',
- u'TestSomeProperty': u'1',
- u'TearDownProp': u'1',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'name': 'AllTests',
+ 'testsuites': [{
+ 'name': 'PropertyOne',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'TestSomeProperties',
+ 'file': 'gtest_xml_outfile1_test_.cc',
+ 'line': 41,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'PropertyOne',
+ 'SetUpProp': '1',
+ 'TestSomeProperty': '1',
+ 'TearDownProp': '1',
}],
}],
}
EXPECTED_2 = {
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'name':
- u'AllTests',
- u'testsuites': [{
- u'name':
- u'PropertyTwo',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'TestSomeProperties',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'timestamp': u'*',
- u'time': u'*',
- u'classname': u'PropertyTwo',
- u'SetUpProp': u'2',
- u'TestSomeProperty': u'2',
- u'TearDownProp': u'2',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'name': 'AllTests',
+ 'testsuites': [{
+ 'name': 'PropertyTwo',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'TestInt64ConvertibleProperties',
+ 'file': 'gtest_xml_outfile2_test_.cc',
+ 'line': 43,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'timestamp': '*',
+ 'time': '*',
+ 'classname': 'PropertyTwo',
+ 'SetUpProp': '2',
+ 'TestFloatProperty': '3.25',
+ 'TestDoubleProperty': '4.75',
+ 'TestSizetProperty': '5',
+ 'TestBoolProperty': 'true',
+ 'TestCharProperty': 'A',
+ 'TestInt16Property': '6',
+ 'TestInt32Property': '7',
+ 'TestInt64Property': '8',
+ 'TestEnumProperty': '9',
+ 'TestAtomicIntProperty': '10',
+ 'TearDownProp': '2',
}],
}],
}
@@ -135,8 +120,9 @@ class GTestJsonOutFilesTest(gtest_test_utils.TestCase):
# We want the trailing '/' that the last "" provides in os.path.join, for
# telling Google Test to create an output directory instead of a single file
# for xml output.
- self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(),
- GTEST_OUTPUT_SUBDIR, '')
+ self.output_dir_ = os.path.join(
+ gtest_test_utils.GetTempDir(), GTEST_OUTPUT_SUBDIR, ''
+ )
self.DeleteFilesAndDir()
def tearDown(self):
@@ -165,17 +151,20 @@ class GTestJsonOutFilesTest(gtest_test_utils.TestCase):
def _TestOutFile(self, test_name, expected):
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name)
command = [gtest_prog_path, '--gtest_output=json:%s' % self.output_dir_]
- p = gtest_test_utils.Subprocess(command,
- working_dir=gtest_test_utils.GetTempDir())
- self.assert_(p.exited)
- self.assertEquals(0, p.exit_code)
+ p = gtest_test_utils.Subprocess(
+ command, working_dir=gtest_test_utils.GetTempDir()
+ )
+ self.assertTrue(p.exited)
+ self.assertEqual(0, p.exit_code)
output_file_name1 = test_name + '.json'
output_file1 = os.path.join(self.output_dir_, output_file_name1)
output_file_name2 = 'lt-' + output_file_name1
output_file2 = os.path.join(self.output_dir_, output_file_name2)
- self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2),
- output_file1)
+ self.assertTrue(
+ os.path.isfile(output_file1) or os.path.isfile(output_file2),
+ output_file1,
+ )
if os.path.isfile(output_file1):
with open(output_file1) as f:
diff --git a/googletest/test/googletest-json-output-unittest.py b/googletest/test/googletest-json-output-unittest.py
index 15861f75cbe8..cb976945202a 100644
--- a/googletest/test/googletest-json-output-unittest.py
+++ b/googletest/test/googletest-json-output-unittest.py
@@ -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'
@@ -54,558 +54,573 @@ SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv
if SUPPORTS_STACK_TRACES:
STACK_TRACE_TEMPLATE = '\nStack trace:\n*'
else:
- STACK_TRACE_TEMPLATE = ''
+ STACK_TRACE_TEMPLATE = '\n'
EXPECTED_NON_EMPTY = {
- u'tests':
- 24,
- u'failures':
- 4,
- u'disabled':
- 2,
- u'errors':
- 0,
- u'timestamp':
- u'*',
- u'time':
- u'*',
- u'ad_hoc_property':
- u'42',
- u'name':
- u'AllTests',
- u'testsuites': [{
- u'name':
- u'SuccessfulTest',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'Succeeds',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'SuccessfulTest'
- }]
- }, {
- u'name':
- u'FailedTest',
- u'tests':
- 1,
- u'failures':
- 1,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name':
- u'Fails',
- u'status':
- u'RUN',
- u'result':
- u'COMPLETED',
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'classname':
- u'FailedTest',
- u'failures': [{
- u'failure': u'gtest_xml_output_unittest_.cc:*\n'
- u'Expected equality of these values:\n'
- u' 1\n 2' + STACK_TRACE_TEMPLATE,
- u'type': u''
- }]
- }]
- }, {
- u'name':
- u'DisabledTest',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 1,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'DISABLED_test_not_run',
- u'status': u'NOTRUN',
- u'result': u'SUPPRESSED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'DisabledTest'
- }]
- }, {
- u'name':
- u'SkippedTest',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'Skipped',
- u'status': u'RUN',
- u'result': u'SKIPPED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'SkippedTest'
- }]
- }, {
- u'name':
- u'MixedResultTest',
- u'tests':
- 3,
- u'failures':
- 1,
- u'disabled':
- 1,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'Succeeds',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'MixedResultTest'
- }, {
- u'name':
- u'Fails',
- u'status':
- u'RUN',
- u'result':
- u'COMPLETED',
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'classname':
- u'MixedResultTest',
- u'failures': [{
- u'failure': u'gtest_xml_output_unittest_.cc:*\n'
- u'Expected equality of these values:\n'
- u' 1\n 2' + STACK_TRACE_TEMPLATE,
- u'type': u''
- }, {
- u'failure': u'gtest_xml_output_unittest_.cc:*\n'
- u'Expected equality of these values:\n'
- u' 2\n 3' + STACK_TRACE_TEMPLATE,
- u'type': u''
- }]
- }, {
- u'name': u'DISABLED_test',
- u'status': u'NOTRUN',
- u'result': u'SUPPRESSED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'MixedResultTest'
- }]
- }, {
- u'name':
- u'XmlQuotingTest',
- u'tests':
- 1,
- u'failures':
- 1,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name':
- u'OutputsCData',
- u'status':
- u'RUN',
- u'result':
- u'COMPLETED',
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'classname':
- u'XmlQuotingTest',
- u'failures': [{
- u'failure': u'gtest_xml_output_unittest_.cc:*\n'
- u'Failed\nXML output: <?xml encoding="utf-8">'
- u'<top><![CDATA[cdata text]]></top>' +
- STACK_TRACE_TEMPLATE,
- u'type': u''
- }]
- }]
- }, {
- u'name':
- u'InvalidCharactersTest',
- u'tests':
- 1,
- u'failures':
- 1,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name':
- u'InvalidCharactersInMessage',
- u'status':
- u'RUN',
- u'result':
- u'COMPLETED',
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'classname':
- u'InvalidCharactersTest',
- u'failures': [{
- u'failure': u'gtest_xml_output_unittest_.cc:*\n'
- u'Failed\nInvalid characters in brackets'
- u' [\x01\x02]' + STACK_TRACE_TEMPLATE,
- u'type': u''
- }]
- }]
- }, {
- u'name':
- u'PropertyRecordingTest',
- u'tests':
- 4,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'SetUpTestSuite':
- u'yes',
- u'TearDownTestSuite':
- u'aye',
- u'testsuite': [{
- u'name': u'OneProperty',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'PropertyRecordingTest',
- u'key_1': u'1'
- }, {
- u'name': u'IntValuedProperty',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'PropertyRecordingTest',
- u'key_int': u'1'
- }, {
- u'name': u'ThreeProperties',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'PropertyRecordingTest',
- u'key_1': u'1',
- u'key_2': u'2',
- u'key_3': u'3'
- }, {
- u'name': u'TwoValuesForOneKeyUsesLastValue',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'PropertyRecordingTest',
- u'key_1': u'2'
- }]
- }, {
- u'name':
- u'NoFixtureTest',
- u'tests':
- 3,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'RecordProperty',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'NoFixtureTest',
- u'key': u'1'
- }, {
- u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'NoFixtureTest',
- u'key_for_utility_int': u'1'
- }, {
- u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'NoFixtureTest',
- u'key_for_utility_string': u'1'
- }]
- }, {
- u'name':
- u'TypedTest/0',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'HasTypeParamAttribute',
- u'type_param': u'int',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'TypedTest/0'
- }]
- }, {
- u'name':
- u'TypedTest/1',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'HasTypeParamAttribute',
- u'type_param': u'long',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'TypedTest/1'
- }]
- }, {
- u'name':
- u'Single/TypeParameterizedTestSuite/0',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'HasTypeParamAttribute',
- u'type_param': u'int',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/TypeParameterizedTestSuite/0'
- }]
- }, {
- u'name':
- u'Single/TypeParameterizedTestSuite/1',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'HasTypeParamAttribute',
- u'type_param': u'long',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/TypeParameterizedTestSuite/1'
- }]
- }, {
- u'name':
- u'Single/ValueParamTest',
- u'tests':
- 4,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'HasValueParamAttribute/0',
- u'value_param': u'33',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/ValueParamTest'
- }, {
- u'name': u'HasValueParamAttribute/1',
- u'value_param': u'42',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/ValueParamTest'
- }, {
- u'name': u'AnotherTestThatHasValueParamAttribute/0',
- u'value_param': u'33',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/ValueParamTest'
- }, {
- u'name': u'AnotherTestThatHasValueParamAttribute/1',
- u'value_param': u'42',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/ValueParamTest'
- }]
- }]
+ 'tests': 26,
+ 'failures': 5,
+ 'disabled': 2,
+ 'errors': 0,
+ 'timestamp': '*',
+ 'time': '*',
+ 'ad_hoc_property': '42',
+ 'name': 'AllTests',
+ 'testsuites': [
+ {
+ 'name': 'SuccessfulTest',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'Succeeds',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 53,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'SuccessfulTest',
+ }],
+ },
+ {
+ 'name': 'FailedTest',
+ 'tests': 1,
+ 'failures': 1,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'Fails',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 61,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'FailedTest',
+ 'failures': [{
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Expected equality of these values:\n'
+ ' 1\n 2'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ }],
+ }],
+ },
+ {
+ 'name': 'DisabledTest',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 1,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'DISABLED_test_not_run',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 68,
+ 'status': 'NOTRUN',
+ 'result': 'SUPPRESSED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'DisabledTest',
+ }],
+ },
+ {
+ 'name': 'SkippedTest',
+ 'tests': 3,
+ 'failures': 1,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [
+ {
+ 'name': 'Skipped',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 75,
+ 'status': 'RUN',
+ 'result': 'SKIPPED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'SkippedTest',
+ },
+ {
+ 'name': 'SkippedWithMessage',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 79,
+ 'status': 'RUN',
+ 'result': 'SKIPPED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'SkippedTest',
+ },
+ {
+ 'name': 'SkippedAfterFailure',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 83,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'SkippedTest',
+ 'failures': [{
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Expected equality of these values:\n'
+ ' 1\n 2'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ }],
+ },
+ ],
+ },
+ {
+ 'name': 'MixedResultTest',
+ 'tests': 3,
+ 'failures': 1,
+ 'disabled': 1,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [
+ {
+ 'name': 'Succeeds',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 88,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'MixedResultTest',
+ },
+ {
+ 'name': 'Fails',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 93,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'MixedResultTest',
+ 'failures': [
+ {
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Expected equality of these values:\n'
+ ' 1\n 2'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ },
+ {
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Expected equality of these values:\n'
+ ' 2\n 3'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ },
+ ],
+ },
+ {
+ 'name': 'DISABLED_test',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 98,
+ 'status': 'NOTRUN',
+ 'result': 'SUPPRESSED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'MixedResultTest',
+ },
+ ],
+ },
+ {
+ 'name': 'XmlQuotingTest',
+ 'tests': 1,
+ 'failures': 1,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'OutputsCData',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 102,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'XmlQuotingTest',
+ 'failures': [{
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Failed\nXML output: <?xml encoding="utf-8">'
+ '<top><![CDATA[cdata text]]></top>'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ }],
+ }],
+ },
+ {
+ 'name': 'InvalidCharactersTest',
+ 'tests': 1,
+ 'failures': 1,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'InvalidCharactersInMessage',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 109,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'InvalidCharactersTest',
+ 'failures': [{
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Failed\nInvalid characters in brackets'
+ ' [\x01\x02]'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ }],
+ }],
+ },
+ {
+ 'name': 'PropertyRecordingTest',
+ 'tests': 4,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'SetUpTestSuite': 'yes',
+ 'TearDownTestSuite': 'aye',
+ 'testsuite': [
+ {
+ 'name': 'OneProperty',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 121,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'PropertyRecordingTest',
+ 'key_1': '1',
+ },
+ {
+ 'name': 'IntValuedProperty',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 125,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'PropertyRecordingTest',
+ 'key_int': '1',
+ },
+ {
+ 'name': 'ThreeProperties',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 129,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'PropertyRecordingTest',
+ 'key_1': '1',
+ 'key_2': '2',
+ 'key_3': '3',
+ },
+ {
+ 'name': 'TwoValuesForOneKeyUsesLastValue',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 135,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'PropertyRecordingTest',
+ 'key_1': '2',
+ },
+ ],
+ },
+ {
+ 'name': 'NoFixtureTest',
+ 'tests': 3,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [
+ {
+ 'name': 'RecordProperty',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 140,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'NoFixtureTest',
+ 'key': '1',
+ },
+ {
+ 'name': 'ExternalUtilityThatCallsRecordIntValuedProperty',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 153,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'NoFixtureTest',
+ 'key_for_utility_int': '1',
+ },
+ {
+ 'name': (
+ 'ExternalUtilityThatCallsRecordStringValuedProperty'
+ ),
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 157,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'NoFixtureTest',
+ 'key_for_utility_string': '1',
+ },
+ ],
+ },
+ {
+ 'name': 'TypedTest/0',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'HasTypeParamAttribute',
+ 'type_param': 'int',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 173,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'TypedTest/0',
+ }],
+ },
+ {
+ 'name': 'TypedTest/1',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'HasTypeParamAttribute',
+ 'type_param': 'long',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 173,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'TypedTest/1',
+ }],
+ },
+ {
+ 'name': 'Single/TypeParameterizedTestSuite/0',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'HasTypeParamAttribute',
+ 'type_param': 'int',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 180,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'Single/TypeParameterizedTestSuite/0',
+ }],
+ },
+ {
+ 'name': 'Single/TypeParameterizedTestSuite/1',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'HasTypeParamAttribute',
+ 'type_param': 'long',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 180,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'Single/TypeParameterizedTestSuite/1',
+ }],
+ },
+ {
+ 'name': 'Single/ValueParamTest',
+ 'tests': 4,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [
+ {
+ 'name': 'HasValueParamAttribute/0',
+ 'value_param': '33',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 164,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'Single/ValueParamTest',
+ },
+ {
+ 'name': 'HasValueParamAttribute/1',
+ 'value_param': '42',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 164,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'Single/ValueParamTest',
+ },
+ {
+ 'name': 'AnotherTestThatHasValueParamAttribute/0',
+ 'value_param': '33',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 165,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'Single/ValueParamTest',
+ },
+ {
+ 'name': 'AnotherTestThatHasValueParamAttribute/1',
+ 'value_param': '42',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 165,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'Single/ValueParamTest',
+ },
+ ],
+ },
+ ],
}
EXPECTED_FILTERED = {
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'name':
- u'AllTests',
- u'ad_hoc_property':
- u'42',
- u'testsuites': [{
- u'name':
- u'SuccessfulTest',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'Succeeds',
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'SuccessfulTest',
- }]
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'name': 'AllTests',
+ 'ad_hoc_property': '42',
+ 'testsuites': [{
+ 'name': 'SuccessfulTest',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'Succeeds',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 53,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'SuccessfulTest',
+ }],
}],
}
-EXPECTED_EMPTY = {
- u'tests': 0,
- u'failures': 0,
- u'disabled': 0,
- u'errors': 0,
- u'time': u'*',
- u'timestamp': u'*',
- u'name': u'AllTests',
- u'testsuites': [],
+EXPECTED_NO_TEST = {
+ 'tests': 0,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'name': 'AllTests',
+ 'testsuites': [{
+ 'name': 'NonTestSuiteFailure',
+ 'tests': 1,
+ 'failures': 1,
+ 'disabled': 0,
+ 'skipped': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': '',
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': '',
+ 'failures': [{
+ 'failure': (
+ 'gtest_no_test_unittest.cc:*\n'
+ 'Expected equality of these values:\n'
+ ' 1\n 2'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ }],
+ }],
+ }],
}
GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
-SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess(
- [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output
+SUPPORTS_TYPED_TESTS = (
+ 'TypedTest'
+ in gtest_test_utils.Subprocess(
+ [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False
+ ).output
+)
class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
- """Unit test for Google Test's JSON output functionality.
- """
+ """Unit test for Google Test's JSON output functionality."""
# This test currently breaks on platforms that do not support typed and
# type-parameterized tests, so we don't run it under them.
@@ -619,14 +634,14 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
"""
self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY, 1)
- def testEmptyJsonOutput(self):
+ def testNoTestJsonOutput(self):
"""Verifies JSON output for a Google Test binary without actual tests.
- Runs a test program that generates an empty JSON output, and
- tests that the JSON output is expected.
+ Runs a test program that generates an JSON output for a binary with no
+ tests, and tests that the JSON output is expected.
"""
- self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_EMPTY, 0)
+ self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_NO_TEST, 0)
def testTimestampValue(self):
"""Checks whether the timestamp attribute in the JSON output is valid.
@@ -641,16 +656,23 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
self.assertTrue(
re.match,
- 'JSON datettime string %s has incorrect format' % date_time_str)
+ 'JSON datettime string %s has incorrect format' % date_time_str,
+ )
date_time_from_json = datetime.datetime(
- year=int(match.group(1)), month=int(match.group(2)),
- day=int(match.group(3)), hour=int(match.group(4)),
- minute=int(match.group(5)), second=int(match.group(6)))
+ year=int(match.group(1)),
+ month=int(match.group(2)),
+ day=int(match.group(3)),
+ hour=int(match.group(4)),
+ minute=int(match.group(5)),
+ second=int(match.group(6)),
+ )
time_delta = abs(datetime.datetime.now() - date_time_from_json)
# timestamp value should be near the current local time
- self.assertTrue(time_delta < datetime.timedelta(seconds=600),
- 'time_delta is %s' % time_delta)
+ self.assertTrue(
+ time_delta < datetime.timedelta(seconds=600),
+ 'time_delta is %s' % time_delta,
+ )
def testDefaultOutputFile(self):
"""Verifies the default output file name.
@@ -658,10 +680,12 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
Confirms that Google Test produces an JSON output file with the expected
default name if no name is explicitly specified.
"""
- output_file = os.path.join(gtest_test_utils.GetTempDir(),
- GTEST_DEFAULT_OUTPUT_FILE)
+ output_file = os.path.join(
+ gtest_test_utils.GetTempDir(), GTEST_DEFAULT_OUTPUT_FILE
+ )
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
- 'gtest_no_test_unittest')
+ 'gtest_no_test_unittest'
+ )
try:
os.remove(output_file)
except OSError:
@@ -671,10 +695,11 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
p = gtest_test_utils.Subprocess(
[gtest_prog_path, '%s=json' % GTEST_OUTPUT_FLAG],
- working_dir=gtest_test_utils.GetTempDir())
- self.assert_(p.exited)
- self.assertEquals(0, p.exit_code)
- self.assert_(os.path.isfile(output_file))
+ working_dir=gtest_test_utils.GetTempDir(),
+ )
+ self.assertTrue(p.exited)
+ self.assertEqual(0, p.exit_code)
+ self.assertTrue(os.path.isfile(output_file))
def testSuppressedJsonOutput(self):
"""Verifies that no JSON output is generated.
@@ -683,28 +708,34 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
shut down before RUN_ALL_TESTS is invoked.
"""
- json_path = os.path.join(gtest_test_utils.GetTempDir(),
- GTEST_PROGRAM_NAME + 'out.json')
+ json_path = os.path.join(
+ gtest_test_utils.GetTempDir(), GTEST_PROGRAM_NAME + 'out.json'
+ )
if os.path.isfile(json_path):
os.remove(json_path)
- command = [GTEST_PROGRAM_PATH,
- '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path),
- '--shut_down_xml']
+ command = [
+ GTEST_PROGRAM_PATH,
+ '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path),
+ '--shut_down_xml',
+ ]
p = gtest_test_utils.Subprocess(command)
if p.terminated_by_signal:
# p.signal is available only if p.terminated_by_signal is True.
self.assertFalse(
p.terminated_by_signal,
- '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal))
+ '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal),
+ )
else:
- self.assert_(p.exited)
- self.assertEquals(1, p.exit_code,
- "'%s' exited with code %s, which doesn't match "
- 'the expected exit code %s.'
- % (command, p.exit_code, 1))
+ self.assertTrue(p.exited)
+ self.assertEqual(
+ 1,
+ p.exit_code,
+ "'%s' exited with code %s, which doesn't match "
+ 'the expected exit code %s.' % (command, p.exit_code, 1),
+ )
- self.assert_(not os.path.isfile(json_path))
+ self.assertTrue(not os.path.isfile(json_path))
def testFilteredTestJsonOutput(self):
"""Verifies JSON output when a filter is applied.
@@ -713,8 +744,12 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
non-selected tests do not show up in the JSON output.
"""
- self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED, 0,
- extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])
+ self._TestJsonOutput(
+ GTEST_PROGRAM_NAME,
+ EXPECTED_FILTERED,
+ 0,
+ extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG],
+ )
def _GetJsonOutput(self, gtest_prog_name, extra_args, expected_exit_code):
"""Returns the JSON output generated by running the program gtest_prog_name.
@@ -726,30 +761,36 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
extra_args: extra arguments to binary invocation.
expected_exit_code: program's exit code.
"""
- json_path = os.path.join(gtest_test_utils.GetTempDir(),
- gtest_prog_name + 'out.json')
+ json_path = os.path.join(
+ gtest_test_utils.GetTempDir(), gtest_prog_name + 'out.json'
+ )
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
- command = (
- [gtest_prog_path, '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path)] +
- extra_args
- )
+ command = [
+ gtest_prog_path,
+ '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path),
+ ] + extra_args
p = gtest_test_utils.Subprocess(command)
if p.terminated_by_signal:
- self.assert_(False,
- '%s was killed by signal %d' % (gtest_prog_name, p.signal))
+ self.assertTrue(
+ False, '%s was killed by signal %d' % (gtest_prog_name, p.signal)
+ )
else:
- self.assert_(p.exited)
- self.assertEquals(expected_exit_code, p.exit_code,
- "'%s' exited with code %s, which doesn't match "
- 'the expected exit code %s.'
- % (command, p.exit_code, expected_exit_code))
+ self.assertTrue(p.exited)
+ self.assertEqual(
+ expected_exit_code,
+ p.exit_code,
+ "'%s' exited with code %s, which doesn't match "
+ 'the expected exit code %s.'
+ % (command, p.exit_code, expected_exit_code),
+ )
with open(json_path) as f:
actual = json.load(f)
return actual
- def _TestJsonOutput(self, gtest_prog_name, expected,
- expected_exit_code, extra_args=None):
+ def _TestJsonOutput(
+ self, gtest_prog_name, expected, expected_exit_code, extra_args=None
+ ):
"""Checks the JSON output generated by the Google Test binary.
Asserts that the JSON document generated by running the program
@@ -764,8 +805,9 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
extra_args: extra arguments to binary invocation.
"""
- actual = self._GetJsonOutput(gtest_prog_name, extra_args or [],
- expected_exit_code)
+ actual = self._GetJsonOutput(
+ gtest_prog_name, extra_args or [], expected_exit_code
+ )
self.assertEqual(expected, gtest_json_test_utils.normalize(actual))
diff --git a/googletest/test/googletest-list-tests-unittest.py b/googletest/test/googletest-list-tests-unittest.py
index 81423a339e8f..977e57f08771 100755
--- a/googletest/test/googletest-list-tests-unittest.py
+++ b/googletest/test/googletest-list-tests-unittest.py
@@ -38,7 +38,7 @@ Google Test) the command line flags.
"""
import re
-import gtest_test_utils
+from googletest.test import gtest_test_utils
# Constants.
@@ -46,11 +46,14 @@ import gtest_test_utils
LIST_TESTS_FLAG = 'gtest_list_tests'
# Path to the googletest-list-tests-unittest_ program.
-EXE_PATH = gtest_test_utils.GetTestExecutablePath('googletest-list-tests-unittest_')
+EXE_PATH = gtest_test_utils.GetTestExecutablePath(
+ 'googletest-list-tests-unittest_'
+)
# The expected output when running googletest-list-tests-unittest_ with
# --gtest_list_tests
-EXPECTED_OUTPUT_NO_FILTER_RE = re.compile(r"""FooDeathTest\.
+EXPECTED_OUTPUT_NO_FILTER_RE = re.compile(
+ r"""FooDeathTest\.
Test1
Foo\.
Bar1
@@ -90,11 +93,13 @@ MyInstantiation/ValueParamTest\.
TestB/0 # GetParam\(\) = one line
TestB/1 # GetParam\(\) = two\\nlines
TestB/2 # GetParam\(\) = a very\\nlo{241}\.\.\.
-""")
+"""
+)
# The expected output when running googletest-list-tests-unittest_ with
# --gtest_list_tests and --gtest_filter=Foo*.
-EXPECTED_OUTPUT_FILTER_FOO_RE = re.compile(r"""FooDeathTest\.
+EXPECTED_OUTPUT_FILTER_FOO_RE = re.compile(
+ r"""FooDeathTest\.
Test1
Foo\.
Bar1
@@ -106,7 +111,8 @@ FooTest\.
Test1
DISABLED_Test2
Test3
-""")
+"""
+)
# Utilities.
@@ -114,8 +120,9 @@ FooTest\.
def Run(args):
"""Runs googletest-list-tests-unittest_ and returns the list of tests printed."""
- return gtest_test_utils.Subprocess([EXE_PATH] + args,
- capture_stderr=False).output
+ return gtest_test_utils.Subprocess(
+ [EXE_PATH] + args, capture_stderr=False
+ ).output
# The unit test.
@@ -125,17 +132,18 @@ class GTestListTestsUnitTest(gtest_test_utils.TestCase):
"""Tests using the --gtest_list_tests flag to list all tests."""
def RunAndVerify(self, flag_value, expected_output_re, other_flag):
- """Runs googletest-list-tests-unittest_ and verifies that it prints
+ """Run googletest-list-tests-unittest_ and verify the output.
+
+ Runs googletest-list-tests-unittest_ and verifies that it prints
the correct tests.
Args:
- flag_value: value of the --gtest_list_tests flag;
- None if the flag should not be present.
- expected_output_re: regular expression that matches the expected
- output after running command;
- other_flag: a different flag to be passed to command
- along with gtest_list_tests;
- None if the flag should not be present.
+ flag_value: value of the --gtest_list_tests flag; None if the flag
+ should not be present.
+ expected_output_re: regular expression that matches the expected output
+ after running command;
+ other_flag: a different flag to be passed to command along with
+ gtest_list_tests; None if the flag should not be present.
"""
if flag_value is None:
@@ -156,49 +164,61 @@ class GTestListTestsUnitTest(gtest_test_utils.TestCase):
output = Run(args)
if expected_output_re:
- self.assert_(
+ self.assertTrue(
expected_output_re.match(output),
- ('when %s is %s, the output of "%s" is "%s",\n'
- 'which does not match regex "%s"' %
- (LIST_TESTS_FLAG, flag_expression, ' '.join(args), output,
- expected_output_re.pattern)))
+ 'when %s is %s, the output of "%s" is "%s",\n'
+ 'which does not match regex "%s"'
+ % (
+ LIST_TESTS_FLAG,
+ flag_expression,
+ ' '.join(args),
+ output,
+ expected_output_re.pattern,
+ ),
+ )
else:
- self.assert_(
+ self.assertTrue(
not EXPECTED_OUTPUT_NO_FILTER_RE.match(output),
- ('when %s is %s, the output of "%s" is "%s"'%
- (LIST_TESTS_FLAG, flag_expression, ' '.join(args), output)))
+ 'when %s is %s, the output of "%s" is "%s"'
+ % (LIST_TESTS_FLAG, flag_expression, ' '.join(args), output),
+ )
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
- self.RunAndVerify(flag_value=None,
- expected_output_re=None,
- other_flag=None)
+ self.RunAndVerify(flag_value=None, expected_output_re=None, other_flag=None)
def testFlag(self):
"""Tests using the --gtest_list_tests flag."""
- self.RunAndVerify(flag_value='0',
- expected_output_re=None,
- other_flag=None)
- self.RunAndVerify(flag_value='1',
- expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE,
- other_flag=None)
+ self.RunAndVerify(flag_value='0', expected_output_re=None, other_flag=None)
+ self.RunAndVerify(
+ flag_value='1',
+ expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE,
+ other_flag=None,
+ )
def testOverrideNonFilterFlags(self):
"""Tests that --gtest_list_tests overrides the non-filter flags."""
- self.RunAndVerify(flag_value='1',
- expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE,
- other_flag='--gtest_break_on_failure')
+ self.RunAndVerify(
+ flag_value='1',
+ expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE,
+ other_flag='--gtest_break_on_failure',
+ )
def testWithFilterFlags(self):
- """Tests that --gtest_list_tests takes into account the
- --gtest_filter flag."""
+ """Tests that --gtest_list_tests takes into account the filter flags.
+
+ Tests that --gtest_list_tests takes into account the
+ --gtest_filter flag.
+ """
- self.RunAndVerify(flag_value='1',
- expected_output_re=EXPECTED_OUTPUT_FILTER_FOO_RE,
- other_flag='--gtest_filter=Foo*')
+ self.RunAndVerify(
+ flag_value='1',
+ expected_output_re=EXPECTED_OUTPUT_FILTER_FOO_RE,
+ other_flag='--gtest_filter=Foo*',
+ )
if __name__ == '__main__':
diff --git a/googletest/test/googletest-list-tests-unittest_.cc b/googletest/test/googletest-list-tests-unittest_.cc
index 493c6f00464a..a1ea6cf4b19d 100644
--- a/googletest/test/googletest-list-tests-unittest_.cc
+++ b/googletest/test/googletest-list-tests-unittest_.cc
@@ -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
@@ -37,41 +36,33 @@
// This program will be invoked from a Python unit test.
// Don't run it directly.
+#include <ostream>
+#include <string>
+
#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 +77,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();
diff --git a/googletest/test/googletest-listener-test.cc b/googletest/test/googletest-listener-test.cc
index 10457afe39a7..d7c47c214a7b 100644
--- a/googletest/test/googletest-listener-test.cc
+++ b/googletest/test/googletest-listener-test.cc
@@ -32,19 +32,14 @@
// This file verifies Google Test event listeners receive events at the
// right times.
+#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "gtest/internal/custom/gtest.h"
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::UnitTest;
// Used by tests to register their events.
@@ -65,8 +60,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 +107,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 +117,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 +245,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);
@@ -281,10 +273,11 @@ int main(int argc, char **argv) {
AddGlobalTestEnvironment(new EnvironmentInvocationCatcher);
- GTEST_CHECK_(events.size() == 0)
+ GTEST_CHECK_(events.empty())
<< "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 +498,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;
}
diff --git a/googletest/test/googletest-message-test.cc b/googletest/test/googletest-message-test.cc
index 962d519114e6..bf1f094c966a 100644
--- a/googletest/test/googletest-message-test.cc
+++ b/googletest/test/googletest-message-test.cc
@@ -30,14 +30,32 @@
//
// Tests for the Message class.
-#include "gtest/gtest-message.h"
+#include <sstream>
+#include <string>
+#include "gtest/gtest-message.h"
#include "gtest/gtest.h"
+#ifdef GTEST_HAS_ABSL
+#include "absl/strings/str_format.h"
+#endif // GTEST_HAS_ABSL
+
namespace {
using ::testing::Message;
+#ifdef GTEST_HAS_ABSL
+struct AbslStringifiablePoint {
+ template <typename Sink>
+ friend void AbslStringify(Sink& sink, const AbslStringifiablePoint& p) {
+ absl::Format(&sink, "(%d, %d)", p.x, p.y);
+ }
+
+ int x;
+ int y;
+};
+#endif // GTEST_HAS_ABSL
+
// Tests the testing::Message class
// Tests the default constructor.
@@ -69,8 +87,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 +127,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",
@@ -126,13 +144,21 @@ TEST(MessageTest, StreamsInt) {
EXPECT_EQ("123", (Message() << 123).GetString());
}
+#ifdef GTEST_HAS_ABSL
+// Tests streaming a type with an AbslStringify definition.
+TEST(MessageTest, StreamsAbslStringify) {
+ EXPECT_EQ("(1, 2)", (Message() << AbslStringifiablePoint{1, 2}).GetString());
+}
+#endif // GTEST_HAS_ABSL
+
// 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()
diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc
index f07b316db3b9..b712c06fa3fb 100644
--- a/googletest/test/googletest-options-test.cc
+++ b/googletest/test/googletest-options-test.cc
@@ -36,12 +36,17 @@
// make-files on Windows and other platforms. Do not #include this file
// anywhere else!
+#include <string>
+
#include "gtest/gtest.h"
-#if GTEST_OS_WINDOWS_MOBILE
-# include <windows.h>
-#elif GTEST_OS_WINDOWS
-# include <direct.h>
+#ifdef GTEST_OS_WINDOWS_MOBILE
+#include <windows.h>
+#elif defined(GTEST_OS_WINDOWS)
+#include <direct.h>
+#elif defined(GTEST_OS_OS2)
+// For strcasecmp on OS/2
+#include <strings.h>
#endif // GTEST_OS_WINDOWS_MOBILE
#include "src/gtest-internal-inl.h"
@@ -58,36 +63,36 @@ 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
+#ifdef GTEST_OS_WINDOWS
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
#else
EXPECT_EQ(expected_output_file, output_file.c_str());
@@ -96,32 +101,29 @@ TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
const std::string exe_str = GetCurrentExecutableName().string();
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
const bool success =
_strcmpi("googletest-options-test", exe_str.c_str()) == 0 ||
_strcmpi("gtest-options-ex_test", exe_str.c_str()) == 0 ||
_strcmpi("gtest_all_test", exe_str.c_str()) == 0 ||
_strcmpi("gtest_dll_test", exe_str.c_str()) == 0;
-#elif GTEST_OS_OS2
+#elif defined(GTEST_OS_OS2)
const bool success =
strcasecmp("googletest-options-test", exe_str.c_str()) == 0 ||
strcasecmp("gtest-options-ex_test", exe_str.c_str()) == 0 ||
strcasecmp("gtest_all_test", exe_str.c_str()) == 0 ||
strcasecmp("gtest_dll_test", exe_str.c_str()) == 0;
-#elif GTEST_OS_FUCHSIA
+#elif defined(GTEST_OS_FUCHSIA)
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
+#ifndef GTEST_OS_FUCHSIA
class XmlOutputChangeDirTest : public Test {
protected:
@@ -141,36 +143,40 @@ 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
+#ifdef GTEST_OS_WINDOWS
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
#else
EXPECT_EQ(expected_output_file, output_file.c_str());
@@ -178,31 +184,31 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
}
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) {
-#if GTEST_OS_WINDOWS
- GTEST_FLAG(output) = "xml:c:\\tmp\\filename.abc";
+#ifdef GTEST_OS_WINDOWS
+ 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
}
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) {
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
const std::string path = "c:\\tmp\\";
#else
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 =
UnitTestOptions::GetAbsolutePathToOutputFile();
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
#else
EXPECT_EQ(expected_output_file, output_file.c_str());
diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt
index 038de921baba..6ddf822ffb47 100644
--- a/googletest/test/googletest-output-test-golden-lin.txt
+++ b/googletest/test/googletest-output-test-golden-lin.txt
@@ -12,7 +12,7 @@ Expected equality of these values:
3
Stack trace: (omitted)
-[==========] Running 85 tests from 40 test suites.
+[==========] Running 90 tests from 43 test suites.
[----------] Global test environment set-up.
FooEnvironment::SetUp() called.
BarEnvironment::SetUp() called.
@@ -956,6 +956,26 @@ Stack trace: (omitted)
~DynamicFixture()
[ FAILED ] BadDynamicFixture2.Derived
DynamicFixture::TearDownTestSuite
+[----------] 1 test from TestSuiteThatFailsToSetUp
+googletest-output-test_.cc:#: Failure
+Value of: false
+ Actual: false
+Expected: true
+Stack trace: (omitted)
+
+[ RUN ] TestSuiteThatFailsToSetUp.ShouldNotRun
+googletest-output-test_.cc:#: Skipped
+
+[ SKIPPED ] TestSuiteThatFailsToSetUp.ShouldNotRun
+[----------] 1 test from TestSuiteThatSkipsInSetUp
+googletest-output-test_.cc:#: Skipped
+Skip entire test suite
+Stack trace: (omitted)
+
+[ RUN ] TestSuiteThatSkipsInSetUp.ShouldNotRun
+googletest-output-test_.cc:#: Skipped
+
+[ SKIPPED ] TestSuiteThatSkipsInSetUp.ShouldNotRun
[----------] 1 test from PrintingFailingParams/FailingParamTest
[ RUN ] PrintingFailingParams/FailingParamTest.Fails/0
googletest-output-test_.cc:#: Failure
@@ -982,6 +1002,43 @@ Expected failure
Stack trace: (omitted)
[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
+[----------] 3 tests from GoogleTestVerification
+[ RUN ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>
+googletest-output-test_.cc:#: Failure
+Parameterized test suite NoTests is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are defined via TEST_P . No test cases will run.
+
+Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from code that always depend on code that provides TEST_P. Failing to do so is often an indication of dead code, e.g. the last TEST_P was removed but the rest got left behind.
+
+To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NoTests);
+Stack trace: (omitted)
+
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>
+[ RUN ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>
+googletest-output-test_.cc:#: Failure
+Parameterized test suite DetectNotInstantiatedTest is defined via TEST_P, but never instantiated. None of the test cases will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only ones provided expand to nothing.
+
+Ideally, TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.)
+
+To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DetectNotInstantiatedTest);
+Stack trace: (omitted)
+
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>
+[ RUN ] GoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>
+googletest-output-test_.cc:#: Failure
+Type parameterized test suite DetectNotInstantiatedTypesTest is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run.
+
+Ideally, TYPED_TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.)
+
+To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DetectNotInstantiatedTypesTest);
+Stack trace: (omitted)
+
+[ FAILED ] GoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>
[----------] Global test environment tear-down
BarEnvironment::TearDown() called.
googletest-output-test_.cc:#: Failure
@@ -995,9 +1052,12 @@ Failed
Expected fatal failure.
Stack trace: (omitted)
-[==========] 85 tests from 40 test suites ran.
+[==========] 90 tests from 43 test suites ran.
[ PASSED ] 31 tests.
-[ FAILED ] 54 tests, listed below:
+[ SKIPPED ] 2 tests, listed below:
+[ SKIPPED ] TestSuiteThatFailsToSetUp.ShouldNotRun
+[ SKIPPED ] TestSuiteThatSkipsInSetUp.ShouldNotRun
+[ FAILED ] 57 tests, listed below:
[ FAILED ] NonfatalFailureTest.EscapesStringOperands
[ FAILED ] NonfatalFailureTest.DiffForLongStrings
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine
@@ -1052,8 +1112,14 @@ Stack trace: (omitted)
[ FAILED ] BadDynamicFixture2.Derived
[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2
[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>
+[ FAILED ] GoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>
+
+57 FAILED TESTS
+[ FAILED ] TestSuiteThatFailsToSetUp: SetUpTestSuite or TearDownTestSuite
-54 FAILED TESTS
+ 1 FAILED TEST SUITE
 YOU HAVE 1 DISABLED TEST
Note: Google Test filter = FatalFailureTest.*:LoggingTest.*
diff --git a/googletest/test/googletest-output-test.py b/googletest/test/googletest-output-test.py
index c727f17a4963..6d80d5325670 100755
--- a/googletest/test/googletest-output-test.py
+++ b/googletest/test/googletest-output-test.py
@@ -29,7 +29,7 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-"""Tests the text output of Google C++ Testing and Mocking Framework.
+r"""Tests the text output of Google C++ Testing and Mocking Framework.
To update the golden file:
googletest_output_test.py --build_dir=BUILD/DIR --gengolden
@@ -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
@@ -63,20 +63,32 @@ PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('googletest-output-test_')
# 'internal_skip_environment_and_ad_hoc_tests' argument.
COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests'])
COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes'])
-COMMAND_WITH_TIME = ({}, [PROGRAM_PATH,
- '--gtest_print_time',
- 'internal_skip_environment_and_ad_hoc_tests',
- '--gtest_filter=FatalFailureTest.*:LoggingTest.*'])
+COMMAND_WITH_TIME = (
+ {},
+ [
+ PROGRAM_PATH,
+ '--gtest_print_time',
+ 'internal_skip_environment_and_ad_hoc_tests',
+ '--gtest_filter=FatalFailureTest.*:LoggingTest.*',
+ ],
+)
COMMAND_WITH_DISABLED = (
- {}, [PROGRAM_PATH,
- '--gtest_also_run_disabled_tests',
- 'internal_skip_environment_and_ad_hoc_tests',
- '--gtest_filter=*DISABLED_*'])
+ {},
+ [
+ PROGRAM_PATH,
+ '--gtest_also_run_disabled_tests',
+ 'internal_skip_environment_and_ad_hoc_tests',
+ '--gtest_filter=*DISABLED_*',
+ ],
+)
COMMAND_WITH_SHARDING = (
{'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'},
- [PROGRAM_PATH,
- 'internal_skip_environment_and_ad_hoc_tests',
- '--gtest_filter=PassingTest.*'])
+ [
+ PROGRAM_PATH,
+ 'internal_skip_environment_and_ad_hoc_tests',
+ '--gtest_filter=PassingTest.*',
+ ],
+)
GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME)
@@ -100,23 +112,27 @@ def RemoveLocations(test_output):
'FILE_NAME:#: '.
"""
- return re.sub(r'.*[/\\]((googletest-output-test_|gtest).cc)(\:\d+|\(\d+\))\: ',
- r'\1:#: ', test_output)
+ return re.sub(
+ r'.*[/\\]((googletest-output-test_|gtest).cc)(\:\d+|\(\d+\))\: ',
+ r'\1:#: ',
+ test_output,
+ )
def RemoveStackTraceDetails(output):
"""Removes all stack traces from a Google Test program's output."""
# *? means "find the shortest string that matches".
- return re.sub(r'Stack trace:(.|\n)*?\n\n',
- 'Stack trace: (omitted)\n\n', output)
+ return re.sub(
+ r'Stack trace:(.|\n)*?\n\n', 'Stack trace: (omitted)\n\n', output
+ )
def RemoveStackTraces(output):
"""Removes all traces of stack traces from a Google Test program's output."""
# *? means "find the shortest string that matches".
- return re.sub(r'Stack trace:(.|\n)*?\n\n', '', output)
+ return re.sub(r'Stack trace:(.|\n)*?\n', '', output)
def RemoveTime(output):
@@ -156,14 +172,12 @@ def NormalizeToCurrentPlatform(test_output):
def RemoveTestCounts(output):
"""Removes test counts from a Google Test program's output."""
- output = re.sub(r'\d+ tests?, listed below',
- '? tests, listed below', output)
- output = re.sub(r'\d+ FAILED TESTS',
- '? FAILED TESTS', output)
- output = re.sub(r'\d+ tests? from \d+ test cases?',
- '? tests from ? test cases', output)
- output = re.sub(r'\d+ tests? from ([a-zA-Z_])',
- r'? tests from \1', output)
+ output = re.sub(r'\d+ tests?, listed below', '? tests, listed below', output)
+ output = re.sub(r'\d+ FAILED TESTS', '? FAILED TESTS', output)
+ output = re.sub(
+ r'\d+ tests? from \d+ test cases?', '? tests from ? test cases', output
+ )
+ output = re.sub(r'\d+ tests? from ([a-zA-Z_])', r'? tests from \1', output)
return re.sub(r'\d+ tests?\.', '? tests.', output)
@@ -175,18 +189,19 @@ def RemoveMatchingTests(test_output, pattern):
Args:
test_output: A string containing the test output.
- pattern: A regex string that matches names of test cases or
- tests to remove.
+ pattern: A regex string that matches names of test cases or tests
+ to remove.
Returns:
Contents of test_output with tests whose names match pattern removed.
"""
test_output = re.sub(
- r'.*\[ RUN \] .*%s(.|\n)*?\[( FAILED | OK )\] .*%s.*\n' % (
- pattern, pattern),
+ r'.*\[ RUN \] .*%s(.|\n)*?\[( FAILED | OK )\] .*%s.*\n'
+ % (pattern, pattern),
'',
- test_output)
+ test_output,
+ )
return re.sub(r'.*%s.*\n' % pattern, '', test_output)
@@ -205,8 +220,8 @@ def GetShellCommandOutput(env_cmd):
Args:
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
- environment variables to set, and element 1 is a string with
- the command and any flags.
+ environment variables to set, and element 1 is a string with the command
+ and any flags.
Returns:
A string with the command's combined standard and diagnostic output.
@@ -222,13 +237,16 @@ def GetShellCommandOutput(env_cmd):
def GetCommandOutput(env_cmd):
- """Runs a command and returns its output with all file location
- info stripped off.
+ """Runs a command and returns output with all file location info stripped off.
Args:
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
- environment variables to set, and element 1 is a string with
- the command and any flags.
+ environment variables to set, and element 1 is a string with the command
+ and any flags.
+
+ Returns:
+ A string with the command's combined standard and diagnostic output. File
+ location info is stripped.
"""
# Disables exception pop-ups on Windows.
@@ -241,10 +259,12 @@ def GetCommandOutput(env_cmd):
def GetOutputOfAllCommands():
"""Returns concatenated output from several representative commands."""
- return (GetCommandOutput(COMMAND_WITH_COLOR) +
- GetCommandOutput(COMMAND_WITH_TIME) +
- GetCommandOutput(COMMAND_WITH_DISABLED) +
- GetCommandOutput(COMMAND_WITH_SHARDING))
+ return (
+ GetCommandOutput(COMMAND_WITH_COLOR)
+ + GetCommandOutput(COMMAND_WITH_TIME)
+ + GetCommandOutput(COMMAND_WITH_DISABLED)
+ + GetCommandOutput(COMMAND_WITH_SHARDING)
+ )
test_list = GetShellCommandOutput(COMMAND_LIST_TESTS)
@@ -253,12 +273,16 @@ SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list
SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list
SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv
-CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and
- SUPPORTS_TYPED_TESTS and
- SUPPORTS_THREADS and
- SUPPORTS_STACK_TRACES)
+CAN_GENERATE_GOLDEN_FILE = (
+ SUPPORTS_DEATH_TESTS
+ and SUPPORTS_TYPED_TESTS
+ and SUPPORTS_THREADS
+ and SUPPORTS_STACK_TRACES
+)
+
class GTestOutputTest(gtest_test_utils.TestCase):
+
def RemoveUnsupportedTests(self, test_output):
if not SUPPORTS_DEATH_TESTS:
test_output = RemoveMatchingTests(test_output, 'DeathTest')
@@ -267,12 +291,13 @@ class GTestOutputTest(gtest_test_utils.TestCase):
test_output = RemoveMatchingTests(test_output, 'TypedDeathTest')
test_output = RemoveMatchingTests(test_output, 'TypeParamDeathTest')
if not SUPPORTS_THREADS:
- test_output = RemoveMatchingTests(test_output,
- 'ExpectFailureWithThreadsTest')
- test_output = RemoveMatchingTests(test_output,
- 'ScopedFakeTestPartResultReporterTest')
- test_output = RemoveMatchingTests(test_output,
- 'WorksConcurrently')
+ test_output = RemoveMatchingTests(
+ test_output, 'ExpectFailureWithThreadsTest'
+ )
+ test_output = RemoveMatchingTests(
+ test_output, 'ScopedFakeTestPartResultReporterTest'
+ )
+ test_output = RemoveMatchingTests(test_output, 'WorksConcurrently')
if not SUPPORTS_STACK_TRACES:
test_output = RemoveStackTraces(test_output)
@@ -297,27 +322,42 @@ class GTestOutputTest(gtest_test_utils.TestCase):
normalized_golden = RemoveTypeInfoDetails(golden)
if CAN_GENERATE_GOLDEN_FILE:
- self.assertEqual(normalized_golden, normalized_actual,
- '\n'.join(difflib.unified_diff(
- normalized_golden.split('\n'),
- normalized_actual.split('\n'),
- 'golden', 'actual')))
+ self.assertEqual(
+ normalized_golden,
+ normalized_actual,
+ '\n'.join(
+ difflib.unified_diff(
+ normalized_golden.split('\n'),
+ normalized_actual.split('\n'),
+ 'golden',
+ 'actual',
+ )
+ ),
+ )
else:
normalized_actual = NormalizeToCurrentPlatform(
- RemoveTestCounts(normalized_actual))
+ RemoveTestCounts(normalized_actual)
+ )
normalized_golden = NormalizeToCurrentPlatform(
- RemoveTestCounts(self.RemoveUnsupportedTests(normalized_golden)))
+ RemoveTestCounts(self.RemoveUnsupportedTests(normalized_golden))
+ )
# This code is very handy when debugging golden file differences:
if os.getenv('DEBUG_GTEST_OUTPUT_TEST'):
- open(os.path.join(
- gtest_test_utils.GetSourceDir(),
- '_googletest-output-test_normalized_actual.txt'), 'wb').write(
- normalized_actual)
- open(os.path.join(
- gtest_test_utils.GetSourceDir(),
- '_googletest-output-test_normalized_golden.txt'), 'wb').write(
- normalized_golden)
+ open(
+ os.path.join(
+ gtest_test_utils.GetSourceDir(),
+ '_googletest-output-test_normalized_actual.txt',
+ ),
+ 'wb',
+ ).write(normalized_actual)
+ open(
+ os.path.join(
+ gtest_test_utils.GetSourceDir(),
+ '_googletest-output-test_normalized_golden.txt',
+ ),
+ 'wb',
+ ).write(normalized_golden)
self.assertEqual(normalized_golden, normalized_actual)
@@ -331,14 +371,13 @@ if __name__ == '__main__':
if CAN_GENERATE_GOLDEN_FILE:
output = GetOutputOfAllCommands()
golden_file = open(GOLDEN_PATH, 'wb')
- golden_file.write(output)
+ golden_file.write(output.encode())
golden_file.close()
else:
- message = (
- """Unable to write a golden file when compiled in an environment
+ message = """Unable to write a golden file when compiled in an environment
that does not support all the required features (death tests,
typed tests, stack traces, and multiple threads).
-Please build this test and generate the golden file using Blaze on Linux.""")
+Please build this test and generate the golden file using Blaze on Linux."""
sys.stderr.write(message)
sys.exit(1)
diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc
index 4f716d843b12..e3560c0182f8 100644
--- a/googletest/test/googletest-output-test_.cc
+++ b/googletest/test/googletest-output-test_.cc
@@ -33,17 +33,18 @@
// desired messages. Therefore, most tests in this file are MEANT TO
// FAIL.
+#include <stdlib.h>
+
+#include <algorithm>
+#include <string>
+
#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
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
using testing::ScopedFakeTestPartResultReporter;
using testing::TestPartResultArray;
@@ -56,9 +57,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 +75,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 +140,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]);
}
@@ -258,7 +250,7 @@ TEST(SCOPED_TRACETest, CanBeRepeated) {
<< "contain trace point A, B, and D.";
}
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
// Tests that SCOPED_TRACE()s can be used concurrently from multiple
// threads. Namely, an assertion should be affected by
// SCOPED_TRACE()s in its own thread only.
@@ -297,16 +289,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 +315,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 +400,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 +422,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 +442,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) {
@@ -476,63 +458,6 @@ TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) {
GTEST_FAIL_AT("foo.cc", 42) << "Expected fatal failure in foo.cc";
}
-#if GTEST_IS_THREADSAFE
-
-// A unary function that may die.
-void DieIf(bool should_die) {
- GTEST_CHECK_(!should_die) << " - death inside DieIf().";
-}
-
-// Tests running death tests in a multi-threaded context.
-
-// Used for coordination between the main and the spawn thread.
-struct SpawnThreadNotifications {
- SpawnThreadNotifications() {}
-
- Notification spawn_thread_started;
- Notification spawn_thread_ok_to_terminate;
-
- private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(SpawnThreadNotifications);
-};
-
-// The function to be executed in the thread spawn by the
-// MultipleThreads test (below).
-static void ThreadRoutine(SpawnThreadNotifications* notifications) {
- // Signals the main thread that this thread has started.
- notifications->spawn_thread_started.Notify();
-
- // Waits for permission to finish from the main thread.
- notifications->spawn_thread_ok_to_terminate.WaitForNotification();
-}
-
-// This is a death-test test, but it's not named with a DeathTest
-// suffix. It starts threads which might interfere with later
-// death tests, so it must run after all other death tests.
-class DeathTestAndMultiThreadsTest : public testing::Test {
- protected:
- // Starts a thread and waits for it to begin.
- void SetUp() override {
- thread_.reset(new ThreadWithParam<SpawnThreadNotifications*>(
- &ThreadRoutine, &notifications_, nullptr));
- notifications_.spawn_thread_started.WaitForNotification();
- }
- // Tells the thread to finish, and reaps it.
- // Depending on the version of the thread library in use,
- // a manager thread might still be left running that will interfere
- // with later death tests. This is unfortunate, but this class
- // cleans up after itself as best it can.
- void TearDown() override {
- notifications_.spawn_thread_ok_to_terminate.Notify();
- }
-
- private:
- SpawnThreadNotifications notifications_;
- std::unique_ptr<ThreadWithParam<SpawnThreadNotifications*> > thread_;
-};
-
-#endif // GTEST_IS_THREADSAFE
-
// The MixedUpTestSuiteTest test case verifies that Google Test will fail a
// test if it uses a different fixture class than what other tests in
// the same test case use. It deliberately contains two fixture
@@ -545,14 +470,12 @@ class DeathTestAndMultiThreadsTest : public testing::Test {
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) {}
@@ -561,16 +484,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.
@@ -584,8 +505,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) {}
@@ -593,15 +513,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;
@@ -609,9 +527,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
@@ -620,53 +538,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
@@ -676,10 +589,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
}
}
@@ -688,9 +599,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
@@ -698,58 +609,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
@@ -759,10 +663,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
}
}
@@ -774,34 +676,32 @@ 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);
-// This #ifdef block tests the output of typed tests.
-#if GTEST_HAS_TYPED_TEST
+// The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P.
+using NoTests = ParamTest;
+INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello"));
+
+// fails under kErrorOnUninstantiatedParameterizedTest=true
+class DetectNotInstantiatedTest : public testing::TestWithParam<int> {};
+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";
@@ -829,20 +729,12 @@ TYPED_TEST(TypedTestWithNames, Success) {}
TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); }
-#endif // GTEST_HAS_TYPED_TEST
-
-// This #ifdef block tests the output of type-parameterized tests.
-#if GTEST_HAS_TYPED_TEST_P
-
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";
@@ -867,66 +759,62 @@ class TypedTestPNames {
};
INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes,
- TypedTestPNames);
+ TypedTestPNames);
-#endif // GTEST_HAS_TYPED_TEST_P
+template <typename T>
+class DetectNotInstantiatedTypesTest : public testing::Test {};
+TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest);
+TYPED_TEST_P(DetectNotInstantiatedTypesTest, Used) {
+ TypeParam instantiate;
+ (void)instantiate;
+}
+REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used);
+
+// kErrorOnUninstantiatedTypeParameterizedTest=true would make the above fail.
+// Adding the following would make that test failure go away.
+//
+// typedef ::testing::Types<char, int, unsigned int> MyTypes;
+// INSTANTIATE_TYPED_TEST_SUITE_P(All, DetectNotInstantiatedTypesTest, MyTypes);
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
// We rely on the golden file to verify that tests whose test case
// name ends with DeathTest are run first.
-TEST(ADeathTest, ShouldRunFirst) {
-}
-
-# if GTEST_HAS_TYPED_TEST
+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) {
-}
-
-# endif // GTEST_HAS_TYPED_TEST
-
-# if GTEST_HAS_TYPED_TEST_P
-
+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);
INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes);
-# endif // GTEST_HAS_TYPED_TEST_P
-
#endif // GTEST_HAS_DEATH_TEST
// Tests various failure conditions of
// 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.";
@@ -942,11 +830,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.");
}
@@ -959,11 +849,12 @@ 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.");
}
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
class ExpectFailureWithThreadsTest : public ExpectFailureTest {
protected:
@@ -1024,7 +915,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");
@@ -1078,7 +970,7 @@ auto dynamic_test = (
"BadDynamicFixture1", "TestBase", nullptr, nullptr, __FILE__, __LINE__,
[]() -> testing::Test* { return new DynamicTest<true>; }),
- // Register two tests with the same fixture incorrectly by ommiting the
+ // Register two tests with the same fixture incorrectly by omitting the
// return type.
testing::RegisterTest(
"BadDynamicFixture2", "FixtureBase", nullptr, nullptr, __FILE__,
@@ -1109,49 +1001,58 @@ class BarEnvironment : public testing::Environment {
}
};
+class TestSuiteThatFailsToSetUp : public testing::Test {
+ public:
+ static void SetUpTestSuite() { EXPECT_TRUE(false); }
+};
+TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); }
+
+class TestSuiteThatSkipsInSetUp : public testing::Test {
+ public:
+ static void SetUpTestSuite() { GTEST_SKIP() << "Skip entire test suite"; }
+};
+TEST_F(TestSuiteThatSkipsInSetUp, 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 =
std::count(argv, argv + argc,
std::string("internal_skip_environment_and_ad_hoc_tests")) > 0;
-#if GTEST_HAS_DEATH_TEST
- if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") {
+#ifdef GTEST_HAS_DEATH_TEST
+ if (!GTEST_FLAG_GET(internal_run_death_test).empty()) {
// Skip the usual output capturing if we're running as the child
// process of an threadsafe-style death test.
-# if GTEST_OS_WINDOWS
+#if defined(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
// are registered, and torn down in the reverse order.
testing::AddGlobalTestEnvironment(new FooEnvironment);
testing::AddGlobalTestEnvironment(new BarEnvironment);
-#if _MSC_VER
-GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
-#endif // _MSC_VER
+ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
return RunAllTests();
}
diff --git a/googletest/test/googletest-param-test-invalid-name1-test.py b/googletest/test/googletest-param-test-invalid-name1-test.py
index 2a08477a77eb..4886e49e80f7 100644
--- a/googletest/test/googletest-param-test-invalid-name1-test.py
+++ b/googletest/test/googletest-param-test-invalid-name1-test.py
@@ -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)
@@ -44,7 +44,7 @@ def Assert(condition):
def TestExitCodeAndOutput(command):
"""Runs the given command and verifies its exit code and output."""
- err = ('Parameterized test name \'"InvalidWithQuotes"\' is invalid')
+ err = 'Parameterized test name \'"InvalidWithQuotes"\' is invalid'
p = gtest_test_utils.Subprocess(command)
Assert(p.terminated_by_signal)
diff --git a/googletest/test/googletest-param-test-invalid-name1-test_.cc b/googletest/test/googletest-param-test-invalid-name1-test_.cc
index 955d699900d8..004733a12c50 100644
--- a/googletest/test/googletest-param-test-invalid-name1-test_.cc
+++ b/googletest/test/googletest-param-test-invalid-name1-test_.cc
@@ -27,17 +27,14 @@
// (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();
}
-
diff --git a/googletest/test/googletest-param-test-invalid-name2-test.py b/googletest/test/googletest-param-test-invalid-name2-test.py
index ab838f463229..bcd8ddf0eece 100644
--- a/googletest/test/googletest-param-test-invalid-name2-test.py
+++ b/googletest/test/googletest-param-test-invalid-name2-test.py
@@ -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)
@@ -44,7 +44,7 @@ def Assert(condition):
def TestExitCodeAndOutput(command):
"""Runs the given command and verifies its exit code and output."""
- err = ('Duplicate parameterized test name \'a\'')
+ err = "Duplicate parameterized test name 'a'"
p = gtest_test_utils.Subprocess(command)
Assert(p.terminated_by_signal)
@@ -58,5 +58,6 @@ class GTestParamTestInvalidName2Test(gtest_test_utils.TestCase):
def testExitCodeAndOutput(self):
TestExitCodeAndOutput(COMMAND)
+
if __name__ == '__main__':
gtest_test_utils.Main()
diff --git a/googletest/test/googletest-param-test-invalid-name2-test_.cc b/googletest/test/googletest-param-test-invalid-name2-test_.cc
index 76371df54f0b..6d88a9ce393f 100644
--- a/googletest/test/googletest-param-test-invalid-name2-test_.cc
+++ b/googletest/test/googletest-param-test-invalid-name2-test_.cc
@@ -27,6 +27,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#include <string>
#include "gtest/gtest.h"
@@ -34,15 +35,13 @@ 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 +50,3 @@ int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
-
-
diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc
index 6c187dfff0c1..c9c5e78e49f4 100644
--- a/googletest/test/googletest-param-test-test.cc
+++ b/googletest/test/googletest-param-test-test.cc
@@ -32,24 +32,27 @@
// 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 <sstream>
-# include <string>
-# include <vector>
+#include <algorithm>
+#include <iostream>
+#include <list>
+#include <set>
+#include <sstream>
+#include <string>
+#include <tuple>
+#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;
using ::testing::Combine;
+using ::testing::ConvertGenerator;
using ::testing::Message;
using ::testing::Range;
using ::testing::TestWithParam;
@@ -84,15 +87,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
@@ -104,15 +106,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>
@@ -215,18 +216,15 @@ 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 {
Message msg;
- msg << value_.c_str() << other.value_.c_str();
+ msg << value_ << other.value_;
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:
@@ -371,19 +369,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);
}
@@ -408,7 +404,7 @@ TEST(BoolTest, BoolWorks) {
TEST(CombineTest, CombineWithTwoParameters) {
const char* foo = "foo";
const char* bar = "bar";
- const ParamGenerator<std::tuple<const char*, int> > gen =
+ const ParamGenerator<std::tuple<const char*, int>> gen =
Combine(Values(foo, bar), Values(3, 4));
std::tuple<const char*, int> expected_values[] = {
@@ -419,7 +415,7 @@ TEST(CombineTest, CombineWithTwoParameters) {
// Tests that Combine() with three parameters generates the expected sequence.
TEST(CombineTest, CombineWithThreeParameters) {
- const ParamGenerator<std::tuple<int, int, int> > gen =
+ const ParamGenerator<std::tuple<int, int, int>> gen =
Combine(Values(0, 1), Values(3, 4), Values(5, 6));
std::tuple<int, int, int> expected_values[] = {
std::make_tuple(0, 3, 5), std::make_tuple(0, 3, 6),
@@ -433,7 +429,7 @@ TEST(CombineTest, CombineWithThreeParameters) {
// sequence generates a sequence with the number of elements equal to the
// number of elements in the sequence generated by the second parameter.
TEST(CombineTest, CombineWithFirstParameterSingleValue) {
- const ParamGenerator<std::tuple<int, int> > gen =
+ const ParamGenerator<std::tuple<int, int>> gen =
Combine(Values(42), Values(0, 1));
std::tuple<int, int> expected_values[] = {std::make_tuple(42, 0),
@@ -445,7 +441,7 @@ TEST(CombineTest, CombineWithFirstParameterSingleValue) {
// sequence generates a sequence with the number of elements equal to the
// number of elements in the sequence generated by the first parameter.
TEST(CombineTest, CombineWithSecondParameterSingleValue) {
- const ParamGenerator<std::tuple<int, int> > gen =
+ const ParamGenerator<std::tuple<int, int>> gen =
Combine(Values(0, 1), Values(42));
std::tuple<int, int> expected_values[] = {std::make_tuple(0, 42),
@@ -456,7 +452,7 @@ TEST(CombineTest, CombineWithSecondParameterSingleValue) {
// Tests that when the first parameter produces an empty sequence,
// Combine() produces an empty sequence, too.
TEST(CombineTest, CombineWithFirstParameterEmptyRange) {
- const ParamGenerator<std::tuple<int, int> > gen =
+ const ParamGenerator<std::tuple<int, int>> gen =
Combine(Range(0, 0), Values(0, 1));
VerifyGeneratorIsEmpty(gen);
}
@@ -464,7 +460,7 @@ TEST(CombineTest, CombineWithFirstParameterEmptyRange) {
// Tests that when the second parameter produces an empty sequence,
// Combine() produces an empty sequence, too.
TEST(CombineTest, CombineWithSecondParameterEmptyRange) {
- const ParamGenerator<std::tuple<int, int> > gen =
+ const ParamGenerator<std::tuple<int, int>> gen =
Combine(Values(0, 1), Range(1, 1));
VerifyGeneratorIsEmpty(gen);
}
@@ -475,7 +471,7 @@ TEST(CombineTest, CombineWithMaxNumberOfParameters) {
const char* foo = "foo";
const char* bar = "bar";
const ParamGenerator<
- std::tuple<const char*, int, int, int, int, int, int, int, int, int> >
+ std::tuple<const char*, int, int, int, int, int, int, int, int, int>>
gen =
Combine(Values(foo, bar), Values(1), Values(2), Values(3), Values(4),
Values(5), Values(6), Values(7), Values(8), Values(9));
@@ -489,24 +485,25 @@ TEST(CombineTest, CombineWithMaxNumberOfParameters) {
class NonDefaultConstructAssignString {
public:
NonDefaultConstructAssignString(const std::string& s) : str_(s) {}
+ NonDefaultConstructAssignString() = delete;
+ NonDefaultConstructAssignString(const NonDefaultConstructAssignString&) =
+ default;
+ NonDefaultConstructAssignString& operator=(
+ const NonDefaultConstructAssignString&) = delete;
+ ~NonDefaultConstructAssignString() = default;
const std::string& str() const { return str_; }
private:
std::string str_;
-
- // Not default constructible
- NonDefaultConstructAssignString();
- // Not assignable
- void operator=(const NonDefaultConstructAssignString&);
};
TEST(CombineTest, NonDefaultConstructAssign) {
- const ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> > gen =
+ const ParamGenerator<std::tuple<int, NonDefaultConstructAssignString>> gen =
Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"),
NonDefaultConstructAssignString("B")));
- ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> >::iterator
+ ParamGenerator<std::tuple<int, NonDefaultConstructAssignString>>::iterator
it = gen.begin();
EXPECT_EQ(0, std::get<0>(*it));
@@ -528,6 +525,63 @@ TEST(CombineTest, NonDefaultConstructAssign) {
EXPECT_TRUE(it == gen.end());
}
+template <typename T>
+class ConstructFromT {
+ public:
+ explicit ConstructFromT(const T& t) : t_(t) {}
+ template <typename... Args,
+ typename std::enable_if<sizeof...(Args) != 1, int>::type = 0>
+ ConstructFromT(Args&&... args) : t_(std::forward<Args>(args)...) {}
+
+ bool operator==(const ConstructFromT& other) const { return other.t_ == t_; }
+
+ const T& get() const { return t_; }
+
+ private:
+ T t_;
+};
+
+TEST(ConvertTest, CombineWithTwoParameters) {
+ const char* foo = "foo";
+ const char* bar = "bar";
+ const ParamGenerator<ConstructFromT<std::tuple<const char*, int>>> gen =
+ ConvertGenerator<std::tuple<const char*, int>>(
+ Combine(Values(foo, bar), Values(3, 4)));
+
+ ConstructFromT<std::tuple<const char*, int>> expected_values[] = {
+ {foo, 3}, {foo, 4}, {bar, 3}, {bar, 4}};
+ VerifyGenerator(gen, expected_values);
+}
+
+TEST(ConvertTest, NonDefaultConstructAssign) {
+ const ParamGenerator<
+ ConstructFromT<std::tuple<int, NonDefaultConstructAssignString>>>
+ gen = ConvertGenerator<std::tuple<int, NonDefaultConstructAssignString>>(
+ Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"),
+ NonDefaultConstructAssignString("B"))));
+
+ ParamGenerator<ConstructFromT<
+ std::tuple<int, NonDefaultConstructAssignString>>>::iterator it =
+ gen.begin();
+
+ EXPECT_EQ(0, std::get<0>(it->get()));
+ EXPECT_EQ("A", std::get<1>(it->get()).str());
+ ++it;
+
+ EXPECT_EQ(0, std::get<0>(it->get()));
+ EXPECT_EQ("B", std::get<1>(it->get()).str());
+ ++it;
+
+ EXPECT_EQ(1, std::get<0>(it->get()));
+ EXPECT_EQ("A", std::get<1>(it->get()).str());
+ ++it;
+
+ EXPECT_EQ(1, std::get<0>(it->get()));
+ EXPECT_EQ("B", std::get<1>(it->get()).str());
+ ++it;
+
+ EXPECT_TRUE(it == gen.end());
+}
// Tests that an generator produces correct sequence after being
// assigned from another generator.
@@ -571,7 +625,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;
}
@@ -593,15 +647,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};
@@ -610,7 +669,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;
@@ -634,9 +693,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;
}
}
@@ -666,7 +725,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_;
@@ -727,8 +787,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));
@@ -778,7 +837,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());
@@ -799,10 +858,10 @@ 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", test_info->name());
+ EXPECT_STREQ("FooSomeTestName/0", test_info->name());
}
INSTANTIATE_TEST_SUITE_P(FortyTwo, MacroNamingTest, Values(42));
@@ -813,12 +872,41 @@ 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());
}
+TEST(MacroNameing, LookupNames) {
+ std::set<std::string> know_suite_names, know_test_names;
+
+ const auto& ins = testing::UnitTest::GetInstance();
+ int ts = 0;
+ while (const testing::TestSuite* suite = ins->GetTestSuite(ts++)) {
+ know_suite_names.insert(suite->name());
+
+ int ti = 0;
+ while (const testing::TestInfo* info = suite->GetTestInfo(ti++)) {
+ know_test_names.insert(std::string(suite->name()) + "." + info->name());
+ }
+ }
+
+ // Check that the expected form of the test suit name actually exists.
+ EXPECT_NE( //
+ know_suite_names.find("FortyTwo/MacroNamingTest"),
+ 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"),
+ know_test_names.end());
+ EXPECT_NE(
+ know_test_names.find("MacroNamingTestNonParametrized.FooSomeTestName"),
+ know_test_names.end());
+}
+
// Tests that user supplied custom parameter names are working correctly.
// Runs the test with a builtin helper method which uses PrintToString,
// as well as a custom function and custom functor to ensure all possible
@@ -869,7 +957,7 @@ INSTANTIATE_TEST_SUITE_P(CustomParamNameLambda, CustomLambdaNamingTest,
});
TEST(CustomNamingTest, CheckNameRegistry) {
- ::testing::UnitTest* unit_test = ::testing::UnitTest::GetInstance();
+ const auto& unit_test = ::testing::UnitTest::GetInstance();
std::set<std::string> test_names;
for (int suite_num = 0; suite_num < unit_test->total_test_suite_count();
++suite_num) {
@@ -892,7 +980,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());
@@ -917,7 +1005,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());
@@ -947,7 +1035,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_;
@@ -975,7 +1063,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());
}
@@ -989,7 +1077,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_;
};
@@ -997,16 +1086,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_);
@@ -1014,11 +1101,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,
@@ -1037,7 +1123,39 @@ TEST_P(MyEnumTest, ChecksParamMoreThanZero) { EXPECT_GE(10, GetParam()); }
INSTANTIATE_TEST_SUITE_P(MyEnumTests, MyEnumTest,
::testing::Values(ENUM1, ENUM2, 0));
-int main(int argc, char **argv) {
+namespace works_here {
+// Never used not instantiated, this should work.
+class NotUsedTest : public testing::TestWithParam<int> {};
+
+///////
+// Never used not instantiated, this should work.
+template <typename T>
+class NotUsedTypeTest : public testing::Test {};
+TYPED_TEST_SUITE_P(NotUsedTypeTest);
+
+// Used but not instantiated, this would fail. but...
+class NotInstantiatedTest : public testing::TestWithParam<int> {};
+// ... we mark is as allowed.
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest);
+
+TEST_P(NotInstantiatedTest, Used) {}
+
+using OtherName = NotInstantiatedTest;
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName);
+TEST_P(OtherName, Used) {}
+
+// Used but not instantiated, this would fail. but...
+template <typename T>
+class NotInstantiatedTypeTest : public testing::Test {};
+TYPED_TEST_SUITE_P(NotInstantiatedTypeTest);
+// ... we mark is as allowed.
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest);
+
+TYPED_TEST_P(NotInstantiatedTypeTest, Used) {}
+REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used);
+} // namespace works_here
+
+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
diff --git a/googletest/test/googletest-param-test-test.h b/googletest/test/googletest-param-test-test.h
index 648057017e84..6d77e1049abc 100644
--- a/googletest/test/googletest-param-test-test.h
+++ b/googletest/test/googletest-param-test-test.h
@@ -32,20 +32,18 @@
// This header file provides classes and functions used internally
// for testing Google Test itself.
-#ifndef GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
-#define GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
+#ifndef GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_
+#define GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_
#include "gtest/gtest.h"
// Test fixture for testing definition and instantiation of a test
// in separate translation units.
-class ExternalInstantiationTest : public ::testing::TestWithParam<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 // GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
+#endif // GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_
diff --git a/googletest/test/googletest-param-test2-test.cc b/googletest/test/googletest-param-test2-test.cc
index 2a29fb1d0686..71727a674f09 100644
--- a/googletest/test/googletest-param-test2-test.cc
+++ b/googletest/test/googletest-param-test2-test.cc
@@ -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));
diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc
index 60d637c32f63..32a2a7b4d642 100644
--- a/googletest/test/googletest-port-test.cc
+++ b/googletest/test/googletest-port-test.cc
@@ -32,17 +32,20 @@
#include "gtest/internal/gtest-port.h"
-#if GTEST_OS_MAC
-# include <time.h>
+#ifdef GTEST_OS_MAC
+#include <time.h>
#endif // GTEST_OS_MAC
+#include <chrono> // NOLINT
#include <list>
#include <memory>
+#include <string>
+#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;
@@ -90,11 +93,11 @@ TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
class Base {
public:
- // Copy constructor and assignment operator do exactly what we need, so we
- // use them.
Base() : member_(0) {}
explicit Base(int n) : member_(n) {}
- virtual ~Base() {}
+ Base(const Base&) = default;
+ Base& operator=(const Base&) = default;
+ virtual ~Base() = default;
int member() { return member_; }
private:
@@ -201,6 +204,13 @@ TEST(ImplicitCastTest, CanUseImplicitConstructor) {
EXPECT_TRUE(converted);
}
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
if (AlwaysFalse())
GTEST_CHECK_(false) << "This should never be executed; "
@@ -216,6 +226,9 @@ TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
else
GTEST_CHECK_(true) << "";
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
switch (0) {
@@ -226,8 +239,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.
@@ -268,9 +281,11 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(nullptr, -1));
}
-#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
+#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || \
+ defined(GTEST_OS_QNX) || defined(GTEST_OS_FUCHSIA) || \
+ defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD) || \
+ defined(GTEST_OS_OPENBSD) || defined(GTEST_OS_GNU_HURD)
void* ThreadFunc(void* data) {
internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
mutex->Lock();
@@ -279,36 +294,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) {
@@ -320,25 +360,27 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
const bool a_false_condition = false;
const char regex[] =
#ifdef _MSC_VER
- "googletest-port-test\\.cc\\(\\d+\\):"
-#elif GTEST_USES_POSIX_RE
- "googletest-port-test\\.cc:[0-9]+"
+ "googletest-port-test\\.cc\\(\\d+\\):"
+#elif defined(GTEST_USES_POSIX_RE)
+ "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);
}
-#if GTEST_HAS_DEATH_TEST
+#ifdef 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");
}
@@ -348,22 +390,16 @@ 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
-
+#ifdef 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
-
-# if GTEST_HAS_TYPED_TEST
+#ifdef GTEST_USES_POSIX_RE
template <typename Str>
class RETest : public ::testing::Test {};
@@ -388,9 +424,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().
@@ -420,9 +456,7 @@ TYPED_TEST(RETest, PartialMatchWorks) {
EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
}
-# endif // GTEST_HAS_TYPED_TEST
-
-#elif GTEST_USES_SIMPLE_RE
+#elif defined(GTEST_USES_SIMPLE_RE)
TEST(IsInSetTest, NulCharIsNotInAnySet) {
EXPECT_FALSE(IsInSet('\0', ""));
@@ -786,8 +820,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"));
@@ -843,17 +876,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().
@@ -888,7 +918,7 @@ TEST(RETest, PartialMatchWorks) {
#endif // GTEST_USES_POSIX_RE
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
TEST(CaptureTest, CapturesStdout) {
CaptureStdout();
@@ -949,14 +979,14 @@ TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
EXPECT_EQ(&i, t2.get());
}
-class NoDefaultContructor {
+class NoDefaultConstructor {
public:
- explicit NoDefaultContructor(const char*) {}
- NoDefaultContructor(const NoDefaultContructor&) {}
+ explicit NoDefaultConstructor(const char*) {}
+ NoDefaultConstructor(const NoDefaultConstructor&) = default;
};
TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
- ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
+ ThreadLocal<NoDefaultConstructor> bar(NoDefaultConstructor("foo"));
bar.pointer();
}
@@ -981,7 +1011,7 @@ TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
}
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
void AddTwo(int* param) { *param += 2; }
@@ -995,12 +1025,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) {
@@ -1011,15 +1042,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
@@ -1030,18 +1061,20 @@ 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));
-#elif GTEST_OS_WINDOWS
+#elif defined(GTEST_OS_WINDOWS)
// 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;
@@ -1051,12 +1084,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.
@@ -1072,14 +1104,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] = std::make_unique<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
@@ -1089,7 +1119,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();
}
@@ -1118,14 +1148,14 @@ class DestructorCall {
public:
DestructorCall() {
invoked_ = false;
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
GTEST_CHECK_(wait_event_.Get() != NULL);
#endif
}
bool CheckDestroyed() const {
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
return false;
#endif
@@ -1134,7 +1164,7 @@ class DestructorCall {
void ReportDestroyed() {
invoked_ = true;
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
::SetEvent(wait_event_.Get());
#endif
}
@@ -1150,12 +1180,13 @@ class DestructorCall {
private:
bool invoked_;
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
AutoHandle wait_event_;
#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_ =
@@ -1180,8 +1211,6 @@ class DestructorTracker {
return DestructorCall::List().size() - 1;
}
const size_t index_;
-
- GTEST_DISALLOW_ASSIGN_(DestructorTracker);
};
typedef ThreadLocal<DestructorTracker>* ThreadParam;
@@ -1251,12 +1280,12 @@ TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
#endif // GTEST_IS_THREADSAFE
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
TEST(WindowsTypesTest, HANDLEIsVoidStar) {
StaticAssertTypeEq<HANDLE, void*>();
}
-#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
+#if defined(GTEST_OS_WINDOWS_MINGW) && !defined(__MINGW64_VERSION_MAJOR)
TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {
StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>();
}
diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc
index 4bdc9adde9e0..bee0ca4abe10 100644
--- a/googletest/test/googletest-printers-test.cc
+++ b/googletest/test/googletest-printers-test.cc
@@ -27,22 +27,26 @@
// (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.
-#include <ctype.h>
-#include <limits.h>
-#include <string.h>
#include <algorithm>
+#include <cctype>
+#include <cstdint>
+#include <cstring>
#include <deque>
#include <forward_list>
+#include <functional>
+#include <limits>
#include <list>
#include <map>
+#include <memory>
+#include <ostream>
#include <set>
#include <sstream>
#include <string>
+#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
@@ -51,33 +55,27 @@
#include "gtest/gtest-printers.h"
#include "gtest/gtest.h"
+#ifdef GTEST_HAS_ABSL
+#include "absl/strings/str_format.h"
+#endif
+
// 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");
@@ -89,11 +87,24 @@ class BiggestIntConvertible {
operator ::testing::internal::BiggestInt() const { return 42; }
};
+// A parent class with two child classes. The parent and one of the kids have
+// stream operators.
+class ParentClass {};
+class ChildClassWithStreamOperator : public ParentClass {};
+class ChildClassWithoutStreamOperator : public ParentClass {};
+static void operator<<(std::ostream& os, const ParentClass&) {
+ os << "ParentClass";
+}
+static void operator<<(std::ostream& os, const ChildClassWithStreamOperator&) {
+ os << "ChildClassWithStreamOperator";
+}
+
// A user-defined unprintable class template in the global namespace.
template <typename T>
class UnprintableTemplateInGlobal {
public:
UnprintableTemplateInGlobal() : value_() {}
+
private:
T value_;
};
@@ -101,7 +112,7 @@ class UnprintableTemplateInGlobal {
// A user-defined streamable type in the global namespace.
class StreamableInGlobal {
public:
- virtual ~StreamableInGlobal() {}
+ virtual ~StreamableInGlobal() = default;
};
inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {
@@ -112,6 +123,19 @@ void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
os << "StreamableInGlobal*";
}
+#ifdef GTEST_HAS_ABSL
+// A user-defined type with AbslStringify
+struct Point {
+ template <typename Sink>
+ friend void AbslStringify(Sink& sink, const Point& p) {
+ absl::Format(&sink, "(%d, %d)", p.x, p.y);
+ }
+
+ int x = 10;
+ int y = 20;
+};
+#endif
+
namespace foo {
// A user-defined unprintable type in a user namespace.
@@ -119,6 +143,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_;
@@ -135,8 +160,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 */) {
@@ -150,6 +174,7 @@ class PrintableViaPrintToTemplate {
explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
const T& value() const { return value_; }
+
private:
T value_;
};
@@ -166,6 +191,7 @@ class StreamableTemplateInFoo {
StreamableTemplateInFoo() : value_() {}
const T& value() const { return value_; }
+
private:
T value_;
};
@@ -176,7 +202,23 @@ inline ::std::ostream& operator<<(::std::ostream& os,
return os << "StreamableTemplateInFoo: " << x.value();
}
-// A user-defined streamable but recursivly-defined container type in
+// A user-defined streamable type in a user namespace whose operator<< is
+// templated on the type of the output stream.
+struct TemplatedStreamableInFoo {};
+
+template <typename OutputStream>
+OutputStream& operator<<(OutputStream& os,
+ const TemplatedStreamableInFoo& /*ts*/) {
+ os << "TemplatedStreamableInFoo";
+ return os;
+}
+
+struct StreamableInLocal {};
+void operator<<(::std::ostream& os, const StreamableInLocal& /* x */) {
+ os << "StreamableInLocal";
+}
+
+// A user-defined streamable but recursively-defined container type in
// a user namespace, it mimics therefore std::filesystem::path or
// boost::filesystem::path.
class PathLike {
@@ -191,7 +233,7 @@ class PathLike {
using value_type = char;
using const_iterator = iterator;
- PathLike() {}
+ PathLike() = default;
iterator begin() const { return iterator(); }
iterator end() const { return iterator(); }
@@ -204,6 +246,32 @@ class PathLike {
} // namespace foo
namespace testing {
+namespace {
+template <typename T>
+class Wrapper {
+ public:
+ explicit Wrapper(T&& value) : value_(std::forward<T>(value)) {}
+
+ const T& value() const { return value_; }
+
+ private:
+ T value_;
+};
+
+} // namespace
+
+namespace internal {
+template <typename T>
+class UniversalPrinter<Wrapper<T>> {
+ public:
+ static void Print(const Wrapper<T>& w, ::std::ostream* os) {
+ *os << "Wrapper(";
+ UniversalPrint(w.value(), os);
+ *os << ')';
+ }
+};
+} // namespace internal
+
namespace gtest_printers_test {
using ::std::deque;
@@ -217,9 +285,7 @@ using ::std::set;
using ::std::vector;
using ::testing::PrintToString;
using ::testing::internal::FormatForComparisonFailureMessage;
-using ::testing::internal::ImplicitCast_;
using ::testing::internal::NativeArray;
-using ::testing::internal::RE;
using ::testing::internal::RelationToSourceReference;
using ::testing::internal::Strings;
using ::testing::internal::UniversalPrint;
@@ -268,6 +334,11 @@ TEST(PrintEnumTest, EnumWithPrintTo) {
EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
}
+#ifdef GTEST_HAS_ABSL
+// Tests printing a class that defines AbslStringify
+TEST(PrintClassTest, AbslStringify) { EXPECT_EQ("(10, 20)", Print(Point())); }
+#endif
+
// Tests printing a class implicitly convertible to BiggestInt.
TEST(PrintClassTest, BiggestIntConvertible) {
@@ -299,17 +370,23 @@ 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, Char32) { EXPECT_EQ("U+0041", Print(U'A')); }
+
+#ifdef __cpp_lib_char8_t
+TEST(PrintCharTest, Char8) { EXPECT_EQ("U+0041", Print(u8'A')); }
+#endif
+
// Tests printing other simple, built-in types.
// bool.
@@ -340,40 +417,92 @@ TEST(PrintBuiltInTypeTest, Wchar_t) {
EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast<wchar_t>(0xC74D)));
}
-// Test that Int64 provides more storage than wchar_t.
+// Test that int64_t provides more storage than wchar_t.
TEST(PrintTypeSizeTest, Wchar_t) {
- EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64));
+ EXPECT_LT(sizeof(wchar_t), sizeof(int64_t));
}
// Various integer types.
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(USHRT_MAX)); // uint16
- EXPECT_EQ("-32768", Print(SHRT_MIN)); // int16
- EXPECT_EQ("4294967295", Print(UINT_MAX)); // uint32
- EXPECT_EQ("-2147483648", Print(INT_MIN)); // int32
+ 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",
+ Print(std::numeric_limits<int32_t>::min())); // int32
EXPECT_EQ("18446744073709551615",
- Print(static_cast<testing::internal::UInt64>(-1))); // uint64
+ Print(std::numeric_limits<uint64_t>::max())); // uint64
EXPECT_EQ("-9223372036854775808",
- Print(static_cast<testing::internal::Int64>(1) << 63)); // int64
+ Print(std::numeric_limits<int64_t>::min())); // int64
+#ifdef __cpp_lib_char8_t
+ EXPECT_EQ("U+0000",
+ Print(std::numeric_limits<char8_t>::min())); // char8_t
+ EXPECT_EQ("U+00FF",
+ Print(std::numeric_limits<char8_t>::max())); // char8_t
+#endif
+ EXPECT_EQ("U+0000",
+ Print(std::numeric_limits<char16_t>::min())); // char16_t
+ EXPECT_EQ("U+FFFF",
+ Print(std::numeric_limits<char16_t>::max())); // char16_t
+ EXPECT_EQ("U+0000",
+ Print(std::numeric_limits<char32_t>::min())); // char32_t
+ EXPECT_EQ("U+FFFFFFFF",
+ Print(std::numeric_limits<char32_t>::max())); // char32_t
}
// Size types.
TEST(PrintBuiltInTypeTest, Size_t) {
EXPECT_EQ("1", Print(sizeof('a'))); // size_t.
-#if !GTEST_OS_WINDOWS
+#ifndef 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) {
- EXPECT_EQ("1.5", Print(1.5f)); // float
+ // float (32-bit precision)
+ EXPECT_EQ("1.5", Print(1.5f));
+
+ EXPECT_EQ("1.0999999", Print(1.09999990f));
+ EXPECT_EQ("1.1", Print(1.10000002f));
+ EXPECT_EQ("1.10000014", Print(1.10000014f));
+ EXPECT_EQ("9e+09", Print(9e9f));
+
+ // double
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.
@@ -407,8 +536,95 @@ 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));
+}
+
+#ifdef __cpp_lib_char8_t
+// const char8_t*.
+TEST(PrintU8StringTest, Const) {
+ const char8_t* p = u8"界";
+ EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE7\\x95\\x8C\"", Print(p));
+}
+
+// char8_t*.
+TEST(PrintU8StringTest, NonConst) {
+ char8_t p[] = u8"世";
+ EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE4\\xB8\\x96\"",
+ Print(static_cast<char8_t*>(p)));
+}
+
+// NULL u8 string.
+TEST(PrintU8StringTest, Null) {
+ const char8_t* p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+
+// Tests that u8 strings are escaped properly.
+TEST(PrintU8StringTest, EscapesProperly) {
+ const char8_t* p = u8"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
+ EXPECT_EQ(PrintPointer(p) +
+ " pointing to u8\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
+ "hello \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
+ Print(p));
+}
+#endif
+
+// const char16_t*.
+TEST(PrintU16StringTest, Const) {
+ const char16_t* p = u"界";
+ EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x754C\"", Print(p));
+}
+
+// char16_t*.
+TEST(PrintU16StringTest, NonConst) {
+ char16_t p[] = u"世";
+ EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x4E16\"",
+ Print(static_cast<char16_t*>(p)));
+}
+
+// NULL u16 string.
+TEST(PrintU16StringTest, Null) {
+ const char16_t* p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+
+// Tests that u16 strings are escaped properly.
+TEST(PrintU16StringTest, EscapesProperly) {
+ const char16_t* p = u"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
+ EXPECT_EQ(PrintPointer(p) +
+ " pointing to u\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
+ "hello \\x4E16\\x754C\"",
+ Print(p));
+}
+
+// const char32_t*.
+TEST(PrintU32StringTest, Const) {
+ const char32_t* p = U"🗺️";
+ EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F5FA\\xFE0F\"", Print(p));
+}
+
+// char32_t*.
+TEST(PrintU32StringTest, NonConst) {
+ char32_t p[] = U"🌌";
+ EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F30C\"",
+ Print(static_cast<char32_t*>(p)));
+}
+
+// NULL u32 string.
+TEST(PrintU32StringTest, Null) {
+ const char32_t* p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+
+// Tests that u32 strings are escaped properly.
+TEST(PrintU32StringTest, EscapesProperly) {
+ const char32_t* p = U"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 🗺️";
+ EXPECT_EQ(PrintPointer(p) +
+ " pointing to U\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
+ "hello \\x1F5FA\\xFE0F\"",
Print(p));
}
@@ -441,10 +657,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
@@ -526,10 +744,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));
}
@@ -538,14 +755,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
@@ -555,7 +771,7 @@ AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
struct Foo {
public:
- virtual ~Foo() {}
+ virtual ~Foo() = default;
int MyMethod(char x) { return x + 1; }
virtual char MyVirtualMethod(int /* n */) { return 'a'; }
@@ -566,8 +782,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
@@ -581,8 +796,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.
@@ -596,47 +810,87 @@ 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));
}
-// const char array with terminating NUL.
-TEST(PrintArrayTest, ConstCharArrayWithTerminatingNul) {
+// char array with terminating NUL.
+TEST(PrintArrayTest, CharArrayWithTerminatingNul) {
const char a[] = "\0Hi";
EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
}
-// const wchar_t array without terminating NUL.
+#ifdef __cpp_lib_char8_t
+// char_t array without terminating NUL.
+TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
+ // Array a contains '\0' in the middle and doesn't end with '\0'.
+ const char8_t a[] = {u8'H', u8'\0', u8'i'};
+ EXPECT_EQ("u8\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
+}
+
+// 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));
+}
+#endif
+
+// const char16_t array without terminating NUL.
+TEST(PrintArrayTest, Char16ArrayWithNoTerminatingNul) {
+ // Array a contains '\0' in the middle and doesn't end with '\0'.
+ const char16_t a[] = {u'こ', u'\0', u'ん', u'に', u'ち', u'は'};
+ EXPECT_EQ("u\"\\x3053\\0\\x3093\\x306B\\x3061\\x306F\" (no terminating NUL)",
+ PrintArrayHelper(a));
+}
+
+// char16_t array with terminating NUL.
+TEST(PrintArrayTest, Char16ArrayWithTerminatingNul) {
+ const char16_t a[] = u"\0こんにちは";
+ EXPECT_EQ("u\"\\0\\x3053\\x3093\\x306B\\x3061\\x306F\"", PrintArrayHelper(a));
+}
+
+// char32_t array without terminating NUL.
+TEST(PrintArrayTest, Char32ArrayWithNoTerminatingNul) {
+ // Array a contains '\0' in the middle and doesn't end with '\0'.
+ const char32_t a[] = {U'👋', U'\0', U'🌌'};
+ EXPECT_EQ("U\"\\x1F44B\\0\\x1F30C\" (no terminating NUL)",
+ PrintArrayHelper(a));
+}
+
+// char32_t array with terminating NUL.
+TEST(PrintArrayTest, Char32ArrayWithTerminatingNul) {
+ const char32_t a[] = U"\0👋🌌";
+ EXPECT_EQ("U\"\\0\\x1F44B\\x1F30C\"", PrintArrayHelper(a));
+}
+
+// wchar_t array without terminating NUL.
TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {
// Array a contains '\0' in the middle and doesn't end with '\0'.
- const wchar_t a[] = { L'H', L'\0', L'i' };
+ const wchar_t a[] = {L'H', L'\0', L'i'};
EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
}
// wchar_t array with terminating NUL.
-TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) {
+TEST(PrintArrayTest, WCharArrayWithTerminatingNul) {
const wchar_t a[] = L"\0Hi";
EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
}
@@ -649,7 +903,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));
}
@@ -669,11 +923,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-!")));
}
@@ -683,23 +940,45 @@ 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
+#ifdef __cpp_lib_char8_t
+TEST(PrintStringTest, U8String) {
+ std::u8string str = u8"Hello, 世界";
+ EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
+ EXPECT_EQ("u8\"Hello, \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", Print(str));
+}
+#endif
+
+TEST(PrintStringTest, U16String) {
+ std::u16string str = u"Hello, 世界";
+ EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
+ EXPECT_EQ("u\"Hello, \\x4E16\\x754C\"", Print(str));
+}
+
+TEST(PrintStringTest, U32String) {
+ std::u32string str = U"Hello, 🗺️";
+ EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type
+ EXPECT_EQ("U\"Hello, \\x1F5FA\\xFE0F\"", Print(str));
+}
+
// Tests printing types that support generic streaming (i.e. streaming
// to std::basic_ostream<Char, CharTraits> for any valid Char and
// CharTraits types).
@@ -758,22 +1037,22 @@ TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
}
-#if GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_STRING_VIEW
-// Tests printing ::absl::string_view.
+// Tests printing internal::StringView.
TEST(PrintStringViewTest, SimpleStringView) {
- const ::absl::string_view sp = "Hello";
+ const internal::StringView sp = "Hello";
EXPECT_EQ("\"Hello\"", Print(sp));
}
TEST(PrintStringViewTest, UnprintableCharacters) {
const char str[] = "NUL (\0) and \r\t";
- const ::absl::string_view sp(str, sizeof(str) - 1);
+ const internal::StringView sp(str, sizeof(str) - 1);
EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Tests printing STL containers.
@@ -789,7 +1068,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) {
EXPECT_EQ("{ 1, 3 }", Print(non_empty));
}
-
TEST(PrintStlContainerTest, OneElementHashMap) {
::std::unordered_map<int, char> map1;
map1[1] = 'a';
@@ -805,11 +1083,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);
@@ -818,7 +1094,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.
@@ -834,8 +1110,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;
}
}
@@ -845,7 +1121,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);
@@ -875,20 +1150,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));
}
@@ -906,32 +1180,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));
}
@@ -978,26 +1254,23 @@ TEST(PrintStdTupleTest, VariousSizes) {
EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
const char* const str = "8";
- ::std::tuple<bool, char, short, testing::internal::Int32, // NOLINT
- testing::internal::Int64, float, double, const char*, void*,
- std::string>
+ ::std::tuple<bool, char, short, int32_t, int64_t, float, double, // NOLINT
+ const char*, void*, std::string>
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;
@@ -1021,8 +1294,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.
@@ -1039,14 +1311,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.
@@ -1064,6 +1337,20 @@ TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
Print(::foo::StreamableTemplateInFoo<int>()));
}
+TEST(PrintStreamableTypeTest, TypeInUserNamespaceWithTemplatedStreamOperator) {
+ EXPECT_EQ("TemplatedStreamableInFoo",
+ Print(::foo::TemplatedStreamableInFoo()));
+}
+
+TEST(PrintStreamableTypeTest, SubclassUsesSuperclassStreamOperator) {
+ ParentClass parent;
+ ChildClassWithStreamOperator child_stream;
+ ChildClassWithoutStreamOperator child_no_stream;
+ EXPECT_EQ("ParentClass", Print(parent));
+ EXPECT_EQ("ChildClassWithStreamOperator", Print(child_stream));
+ EXPECT_EQ("ParentClass", Print(child_no_stream));
+}
+
// Tests printing a user-defined recursive container type that has a <<
// operator.
TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
@@ -1075,8 +1362,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 <<
@@ -1098,16 +1384,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));
}
@@ -1123,33 +1407,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
@@ -1158,8 +1438,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
@@ -1173,9 +1452,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.
@@ -1191,8 +1469,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';
@@ -1209,8 +1486,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';
@@ -1307,13 +1583,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";
@@ -1338,7 +1612,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 }");
}
@@ -1355,8 +1629,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"
@@ -1367,62 +1641,86 @@ TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
"\n As Text: \"From ä — ẑ\"");
}
+TEST(PrintToStringTest, PrintStreamableInLocal) {
+ EXPECT_STREQ("StreamableInLocal",
+ PrintToString(foo::StreamableInLocal()).c_str());
+}
+
+TEST(PrintToStringTest, PrintReferenceToStreamableInLocal) {
+ foo::StreamableInLocal s;
+ std::reference_wrapper<foo::StreamableInLocal> r(s);
+ EXPECT_STREQ("StreamableInLocal", PrintToString(r).c_str());
+}
+
+TEST(PrintToStringTest, PrintReferenceToStreamableInGlobal) {
+ StreamableInGlobal s;
+ std::reference_wrapper<StreamableInGlobal> r(s);
+ EXPECT_STREQ("StreamableInGlobal", PrintToString(r).c_str());
+}
+
+#ifdef GTEST_HAS_ABSL
+TEST(PrintToStringTest, AbslStringify) {
+ EXPECT_PRINT_TO_STRING_(Point(), "(10, 20)");
+}
+#endif
+
TEST(IsValidUTF8Test, IllFormedUTF8) {
// The following test strings are ill-formed UTF-8 and are printed
// as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
// expected to fail, thus output does not contain "As Text:".
- static const char *const kTestdata[][2] = {
- // 2-byte lead byte followed by a single-byte character.
- {"\xC3\x74", "\"\\xC3t\""},
- // Valid 2-byte character followed by an orphan trail byte.
- {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
- // Lead byte without trail byte.
- {"abc\xC3", "\"abc\\xC3\""},
- // 3-byte lead byte, single-byte character, orphan trail byte.
- {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
- // Truncated 3-byte character.
- {"\xE2\x80", "\"\\xE2\\x80\""},
- // Truncated 3-byte character followed by valid 2-byte char.
- {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
- // Truncated 3-byte character followed by a single-byte character.
- {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
- // 3-byte lead byte followed by valid 3-byte character.
- {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
- // 4-byte lead byte followed by valid 3-byte character.
- {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
- // Truncated 4-byte character.
- {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
- // Invalid UTF-8 byte sequences embedded in other chars.
- {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
- {"abc\xC3\x84\xE2\x80\xC3\x84xyz",
- "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
- // Non-shortest UTF-8 byte sequences are also ill-formed.
- // The classics: xC0, xC1 lead byte.
- {"\xC0\x80", "\"\\xC0\\x80\""},
- {"\xC1\x81", "\"\\xC1\\x81\""},
- // Non-shortest sequences.
- {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
- {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
- // Last valid code point before surrogate range, should be printed as text,
- // too.
- {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"퟿\""},
- // Start of surrogate lead. Surrogates are not printed as text.
- {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
- // Last non-private surrogate lead.
- {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
- // First private-use surrogate lead.
- {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
- // Last private-use surrogate lead.
- {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
- // Mid-point of surrogate trail.
- {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
- // First valid code point after surrogate range, should be printed as text,
- // too.
- {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}
- };
-
- for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) {
+ 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]);
}
}
@@ -1472,6 +1770,13 @@ TEST(UniversalPrintTest, WorksForReference) {
EXPECT_EQ("123", ss.str());
}
+TEST(UniversalPrintTest, WorksForPairWithConst) {
+ std::pair<const Wrapper<std::string>, int> p(Wrapper<std::string>("abc"), 1);
+ ::std::stringstream ss;
+ UniversalPrint(p, &ss);
+ EXPECT_EQ("(Wrapper(\"abc\"), 1)", ss.str());
+}
+
TEST(UniversalPrintTest, WorksForCString) {
const char* s1 = "abc";
::std::stringstream ss1;
@@ -1501,21 +1806,80 @@ TEST(UniversalPrintTest, WorksForCharArray) {
EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
}
+TEST(UniversalPrintTest, IncompleteType) {
+ struct Incomplete;
+ char some_object = 0;
+ EXPECT_EQ("(incomplete type)",
+ PrintToString(reinterpret_cast<Incomplete&>(some_object)));
+}
+
+TEST(UniversalPrintTest, SmartPointers) {
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
+ std::unique_ptr<int> p(new int(17));
+ EXPECT_EQ("(ptr = " + PrintPointer(p.get()) + ", value = 17)",
+ PrintToString(p));
+ std::unique_ptr<int[]> p2(new int[2]);
+ EXPECT_EQ("(" + PrintPointer(p2.get()) + ")", PrintToString(p2));
+
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
+ std::shared_ptr<int> p3(new int(1979));
+ EXPECT_EQ("(ptr = " + PrintPointer(p3.get()) + ", value = 1979)",
+ PrintToString(p3));
+#if defined(__cpp_lib_shared_ptr_arrays) && \
+ (__cpp_lib_shared_ptr_arrays >= 201611L)
+ std::shared_ptr<int[]> p4(new int[2]);
+ EXPECT_EQ("(" + PrintPointer(p4.get()) + ")", PrintToString(p4));
+#endif
+
+ // modifiers
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile const int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int[]>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int[]>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int[]>()));
+ EXPECT_EQ("(nullptr)",
+ PrintToString(std::unique_ptr<volatile const int[]>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile const int>()));
+#if defined(__cpp_lib_shared_ptr_arrays) && \
+ (__cpp_lib_shared_ptr_arrays >= 201611L)
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int[]>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int[]>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int[]>()));
+ EXPECT_EQ("(nullptr)",
+ PrintToString(std::shared_ptr<volatile const int[]>()));
+#endif
+
+ // void
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<void, void (*)(void*)>(
+ nullptr, nullptr)));
+ EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
+ PrintToString(
+ std::unique_ptr<void, void (*)(void*)>(p.get(), [](void*) {})));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<void>()));
+ EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
+ PrintToString(std::shared_ptr<void>(p.get(), [](void*) {})));
+}
+
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
EXPECT_EQ(0u, result.size());
}
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]);
@@ -1530,32 +1894,66 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
EXPECT_EQ("\"a\"", result[1]);
}
-#if GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_ANY
+class PrintAnyTest : public ::testing::Test {
+ protected:
+ template <typename T>
+ static std::string ExpectedTypeName() {
+#if GTEST_HAS_RTTI
+ return internal::GetTypeName<T>();
+#else
+ return "<unknown_type>";
+#endif // GTEST_HAS_RTTI
+ }
+};
+
+TEST_F(PrintAnyTest, Empty) {
+ internal::Any any;
+ EXPECT_EQ("no value", PrintToString(any));
+}
+
+TEST_F(PrintAnyTest, NonEmpty) {
+ internal::Any any;
+ constexpr int val1 = 10;
+ const std::string val2 = "content";
+
+ any = val1;
+ EXPECT_EQ("value of type " + ExpectedTypeName<int>(), PrintToString(any));
+
+ any = val2;
+ EXPECT_EQ("value of type " + ExpectedTypeName<std::string>(),
+ PrintToString(any));
+}
+#endif // GTEST_INTERNAL_HAS_ANY
+#if GTEST_INTERNAL_HAS_OPTIONAL
TEST(PrintOptionalTest, Basic) {
- absl::optional<int> value;
+ EXPECT_EQ("(nullopt)", PrintToString(internal::Nullopt()));
+ internal::Optional<int> value;
EXPECT_EQ("(nullopt)", PrintToString(value));
value = {7};
EXPECT_EQ("(7)", PrintToString(value));
- EXPECT_EQ("(1.1)", PrintToString(absl::optional<double>{1.1}));
- EXPECT_EQ("(\"A\")", PrintToString(absl::optional<std::string>{"A"}));
+ EXPECT_EQ("(1.1)", PrintToString(internal::Optional<double>{1.1}));
+ EXPECT_EQ("(\"A\")", PrintToString(internal::Optional<std::string>{"A"}));
}
+#endif // GTEST_INTERNAL_HAS_OPTIONAL
+#if GTEST_INTERNAL_HAS_VARIANT
struct NonPrintable {
unsigned char contents = 17;
};
TEST(PrintOneofTest, Basic) {
- using Type = absl::variant<int, StreamableInGlobal, NonPrintable>;
- EXPECT_EQ("('int' with value 7)", PrintToString(Type(7)));
- EXPECT_EQ("('StreamableInGlobal' with value StreamableInGlobal)",
+ using Type = internal::Variant<int, StreamableInGlobal, NonPrintable>;
+ EXPECT_EQ("('int(index = 0)' with value 7)", PrintToString(Type(7)));
+ EXPECT_EQ("('StreamableInGlobal(index = 1)' with value StreamableInGlobal)",
PrintToString(Type(StreamableInGlobal{})));
EXPECT_EQ(
- "('testing::gtest_printers_test::NonPrintable' with value 1-byte object "
- "<11>)",
+ "('testing::gtest_printers_test::NonPrintable(index = 2)' with value "
+ "1-byte object <11>)",
PrintToString(Type(NonPrintable{})));
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_VARIANT
namespace {
class string_ref;
diff --git a/ci/log-config.sh b/googletest/test/googletest-setuptestsuite-test.py
index 5fef11948b18..899531f32792 100755
--- a/ci/log-config.sh
+++ b/googletest/test/googletest-setuptestsuite-test.py
@@ -1,7 +1,7 @@
-#!/usr/bin/env bash
-# Copyright 2017 Google Inc.
-# All Rights Reserved.
+#!/usr/bin/env python
#
+# Copyright 2019, 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
@@ -29,23 +29,30 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-set -e
+"""Verifies that SetUpTestSuite and TearDownTestSuite errors are noticed."""
-# ccache on OS X needs installation first
-# reset ccache statistics
-ccache --zero-stats
+from googletest.test import gtest_test_utils
-echo PATH=${PATH}
+COMMAND = gtest_test_utils.GetTestExecutablePath(
+ 'googletest-setuptestsuite-test_'
+)
-echo "Compiler configuration:"
-echo CXX=${CXX}
-echo CC=${CC}
-echo CXXFLAGS=${CXXFLAGS}
-echo "C++ compiler version:"
-${CXX} --version || echo "${CXX} does not seem to support the --version flag"
-${CXX} -v || echo "${CXX} does not seem to support the -v flag"
+class GTestSetUpTestSuiteTest(gtest_test_utils.TestCase):
-echo "C compiler version:"
-${CC} --version || echo "${CXX} does not seem to support the --version flag"
-${CC} -v || echo "${CXX} does not seem to support the -v flag"
+ def testSetupErrorAndTearDownError(self):
+ p = gtest_test_utils.Subprocess(COMMAND)
+ self.assertNotEqual(p.exit_code, 0, msg=p.output)
+
+ self.assertIn(
+ (
+ '[ FAILED ] SetupFailTest: SetUpTestSuite or TearDownTestSuite\n['
+ ' FAILED ] TearDownFailTest: SetUpTestSuite or'
+ ' TearDownTestSuite\n\n 2 FAILED TEST SUITES\n'
+ ),
+ p.output,
+ )
+
+
+if __name__ == '__main__':
+ gtest_test_utils.Main()
diff --git a/googletest/test/googletest-test2_test.cc b/googletest/test/googletest-setuptestsuite-test_.cc
index 2e425daebab6..d20899f56866 100644
--- a/googletest/test/googletest-test2_test.cc
+++ b/googletest/test/googletest-setuptestsuite-test_.cc
@@ -27,35 +27,18 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Tests for Google Test itself. This verifies that the basic constructs of
-// Google Test work.
-
#include "gtest/gtest.h"
-#include "googletest-param-test-test.h"
-
-using ::testing::Values;
-using ::testing::internal::ParamGenerator;
-// Tests that generators defined in a different translation unit
-// are functional. The test using extern_gen_2 is defined
-// in googletest-param-test-test.cc.
-ParamGenerator<int> extern_gen_2 = Values(33);
+class SetupFailTest : public ::testing::Test {
+ protected:
+ static void SetUpTestSuite() { ASSERT_EQ("", "SET_UP_FAIL"); }
+};
-// Tests that a parameterized test case can be defined in one translation unit
-// and instantiated in another. The test is defined in
-// googletest-param-test-test.cc and ExternalInstantiationTest fixture class is
-// defined in gtest-param-test_test.h.
-INSTANTIATE_TEST_SUITE_P(MultiplesOf33,
- ExternalInstantiationTest,
- Values(33, 66));
+TEST_F(SetupFailTest, NoopPassingTest) {}
-// Tests that a parameterized test case can be instantiated
-// in multiple translation units. Another instantiation is defined
-// 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));
+class TearDownFailTest : public ::testing::Test {
+ protected:
+ static void TearDownTestSuite() { ASSERT_EQ("", "TEAR_DOWN_FAIL"); }
+};
+TEST_F(TearDownFailTest, NoopPassingTest) {}
diff --git a/googletest/test/googletest-shuffle-test.py b/googletest/test/googletest-shuffle-test.py
index 573cc5eca3fc..61e3a15ec3d7 100755
--- a/googletest/test/googletest-shuffle-test.py
+++ b/googletest/test/googletest-shuffle-test.py
@@ -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_')
@@ -130,38 +130,50 @@ def CalculateTestLists():
if not ALL_TESTS:
ALL_TESTS.extend(
- GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0])
+ GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0]
+ )
if not ACTIVE_TESTS:
ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0])
if not FILTERED_TESTS:
FILTERED_TESTS.extend(
- GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0])
+ GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0]
+ )
if not SHARDED_TESTS:
SHARDED_TESTS.extend(
- GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
- SHARD_INDEX_ENV_VAR: '1'},
- [])[0])
+ GetTestsForAllIterations(
+ {TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '1'}, []
+ )[0]
+ )
if not SHUFFLED_ALL_TESTS:
- SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations(
- {}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0])
+ SHUFFLED_ALL_TESTS.extend(
+ GetTestsForAllIterations(
+ {}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)]
+ )[0]
+ )
if not SHUFFLED_ACTIVE_TESTS:
- SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations(
- {}, [ShuffleFlag(), RandomSeedFlag(1)])[0])
+ SHUFFLED_ACTIVE_TESTS.extend(
+ GetTestsForAllIterations({}, [ShuffleFlag(), RandomSeedFlag(1)])[0]
+ )
if not SHUFFLED_FILTERED_TESTS:
- SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations(
- {}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0])
+ SHUFFLED_FILTERED_TESTS.extend(
+ GetTestsForAllIterations(
+ {}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)]
+ )[0]
+ )
if not SHUFFLED_SHARDED_TESTS:
SHUFFLED_SHARDED_TESTS.extend(
- GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
- SHARD_INDEX_ENV_VAR: '1'},
- [ShuffleFlag(), RandomSeedFlag(1)])[0])
+ GetTestsForAllIterations(
+ {TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '1'},
+ [ShuffleFlag(), RandomSeedFlag(1)],
+ )[0]
+ )
class GTestShuffleUnitTest(gtest_test_utils.TestCase):
@@ -177,66 +189,91 @@ class GTestShuffleUnitTest(gtest_test_utils.TestCase):
self.assertEqual(len(SHARDED_TESTS), len(SHUFFLED_SHARDED_TESTS))
def testShuffleChangesTestOrder(self):
- self.assert_(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS)
- self.assert_(SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS)
- self.assert_(SHUFFLED_FILTERED_TESTS != FILTERED_TESTS,
- SHUFFLED_FILTERED_TESTS)
- self.assert_(SHUFFLED_SHARDED_TESTS != SHARDED_TESTS,
- SHUFFLED_SHARDED_TESTS)
+ self.assertTrue(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS)
+ self.assertTrue(
+ SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS
+ )
+ self.assertTrue(
+ SHUFFLED_FILTERED_TESTS != FILTERED_TESTS, SHUFFLED_FILTERED_TESTS
+ )
+ self.assertTrue(
+ SHUFFLED_SHARDED_TESTS != SHARDED_TESTS, SHUFFLED_SHARDED_TESTS
+ )
def testShuffleChangesTestCaseOrder(self):
- self.assert_(GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS),
- GetTestCases(SHUFFLED_ALL_TESTS))
- self.assert_(
+ self.assertTrue(
+ GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS),
+ GetTestCases(SHUFFLED_ALL_TESTS),
+ )
+ self.assertTrue(
GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS),
- GetTestCases(SHUFFLED_ACTIVE_TESTS))
- self.assert_(
+ GetTestCases(SHUFFLED_ACTIVE_TESTS),
+ )
+ self.assertTrue(
GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS),
- GetTestCases(SHUFFLED_FILTERED_TESTS))
- self.assert_(
+ GetTestCases(SHUFFLED_FILTERED_TESTS),
+ )
+ self.assertTrue(
GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS),
- GetTestCases(SHUFFLED_SHARDED_TESTS))
+ GetTestCases(SHUFFLED_SHARDED_TESTS),
+ )
def testShuffleDoesNotRepeatTest(self):
for test in SHUFFLED_ALL_TESTS:
- self.assertEqual(1, SHUFFLED_ALL_TESTS.count(test),
- '%s appears more than once' % (test,))
+ self.assertEqual(
+ 1,
+ SHUFFLED_ALL_TESTS.count(test),
+ '%s appears more than once' % (test,),
+ )
for test in SHUFFLED_ACTIVE_TESTS:
- self.assertEqual(1, SHUFFLED_ACTIVE_TESTS.count(test),
- '%s appears more than once' % (test,))
+ self.assertEqual(
+ 1,
+ SHUFFLED_ACTIVE_TESTS.count(test),
+ '%s appears more than once' % (test,),
+ )
for test in SHUFFLED_FILTERED_TESTS:
- self.assertEqual(1, SHUFFLED_FILTERED_TESTS.count(test),
- '%s appears more than once' % (test,))
+ self.assertEqual(
+ 1,
+ SHUFFLED_FILTERED_TESTS.count(test),
+ '%s appears more than once' % (test,),
+ )
for test in SHUFFLED_SHARDED_TESTS:
- self.assertEqual(1, SHUFFLED_SHARDED_TESTS.count(test),
- '%s appears more than once' % (test,))
+ self.assertEqual(
+ 1,
+ SHUFFLED_SHARDED_TESTS.count(test),
+ '%s appears more than once' % (test,),
+ )
def testShuffleDoesNotCreateNewTest(self):
for test in SHUFFLED_ALL_TESTS:
- self.assert_(test in ALL_TESTS, '%s is an invalid test' % (test,))
+ self.assertTrue(test in ALL_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_ACTIVE_TESTS:
- self.assert_(test in ACTIVE_TESTS, '%s is an invalid test' % (test,))
+ self.assertTrue(test in ACTIVE_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_FILTERED_TESTS:
- self.assert_(test in FILTERED_TESTS, '%s is an invalid test' % (test,))
+ self.assertTrue(test in FILTERED_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_SHARDED_TESTS:
- self.assert_(test in SHARDED_TESTS, '%s is an invalid test' % (test,))
+ self.assertTrue(test in SHARDED_TESTS, '%s is an invalid test' % (test,))
def testShuffleIncludesAllTests(self):
for test in ALL_TESTS:
- self.assert_(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,))
+ self.assertTrue(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,))
for test in ACTIVE_TESTS:
- self.assert_(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,))
+ self.assertTrue(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,))
for test in FILTERED_TESTS:
- self.assert_(test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,))
+ self.assertTrue(
+ test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,)
+ )
for test in SHARDED_TESTS:
- self.assert_(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,))
+ self.assertTrue(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,))
def testShuffleLeavesDeathTestsAtFront(self):
non_death_test_found = False
for test in SHUFFLED_ACTIVE_TESTS:
if 'DeathTest.' in test:
- self.assert_(not non_death_test_found,
- '%s appears after a non-death test' % (test,))
+ self.assertTrue(
+ not non_death_test_found,
+ '%s appears after a non-death test' % (test,),
+ )
else:
non_death_test_found = True
@@ -246,9 +283,11 @@ class GTestShuffleUnitTest(gtest_test_utils.TestCase):
[test_case, _] = test.split('.')
if test_cases and test_cases[-1] != test_case:
test_cases.append(test_case)
- self.assertEqual(1, test_cases.count(test_case),
- 'Test case %s is not grouped together in %s' %
- (test_case, tests))
+ self.assertEqual(
+ 1,
+ test_cases.count(test_case),
+ 'Test case %s is not grouped together in %s' % (test_case, tests),
+ )
def testShuffleDoesNotInterleaveTestCases(self):
self._VerifyTestCasesDoNotInterleave(SHUFFLED_ALL_TESTS)
@@ -262,56 +301,71 @@ class GTestShuffleUnitTest(gtest_test_utils.TestCase):
# iteration, and this test depends on the current implementation
# picking successive numbers. This dependency is not ideal, but
# makes the test much easier to write.
+ # pylint: disable-next=unbalanced-tuple-unpacking
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
GetTestsForAllIterations(
- {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
+ {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]
+ )
+ )
# Make sure running the tests with random seed 1 gets the same
# order as in iteration 1 above.
- [tests_with_seed1] = GetTestsForAllIterations(
- {}, [ShuffleFlag(), RandomSeedFlag(1)])
+ tests_with_seed1 = GetTestsForAllIterations(
+ {}, [ShuffleFlag(), RandomSeedFlag(1)]
+ )[0]
self.assertEqual(tests_in_iteration1, tests_with_seed1)
# Make sure running the tests with random seed 2 gets the same
# order as in iteration 2 above. Success means that Google Test
# correctly restores the test order before re-shuffling at the
# beginning of iteration 2.
- [tests_with_seed2] = GetTestsForAllIterations(
- {}, [ShuffleFlag(), RandomSeedFlag(2)])
+ tests_with_seed2 = GetTestsForAllIterations(
+ {}, [ShuffleFlag(), RandomSeedFlag(2)]
+ )[0]
self.assertEqual(tests_in_iteration2, tests_with_seed2)
# Make sure running the tests with random seed 3 gets the same
# order as in iteration 3 above. Success means that Google Test
# correctly restores the test order before re-shuffling at the
# beginning of iteration 3.
- [tests_with_seed3] = GetTestsForAllIterations(
- {}, [ShuffleFlag(), RandomSeedFlag(3)])
+ tests_with_seed3 = GetTestsForAllIterations(
+ {}, [ShuffleFlag(), RandomSeedFlag(3)]
+ )[0]
self.assertEqual(tests_in_iteration3, tests_with_seed3)
def testShuffleGeneratesNewOrderInEachIteration(self):
+ # pylint: disable-next=unbalanced-tuple-unpacking
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
GetTestsForAllIterations(
- {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
-
- self.assert_(tests_in_iteration1 != tests_in_iteration2,
- tests_in_iteration1)
- self.assert_(tests_in_iteration1 != tests_in_iteration3,
- tests_in_iteration1)
- self.assert_(tests_in_iteration2 != tests_in_iteration3,
- tests_in_iteration2)
+ {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]
+ )
+ )
+
+ self.assertTrue(
+ tests_in_iteration1 != tests_in_iteration2, tests_in_iteration1
+ )
+ self.assertTrue(
+ tests_in_iteration1 != tests_in_iteration3, tests_in_iteration1
+ )
+ self.assertTrue(
+ tests_in_iteration2 != tests_in_iteration3, tests_in_iteration2
+ )
def testShuffleShardedTestsPreservesPartition(self):
# If we run M tests on N shards, the same M tests should be run in
# total, regardless of the random seeds used by the shards.
- [tests1] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
- SHARD_INDEX_ENV_VAR: '0'},
- [ShuffleFlag(), RandomSeedFlag(1)])
- [tests2] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
- SHARD_INDEX_ENV_VAR: '1'},
- [ShuffleFlag(), RandomSeedFlag(20)])
- [tests3] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
- SHARD_INDEX_ENV_VAR: '2'},
- [ShuffleFlag(), RandomSeedFlag(25)])
+ tests1 = GetTestsForAllIterations(
+ {TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '0'},
+ [ShuffleFlag(), RandomSeedFlag(1)],
+ )[0]
+ tests2 = GetTestsForAllIterations(
+ {TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '1'},
+ [ShuffleFlag(), RandomSeedFlag(20)],
+ )[0]
+ tests3 = GetTestsForAllIterations(
+ {TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '2'},
+ [ShuffleFlag(), RandomSeedFlag(25)],
+ )[0]
sorted_sharded_tests = tests1 + tests2 + tests3
sorted_sharded_tests.sort()
sorted_active_tests = []
@@ -319,5 +373,6 @@ class GTestShuffleUnitTest(gtest_test_utils.TestCase):
sorted_active_tests.sort()
self.assertEqual(sorted_active_tests, sorted_sharded_tests)
+
if __name__ == '__main__':
gtest_test_utils.Main()
diff --git a/googletest/test/googletest-shuffle-test_.cc b/googletest/test/googletest-shuffle-test_.cc
index c1fc106686e2..b570c48800d3 100644
--- a/googletest/test/googletest-shuffle-test_.cc
+++ b/googletest/test/googletest-shuffle-test_.cc
@@ -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"
@@ -36,7 +35,6 @@ namespace {
using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest;
-using ::testing::Message;
using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
@@ -82,13 +80,13 @@ class TestNamePrinter : public EmptyTestEventListener {
}
void OnTestStart(const TestInfo& test_info) override {
- printf("%s.%s\n", test_info.test_case_name(), test_info.name());
+ printf("%s.%s\n", test_info.test_suite_name(), test_info.name());
}
};
} // namespace
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
InitGoogleTest(&argc, argv);
// Replaces the default printer with TestNamePrinter, which prints
diff --git a/googletest/test/googletest-test-part-test.cc b/googletest/test/googletest-test-part-test.cc
index 44cf7ca044b8..076e5be2fa44 100644
--- a/googletest/test/googletest-test-part-test.cc
+++ b/googletest/test/googletest-test-part-test.cc
@@ -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());
diff --git a/googletest/test/googletest-throw-on-failure-test.py b/googletest/test/googletest-throw-on-failure-test.py
index ea627c479d5b..106b004423ec 100755
--- a/googletest/test/googletest-throw-on-failure-test.py
+++ b/googletest/test/googletest-throw-on-failure-test.py
@@ -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.
@@ -47,15 +47,22 @@ THROW_ON_FAILURE = 'gtest_throw_on_failure'
# Path to the googletest-throw-on-failure-test_ program, compiled with
# exceptions disabled.
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
- 'googletest-throw-on-failure-test_')
+ 'googletest-throw-on-failure-test_'
+)
# Utilities.
def SetEnvVar(env_var, value):
- """Sets an environment variable to a given value; unsets it when the
+ """Sets an environment variable.
+
+ Sets an environment variable to a given value; unsets it when the
given value is None.
+
+ Args:
+ env_var: environment variable.
+ value: value to set.
"""
env_var = env_var.upper()
@@ -78,14 +85,16 @@ class ThrowOnFailureTest(gtest_test_utils.TestCase):
"""Tests the throw-on-failure mode."""
def RunAndVerify(self, env_var_value, flag_value, should_fail):
- """Runs googletest-throw-on-failure-test_ and verifies that it does
+ """Runs googletest-throw-on-failure-test_ and verifies its behavior.
+
+ Runs googletest-throw-on-failure-test_ and verifies that it does
(or does not) exit with a non-zero code.
Args:
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
- variable; None if the variable should be unset.
- flag_value: value of the --gtest_break_on_failure flag;
- None if the flag should not be present.
+ variable; None if the variable should be unset.
+ flag_value: value of the --gtest_break_on_failure flag; None if the
+ flag should not be present.
should_fail: True if and only if the program is expected to fail.
"""
@@ -116,11 +125,16 @@ class ThrowOnFailureTest(gtest_test_utils.TestCase):
SetEnvVar(THROW_ON_FAILURE, None)
- msg = ('when %s%s, an assertion failure in "%s" %s cause a non-zero '
- 'exit code.' %
- (THROW_ON_FAILURE, env_var_value_msg, ' '.join(command),
- should_or_not))
- self.assert_(failed == should_fail, msg)
+ msg = (
+ 'when %s%s, an assertion failure in "%s" %s cause a non-zero exit code.'
+ % (
+ THROW_ON_FAILURE,
+ env_var_value_msg,
+ ' '.join(command),
+ should_or_not,
+ )
+ )
+ self.assertTrue(failed == should_fail, msg)
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
@@ -130,38 +144,22 @@ class ThrowOnFailureTest(gtest_test_utils.TestCase):
def testThrowOnFailureEnvVar(self):
"""Tests using the GTEST_THROW_ON_FAILURE environment variable."""
- self.RunAndVerify(env_var_value='0',
- flag_value=None,
- should_fail=False)
- self.RunAndVerify(env_var_value='1',
- flag_value=None,
- should_fail=True)
+ self.RunAndVerify(env_var_value='0', flag_value=None, should_fail=False)
+ self.RunAndVerify(env_var_value='1', flag_value=None, should_fail=True)
def testThrowOnFailureFlag(self):
"""Tests using the --gtest_throw_on_failure flag."""
- self.RunAndVerify(env_var_value=None,
- flag_value='0',
- should_fail=False)
- self.RunAndVerify(env_var_value=None,
- flag_value='1',
- should_fail=True)
+ self.RunAndVerify(env_var_value=None, flag_value='0', should_fail=False)
+ self.RunAndVerify(env_var_value=None, flag_value='1', should_fail=True)
def testThrowOnFailureFlagOverridesEnvVar(self):
"""Tests that --gtest_throw_on_failure overrides GTEST_THROW_ON_FAILURE."""
- self.RunAndVerify(env_var_value='0',
- flag_value='0',
- should_fail=False)
- self.RunAndVerify(env_var_value='0',
- flag_value='1',
- should_fail=True)
- self.RunAndVerify(env_var_value='1',
- flag_value='0',
- should_fail=False)
- self.RunAndVerify(env_var_value='1',
- flag_value='1',
- should_fail=True)
+ self.RunAndVerify(env_var_value='0', flag_value='0', should_fail=False)
+ self.RunAndVerify(env_var_value='0', flag_value='1', should_fail=True)
+ self.RunAndVerify(env_var_value='1', flag_value='0', should_fail=False)
+ self.RunAndVerify(env_var_value='1', flag_value='1', should_fail=True)
if __name__ == '__main__':
diff --git a/googletest/test/googletest-throw-on-failure-test_.cc b/googletest/test/googletest-throw-on-failure-test_.cc
index 83bb914c7e47..3b81a5a1db66 100644
--- a/googletest/test/googletest-throw-on-failure-test_.cc
+++ b/googletest/test/googletest-throw-on-failure-test_.cc
@@ -27,18 +27,18 @@
// (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
diff --git a/googletest/test/googletest-uninitialized-test.py b/googletest/test/googletest-uninitialized-test.py
index 69595a0ddede..e5af7c8421bf 100755
--- a/googletest/test/googletest-uninitialized-test.py
+++ b/googletest/test/googletest-uninitialized-test.py
@@ -31,9 +31,11 @@
"""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_')
+COMMAND = gtest_test_utils.GetTestExecutablePath(
+ 'googletest-uninitialized-test_'
+)
def Assert(condition):
@@ -54,11 +56,12 @@ def TestExitCodeAndOutput(command):
# Verifies that 'command' exits with code 1.
p = gtest_test_utils.Subprocess(command)
if p.exited and p.exit_code == 0:
- Assert('IMPORTANT NOTICE' in p.output);
+ Assert('IMPORTANT NOTICE' in p.output)
Assert('InitGoogleTest' in p.output)
class GTestUninitializedTest(gtest_test_utils.TestCase):
+
def testExitCodeAndOutput(self):
TestExitCodeAndOutput(COMMAND)
diff --git a/googletest/test/googletest-uninitialized-test_.cc b/googletest/test/googletest-uninitialized-test_.cc
index b4434d51eebf..88b61fcefd5e 100644
--- a/googletest/test/googletest-uninitialized-test_.cc
+++ b/googletest/test/googletest-uninitialized-test_.cc
@@ -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(); }
diff --git a/googletest/test/gtest-typed-test2_test.cc b/googletest/test/gtest-typed-test2_test.cc
index 70001604ca06..f2eae12058b7 100644
--- a/googletest/test/gtest-typed-test2_test.cc
+++ b/googletest/test/gtest-typed-test2_test.cc
@@ -27,18 +27,13 @@
// (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"
-
-#if GTEST_HAS_TYPED_TEST_P
+#include "test/gtest-typed-test_test.h"
// Tests that the same type-parameterized test case can be
// instantiated in different translation units linked together.
// (ContainerTest is also instantiated in gtest-typed-test_test.cc.)
INSTANTIATE_TYPED_TEST_SUITE_P(Vector, ContainerTest,
testing::Types<std::vector<int> >);
-
-#endif // GTEST_HAS_TYPED_TEST_P
diff --git a/googletest/test/gtest-typed-test_test.cc b/googletest/test/gtest-typed-test_test.cc
index 5411832ab269..0cc8b21145da 100644
--- a/googletest/test/gtest-typed-test_test.cc
+++ b/googletest/test/gtest-typed-test_test.cc
@@ -27,18 +27,16 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
#include "test/gtest-typed-test_test.h"
#include <set>
+#include <string>
#include <type_traits>
#include <vector>
#include "gtest/gtest.h"
-#if _MSC_VER
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)
-#endif // _MSC_VER
using testing::Test;
@@ -50,9 +48,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_;
@@ -88,9 +84,6 @@ class CommonTest : public Test {
template <typename T>
T* CommonTest<T>::shared_ = nullptr;
-// This #ifdef block tests typed tests.
-#if GTEST_HAS_TYPED_TEST
-
using testing::Types;
// Tests that SetUpTestSuite()/TearDownTestSuite(), fixture ctor/dtor,
@@ -133,8 +126,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.
@@ -142,8 +134,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.
@@ -158,15 +149,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
@@ -193,22 +181,17 @@ TYPED_TEST(TypedTestWithNames, TestSuiteName) {
if (std::is_same<TypeParam, char>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"TypedTestWithNames/char0");
}
if (std::is_same<TypeParam, int>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"TypedTestWithNames/int1");
}
}
-#endif // GTEST_HAS_TYPED_TEST
-
-// This #ifdef block tests type-parameterized tests.
-#if GTEST_HAS_TYPED_TEST_P
-
using testing::Types;
using testing::internal::TypedTestSuitePState;
@@ -228,7 +211,7 @@ class TypedTestSuitePStateTest : public Test {
TEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) {
const char* tests = "A, B, C";
EXPECT_EQ(tests,
- state_.VerifyRegisteredTestNames("foo.cc", 1, tests));
+ state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests));
}
// Makes sure that the order of the tests and spaces around the names
@@ -236,33 +219,33 @@ TEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) {
TEST_F(TypedTestSuitePStateTest, IgnoresOrderAndSpaces) {
const char* tests = "A,C, B";
EXPECT_EQ(tests,
- state_.VerifyRegisteredTestNames("foo.cc", 1, tests));
+ state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests));
}
using TypedTestSuitePStateDeathTest = TypedTestSuitePStateTest;
TEST_F(TypedTestSuitePStateDeathTest, DetectsDuplicates) {
EXPECT_DEATH_IF_SUPPORTED(
- state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, A, C"),
+ state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, A, C"),
"foo\\.cc.1.?: Test A is listed more than once\\.");
}
TEST_F(TypedTestSuitePStateDeathTest, DetectsExtraTest) {
EXPECT_DEATH_IF_SUPPORTED(
- state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C, D"),
+ state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C, D"),
"foo\\.cc.1.?: No test named D can be found in this test suite\\.");
}
TEST_F(TypedTestSuitePStateDeathTest, DetectsMissedTest) {
EXPECT_DEATH_IF_SUPPORTED(
- state_.VerifyRegisteredTestNames("foo.cc", 1, "A, C"),
+ state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, C"),
"foo\\.cc.1.?: You forgot to list test B\\.");
}
// Tests that defining a test for a parameterized test case generates
// a run-time error if the test case has been registered.
TEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) {
- state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C");
+ state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C");
EXPECT_DEATH_IF_SUPPORTED(
state_.AddTestName("foo.cc", 2, "FooTest", "D"),
"foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_SUITE_P"
@@ -273,8 +256,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);
@@ -298,8 +280,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);
@@ -315,13 +297,13 @@ TYPED_TEST_P(TypeParametrizedTestWithNames, TestSuiteName) {
if (std::is_same<TypeParam, char>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"CustomName/TypeParametrizedTestWithNames/parChar0");
}
if (std::is_same<TypeParam, int>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"CustomName/TypeParametrizedTestWithNames/parInt1");
}
}
@@ -342,14 +324,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);
@@ -367,8 +348,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);
@@ -404,21 +384,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);
@@ -426,37 +402,22 @@ 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
-#endif // GTEST_HAS_TYPED_TEST_P
-
-#if !defined(GTEST_HAS_TYPED_TEST) && !defined(GTEST_HAS_TYPED_TEST_P)
-
-// Google Test may not support type-parameterized tests with some
-// compilers. If we use conditional compilation to compile out all
-// code referring to the gtest_main library, MSVC linker will not link
-// that library at all and consequently complain about missing entry
-// point defined in that library (fatal error LNK1561: entry point
-// must be defined). This dummy test keeps gtest_main linked in.
-TEST(DummyTest, TypedTestsAreNotSupportedOnThisPlatform) {}
-
-#if _MSC_VER
-GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
-#endif // _MSC_VER
-
-#endif // #if !defined(GTEST_HAS_TYPED_TEST) && !defined(GTEST_HAS_TYPED_TEST_P)
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
diff --git a/googletest/test/gtest-typed-test_test.h b/googletest/test/gtest-typed-test_test.h
index 23137b7ef798..f3ef0a596297 100644
--- a/googletest/test/gtest-typed-test_test.h
+++ b/googletest/test/gtest-typed-test_test.h
@@ -27,14 +27,11 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
-#define GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
+#ifndef GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_
+#define GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_
#include "gtest/gtest.h"
-#if GTEST_HAS_TYPED_TEST_P
-
using testing::Test;
// For testing that the same type-parameterized test case can be
@@ -43,23 +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);
-
-#endif // GTEST_HAS_TYPED_TEST_P
+REGISTER_TYPED_TEST_SUITE_P(ContainerTest, CanBeDefaultConstructed,
+ InitialSizeIsZero);
-#endif // GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
+#endif // GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_
diff --git a/googletest/test/gtest-unittest-api_test.cc b/googletest/test/gtest-unittest-api_test.cc
index 480a41fb42ee..2ea692739ad4 100644
--- a/googletest/test/gtest-unittest-api_test.cc
+++ b/googletest/test/gtest-unittest-api_test.cc
@@ -32,11 +32,12 @@
// 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 {
@@ -55,14 +56,13 @@ class UnitTestHelper {
// name. The caller is responsible for deleting the array.
static TestSuite const** GetSortedTestSuites() {
UnitTest& unit_test = *UnitTest::GetInstance();
- auto const** const test_suites =
- new const TestSuite*[unit_test.total_test_suite_count()];
+ auto const** const test_suites = new const TestSuite*[static_cast<size_t>(
+ 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;
}
@@ -83,8 +82,8 @@ class UnitTestHelper {
// sorted by the test name. The caller is responsible for deleting the
// array.
static TestInfo const** GetSortedTests(const TestSuite* test_suite) {
- TestInfo const** const tests =
- new const TestInfo*[test_suite->total_test_count()];
+ TestInfo const** const tests = new const TestInfo*[static_cast<size_t>(
+ test_suite->total_test_count())];
for (int i = 0; i < test_suite->total_test_count(); ++i)
tests[i] = test_suite->GetTestInfo(i);
@@ -95,23 +94,19 @@ class UnitTestHelper {
}
};
-#if GTEST_HAS_TYPED_TEST
-template <typename T> class TestSuiteWithCommentTest : public Test {};
+template <typename T>
+class TestSuiteWithCommentTest : public Test {};
TYPED_TEST_SUITE(TestSuiteWithCommentTest, Types<int>);
TYPED_TEST(TestSuiteWithCommentTest, Dummy) {}
const int kTypedTestSuites = 1;
const int kTypedTests = 1;
-#else
-const int kTypedTestSuites = 0;
-const int kTypedTests = 0;
-#endif // GTEST_HAS_TYPED_TEST
// We can only test the accessors that do not change value while tests run.
// Since tests can be run in any order, the values the accessors that track
// test execution (such as failed_test_count) can not be predicted.
TEST(ApiTest, UnitTestImmutableAccessorsWork) {
- UnitTest* unit_test = UnitTest::GetInstance();
+ const auto& unit_test = UnitTest::GetInstance();
ASSERT_EQ(2 + kTypedTestSuites, unit_test->total_test_suite_count());
EXPECT_EQ(1 + kTypedTestSuites, unit_test->test_suite_to_run_count());
@@ -123,9 +118,7 @@ TEST(ApiTest, UnitTestImmutableAccessorsWork) {
EXPECT_STREQ("ApiTest", test_suites[0]->name());
EXPECT_STREQ("DISABLED_Test", test_suites[1]->name());
-#if GTEST_HAS_TYPED_TEST
EXPECT_STREQ("TestSuiteWithCommentTest/0", test_suites[2]->name());
-#endif // GTEST_HAS_TYPED_TEST
delete[] test_suites;
@@ -183,12 +176,11 @@ TEST(ApiTest, TestSuiteImmutableAccessorsWork) {
delete[] tests;
tests = nullptr;
-#if GTEST_HAS_TYPED_TEST
test_suite = UnitTestHelper::FindTestSuite("TestSuiteWithCommentTest/0");
ASSERT_TRUE(test_suite != nullptr);
EXPECT_STREQ("TestSuiteWithCommentTest/0", test_suite->name());
- EXPECT_STREQ(GetTypeName<int>().c_str(), test_suite->type_param());
+ EXPECT_STREQ(GetTypeName<Types<int>>().c_str(), test_suite->type_param());
EXPECT_TRUE(test_suite->should_run());
EXPECT_EQ(0, test_suite->disabled_test_count());
EXPECT_EQ(1, test_suite->test_to_run_count());
@@ -199,11 +191,10 @@ TEST(ApiTest, TestSuiteImmutableAccessorsWork) {
EXPECT_STREQ("Dummy", tests[0]->name());
EXPECT_STREQ("TestSuiteWithCommentTest/0", tests[0]->test_suite_name());
EXPECT_TRUE(IsNull(tests[0]->value_param()));
- EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param());
+ EXPECT_STREQ(GetTypeName<Types<int>>().c_str(), tests[0]->type_param());
EXPECT_TRUE(tests[0]->should_run());
delete[] tests;
-#endif // GTEST_HAS_TYPED_TEST
}
TEST(ApiTest, TestSuiteDisabledAccessorsWork) {
@@ -233,7 +224,7 @@ TEST(DISABLED_Test, Dummy2) {}
class FinalSuccessChecker : public Environment {
protected:
void TearDown() override {
- UnitTest* unit_test = UnitTest::GetInstance();
+ const auto& unit_test = UnitTest::GetInstance();
EXPECT_EQ(1 + kTypedTestSuites, unit_test->successful_test_suite_count());
EXPECT_EQ(3 + kTypedTests, unit_test->successful_test_count());
@@ -263,9 +254,9 @@ class FinalSuccessChecker : public Environment {
EXPECT_EQ(0, test_suites[1]->successful_test_count());
EXPECT_EQ(0, test_suites[1]->failed_test_count());
-#if GTEST_HAS_TYPED_TEST
EXPECT_STREQ("TestSuiteWithCommentTest/0", test_suites[2]->name());
- EXPECT_STREQ(GetTypeName<int>().c_str(), test_suites[2]->type_param());
+ EXPECT_STREQ(GetTypeName<Types<int>>().c_str(),
+ test_suites[2]->type_param());
EXPECT_TRUE(test_suites[2]->should_run());
EXPECT_EQ(0, test_suites[2]->disabled_test_count());
ASSERT_EQ(1, test_suites[2]->total_test_count());
@@ -273,7 +264,6 @@ class FinalSuccessChecker : public Environment {
EXPECT_EQ(0, test_suites[2]->failed_test_count());
EXPECT_TRUE(test_suites[2]->Passed());
EXPECT_FALSE(test_suites[2]->Failed());
-#endif // GTEST_HAS_TYPED_TEST
const TestSuite* test_suite = UnitTestHelper::FindTestSuite("ApiTest");
const TestInfo** tests = UnitTestHelper::GetSortedTests(test_suite);
@@ -310,20 +300,18 @@ class FinalSuccessChecker : public Environment {
delete[] tests;
-#if GTEST_HAS_TYPED_TEST
test_suite = UnitTestHelper::FindTestSuite("TestSuiteWithCommentTest/0");
tests = UnitTestHelper::GetSortedTests(test_suite);
EXPECT_STREQ("Dummy", tests[0]->name());
EXPECT_STREQ("TestSuiteWithCommentTest/0", tests[0]->test_suite_name());
EXPECT_TRUE(IsNull(tests[0]->value_param()));
- EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param());
+ EXPECT_STREQ(GetTypeName<Types<int>>().c_str(), tests[0]->type_param());
EXPECT_TRUE(tests[0]->should_run());
EXPECT_TRUE(tests[0]->result()->Passed());
EXPECT_EQ(0, tests[0]->result()->test_property_count());
delete[] tests;
-#endif // GTEST_HAS_TYPED_TEST
delete[] test_suites;
}
};
@@ -331,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());
diff --git a/googletest/test/gtest_assert_by_exception_test.cc b/googletest/test/gtest_assert_by_exception_test.cc
index ada4cb30ef68..f507eac47575 100644
--- a/googletest/test/gtest_assert_by_exception_test.cc
+++ b/googletest/test/gtest_assert_by_exception_test.cc
@@ -27,16 +27,16 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
// Tests 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);
diff --git a/googletest/test/gtest_dirs_test.cc b/googletest/test/gtest_dirs_test.cc
new file mode 100644
index 000000000000..1a5b63d3c28f
--- /dev/null
+++ b/googletest/test/gtest_dirs_test.cc
@@ -0,0 +1,101 @@
+#include <sys/stat.h>
+
+#include <cstdlib>
+#include <cstring>
+#include <string>
+
+#include "gtest/gtest.h"
+#include "gtest/internal/gtest-port.h"
+
+#if GTEST_HAS_FILE_SYSTEM
+
+namespace {
+
+class SetEnv {
+ public:
+ // Sets the environment value with name `name` to `value`, unless `value` is
+ // nullptr, in which case it unsets it. Restores the original value on
+ // destruction.
+ SetEnv(const char* name, const char* value) : name_(name) {
+ const char* old_value = getenv(name);
+ if (old_value != nullptr) {
+ saved_value_ = old_value;
+ have_saved_value_ = true;
+ }
+ if (value == nullptr) {
+ GTEST_CHECK_POSIX_SUCCESS_(unsetenv(name));
+ } else {
+ GTEST_CHECK_POSIX_SUCCESS_(setenv(name, value, 1 /*overwrite*/));
+ }
+ }
+
+ ~SetEnv() {
+ if (have_saved_value_) {
+ GTEST_CHECK_POSIX_SUCCESS_(
+ setenv(name_.c_str(), saved_value_.c_str(), 1 /*overwrite*/));
+ } else {
+ GTEST_CHECK_POSIX_SUCCESS_(unsetenv(name_.c_str()));
+ }
+ }
+
+ private:
+ std::string name_;
+ bool have_saved_value_ = false;
+ std::string saved_value_;
+};
+
+class MakeTempDir {
+ public:
+ // Creates a directory with a unique name including `testname`.
+ // The destructor removes it.
+ explicit MakeTempDir(const std::string& testname) {
+ // mkdtemp requires that the last 6 characters of the input pattern
+ // are Xs, and the string is modified by replacing those characters.
+ std::string pattern = "/tmp/" + testname + "_XXXXXX";
+ GTEST_CHECK_(mkdtemp(pattern.data()) != nullptr);
+ dirname_ = pattern;
+ }
+
+ ~MakeTempDir() { GTEST_CHECK_POSIX_SUCCESS_(rmdir(dirname_.c_str())); }
+
+ const char* DirName() const { return dirname_.c_str(); }
+
+ private:
+ std::string dirname_;
+};
+
+bool StartsWith(const std::string& str, const std::string& prefix) {
+ return str.substr(0, prefix.size()) == prefix;
+}
+
+TEST(TempDirTest, InEnvironment) {
+ // Since the test infrastructure might be verifying directory existence or
+ // even creating subdirectories, we need to be careful that the directories we
+ // specify are actually valid.
+ MakeTempDir temp_dir("TempDirTest_InEnvironment");
+ SetEnv set_env("TEST_TMPDIR", temp_dir.DirName());
+ EXPECT_TRUE(StartsWith(testing::TempDir(), temp_dir.DirName()));
+}
+
+TEST(TempDirTest, NotInEnvironment) {
+ SetEnv set_env("TEST_TMPDIR", nullptr);
+ EXPECT_NE(testing::TempDir(), "");
+}
+
+TEST(SrcDirTest, InEnvironment) {
+ // Since the test infrastructure might be verifying directory existence or
+ // even creating subdirectories, we need to be careful that the directories we
+ // specify are actually valid.
+ MakeTempDir temp_dir("SrcDirTest_InEnvironment");
+ SetEnv set_env("TEST_SRCDIR", temp_dir.DirName());
+ EXPECT_TRUE(StartsWith(testing::SrcDir(), temp_dir.DirName()));
+}
+
+TEST(SrcDirTest, NotInEnvironment) {
+ SetEnv set_env("TEST_SRCDIR", nullptr);
+ EXPECT_NE(testing::SrcDir(), "");
+}
+
+#endif // GTEST_HAS_FILE_SYSTEM
+
+} // namespace
diff --git a/googletest/test/gtest_environment_test.cc b/googletest/test/gtest_environment_test.cc
index 064bfc50b918..122eaf3ca802 100644
--- a/googletest/test/gtest_environment_test.cc
+++ b/googletest/test/gtest_environment_test.cc
@@ -30,20 +30,15 @@
//
// 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(),
diff --git a/googletest/test/gtest_help_test.py b/googletest/test/gtest_help_test.py
index 582d24c2dcce..85a0c33c982c 100755
--- a/googletest/test/gtest_help_test.py
+++ b/googletest/test/gtest_help_test.py
@@ -39,41 +39,61 @@ SYNOPSIS
import os
import re
-import gtest_test_utils
+import sys
+from googletest.test import gtest_test_utils
+IS_DARWIN = os.name == 'posix' and os.uname()[0] == 'Darwin'
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'
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
+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.*' +
- FLAG_PREFIX + r'filter=.*' +
- FLAG_PREFIX + r'also_run_disabled_tests.*' +
- FLAG_PREFIX + r'repeat=.*' +
- FLAG_PREFIX + r'shuffle.*' +
- FLAG_PREFIX + r'random_seed=.*' +
- FLAG_PREFIX + r'color=.*' +
- FLAG_PREFIX + r'print_time.*' +
- FLAG_PREFIX + r'output=.*' +
- FLAG_PREFIX + r'break_on_failure.*' +
- FLAG_PREFIX + r'throw_on_failure.*' +
- FLAG_PREFIX + r'catch_exceptions=0.*',
- re.DOTALL)
+ FLAG_PREFIX
+ + r'list_tests.*'
+ + FLAG_PREFIX
+ + r'filter=.*'
+ + FLAG_PREFIX
+ + r'also_run_disabled_tests.*'
+ + FLAG_PREFIX
+ + r'repeat=.*'
+ + FLAG_PREFIX
+ + r'shuffle.*'
+ + FLAG_PREFIX
+ + r'random_seed=.*'
+ + FLAG_PREFIX
+ + r'color=.*'
+ + FLAG_PREFIX
+ + r'brief.*'
+ + FLAG_PREFIX
+ + r'print_time.*'
+ + FLAG_PREFIX
+ + r'output=.*'
+ + FLAG_PREFIX
+ + r'break_on_failure.*'
+ + FLAG_PREFIX
+ + r'throw_on_failure.*'
+ + FLAG_PREFIX
+ + r'catch_exceptions=0.*',
+ re.DOTALL,
+)
def RunWithFlag(flag):
@@ -107,18 +127,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:
- self.assert_(STREAM_RESULT_TO_FLAG in output, output)
+ if IS_DARWIN or 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.
@@ -131,40 +170,32 @@ 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)
-
def testRunsTestsWithoutHelpFlag(self):
- """Verifies that when no help flag is specified, the tests are run
- and the help message is not printed."""
+ """Verifies correct behavior when no help flag is specified.
+
+ Verifies that when no help flag is specified, the tests are run
+ and the help message is not printed.
+ """
self.TestNonHelpFlag(None)
def testRunsTestsWithGtestInternalFlag(self):
- """Verifies that the tests are run and no help message is printed when
- a flag starting with Google Test prefix and 'internal_' is supplied."""
+ """Verifies correct behavior when internal testing flag is specified.
+
+ Verifies that the tests are run and no help message is printed when
+ a flag starting with Google Test prefix and 'internal_' is supplied.
+ """
self.TestNonHelpFlag(INTERNAL_FLAG_FOR_TESTING)
if __name__ == '__main__':
+ if '--has_absl_flags' in sys.argv:
+ sys.argv.remove('--has_absl_flags')
gtest_test_utils.Main()
diff --git a/googletest/test/gtest_help_test_.cc b/googletest/test/gtest_help_test_.cc
index 750ae6ce95fc..18b5f3cddab5 100644
--- a/googletest/test/gtest_help_test_.cc
+++ b/googletest/test/gtest_help_test_.cc
@@ -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.
@@ -40,6 +39,6 @@ TEST(HelpFlagTest, ShouldNotBeRun) {
ASSERT_TRUE(false) << "Tests shouldn't be run when --help is specified.";
}
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
TEST(DeathTest, UsedByPythonScriptToDetectSupportForDeathTestsInThisBinary) {}
#endif
diff --git a/googletest/test/gtest_json_test_utils.py b/googletest/test/gtest_json_test_utils.py
index 62bbfc288f82..86a5925b079e 100644
--- a/googletest/test/gtest_json_test_utils.py
+++ b/googletest/test/gtest_json_test_utils.py
@@ -42,6 +42,7 @@ def normalize(obj):
Normalized output without any references to transient information that may
change from run to run.
"""
+
def _normalize(key, value):
if key == 'time':
return re.sub(r'^\d+(\.\d+)?s$', '*', value)
@@ -50,8 +51,11 @@ 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):
return {k: _normalize(k, v) for k, v in obj.items()}
if isinstance(obj, list):
diff --git a/googletest/test/gtest_list_output_unittest.py b/googletest/test/gtest_list_output_unittest.py
index 3bba7ea2cfd3..afd521d2fa34 100644
--- a/googletest/test/gtest_list_output_unittest.py
+++ b/googletest/test/gtest_list_output_unittest.py
@@ -40,22 +40,48 @@ 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'
EXPECTED_XML = """<\?xml version="1.0" encoding="UTF-8"\?>
-<testsuites tests="2" name="AllTests">
+<testsuites tests="16" name="AllTests">
<testsuite name="FooTest" tests="2">
<testcase name="Test1" file=".*gtest_list_output_unittest_.cc" line="43" />
<testcase name="Test2" file=".*gtest_list_output_unittest_.cc" line="45" />
</testsuite>
+ <testsuite name="FooTestFixture" tests="2">
+ <testcase name="Test3" file=".*gtest_list_output_unittest_.cc" line="48" />
+ <testcase name="Test4" file=".*gtest_list_output_unittest_.cc" line="49" />
+ </testsuite>
+ <testsuite name="TypedTest/0" tests="2">
+ <testcase name="Test7" type_param="int" file=".*gtest_list_output_unittest_.cc" line="60" />
+ <testcase name="Test8" type_param="int" file=".*gtest_list_output_unittest_.cc" line="61" />
+ </testsuite>
+ <testsuite name="TypedTest/1" tests="2">
+ <testcase name="Test7" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="60" />
+ <testcase name="Test8" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="61" />
+ </testsuite>
+ <testsuite name="Single/TypeParameterizedTestSuite/0" tests="2">
+ <testcase name="Test9" type_param="int" file=".*gtest_list_output_unittest_.cc" line="66" />
+ <testcase name="Test10" type_param="int" file=".*gtest_list_output_unittest_.cc" line="67" />
+ </testsuite>
+ <testsuite name="Single/TypeParameterizedTestSuite/1" tests="2">
+ <testcase name="Test9" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="66" />
+ <testcase name="Test10" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="67" />
+ </testsuite>
+ <testsuite name="ValueParam/ValueParamTest" tests="4">
+ <testcase name="Test5/0" value_param="33" file=".*gtest_list_output_unittest_.cc" line="52" />
+ <testcase name="Test5/1" value_param="42" file=".*gtest_list_output_unittest_.cc" line="52" />
+ <testcase name="Test6/0" value_param="33" file=".*gtest_list_output_unittest_.cc" line="53" />
+ <testcase name="Test6/1" value_param="42" file=".*gtest_list_output_unittest_.cc" line="53" />
+ </testsuite>
</testsuites>
"""
EXPECTED_JSON = """{
- "tests": 2,
+ "tests": 16,
"name": "AllTests",
"testsuites": \[
{
@@ -73,6 +99,124 @@ EXPECTED_JSON = """{
"line": 45
}
\]
+ },
+ {
+ "name": "FooTestFixture",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test3",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 48
+ },
+ {
+ "name": "Test4",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 49
+ }
+ \]
+ },
+ {
+ "name": "TypedTest\\\\/0",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test7",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 60
+ },
+ {
+ "name": "Test8",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 61
+ }
+ \]
+ },
+ {
+ "name": "TypedTest\\\\/1",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test7",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 60
+ },
+ {
+ "name": "Test8",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 61
+ }
+ \]
+ },
+ {
+ "name": "Single\\\\/TypeParameterizedTestSuite\\\\/0",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test9",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 66
+ },
+ {
+ "name": "Test10",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 67
+ }
+ \]
+ },
+ {
+ "name": "Single\\\\/TypeParameterizedTestSuite\\\\/1",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test9",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 66
+ },
+ {
+ "name": "Test10",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 67
+ }
+ \]
+ },
+ {
+ "name": "ValueParam\\\\/ValueParamTest",
+ "tests": 4,
+ "testsuite": \[
+ {
+ "name": "Test5\\\\/0",
+ "value_param": "33",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 52
+ },
+ {
+ "name": "Test5\\\\/1",
+ "value_param": "42",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 52
+ },
+ {
+ "name": "Test6\\\\/0",
+ "value_param": "33",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 53
+ },
+ {
+ "name": "Test6\\\\/1",
+ "value_param": "42",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 53
+ }
+ \]
}
\]
}
@@ -80,8 +224,7 @@ EXPECTED_JSON = """{
class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase):
- """Unit test for Google Test's list tests with output to file functionality.
- """
+ """Unit test for Google Test's list tests with output to file functionality."""
def testXml(self):
"""Verifies XML output for listing tests in a Google Test binary.
@@ -100,22 +243,26 @@ class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase):
self._TestOutput('json', EXPECTED_JSON)
def _GetOutput(self, out_format):
- file_path = os.path.join(gtest_test_utils.GetTempDir(),
- 'test_out.' + out_format)
+ file_path = os.path.join(
+ gtest_test_utils.GetTempDir(), 'test_out.' + out_format
+ )
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
- 'gtest_list_output_unittest_')
+ 'gtest_list_output_unittest_'
+ )
- command = ([
+ command = [
gtest_prog_path,
'%s=%s:%s' % (GTEST_OUTPUT_FLAG, out_format, file_path),
- '--gtest_list_tests'
- ])
+ '--gtest_list_tests',
+ ]
environ_copy = os.environ.copy()
p = gtest_test_utils.Subprocess(
- command, env=environ_copy, working_dir=gtest_test_utils.GetTempDir())
+ command, env=environ_copy, working_dir=gtest_test_utils.GetTempDir()
+ )
- self.assert_(p.exited)
- self.assertEquals(0, p.exit_code)
+ self.assertTrue(p.exited)
+ self.assertEqual(0, p.exit_code)
+ self.assertTrue(os.path.isfile(file_path))
with open(file_path) as f:
result = f.read()
return result
@@ -128,11 +275,12 @@ class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase):
for actual_line in actual_lines:
expected_line = expected_lines[line_count]
expected_line_re = re.compile(expected_line.strip())
- self.assert_(
+ self.assertTrue(
expected_line_re.match(actual_line.strip()),
- ('actual output of "%s",\n'
- 'which does not match expected regex of "%s"\n'
- 'on line %d' % (actual, expected_output, line_count)))
+ 'actual output of "%s",\n'
+ 'which does not match expected regex of "%s"\n'
+ 'on line %d' % (actual, expected_output, line_count),
+ )
line_count = line_count + 1
diff --git a/googletest/test/gtest_list_output_unittest_.cc b/googletest/test/gtest_list_output_unittest_.cc
index b1c7b4de3461..92b9d4f28eec 100644
--- a/googletest/test/gtest_list_output_unittest_.cc
+++ b/googletest/test/gtest_list_output_unittest_.cc
@@ -44,6 +44,32 @@ TEST(FooTest, Test1) {}
TEST(FooTest, Test2) {}
+class FooTestFixture : public ::testing::Test {};
+TEST_F(FooTestFixture, Test3) {}
+TEST_F(FooTestFixture, Test4) {}
+
+class ValueParamTest : public ::testing::TestWithParam<int> {};
+TEST_P(ValueParamTest, Test5) {}
+TEST_P(ValueParamTest, Test6) {}
+INSTANTIATE_TEST_SUITE_P(ValueParam, ValueParamTest, ::testing::Values(33, 42));
+
+template <typename T>
+class TypedTest : public ::testing::Test {};
+typedef testing::Types<int, bool> TypedTestTypes;
+TYPED_TEST_SUITE(TypedTest, TypedTestTypes);
+TYPED_TEST(TypedTest, Test7) {}
+TYPED_TEST(TypedTest, Test8) {}
+
+template <typename T>
+class TypeParameterizedTestSuite : public ::testing::Test {};
+TYPED_TEST_SUITE_P(TypeParameterizedTestSuite);
+TYPED_TEST_P(TypeParameterizedTestSuite, Test9) {}
+TYPED_TEST_P(TypeParameterizedTestSuite, Test10) {}
+REGISTER_TYPED_TEST_SUITE_P(TypeParameterizedTestSuite, Test9, Test10);
+typedef testing::Types<int, bool> TypeParameterizedTestSuiteTypes; // NOLINT
+INSTANTIATE_TYPED_TEST_SUITE_P(Single, TypeParameterizedTestSuite,
+ TypeParameterizedTestSuiteTypes);
+
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
diff --git a/googletest/test/gtest_main_unittest.cc b/googletest/test/gtest_main_unittest.cc
index eddedeabe8f3..29cd5510a4b1 100644
--- a/googletest/test/gtest_main_unittest.cc
+++ b/googletest/test/gtest_main_unittest.cc
@@ -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
diff --git a/googletest/test/gtest_pred_impl_unittest.cc b/googletest/test/gtest_pred_impl_unittest.cc
index 1afe5e2da7fe..033e2d9f6519 100644
--- a/googletest/test/gtest_pred_impl_unittest.cc
+++ b/googletest/test/gtest_pred_impl_unittest.cc
@@ -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 01/02/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
@@ -48,9 +45,10 @@
// stand-alone regression test.
#include <iostream>
+#include <ostream>
-#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
+#include "gtest/gtest.h"
// A user-defined data type.
struct Bool {
@@ -78,15 +76,10 @@ bool PredFunction1(T1 v1) {
return v1 > 0;
}
-// The following two functions are needed to circumvent a bug in
-// gcc 2.95.3, which sometimes has problem with the above template
-// function.
-bool PredFunction1Int(int v1) {
- return v1 > 0;
-}
-bool PredFunction1Bool(Bool v1) {
- return v1 > 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 PredFunction1Int(int v1) { return v1 > 0; }
+bool PredFunction1Bool(Bool v1) { return v1 > 0; }
// A unary predicate functor.
struct PredFunctor1 {
@@ -98,22 +91,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);
}
};
@@ -131,13 +119,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.";
@@ -165,104 +152,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;
}
@@ -270,147 +253,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;
}
@@ -418,44 +401,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.
@@ -465,47 +452,35 @@ bool PredFunction2(T1 v1, T2 v2) {
return v1 + v2 > 0;
}
-// The following two functions are needed to circumvent a bug in
-// gcc 2.95.3, which sometimes has problem with the above template
-// function.
-bool PredFunction2Int(int v1, int v2) {
- return v1 + v2 > 0;
-}
-bool PredFunction2Bool(Bool v1, Bool v2) {
- return v1 + v2 > 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 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);
}
};
@@ -523,16 +498,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.";
@@ -562,116 +535,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;
}
@@ -679,163 +636,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;
}
@@ -843,48 +784,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,52 +835,38 @@ bool PredFunction3(T1 v1, T2 v2, T3 v3) {
return v1 + v2 + v3 > 0;
}
-// The following two functions are needed to circumvent a bug in
-// gcc 2.95.3, which sometimes has problem with the above template
-// function.
-bool 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;
-}
+// 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; }
// 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);
}
};
@@ -957,19 +884,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.";
@@ -1001,128 +925,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;
}
@@ -1130,70 +1026,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;
}
@@ -1201,19 +1088,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;
}
@@ -1221,67 +1103,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;
}
@@ -1289,19 +1164,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;
}
@@ -1310,52 +1180,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.
@@ -1365,9 +1233,8 @@ bool PredFunction4(T1 v1, T2 v2, T3 v3, T4 v4) {
return v1 + v2 + v3 + v4 > 0;
}
-// The following two functions are needed to circumvent a bug in
-// gcc 2.95.3, which sometimes has problem with the above template
-// function.
+// The following two functions are needed because a compiler doesn't have
+// a context yet to know which template function must be instantiated.
bool PredFunction4Int(int v1, int v2, int v3, int v4) {
return v1 + v2 + v3 + v4 > 0;
}
@@ -1378,43 +1245,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);
}
@@ -1433,22 +1288,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.";
@@ -1482,21 +1333,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;
}
@@ -1504,21 +1348,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;
}
@@ -1526,73 +1363,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;
}
@@ -1600,21 +1424,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;
}
@@ -1623,195 +1440,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;
}
@@ -1819,56 +1596,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.
@@ -1878,9 +1649,8 @@ bool PredFunction5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) {
return v1 + v2 + v3 + v4 + v5 > 0;
}
-// The following two functions are needed to circumvent a bug in
-// gcc 2.95.3, which sometimes has problem with the above template
-// function.
+// The following two functions are needed because a compiler doesn't have
+// a context yet to know which template function must be instantiated.
bool PredFunction5Int(int v1, int v2, int v3, int v4, int v5) {
return v1 + v2 + v3 + v4 + v5 > 0;
}
@@ -1891,10 +1661,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;
}
@@ -1902,37 +1669,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);
}
@@ -1951,25 +1707,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.";
@@ -2005,152 +1756,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;
}
@@ -2158,211 +1863,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;
}
@@ -2370,58 +2021,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;
+ },
+ "");
}
diff --git a/googletest/test/gtest_premature_exit_test.cc b/googletest/test/gtest_premature_exit_test.cc
index 1d1187eff006..1a0c5ea4f0d3 100644
--- a/googletest/test/gtest_premature_exit_test.cc
+++ b/googletest/test/gtest_premature_exit_test.cc
@@ -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();
diff --git a/googletest/test/gtest_repeat_test.cc b/googletest/test/gtest_repeat_test.cc
index 7da4a15ea141..f67b7886e1a3 100644
--- a/googletest/test/gtest_repeat_test.cc
+++ b/googletest/test/gtest_repeat_test.cc
@@ -27,44 +27,32 @@
// (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.
@@ -73,7 +61,7 @@ int g_environment_tear_down_count = 0;
class MyEnvironment : public testing::Environment {
public:
- MyEnvironment() {}
+ MyEnvironment() = default;
void SetUp() override { g_environment_set_up_count++; }
void TearDown() override { g_environment_tear_down_count++; }
};
@@ -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());
diff --git a/ci/env-osx.sh b/googletest/test/gtest_skip_check_output_test.py
index 9c421e14314c..b30a16504b5b 100755
--- a/ci/env-osx.sh
+++ b/googletest/test/gtest_skip_check_output_test.py
@@ -1,7 +1,6 @@
-#!/usr/bin/env bash
-# Copyright 2017 Google Inc.
-# All Rights Reserved.
+#!/usr/bin/env python
#
+# Copyright 2019 Google LLC. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
@@ -28,20 +27,34 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+"""Tests Google Test's gtest skip in environment setup behavior.
-#
-# This file should be sourced, and not executed as a standalone script.
-#
+This script invokes gtest_skip_in_environment_setup_test_ and verifies its
+output.
+"""
+
+import re
+
+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')
+
+OUTPUT = gtest_test_utils.Subprocess([EXE_PATH]).output
+
+
+# Test.
+class SkipEntireEnvironmentTest(gtest_test_utils.TestCase):
+
+ def testSkipEntireEnvironmentTest(self):
+ self.assertIn('Skipped\nskipping single test\n', OUTPUT)
+ skip_fixture = 'Skipped\nskipping all tests for this fixture\n'
+ self.assertIsNotNone(
+ re.search(skip_fixture + '.*' + skip_fixture, OUTPUT, flags=re.DOTALL),
+ repr(OUTPUT),
+ )
+ self.assertNotIn('FAILED', OUTPUT)
-# TODO() - we can check if this is being sourced using $BASH_VERSION and $BASH_SOURCE[0] != ${0}.
-#
-if [ "${TRAVIS_OS_NAME}" = "osx" ]; then
- if [ "$CXX" = "clang++" ]; then
- # $PATH needs to be adjusted because the llvm tap doesn't install the
- # package to /usr/local/bin, etc, like the gcc tap does.
- # See: https://github.com/Homebrew/legacy-homebrew/issues/29733
- clang_version=3.9
- export PATH="/usr/local/opt/llvm@${clang_version}/bin:$PATH";
- fi
-fi
+if __name__ == '__main__':
+ gtest_test_utils.Main()
diff --git a/googletest/test/gtest_skip_environment_check_output_test.py b/googletest/test/gtest_skip_environment_check_output_test.py
index 6e791556aa71..388a4e95f50f 100755
--- a/googletest/test/gtest_skip_environment_check_output_test.py
+++ b/googletest/test/gtest_skip_environment_check_output_test.py
@@ -33,11 +33,12 @@ 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(
- 'gtest_skip_in_environment_setup_test')
+ 'gtest_skip_in_environment_setup_test'
+)
OUTPUT = gtest_test_utils.Subprocess([EXE_PATH]).output
diff --git a/googletest/test/gtest_skip_in_environment_setup_test.cc b/googletest/test/gtest_skip_in_environment_setup_test.cc
index 937231063816..5f21c27dcdbd 100644
--- a/googletest/test/gtest_skip_in_environment_setup_test.cc
+++ b/googletest/test/gtest_skip_in_environment_setup_test.cc
@@ -31,6 +31,7 @@
// testcases being skipped.
#include <iostream>
+
#include "gtest/gtest.h"
class SetupEnvironment : public testing::Environment {
diff --git a/googletest/test/gtest_skip_test.cc b/googletest/test/gtest_skip_test.cc
index 717e105e2e07..e1b8d655adae 100644
--- a/googletest/test/gtest_skip_test.cc
+++ b/googletest/test/gtest_skip_test.cc
@@ -35,7 +35,7 @@
using ::testing::Test;
TEST(SkipTest, DoesSkip) {
- GTEST_SKIP();
+ GTEST_SKIP() << "skipping single test";
EXPECT_EQ(0, 1);
}
@@ -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); }
diff --git a/googletest/test/gtest_sole_header_test.cc b/googletest/test/gtest_sole_header_test.cc
index 1d94ac6b3ad9..e8e22a83c58c 100644
--- a/googletest/test/gtest_sole_header_test.cc
+++ b/googletest/test/gtest_sole_header_test.cc
@@ -35,9 +35,7 @@
namespace {
-void Subroutine() {
- EXPECT_EQ(42, 42);
-}
+void Subroutine() { EXPECT_EQ(42, 42); }
TEST(NoFatalFailureTest, ExpectNoFatalFailure) {
EXPECT_NO_FATAL_FAILURE(;);
diff --git a/googletest/test/gtest_stress_test.cc b/googletest/test/gtest_stress_test.cc
index 843481910f03..af8e757dc0bc 100644
--- a/googletest/test/gtest_stress_test.cc
+++ b/googletest/test/gtest_stress_test.cc
@@ -27,17 +27,18 @@
// (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 <algorithm>
+#include <memory>
+#include <string>
#include <vector>
+#include "gtest/gtest.h"
#include "src/gtest-internal-inl.h"
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
namespace testing {
namespace {
@@ -66,8 +67,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 +121,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] = std::make_unique<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 +147,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 +194,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 +224,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 +236,7 @@ int main(int argc, char **argv) {
#else
TEST(StressTest,
- DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) {
-}
+ DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) {}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
diff --git a/googletest/test/gtest_test_macro_stack_footprint_test.cc b/googletest/test/gtest_test_macro_stack_footprint_test.cc
index a48db05012cc..45f368b3a5e3 100644
--- a/googletest/test/gtest_test_macro_stack_footprint_test.cc
+++ b/googletest/test/gtest_test_macro_stack_footprint_test.cc
@@ -39,42 +39,42 @@
// 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.
diff --git a/googletest/test/gtest_test_utils.py b/googletest/test/gtest_test_utils.py
index ef9363c36945..964fa9fa50d4 100755
--- a/googletest/test/gtest_test_utils.py
+++ b/googletest/test/gtest_test_utils.py
@@ -29,9 +29,10 @@
"""Unit test utilities for Google C++ Testing and Mocking Framework."""
# Suppresses the 'Import not at the top of the file' lint complaint.
-# pylint: disable-msg=C6204
+# pylint: disable=g-import-not-at-top
import os
+import subprocess
import sys
IS_WINDOWS = os.name == 'nt'
@@ -42,14 +43,7 @@ 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
+# pylint: enable=g-import-not-at-top
GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'
@@ -69,23 +63,22 @@ def SetEnvVar(env_var, value):
# Here we expose a class from a particular module, depending on the
-# environment. The comment suppresses the 'Invalid variable name' lint
-# complaint.
-TestCase = _test_module.TestCase # pylint: disable=C6409
+# environment.
+TestCase = _test_module.TestCase
# Initially maps a flag to its default value. After
# _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
-_flag_map = {'source_dir': os.path.dirname(sys.argv[0]),
- 'build_dir': os.path.dirname(sys.argv[0])}
+_flag_map = {
+ 'source_dir': os.path.dirname(sys.argv[0]),
+ 'build_dir': os.path.dirname(sys.argv[0]),
+}
_gtest_flags_are_parsed = False
def _ParseAndStripGTestFlags(argv):
"""Parses and strips Google Test flags from argv. This is idempotent."""
- # Suppresses the lint complaint about a global variable since we need it
- # here to maintain module-wide state.
- global _gtest_flags_are_parsed # pylint: disable=W0603
+ global _gtest_flags_are_parsed
if _gtest_flags_are_parsed:
return
@@ -100,7 +93,7 @@ def _ParseAndStripGTestFlags(argv):
while i < len(argv):
prefix = '--' + flag + '='
if argv[i].startswith(prefix):
- _flag_map[flag] = argv[i][len(prefix):]
+ _flag_map[flag] = argv[i][len(prefix) :]
del argv[i]
break
else:
@@ -156,15 +149,16 @@ def GetTestExecutablePath(executable_name, build_dir=None):
Args:
executable_name: name of the test binary that the test script runs.
- build_dir: directory where to look for executables, by default
- the result of GetBuildDir().
+ build_dir: directory where to look for executables, by default the
+ result of GetBuildDir().
Returns:
The absolute path of the test binary.
"""
- path = os.path.abspath(os.path.join(build_dir or GetBuildDir(),
- executable_name))
+ path = os.path.abspath(
+ os.path.join(build_dir or GetBuildDir(), executable_name)
+ )
if (IS_WINDOWS or IS_CYGWIN or IS_OS2) and not path.endswith('.exe'):
path += '.exe'
@@ -172,8 +166,9 @@ def GetTestExecutablePath(executable_name, build_dir=None):
message = (
'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
+ 'environment variable.' % path
+ )
+ print(message, file=sys.stderr)
sys.exit(1)
return path
@@ -200,6 +195,7 @@ def GetExitStatus(exit_code):
class Subprocess:
+
def __init__(self, command, working_dir=None, capture_stderr=True, env=None):
"""Changes into a specified directory, if provided, and executes a command.
@@ -209,7 +205,7 @@ class Subprocess:
command: The command to run, in the form of sys.argv.
working_dir: The directory to change into.
capture_stderr: Determines whether to capture stderr in the output member
- or to discard it.
+ or to discard it.
env: Dictionary with environment to pass to the subprocess.
Returns:
@@ -217,7 +213,6 @@ class Subprocess:
following attributes:
terminated_by_signal True if and only if the child process has been
terminated by a signal.
- signal Sygnal that terminated the child process.
exited True if and only if the child process exited
normally.
exit_code The code with which the child process exited.
@@ -225,74 +220,27 @@ 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)
-
- if self._return_code < 0:
+ 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
self.exited = False
- self.signal = -self._return_code
else:
self.terminated_by_signal = False
self.exited = True
diff --git a/googletest/test/gtest_testbridge_test.py b/googletest/test/gtest_testbridge_test.py
index 87ffad73d400..0d58758b0b68 100755
--- a/googletest/test/gtest_testbridge_test.py
+++ b/googletest/test/gtest_testbridge_test.py
@@ -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)
@@ -52,7 +52,7 @@ class GTestTestFilterTest(gtest_test_utils.TestCase):
subprocess_env[TESTBRIDGE_NAME] = '*.TestThatSucceeds'
p = gtest_test_utils.Subprocess(COMMAND, env=subprocess_env)
- self.assertEquals(0, p.exit_code)
+ self.assertEqual(0, p.exit_code)
Assert('filter = *.TestThatSucceeds' in p.output)
Assert('[ OK ] TestFilterTest.TestThatSucceeds' in p.output)
diff --git a/googletest/test/gtest_testbridge_test_.cc b/googletest/test/gtest_testbridge_test_.cc
index 24617b209e10..c2c000dca50d 100644
--- a/googletest/test/gtest_testbridge_test_.cc
+++ b/googletest/test/gtest_testbridge_test_.cc
@@ -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.
diff --git a/googletest/test/gtest_throw_on_failure_ex_test.cc b/googletest/test/gtest_throw_on_failure_ex_test.cc
index 1d95adbf537b..25d7c797ed4c 100644
--- a/googletest/test/gtest_throw_on_failure_ex_test.cc
+++ b/googletest/test/gtest_throw_on_failure_ex_test.cc
@@ -27,16 +27,16 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
// Tests 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.");
diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc
index 39749b7b19f8..6caa03fd34d9 100644
--- a/googletest/test/gtest_unittest.cc
+++ b/googletest/test/gtest_unittest.cc
@@ -37,21 +37,19 @@
// 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(filter) != "unknown"
- || testing::GTEST_FLAG(list_tests)
- || testing::GTEST_FLAG(output) != "unknown"
- || 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.
}
@@ -60,15 +58,36 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
#include <string.h>
#include <time.h>
+#include <cstdint>
#include <map>
+#include <memory>
#include <ostream>
+#include <set>
+#include <stdexcept>
+#include <string>
#include <type_traits>
#include <unordered_set>
+#include <utility>
#include <vector>
#include "gtest/gtest-spi.h"
#include "src/gtest-internal-inl.h"
+struct ConvertibleGlobalType {
+ // The inner enable_if is to ensure invoking is_constructible doesn't fail.
+ // The outer enable_if is to ensure the overload resolution doesn't encounter
+ // an ambiguity.
+ template <
+ class T,
+ std::enable_if_t<
+ false, std::enable_if_t<std::is_constructible<T>::value, int>> = 0>
+ operator T() const; // NOLINT(google-explicit-constructor)
+};
+void operator<<(ConvertibleGlobalType&, int);
+static_assert(sizeof(decltype(std::declval<ConvertibleGlobalType&>()
+ << 1)(*)()) > 0,
+ "error in operator<< overload resolution");
+
namespace testing {
namespace internal {
@@ -111,15 +130,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());
}
@@ -137,8 +156,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(
@@ -170,7 +189,7 @@ class TestEventListenersAccessor {
}
static void SuppressEventForwarding(TestEventListeners* listeners) {
- listeners->SuppressEventForwarding();
+ listeners->SuppressEventForwarding(true);
}
};
@@ -196,29 +215,13 @@ 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(filter);
-using testing::GTEST_FLAG(list_tests);
-using testing::GTEST_FLAG(output);
-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;
using testing::Message;
using testing::ScopedFakeTestPartResultReporter;
using testing::StaticAssertTypeEq;
using testing::Test;
-using testing::TestCase;
using testing::TestEventListeners;
using testing::TestInfo;
using testing::TestPartResult;
@@ -240,8 +243,6 @@ using testing::internal::FloatingPoint;
using testing::internal::ForEach;
using testing::internal::FormatEpochTimeInMillisAsIso8601;
using testing::internal::FormatTimeInMillisAsSeconds;
-using testing::internal::GTestFlagSaver;
-using testing::internal::GetCurrentOsStackTraceExceptTop;
using testing::internal::GetElementOr;
using testing::internal::GetNextRandomSeed;
using testing::internal::GetRandomSeedFromFlag;
@@ -249,16 +250,16 @@ using testing::internal::GetTestTypeId;
using testing::internal::GetTimeInMillis;
using testing::internal::GetTypeId;
using testing::internal::GetUnitTestImpl;
-using testing::internal::Int32;
+using testing::internal::GTestFlagSaver;
+using testing::internal::HasDebugStringAndShortDebugString;
using testing::internal::Int32FromEnvOrDie;
-using testing::internal::IsAProtocolMessage;
using testing::internal::IsContainer;
using testing::internal::IsContainerTest;
using testing::internal::IsNotContainer;
+using testing::internal::kMaxRandomSeed;
+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;
@@ -271,30 +272,23 @@ using testing::internal::StreamableToString;
using testing::internal::String;
using testing::internal::TestEventListenersAccessor;
using testing::internal::TestResultAccessor;
-using testing::internal::UInt32;
-using testing::internal::UnitTestImpl;
using testing::internal::WideStringToUtf8;
using testing::internal::edit_distance::CalculateOptimalEdits;
using testing::internal::edit_distance::CreateUnifiedDiff;
using testing::internal::edit_distance::EditType;
-using testing::internal::kMaxRandomSeed;
-using testing::internal::kTestTypeIdInGoogleTest;
-using testing::kMaxStackTraceDepth;
#if GTEST_HAS_STREAM_REDIRECTION
using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStdout;
#endif
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
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] << " ";
@@ -401,7 +395,7 @@ TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
// Tests FormatTimeInMillisAsSeconds().
TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
- EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
+ EXPECT_EQ("0.", FormatTimeInMillisAsSeconds(0));
}
TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
@@ -409,7 +403,11 @@ TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
- EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
+ EXPECT_EQ("3.", FormatTimeInMillisAsSeconds(3000));
+ EXPECT_EQ("10.", FormatTimeInMillisAsSeconds(10000));
+ EXPECT_EQ("100.", FormatTimeInMillisAsSeconds(100000));
+ EXPECT_EQ("123.456", FormatTimeInMillisAsSeconds(123456));
+ EXPECT_EQ("1234567.89", FormatTimeInMillisAsSeconds(1234567890));
}
TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
@@ -417,12 +415,16 @@ TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
- EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
+ EXPECT_EQ("-3.", FormatTimeInMillisAsSeconds(-3000));
+ EXPECT_EQ("-10.", FormatTimeInMillisAsSeconds(-10000));
+ EXPECT_EQ("-100.", FormatTimeInMillisAsSeconds(-100000));
+ EXPECT_EQ("-123.456", FormatTimeInMillisAsSeconds(-123456));
+ EXPECT_EQ("-1234567.89", FormatTimeInMillisAsSeconds(-1234567890));
}
// 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.
@@ -435,11 +437,12 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
private:
void SetUp() override {
- saved_tz_ = nullptr;
+ saved_tz_.reset();
- GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
- if (getenv("TZ"))
- saved_tz_ = strdup(getenv("TZ"));
+ GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv: deprecated */)
+ if (const char* tz = getenv("TZ")) {
+ saved_tz_ = std::make_unique<std::string>(tz);
+ }
GTEST_DISABLE_MSC_DEPRECATED_POP_()
// Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
@@ -449,16 +452,15 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
}
void TearDown() override {
- SetTimeZone(saved_tz_);
- free(const_cast<char*>(saved_tz_));
- saved_tz_ = nullptr;
+ SetTimeZone(saved_tz_ != nullptr ? saved_tz_->c_str() : nullptr);
+ saved_tz_.reset();
}
static void SetTimeZone(const char* time_zone) {
// tzset() distinguishes between the TZ variable being present and empty
// and not being present, so we have to consider the case of time_zone
// being NULL.
-#if _MSC_VER || GTEST_OS_WINDOWS_MINGW
+#if defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW)
// ...Unless it's MSVC, whose standard library's _putenv doesn't
// distinguish between an empty and a missing variable.
const std::string env_var =
@@ -468,6 +470,12 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
tzset();
GTEST_DISABLE_MSC_WARNINGS_POP_()
#else
+#if defined(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 {
@@ -477,40 +485,39 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
#endif
}
- const char* saved_tz_;
+ std::unique_ptr<std::string> saved_tz_; // Empty and null are different here
};
const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
- EXPECT_EQ("2011-10-31T18:52:42",
+ EXPECT_EQ("2011-10-31T18:52:42.000",
FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
}
-TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) {
- EXPECT_EQ(
- "2011-10-31T18:52:42",
- FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
+TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
+ EXPECT_EQ("2011-10-31T18:52:42.234",
+ FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
- EXPECT_EQ("2011-09-03T05:07:02",
+ EXPECT_EQ("2011-09-03T05:07:02.000",
FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
- EXPECT_EQ("2011-09-28T17:08:22",
+ EXPECT_EQ("2011-09-28T17:08:22.000",
FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
- EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0));
+ 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.
@@ -584,10 +591,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().
@@ -615,20 +622,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_
@@ -680,7 +684,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());
}
@@ -689,12 +693,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());
}
@@ -729,11 +733,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());
}
@@ -741,13 +745,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_
@@ -755,21 +759,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_
@@ -778,9 +785,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, "
@@ -788,7 +794,7 @@ TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
}
TEST(RandomTest, GeneratesNumbersWithinRange) {
- const UInt32 kRange = 10000;
+ constexpr uint32_t kRange = 10000;
testing::internal::Random random(12345);
for (int i = 0; i < 10; i++) {
EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
@@ -801,10 +807,10 @@ TEST(RandomTest, GeneratesNumbersWithinRange) {
}
TEST(RandomTest, RepeatsWhenReseeded) {
- const int kSeed = 123;
- const int kArraySize = 10;
- const UInt32 kRange = 10000;
- UInt32 values[kArraySize];
+ constexpr int kSeed = 123;
+ constexpr int kArraySize = 10;
+ constexpr uint32_t kRange = 10000;
+ uint32_t values[kArraySize];
testing::internal::Random random(kSeed);
for (int i = 0; i < kArraySize; i++) {
@@ -909,7 +915,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]) {
@@ -936,8 +942,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);
}
@@ -962,7 +968,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_);
@@ -984,7 +990,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_);
@@ -1009,7 +1015,7 @@ TEST_F(VectorShuffleTest, ShufflesEntireVector) {
}
TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
- const int kRangeSize = kVectorSize/2;
+ const int kRangeSize = kVectorSize / 2;
ShuffleRange(&random_, 0, kRangeSize, &vector_);
@@ -1031,11 +1037,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));
}
@@ -1096,17 +1102,16 @@ TEST(StringTest, CaseInsensitiveWideCStringEquals) {
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// 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
+#ifdef GTEST_OS_WINDOWS_MOBILE
TEST(StringTest, AnsiAndUtf16Null) {
EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
@@ -1115,21 +1120,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
@@ -1151,9 +1156,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.";
@@ -1161,10 +1164,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();
@@ -1201,10 +1201,10 @@ TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
EXPECT_EQ(1, results.size());
}
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
class ScopedFakeTestPartResultReporterWithThreadsTest
- : public ScopedFakeTestPartResultReporterTest {
+ : public ScopedFakeTestPartResultReporterTest {
protected:
static void AddFailureInOtherThread(FailureMode failure) {
ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
@@ -1257,7 +1257,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
@@ -1285,7 +1285,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) {
@@ -1304,16 +1304,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}.
@@ -1321,8 +1325,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) {
@@ -1341,18 +1344,22 @@ 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
+#ifdef GTEST_IS_THREADSAFE
typedef ScopedFakeTestPartResultReporterWithThreadsTest
ExpectFailureWithThreadsTest;
@@ -1393,21 +1400,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!");
@@ -1420,10 +1424,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.
@@ -1594,21 +1598,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(filter) = "";
- GTEST_FLAG(list_tests) = false;
- GTEST_FLAG(output) = "";
- 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
@@ -1621,37 +1628,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_STREQ("", GTEST_FLAG(filter).c_str());
- EXPECT_FALSE(GTEST_FLAG(list_tests));
- EXPECT_STREQ("", GTEST_FLAG(output).c_str());
- 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(filter) = "abc";
- GTEST_FLAG(list_tests) = true;
- GTEST_FLAG(output) = "xml:foo.xml";
- 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:
@@ -1665,21 +1678,17 @@ 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
// variable. The caller must ensure that both arguments are not NULL.
static void SetEnv(const char* name, const char* value) {
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// Environment variables are not supported on Windows CE.
return;
#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
@@ -1690,19 +1699,19 @@ 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::string* prev_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*'.
// We cast away the 'const' since that would work for both variants.
putenv(const_cast<char*>(added_env[name]->c_str()));
delete prev_env;
-#elif GTEST_OS_WINDOWS // If we are on Windows proper.
+#elif defined(GTEST_OS_WINDOWS) // If we are on Windows proper.
_putenv((Message() << name << "=" << value).GetString().c_str());
#else
if (*value == '\0') {
@@ -1713,7 +1722,7 @@ static void SetEnv(const char* name, const char* value) {
#endif // GTEST_OS_WINDOWS_MOBILE
}
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
// Environment variables are not supported on Windows CE.
using testing::internal::Int32FromGTestEnv;
@@ -1727,7 +1736,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.
@@ -1753,7 +1762,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
@@ -1767,29 +1776,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 value = 123;
- EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
+ int32_t value = 123;
+ 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 value = 123;
- EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
+ int32_t value = 123;
+ 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);
}
@@ -1799,11 +1808,11 @@ TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
printf("(expecting 2 warnings)\n");
- Int32 value = 123;
- EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
+ int32_t value = 123;
+ 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);
}
@@ -1811,19 +1820,18 @@ TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
// returns true when the flag represents a valid decimal integer in
// the range of an Int32.
TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
- Int32 value = 123;
- EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
+ int32_t value = 123;
+ 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);
}
// Tests that Int32FromEnvOrDie() parses the value of the var or
// returns the correct default.
// Environment variables are not supported on Windows CE.
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
@@ -1834,21 +1842,19 @@ TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
#endif // !GTEST_OS_WINDOWS_MOBILE
// Tests that Int32FromEnvOrDie() aborts with an error message
-// if the variable is not an Int32.
+// if the variable is not an int32_t.
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
-// if the variable cannot be represented by an Int32.
+// if the variable cannot be represented by an int32_t.
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
@@ -1898,7 +1904,7 @@ TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
// Tests that sharding is enabled if total_shards > 1 and
// we are not in a death test subprocess.
// Environment variables are not supported on Windows CE.
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
SetEnv(index_var_, "4");
SetEnv(total_var_, "22");
@@ -1955,7 +1961,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;
}
}
}
@@ -1967,7 +1974,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);
}
@@ -1999,8 +2006,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(
@@ -2027,10 +2034,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(
@@ -2069,8 +2076,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.
@@ -2111,16 +2117,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");
}
@@ -2168,9 +2171,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 {
@@ -2217,41 +2218,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();
@@ -2259,14 +2256,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.
@@ -2276,11 +2271,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.
@@ -2288,15 +2284,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
@@ -2308,14 +2306,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.
@@ -2327,19 +2326,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.
@@ -2347,13 +2350,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
@@ -2371,9 +2378,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.";
@@ -2382,19 +2388,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.";
@@ -2405,7 +2415,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 "
@@ -2415,9 +2425,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) {
@@ -2433,7 +2441,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
}
@@ -2446,31 +2454,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*
@@ -2487,20 +2491,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.
@@ -2523,8 +2525,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.
@@ -2533,8 +2534,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.
@@ -2546,8 +2546,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.
@@ -2565,17 +2564,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.
@@ -2588,22 +2587,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";
@@ -2637,12 +2633,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
@@ -2663,13 +2660,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
@@ -2693,13 +2691,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
@@ -2712,13 +2710,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
@@ -2759,26 +2758,26 @@ class FloatingPointTest : public Test {
typedef typename Floating::Bits Bits;
void SetUp() override {
- const size_t max_ulps = Floating::kMaxUlps;
+ const uint32_t max_ulps = Floating::kMaxUlps;
// The bits that represent 0.0.
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();
@@ -2787,23 +2786,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_;
};
@@ -2816,17 +2815,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.
@@ -2847,10 +2842,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.
@@ -2862,8 +2858,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.
@@ -2892,15 +2887,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.
@@ -2924,22 +2915,18 @@ TEST_F(FloatTest, Commutative) {
TEST_F(FloatTest, EXPECT_NEAR) {
EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
EXPECT_NEAR(2.0f, 3.0f, 1.0f);
- EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
+ EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
"The difference between 1.0f and 1.5f is 0.5, "
"which exceeds 0.25f");
- // To work around a bug in gcc 2.95.0, there is intentionally no
- // space after the first comma in the previous line.
}
// Tests ASSERT_NEAR.
TEST_F(FloatTest, ASSERT_NEAR) {
ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
ASSERT_NEAR(2.0f, 3.0f, 1.0f);
- EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
+ EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
"The difference between 1.0f and 1.5f is 0.5, "
"which exceeds 0.25f");
- // To work around a bug in gcc 2.95.0, there is intentionally no
- // space after the first comma in the previous line.
}
// Tests the cases where FloatLE() should succeed.
@@ -2958,36 +2945,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.
@@ -3008,10 +2999,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.
@@ -3023,8 +3016,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.
@@ -3048,12 +3040,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.
@@ -3080,8 +3070,13 @@ TEST_F(DoubleTest, EXPECT_NEAR) {
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
"The difference between 1.0 and 1.5 is 0.5, "
"which exceeds 0.25");
- // To work around a bug in gcc 2.95.0, there is intentionally no
- // space after the first comma in the previous statement.
+ // At this magnitude adjacent doubles are 512.0 apart, so this triggers a
+ // slightly different failure reporting path.
+ EXPECT_NONFATAL_FAILURE(
+ EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),
+ "The abs_error parameter 1.0 evaluates to 1 which is smaller than the "
+ "minimum distance between doubles for numbers of this magnitude which is "
+ "512");
}
// Tests ASSERT_NEAR.
@@ -3091,8 +3086,6 @@ TEST_F(DoubleTest, ASSERT_NEAR) {
EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
"The difference between 1.0 and 1.5 is 0.5, "
"which exceeds 0.25");
- // To work around a bug in gcc 2.95.0, there is intentionally no
- // space after the first comma in the previous statement.
}
// Tests the cases where DoubleLE() should succeed.
@@ -3111,22 +3104,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.
@@ -3138,9 +3138,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.
@@ -3179,11 +3177,8 @@ TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
// Tests that disabled typed tests aren't run.
-#if GTEST_HAS_TYPED_TEST
-
template <typename T>
-class TypedTest : public Test {
-};
+class TypedTest : public Test {};
typedef testing::Types<int, double> NumericTypes;
TYPED_TEST_SUITE(TypedTest, NumericTypes);
@@ -3193,8 +3188,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);
@@ -3202,15 +3196,10 @@ TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
FAIL() << "Unexpected failure: Disabled typed test should not run.";
}
-#endif // GTEST_HAS_TYPED_TEST
-
// Tests that disabled type-parameterized tests aren't run.
-#if GTEST_HAS_TYPED_TEST_P
-
template <typename T>
-class TypedTestP : public Test {
-};
+class TypedTestP : public Test {};
TYPED_TEST_SUITE_P(TypedTestP);
@@ -3224,8 +3213,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);
@@ -3238,8 +3226,6 @@ REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
-#endif // GTEST_HAS_TYPED_TEST_P
-
// Tests that assertion macros evaluate their arguments exactly once.
class SingleEvaluationTest : public Test {
@@ -3247,15 +3233,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 +3280,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_);
}
@@ -3345,51 +3326,77 @@ TEST_F(SingleEvaluationTest, OtherCases) {
#if GTEST_HAS_EXCEPTIONS
-void ThrowAnInteger() {
- throw 1;
-}
+#if GTEST_HAS_RTTI
+
+#define ERROR_DESC "std::runtime_error"
+
+#else // GTEST_HAS_RTTI
+
+#define ERROR_DESC "an std::exception-derived error"
+
+#endif // GTEST_HAS_RTTI
+
+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_EQ(3, a_);
+
// failed EXPECT_THROW, throws nothing
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
- EXPECT_EQ(3, a_);
+ EXPECT_EQ(4, a_);
// successful EXPECT_NO_THROW
EXPECT_NO_THROW(a_++);
- EXPECT_EQ(4, a_);
+ EXPECT_EQ(5, a_);
// failed EXPECT_NO_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
- a_++;
- ThrowAnInteger();
- }), "it throws");
- EXPECT_EQ(5, a_);
+ a_++;
+ ThrowAnInteger();
+ }),
+ "it throws");
+ EXPECT_EQ(6, a_);
// successful EXPECT_ANY_THROW
EXPECT_ANY_THROW({ // NOLINT
a_++;
ThrowAnInteger();
});
- EXPECT_EQ(6, a_);
+ EXPECT_EQ(7, a_);
// failed EXPECT_ANY_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
- EXPECT_EQ(7, a_);
+ EXPECT_EQ(8, a_);
}
#endif // GTEST_HAS_EXCEPTIONS
@@ -3398,12 +3405,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());
@@ -3422,12 +3425,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) {
@@ -3472,10 +3473,10 @@ TEST_F(NoFatalFailureTest, MessageIsStreamable) {
TestPartResultArray gtest_failures;
{
ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
- EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
+ EXPECT_NO_FATAL_FAILURE([] { FAIL() << "foo"; }()) << "my message";
}
ASSERT_EQ(2, gtest_failures.size());
- EXPECT_EQ(TestPartResult::kNonFatalFailure,
+ EXPECT_EQ(TestPartResult::kFatalFailure,
gtest_failures.GetTestPartResult(0).type());
EXPECT_EQ(TestPartResult::kNonFatalFailure,
gtest_failures.GetTestPartResult(1).type());
@@ -3550,8 +3551,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 <"
@@ -3564,8 +3566,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"
@@ -3575,8 +3576,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"
@@ -3585,8 +3585,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"
@@ -3603,9 +3602,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"
@@ -3640,24 +3638,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.
@@ -3705,7 +3700,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
@@ -3716,28 +3711,25 @@ 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).
TEST(AssertionTest, ASSERT_EQ_NULL) {
// A success.
const char* p = nullptr;
- // Some older GCC versions may issue a spurious warning in this or the next
- // assertion statement. This warning should not be suppressed with
- // static_cast since the test verifies the ability to use bare NULL as the
- // expected parameter to the macro.
ASSERT_EQ(nullptr, p);
// A failure.
@@ -3756,8 +3748,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.
@@ -3772,30 +3763,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
@@ -3806,14 +3793,21 @@ 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(
ASSERT_THROW(ThrowAnInteger(), bool),
"Expected: ThrowAnInteger() throws an exception of type bool.\n"
" Actual: it throws a different type.");
-# endif
+ EXPECT_FATAL_FAILURE(
+ 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
+ " "
+ "with description \"A description\".");
+#endif
EXPECT_FATAL_FAILURE(
ASSERT_THROW(ThrowNothing(), bool),
@@ -3827,15 +3821,20 @@ TEST(AssertionTest, ASSERT_NO_THROW) {
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
"Expected: ThrowAnInteger() doesn't throw an exception."
"\n Actual: it throws.");
+ EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
+ "Expected: ThrowRuntimeError(\"A description\") "
+ "doesn't throw an exception.\n "
+ "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
@@ -3849,14 +3848,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.
@@ -3868,6 +3864,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.
@@ -3880,10 +3877,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() {
@@ -3902,8 +3896,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");
@@ -3914,18 +3909,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);
@@ -3941,7 +3934,7 @@ TEST(AssertionTest, NamedEnum) {
enum {
kCaseA = -1,
-# if GTEST_OS_LINUX
+#ifdef 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
@@ -3954,21 +3947,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
+#ifdef 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);
@@ -3976,10 +3969,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);
@@ -3988,34 +3979,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
+#ifdef 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.
@@ -4026,8 +4008,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) {
@@ -4035,35 +4017,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.
@@ -4073,34 +4055,34 @@ 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
-#ifdef __BORLANDC__
-// Silences warnings: "Condition is always true", "Unreachable code"
-# pragma option push -w-ccc -w-rch
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
#endif
-
// Tests that the assertion macros behave like single statements.
TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
@@ -4112,14 +4094,16 @@ TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
else
; // NOLINT
- if (AlwaysFalse())
- ASSERT_LT(1, 3);
+ if (AlwaysFalse()) ASSERT_LT(1, 3);
if (AlwaysFalse())
; // NOLINT
else
EXPECT_GT(3, 2) << "";
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
#if GTEST_HAS_EXCEPTIONS
// Tests that the compiler will not complain about unreachable code in the
@@ -4136,33 +4120,52 @@ TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
}
+TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
+ EXPECT_THROW(throw std::exception(), std::exception);
+}
+
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#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());
else
; // NOLINT
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+
#endif // GTEST_HAS_EXCEPTIONS
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
@@ -4185,6 +4188,9 @@ TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
else
ASSERT_NO_FATAL_FAILURE(SUCCEED());
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
// Tests that the assertion macros work well with switch statements.
TEST(AssertionSyntaxTest, WorksWithSwitch) {
@@ -4196,8 +4202,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.
@@ -4208,22 +4214,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
@@ -4314,31 +4318,26 @@ TEST(AssertionWithMessageTest, ASSERT_STR) {
TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
- EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.", // NOLINT
+ EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT
"Expect failure.");
- // To work around a bug in gcc 2.95.0, there is intentionally no
- // space after the first comma in the previous statement.
}
// 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) {
@@ -4352,16 +4351,19 @@ TEST(AssertionWithMessageTest, ASSERT_TRUE) {
"(null)(null)");
}
-#if GTEST_OS_WINDOWS
+#ifdef 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
@@ -4377,8 +4379,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.
@@ -4407,8 +4408,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.
@@ -4427,19 +4427,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
@@ -4450,18 +4451,13 @@ 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).
TEST(ExpectTest, EXPECT_EQ_NULL) {
// A success.
const char* p = nullptr;
- // Some older GCC versions may issue a spurious warning in this or the next
- // assertion statement. This warning should not be suppressed with
- // static_cast since the test verifies the ability to use bare NULL as the
- // expected parameter to the macro.
EXPECT_EQ(nullptr, p);
// A failure.
@@ -4480,8 +4476,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.
@@ -4491,19 +4486,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.
@@ -4512,8 +4504,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.
@@ -4521,8 +4512,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.
@@ -4531,8 +4521,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.
@@ -4540,8 +4529,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
@@ -4553,6 +4541,13 @@ TEST(ExpectTest, EXPECT_THROW) {
"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(ThrowNothing(), bool),
"Expected: ThrowNothing() throws an exception of type bool.\n"
" Actual: it throws nothing.");
@@ -4564,15 +4559,20 @@ TEST(ExpectTest, EXPECT_NO_THROW) {
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
"Expected: ThrowAnInteger() doesn't throw an "
"exception.\n Actual: it throws.");
+ EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
+ "Expected: ThrowRuntimeError(\"A description\") "
+ "doesn't throw an exception.\n "
+ "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
@@ -4584,7 +4584,6 @@ TEST(ExpectTest, ExpectPrecedence) {
" true && false\n Which is: false");
}
-
// Tests the StreamableToString() function.
// Tests using StreamableToString() on a scalar.
@@ -4622,8 +4621,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.
@@ -4631,25 +4629,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.
//
@@ -4663,10 +4660,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.
@@ -4680,8 +4679,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);
}
@@ -4702,8 +4700,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.");
}
@@ -4736,37 +4733,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.
@@ -4782,8 +4776,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'");
@@ -4802,13 +4795,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.
@@ -4829,28 +4820,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
@@ -4868,10 +4862,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");
@@ -4890,16 +4882,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.
@@ -4921,15 +4910,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_;
}
@@ -4978,7 +4963,7 @@ TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
// both in a TEST and in a TEST_F.
class Foo {
public:
- Foo() {}
+ Foo() = default;
private:
int Bar() const { return 1; }
@@ -4991,9 +4976,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 {
@@ -5003,9 +4986,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.
@@ -5140,15 +5121,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() << ")";
}
@@ -5165,7 +5145,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) {
@@ -5190,14 +5170,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
@@ -5215,7 +5193,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,
@@ -5246,21 +5224,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";
@@ -5269,11 +5244,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 {
@@ -5287,14 +5260,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();
}
};
@@ -5303,7 +5274,7 @@ class TestInfoTest : public Test {
TEST_F(TestInfoTest, Names) {
const TestInfo* const test_info = GetTestInfo("Names");
- ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
+ ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
ASSERT_STREQ("Names", test_info->name());
}
@@ -5318,26 +5289,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;
@@ -5346,8 +5316,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);
@@ -5356,8 +5325,7 @@ TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
}
template <typename T>
-class CodeLocationForTYPEDTESTP : public Test {
-};
+class CodeLocationForTYPEDTESTP : public Test {};
TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
@@ -5370,10 +5338,11 @@ 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
-#ifndef REMOVE_LEGACY_TEST_CASEAPI
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
class SetUpTestCaseTest : public Test {
protected:
// This will be called once before the first test in this test case
@@ -5429,10 +5398,8 @@ 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_);
-}
-#endif // REMOVE_LEGACY_TEST_CASEAPI
+TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); }
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Tests SetupTestSuite/TearDown TestSuite
class SetUpTestSuiteTest : public Test {
@@ -5501,20 +5468,24 @@ TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
// The Flags struct stores a copy of all Google Test flags.
struct Flags {
// Constructs a Flags struct where each flag has its default value.
- Flags() : also_run_disabled_tests(false),
- break_on_failure(false),
- catch_exceptions(false),
- death_test_use_fork(false),
- filter(""),
- list_tests(false),
- output(""),
- print_time(true),
- random_seed(0),
- repeat(1),
- shuffle(false),
- stack_trace_depth(kMaxStackTraceDepth),
- stream_result_to(""),
- throw_on_failure(false) {}
+ Flags()
+ : also_run_disabled_tests(false),
+ break_on_failure(false),
+ catch_exceptions(false),
+ death_test_use_fork(false),
+ fail_fast(false),
+ filter(""),
+ list_tests(false),
+ output(""),
+ brief(false),
+ print_time(true),
+ random_seed(0),
+ repeat(1),
+ recreate_environments_when_repeating(true),
+ shuffle(false),
+ stack_trace_depth(kMaxStackTraceDepth),
+ stream_result_to(""),
+ throw_on_failure(false) {}
// Factory methods.
@@ -5550,6 +5521,14 @@ struct Flags {
return flags;
}
+ // Creates a Flags struct where the gtest_fail_fast flag has
+ // the given value.
+ static Flags FailFast(bool fail_fast) {
+ Flags flags;
+ flags.fail_fast = fail_fast;
+ return flags;
+ }
+
// Creates a Flags struct where the gtest_filter flag has the given
// value.
static Flags Filter(const char* filter) {
@@ -5574,6 +5553,14 @@ struct Flags {
return flags;
}
+ // Creates a Flags struct where the gtest_brief flag has the given
+ // value.
+ static Flags Brief(bool brief) {
+ Flags flags;
+ flags.brief = brief;
+ return flags;
+ }
+
// Creates a Flags struct where the gtest_print_time flag has the given
// value.
static Flags PrintTime(bool print_time) {
@@ -5584,7 +5571,7 @@ struct Flags {
// Creates a Flags struct where the gtest_random_seed flag has the given
// value.
- static Flags RandomSeed(Int32 random_seed) {
+ static Flags RandomSeed(int32_t random_seed) {
Flags flags;
flags.random_seed = random_seed;
return flags;
@@ -5592,12 +5579,22 @@ struct Flags {
// Creates a Flags struct where the gtest_repeat flag has the given
// value.
- static Flags Repeat(Int32 repeat) {
+ static Flags Repeat(int32_t repeat) {
Flags flags;
flags.repeat = repeat;
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) {
@@ -5608,7 +5605,7 @@ struct Flags {
// Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
// the given value.
- static Flags StackTraceDepth(Int32 stack_trace_depth) {
+ static Flags StackTraceDepth(int32_t stack_trace_depth) {
Flags flags;
flags.stack_trace_depth = stack_trace_depth;
return flags;
@@ -5635,14 +5632,17 @@ struct Flags {
bool break_on_failure;
bool catch_exceptions;
bool death_test_use_fork;
+ bool fail_fast;
const char* filter;
bool list_tests;
const char* output;
+ bool brief;
bool print_time;
- Int32 random_seed;
- Int32 repeat;
+ int32_t random_seed;
+ int32_t repeat;
+ bool recreate_environments_when_repeating;
bool shuffle;
- Int32 stack_trace_depth;
+ int32_t stack_trace_depth;
const char* stream_result_to;
bool throw_on_failure;
};
@@ -5652,20 +5652,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(filter) = "";
- GTEST_FLAG(list_tests) = false;
- GTEST_FLAG(output) = "";
- 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.
@@ -5682,43 +5685,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_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.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);
@@ -5731,16 +5739,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;
}
@@ -5748,10 +5756,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.
@@ -5772,13 +5780,13 @@ TEST_F(ParseFlagsTest, NoFlag) {
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
}
-// Tests parsing a bad --gtest_filter flag.
-TEST_F(ParseFlagsTest, FilterBad) {
- const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
+// Tests parsing --gtest_fail_fast.
+TEST_F(ParseFlagsTest, FailFast) {
+ const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
- const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
+ const char* argv2[] = {"foo.exe", nullptr};
- GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
}
// Tests parsing an empty --gtest_filter flag.
@@ -5933,15 +5941,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};
@@ -5967,8 +5966,35 @@ 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
+TEST_F(ParseFlagsTest, BriefFlag) {
+ const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
+
+ const char* argv2[] = {"foo.exe", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
+}
+
+// Tests having a --gtest_brief flag with a "true" value
+TEST_F(ParseFlagsTest, BriefFlagTrue) {
+ const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
+
+ const char* argv2[] = {"foo.exe", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
+}
+
+// Tests having a --gtest_brief flag with a "false" value
+TEST_F(ParseFlagsTest, BriefFlagFalse) {
+ const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
+
+ const char* argv2[] = {"foo.exe", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
}
// Tests having a --gtest_print_time flag
@@ -6034,6 +6060,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};
@@ -6108,8 +6148,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.
@@ -6140,23 +6180,78 @@ 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 defined(GTEST_HAS_ABSL) && defined(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 !defined(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 defined(GTEST_HAS_ABSL) && defined(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 !defined(GTEST_HAS_ABSL)
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
+#else
+ static_cast<void>(argv);
+ static_cast<void>(argv2);
+#endif
+}
+
+#ifdef 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
+
+TEST_F(ParseFlagsTest, UnrecognizedFlags) {
+ const char* argv[] = {"foo.exe", "--gtest_filter=abcd", "--other_flag",
+ nullptr};
+
+ const char* argv2[] = {"foo.exe", "--other_flag", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abcd"), false);
+}
+
+#ifdef 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;
@@ -6165,12 +6260,12 @@ 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 {
public:
- virtual void SetUp() {
+ void SetUp() override {
ParseFlagsTest::SetUp();
testdata_path_.Set(internal::FilePath(
@@ -6180,7 +6275,7 @@ class FlagfileTest : public ParseFlagsTest {
EXPECT_TRUE(testdata_path_.CreateFolder());
}
- virtual void TearDown() {
+ void TearDown() override {
testing::internal::posix::RmDir(testdata_path_.c_str());
ParseFlagsTest::TearDown();
}
@@ -6213,8 +6308,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();
@@ -6227,10 +6322,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();
@@ -6254,8 +6349,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.";
}
@@ -6263,8 +6357,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.";
}
@@ -6273,12 +6366,11 @@ 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_case_name())
- << "Expected the name of the currently running test case.";
+ EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
+ << "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test.";
}
@@ -6288,19 +6380,17 @@ 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_case_name())
- << "Expected the name of the currently running test case.";
+ EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
+ << "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test.";
}
} // 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 {
@@ -6349,13 +6439,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) {
@@ -6378,7 +6467,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) {
@@ -6449,28 +6538,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
@@ -6478,67 +6571,67 @@ 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
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW)
// On Windows, we ignore the TERM variable as it's usually not set.
SetEnv("TERM", "dumb");
@@ -6553,46 +6646,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.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
- SetEnv("TERM", "xterm-color"); // TERM supports colors.
+ SetEnv("TERM", "xterm-kitty"); // 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.
@@ -6715,12 +6811,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:
@@ -6777,8 +6871,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);
@@ -6821,7 +6915,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) {
@@ -6831,32 +6926,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());
@@ -6876,8 +6971,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);
@@ -6895,17 +6990,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";},
+TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprocesses) {
+ EXPECT_DEATH_IF_SUPPORTED(
+ {
+ GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
+ *GetUnitTestImpl()->listeners()))
+ << "expected failure";
+ },
"expected failure");
}
@@ -6922,8 +7020,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);
@@ -6936,8 +7034,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);
}
@@ -6959,8 +7057,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.
@@ -6981,8 +7079,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);
@@ -6995,8 +7093,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);
}
@@ -7018,8 +7116,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.
@@ -7027,7 +7125,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
@@ -7081,24 +7179,69 @@ GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
class ConversionHelperBase {};
class ConversionHelperDerived : public ConversionHelperBase {};
-// Tests that IsAProtocolMessage<T>::value is a compile-time constant.
-TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
- GTEST_COMPILE_ASSERT_(IsAProtocolMessage<::proto2::Message>::value,
- const_true);
- GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
-}
+struct HasDebugStringMethods {
+ std::string DebugString() const { return ""; }
+ std::string ShortDebugString() const { return ""; }
+};
+
+struct InheritsDebugStringMethods : public HasDebugStringMethods {};
+
+struct WrongTypeDebugStringMethod {
+ std::string DebugString() const { return ""; }
+ int ShortDebugString() const { return 1; }
+};
-// Tests that IsAProtocolMessage<T>::value is true when T is
-// proto2::Message or a sub-class of it.
-TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
- EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
+struct NotConstDebugStringMethod {
+ std::string DebugString() { return ""; }
+ std::string ShortDebugString() const { return ""; }
+};
+
+struct MissingDebugStringMethod {
+ std::string DebugString() { return ""; }
+};
+
+struct IncompleteType;
+
+// Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
+// constant.
+TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
+ static_assert(HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
+ "const_true");
+ static_assert(
+ HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
+ "const_true");
+ static_assert(HasDebugStringAndShortDebugString<
+ const InheritsDebugStringMethods>::value,
+ "const_true");
+ static_assert(
+ !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
+ "const_false");
+ static_assert(
+ !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
+ "const_false");
+ static_assert(
+ !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
+ "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
+// needed methods.
+TEST(HasDebugStringAndShortDebugStringTest,
+ ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
+ EXPECT_TRUE(
+ HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
}
-// Tests that IsAProtocolMessage<T>::value is false when T is neither
-// ::proto2::Message nor a sub-class of it.
-TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
- EXPECT_FALSE(IsAProtocolMessage<int>::value);
- EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
+// Tests that HasDebugStringAndShortDebugString<T>::value is false when T
+// doesn't have needed methods.
+TEST(HasDebugStringAndShortDebugStringTest,
+ ValueIsFalseWhenTypeIsNotAProtocolMessage) {
+ EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);
+ EXPECT_FALSE(
+ HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);
}
// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
@@ -7132,7 +7275,6 @@ TEST(GTestReferenceToConstTest, Works) {
TestGTestReferenceToConst<const std::string&, const std::string&>();
}
-
// Tests IsContainerTest.
class NonContainer {};
@@ -7144,10 +7286,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 {
@@ -7196,8 +7337,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));
@@ -7207,9 +7348,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));
@@ -7227,11 +7368,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));
}
@@ -7257,7 +7398,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);
@@ -7272,7 +7413,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());
@@ -7302,7 +7443,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());
@@ -7321,14 +7462,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());
@@ -7353,20 +7494,15 @@ TEST(IndexSequence, MakeIndexSequence) {
// ElemFromList
TEST(ElemFromList, Basic) {
using testing::internal::ElemFromList;
- using Idx = testing::internal::MakeIndexSequence<3>::type;
- EXPECT_TRUE((
- std::is_same<int, ElemFromList<0, Idx, int, double, char>::type>::value));
EXPECT_TRUE(
- (std::is_same<double,
- ElemFromList<1, Idx, int, double, char>::type>::value));
+ (std::is_same<int, ElemFromList<0, int, double, char>::type>::value));
EXPECT_TRUE(
- (std::is_same<char,
- ElemFromList<2, Idx, int, double, char>::type>::value));
+ (std::is_same<double, ElemFromList<1, int, double, char>::type>::value));
EXPECT_TRUE(
- (std::is_same<
- char, ElemFromList<7, testing::internal::MakeIndexSequence<12>::type,
- int, int, int, int, int, int, int, char, int, int,
- int, int>::type>::value));
+ (std::is_same<char, ElemFromList<2, int, double, char>::type>::value));
+ EXPECT_TRUE((
+ std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int,
+ char, int, int, int, int>::type>::value));
}
// FlatTuple
@@ -7378,7 +7514,8 @@ TEST(FlatTuple, Basic) {
EXPECT_EQ(0.0, tuple.Get<1>());
EXPECT_EQ(nullptr, tuple.Get<2>());
- tuple = FlatTuple<int, double, const char*>(7, 3.2, "Foo");
+ tuple = FlatTuple<int, double, const char*>(
+ testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo");
EXPECT_EQ(7, tuple.Get<0>());
EXPECT_EQ(3.2, tuple.Get<1>());
EXPECT_EQ(std::string("Foo"), tuple.Get<2>());
@@ -7387,6 +7524,147 @@ TEST(FlatTuple, Basic) {
EXPECT_EQ(5.1, tuple.Get<1>());
}
+namespace {
+std::string AddIntToString(int i, const std::string& s) {
+ return s + std::to_string(i);
+}
+} // namespace
+
+TEST(FlatTuple, Apply) {
+ using testing::internal::FlatTuple;
+
+ FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},
+ 5, "Hello"};
+
+ // Lambda.
+ EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
+ return i == static_cast<int>(s.size());
+ }));
+
+ // Function.
+ EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
+
+ // Mutating operations.
+ tuple.Apply([](int& i, std::string& s) {
+ ++i;
+ s += s;
+ });
+ EXPECT_EQ(tuple.Get<0>(), 6);
+ EXPECT_EQ(tuple.Get<1>(), "HelloHello");
+}
+
+struct ConstructionCounting {
+ ConstructionCounting() { ++default_ctor_calls; }
+ ~ConstructionCounting() { ++dtor_calls; }
+ ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }
+ ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }
+ ConstructionCounting& operator=(const ConstructionCounting&) {
+ ++copy_assignment_calls;
+ return *this;
+ }
+ ConstructionCounting& operator=(ConstructionCounting&&) noexcept {
+ ++move_assignment_calls;
+ return *this;
+ }
+
+ static void Reset() {
+ default_ctor_calls = 0;
+ dtor_calls = 0;
+ copy_ctor_calls = 0;
+ move_ctor_calls = 0;
+ copy_assignment_calls = 0;
+ move_assignment_calls = 0;
+ }
+
+ static int default_ctor_calls;
+ static int dtor_calls;
+ static int copy_ctor_calls;
+ static int move_ctor_calls;
+ static int copy_assignment_calls;
+ static int move_assignment_calls;
+};
+
+int ConstructionCounting::default_ctor_calls = 0;
+int ConstructionCounting::dtor_calls = 0;
+int ConstructionCounting::copy_ctor_calls = 0;
+int ConstructionCounting::move_ctor_calls = 0;
+int ConstructionCounting::copy_assignment_calls = 0;
+int ConstructionCounting::move_assignment_calls = 0;
+
+TEST(FlatTuple, ConstructorCalls) {
+ using testing::internal::FlatTuple;
+
+ // Default construction.
+ ConstructionCounting::Reset();
+ { FlatTuple<ConstructionCounting> tuple; }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Copy construction.
+ ConstructionCounting::Reset();
+ {
+ ConstructionCounting elem;
+ FlatTuple<ConstructionCounting> tuple{
+ testing::internal::FlatTupleConstructTag{}, elem};
+ }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Move construction.
+ ConstructionCounting::Reset();
+ {
+ FlatTuple<ConstructionCounting> tuple{
+ testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}};
+ }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Copy assignment.
+ // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
+ // elements
+ ConstructionCounting::Reset();
+ {
+ FlatTuple<ConstructionCounting> tuple;
+ ConstructionCounting elem;
+ tuple.Get<0>() = elem;
+ }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Move assignment.
+ // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
+ // elements
+ ConstructionCounting::Reset();
+ {
+ FlatTuple<ConstructionCounting> tuple;
+ tuple.Get<0>() = ConstructionCounting{};
+ }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);
+
+ ConstructionCounting::Reset();
+}
+
TEST(FlatTuple, ManyTypes) {
using testing::internal::FlatTuple;
@@ -7439,22 +7717,7 @@ TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
}
// Tests ad_hoc_test_result().
-
-class AdHocTestResultTest : public testing::Test {
- protected:
- static void SetUpTestSuite() {
- FAIL() << "A failure happened inside SetUpTestSuite().";
- }
-};
-
-TEST_F(AdHocTestResultTest, AdHocTestResultForTestSuiteShowsFailure) {
- const testing::TestResult& test_result = testing::UnitTest::GetInstance()
- ->current_test_suite()
- ->ad_hoc_test_result();
- EXPECT_TRUE(test_result.Failed());
-}
-
-TEST_F(AdHocTestResultTest, AdHocTestResultTestForUnitTestDoesNotShowFailure) {
+TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
const testing::TestResult& test_result =
testing::UnitTest::GetInstance()->ad_hoc_test_result();
EXPECT_FALSE(test_result.Failed());
@@ -7471,7 +7734,7 @@ auto* dynamic_test = testing::RegisterTest(
__LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });
TEST(RegisterTest, WasRegistered) {
- auto* unittest = testing::UnitTest::GetInstance();
+ const auto& unittest = testing::UnitTest::GetInstance();
for (int i = 0; i < unittest->total_test_suite_count(); ++i) {
auto* tests = unittest->GetTestSuite(i);
if (tests->name() != std::string("DynamicUnitTestFixture")) continue;
@@ -7486,3 +7749,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("", ""));
+}
diff --git a/googletest/test/gtest_xml_outfile2_test_.cc b/googletest/test/gtest_xml_outfile2_test_.cc
index f9a2a6e9846d..4a76429c559c 100644
--- a/googletest/test/gtest_xml_outfile2_test_.cc
+++ b/googletest/test/gtest_xml_outfile2_test_.cc
@@ -30,6 +30,8 @@
// gtest_xml_outfile2_test_ writes some xml via TestProperty used by
// gtest_xml_outfiles_test.py
+#include <atomic>
+
#include "gtest/gtest.h"
class PropertyTwo : public testing::Test {
@@ -38,6 +40,38 @@ class PropertyTwo : public testing::Test {
void TearDown() override { RecordProperty("TearDownProp", 2); }
};
-TEST_F(PropertyTwo, TestSomeProperties) {
- RecordProperty("TestSomeProperty", 2);
+TEST_F(PropertyTwo, TestInt64ConvertibleProperties) {
+ float float_prop = 3.25;
+ RecordProperty("TestFloatProperty", float_prop);
+
+ double double_prop = 4.75;
+ RecordProperty("TestDoubleProperty", double_prop);
+
+ // Validate we can write an unsigned size_t as a property
+ size_t size_t_prop = 5;
+ RecordProperty("TestSizetProperty", size_t_prop);
+
+ bool bool_prop = true;
+ RecordProperty("TestBoolProperty", bool_prop);
+
+ char char_prop = 'A';
+ RecordProperty("TestCharProperty", char_prop);
+
+ int16_t int16_prop = 6;
+ RecordProperty("TestInt16Property", int16_prop);
+
+ int32_t int32_prop = 7;
+ RecordProperty("TestInt32Property", int32_prop);
+
+ int64_t int64_prop = 8;
+ RecordProperty("TestInt64Property", int64_prop);
+
+ enum Foo {
+ NINE = 9,
+ };
+ Foo enum_prop = NINE;
+ RecordProperty("TestEnumProperty", enum_prop);
+
+ std::atomic<int> atomic_int_prop(10);
+ RecordProperty("TestAtomicIntProperty", atomic_int_prop);
}
diff --git a/googletest/test/gtest_xml_outfiles_test.py b/googletest/test/gtest_xml_outfiles_test.py
index e093f6f05e3e..d17cc0c9aee2 100755
--- a/googletest/test/gtest_xml_outfiles_test.py
+++ b/googletest/test/gtest_xml_outfiles_test.py
@@ -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_"
@@ -42,8 +42,8 @@ GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_"
EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests">
- <testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyOne">
+ <testsuite name="PropertyOne" tests="1" failures="0" skipped="0" disabled="0" errors="0" time="*" timestamp="*">
+ <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"/>
@@ -56,11 +56,20 @@ EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?>
EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests">
- <testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyTwo">
+ <testsuite name="PropertyTwo" tests="1" failures="0" skipped="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testcase name="TestInt64ConvertibleProperties" file="gtest_xml_outfile2_test_.cc" line="43" status="run" result="completed" time="*" timestamp="*" classname="PropertyTwo">
<properties>
<property name="SetUpProp" value="2"/>
- <property name="TestSomeProperty" value="2"/>
+ <property name="TestFloatProperty" value="3.25"/>
+ <property name="TestDoubleProperty" value="4.75"/>
+ <property name="TestSizetProperty" value="5"/>
+ <property name="TestBoolProperty" value="true"/>
+ <property name="TestCharProperty" value="A"/>
+ <property name="TestInt16Property" value="6"/>
+ <property name="TestInt32Property" value="7"/>
+ <property name="TestInt64Property" value="8"/>
+ <property name="TestEnumProperty" value="9"/>
+ <property name="TestAtomicIntProperty" value="10"/>
<property name="TearDownProp" value="2"/>
</properties>
</testcase>
@@ -76,8 +85,9 @@ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):
# We want the trailing '/' that the last "" provides in os.path.join, for
# telling Google Test to create an output directory instead of a single file
# for xml output.
- self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(),
- GTEST_OUTPUT_SUBDIR, "")
+ self.output_dir_ = os.path.join(
+ gtest_test_utils.GetTempDir(), GTEST_OUTPUT_SUBDIR, ""
+ )
self.DeleteFilesAndDir()
def tearDown(self):
@@ -106,17 +116,20 @@ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):
def _TestOutFile(self, test_name, expected_xml):
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name)
command = [gtest_prog_path, "--gtest_output=xml:%s" % self.output_dir_]
- p = gtest_test_utils.Subprocess(command,
- working_dir=gtest_test_utils.GetTempDir())
- self.assert_(p.exited)
- self.assertEquals(0, p.exit_code)
+ p = gtest_test_utils.Subprocess(
+ command, working_dir=gtest_test_utils.GetTempDir()
+ )
+ self.assertTrue(p.exited)
+ self.assertEqual(0, p.exit_code)
output_file_name1 = test_name + ".xml"
output_file1 = os.path.join(self.output_dir_, output_file_name1)
- output_file_name2 = 'lt-' + output_file_name1
+ output_file_name2 = "lt-" + output_file_name1
output_file2 = os.path.join(self.output_dir_, output_file_name2)
- self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2),
- output_file1)
+ self.assertTrue(
+ os.path.isfile(output_file1) or os.path.isfile(output_file2),
+ output_file1,
+ )
expected = minidom.parseString(expected_xml)
if os.path.isfile(output_file1):
@@ -124,8 +137,7 @@ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):
else:
actual = minidom.parse(output_file2)
self.NormalizeXml(actual.documentElement)
- self.AssertEquivalentNodes(expected.documentElement,
- actual.documentElement)
+ self.AssertEquivalentNodes(expected.documentElement, actual.documentElement)
expected.unlink()
actual.unlink()
diff --git a/googletest/test/gtest_xml_output_unittest.py b/googletest/test/gtest_xml_output_unittest.py
index 63b1af0b6c10..422569e48398 100755
--- a/googletest/test/gtest_xml_output_unittest.py
+++ b/googletest/test/gtest_xml_output_unittest.py
@@ -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'
@@ -59,181 +59,215 @@ SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv
if SUPPORTS_STACK_TRACES:
STACK_TRACE_TEMPLATE = '\nStack trace:\n*'
+ STACK_TRACE_ENTITY_TEMPLATE = ''
else:
- STACK_TRACE_TEMPLATE = ''
+ STACK_TRACE_TEMPLATE = '\n'
+ STACK_TRACE_ENTITY_TEMPLATE = '&#x0A;'
# unittest.main() can't handle unknown flags
sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)
EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
-<testsuites tests="24" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
- <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
+<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" file="gtest_xml_output_unittest_.cc" line="53" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
</testsuite>
- <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="Fails" 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:*
+ <testsuite name="FailedTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="Fails" file="gtest_xml_output_unittest_.cc" line="61" 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%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Expected equality of these values:
1
2%(stack)s]]></failure>
</testcase>
</testsuite>
- <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*" timestamp="*">
- <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"/>
- <testcase name="Fails" 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:*
+ <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="88" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"/>
+ <testcase name="Fails" file="gtest_xml_output_unittest_.cc" line="93" 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%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Expected equality of these values:
1
2%(stack)s]]></failure>
- <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 2&#x0A; 3" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 2&#x0A; 3%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
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="98" status="notrun" result="suppressed" time="*" timestamp="*" classname="MixedResultTest"/>
</testsuite>
- <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="OutputsCData" 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:*
+ <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="OutputsCData" file="gtest_xml_output_unittest_.cc" line="102" 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;%(stack_entity)s" 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" errors="0" time="*" timestamp="*">
- <testcase name="InvalidCharactersInMessage" 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:*
+ <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="InvalidCharactersInMessage" file="gtest_xml_output_unittest_.cc" line="109" status="run" result="completed" time="*" timestamp="*" classname="InvalidCharactersTest">
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;Invalid characters in brackets []%(stack_entity)s" 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" errors="0" time="*" timestamp="*">
- <testcase name="DISABLED_test_not_run" status="notrun" result="suppressed" time="*" timestamp="*" classname="DisabledTest"/>
+ <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="DISABLED_test_not_run" file="gtest_xml_output_unittest_.cc" line="68" status="notrun" result="suppressed" time="*" timestamp="*" classname="DisabledTest"/>
</testsuite>
- <testsuite name="SkippedTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="Skipped" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest"/>
+ <testsuite name="SkippedTest" tests="3" failures="1" disabled="0" skipped="2" errors="0" time="*" timestamp="*">
+ <testcase name="Skipped" status="run" file="gtest_xml_output_unittest_.cc" line="75" result="skipped" time="*" timestamp="*" classname="SkippedTest">
+ <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;%(stack_entity)s"><![CDATA[gtest_xml_output_unittest_.cc:*
+%(stack)s]]></skipped>
+ </testcase>
+ <testcase name="SkippedWithMessage" file="gtest_xml_output_unittest_.cc" line="79" 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.%(stack_entity)s"><![CDATA[gtest_xml_output_unittest_.cc:*
+It is good practice to tell why you skip a test.%(stack)s]]></skipped>
+ </testcase>
+ <testcase name="SkippedAfterFailure" file="gtest_xml_output_unittest_.cc" line="83" 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%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+Expected equality of these values:
+ 1
+ 2%(stack)s]]></failure>
+ <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;It is good practice to tell why you skip a test.%(stack_entity)s"><![CDATA[gtest_xml_output_unittest_.cc:*
+It is good practice to tell why you skip a test.%(stack)s]]></skipped>
+ </testcase>
+
</testsuite>
- <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
- <testcase name="OneProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
+ <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
+ <testcase name="OneProperty" file="gtest_xml_output_unittest_.cc" line="121" 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="125" 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="129" 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="135" 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" errors="0" time="*" timestamp="*">
- <testcase name="RecordProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
+ <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="RecordProperty" file="gtest_xml_output_unittest_.cc" line="140" 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="153" 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="157" 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" 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" />
+ <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="HasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="164" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
+ <testcase name="HasValueParamAttribute/1" file="gtest_xml_output_unittest_.cc" line="164" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
+ <testcase name="AnotherTestThatHasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="165" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
+ <testcase name="AnotherTestThatHasValueParamAttribute/1" file="gtest_xml_output_unittest_.cc" line="165" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
</testsuite>
- <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" />
+ <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="173" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" />
</testsuite>
- <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" />
+ <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="173" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" />
</testsuite>
- <testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" />
+ <testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="180" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" />
</testsuite>
- <testsuite name="Single/TypeParameterizedTestSuite/1" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" />
+ <testsuite name="Single/TypeParameterizedTestSuite/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="180" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" />
</testsuite>
</testsuites>""" % {
- 'stack': STACK_TRACE_TEMPLATE
+ 'stack': STACK_TRACE_TEMPLATE,
+ 'stack_entity': STACK_TRACE_ENTITY_TEMPLATE,
}
EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*"
timestamp="*" name="AllTests" ad_hoc_property="42">
- <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0"
+ <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="53" 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" errors="0" time="*" timestamp="*">
- <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
+ <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="53" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
</testsuite>
- <testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
- <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
+ <testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
+ <testcase name="IntValuedProperty" file="gtest_xml_output_unittest_.cc" line="125" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<properties>
- <property name="key_1" value="2"/>
+ <property name="key_int" value="1"/>
</properties>
</testcase>
</testsuite>
- <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
+ <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="HasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="164" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
</testsuite>
</testsuites>"""
-EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
+EXPECTED_NO_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="0" failures="0" disabled="0" errors="0" time="*"
timestamp="*" name="AllTests">
-</testsuites>"""
+ <testsuite name="NonTestSuiteFailure" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="" status="run" result="completed" time="*" timestamp="*" classname="">
+ <failure message="gtest_no_test_unittest.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2%(stack_entity)s" type=""><![CDATA[gtest_no_test_unittest.cc:*
+Expected equality of these values:
+ 1
+ 2%(stack)s]]></failure>
+ </testcase>
+ </testsuite>
+</testsuites>""" % {
+ 'stack': STACK_TRACE_TEMPLATE,
+ 'stack_entity': STACK_TRACE_ENTITY_TEMPLATE,
+}
GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
-SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess(
- [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output
+SUPPORTS_TYPED_TESTS = (
+ 'TypedTest'
+ in gtest_test_utils.Subprocess(
+ [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False
+ ).output
+)
class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
- """
- Unit test for Google Test's XML output functionality.
- """
+ """Unit test for Google Test's XML output functionality."""
# This test currently breaks on platforms that do not support typed and
# type-parameterized tests, so we don't run it under them.
if SUPPORTS_TYPED_TESTS:
+
def testNonEmptyXmlOutput(self):
- """
+ """Generates non-empty XML and verifies it matches the expected output.
+
Runs a test program that generates a non-empty XML output, and
tests that the XML output is expected.
"""
self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1)
- def testEmptyXmlOutput(self):
+ def testNoTestXmlOutput(self):
"""Verifies XML output for a Google Test binary without actual tests.
- Runs a test program that generates an empty XML output, and
- tests that the XML output is expected.
+ Runs a test program that generates an XML output for a binary without tests,
+ and tests that the XML output is expected.
"""
- self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_EMPTY_XML, 0)
+ self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_NO_TEST_XML, 0)
def testTimestampValue(self):
"""Checks whether the timestamp attribute in the XML output is valid.
@@ -247,28 +281,34 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
# parse the expected datetime manually.
match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
self.assertTrue(
- re.match,
- 'XML datettime string %s has incorrect format' % date_time_str)
+ re.match, 'XML datettime string %s has incorrect format' % date_time_str
+ )
date_time_from_xml = datetime.datetime(
- year=int(match.group(1)), month=int(match.group(2)),
- day=int(match.group(3)), hour=int(match.group(4)),
- minute=int(match.group(5)), second=int(match.group(6)))
+ year=int(match.group(1)),
+ month=int(match.group(2)),
+ day=int(match.group(3)),
+ hour=int(match.group(4)),
+ minute=int(match.group(5)),
+ second=int(match.group(6)),
+ )
time_delta = abs(datetime.datetime.now() - date_time_from_xml)
# timestamp value should be near the current local time
- self.assertTrue(time_delta < datetime.timedelta(seconds=600),
- 'time_delta is %s' % time_delta)
+ self.assertLess(time_delta, datetime.timedelta(seconds=600))
actual.unlink()
def testDefaultOutputFile(self):
- """
+ """Tests XML file with default name is created when name is not specified.
+
Confirms that Google Test produces an XML output file with the expected
default name if no name is explicitly specified.
"""
- output_file = os.path.join(gtest_test_utils.GetTempDir(),
- GTEST_DEFAULT_OUTPUT_FILE)
+ output_file = os.path.join(
+ gtest_test_utils.GetTempDir(), GTEST_DEFAULT_OUTPUT_FILE
+ )
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
- 'gtest_no_test_unittest')
+ 'gtest_no_test_unittest'
+ )
try:
os.remove(output_file)
except OSError:
@@ -278,39 +318,47 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
p = gtest_test_utils.Subprocess(
[gtest_prog_path, '%s=xml' % GTEST_OUTPUT_FLAG],
- working_dir=gtest_test_utils.GetTempDir())
- self.assert_(p.exited)
- self.assertEquals(0, p.exit_code)
- self.assert_(os.path.isfile(output_file))
+ working_dir=gtest_test_utils.GetTempDir(),
+ )
+ self.assertTrue(p.exited)
+ self.assertEqual(0, p.exit_code)
+ self.assertTrue(os.path.isfile(output_file))
def testSuppressedXmlOutput(self):
- """
+ """Verifies XML output is suppressed if default listener is shut down.
+
Tests that no XML file is generated if the default XML listener is
shut down before RUN_ALL_TESTS is invoked.
"""
- xml_path = os.path.join(gtest_test_utils.GetTempDir(),
- GTEST_PROGRAM_NAME + 'out.xml')
+ xml_path = os.path.join(
+ gtest_test_utils.GetTempDir(), GTEST_PROGRAM_NAME + 'out.xml'
+ )
if os.path.isfile(xml_path):
os.remove(xml_path)
- command = [GTEST_PROGRAM_PATH,
- '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path),
- '--shut_down_xml']
+ command = [
+ GTEST_PROGRAM_PATH,
+ '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path),
+ '--shut_down_xml',
+ ]
p = gtest_test_utils.Subprocess(command)
if p.terminated_by_signal:
# p.signal is available only if p.terminated_by_signal is True.
self.assertFalse(
p.terminated_by_signal,
- '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal))
+ '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal),
+ )
else:
- self.assert_(p.exited)
- self.assertEquals(1, p.exit_code,
- "'%s' exited with code %s, which doesn't match "
- 'the expected exit code %s.'
- % (command, p.exit_code, 1))
+ self.assertTrue(p.exited)
+ self.assertEqual(
+ 1,
+ p.exit_code,
+ "'%s' exited with code %s, which doesn't match "
+ 'the expected exit code %s.' % (command, p.exit_code, 1),
+ )
- self.assert_(not os.path.isfile(xml_path))
+ self.assertFalse(os.path.isfile(xml_path))
def testFilteredTestXmlOutput(self):
"""Verifies XML output when a filter is applied.
@@ -319,8 +367,12 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
non-selected tests do not show up in the XML output.
"""
- self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0,
- extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])
+ self._TestXmlOutput(
+ GTEST_PROGRAM_NAME,
+ EXPECTED_FILTERED_TEST_XML,
+ 0,
+ extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG],
+ )
def testShardedTestXmlOutput(self):
"""Verifies XML output when run using multiple shards.
@@ -333,53 +385,81 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
GTEST_PROGRAM_NAME,
EXPECTED_SHARDED_TEST_XML,
0,
- extra_env={SHARD_INDEX_ENV_VAR: '0',
- TOTAL_SHARDS_ENV_VAR: '10'})
+ extra_env={SHARD_INDEX_ENV_VAR: '0', TOTAL_SHARDS_ENV_VAR: '10'},
+ )
+
+ def _GetXmlOutput(
+ self, gtest_prog_name, extra_args, extra_env, expected_exit_code
+ ):
+ """Returns the XML output generated by running the program gtest_prog_name.
- def _GetXmlOutput(self, gtest_prog_name, extra_args, extra_env,
- expected_exit_code):
- """
- Returns the xml output generated by running the program gtest_prog_name.
Furthermore, the program's exit code must be expected_exit_code.
+
+ Args:
+ gtest_prog_name: Program to run.
+ extra_args: Optional arguments to pass to program.
+ extra_env: Optional environment variables to set.
+ expected_exit_code: Expected exit code from running gtest_prog_name.
"""
- xml_path = os.path.join(gtest_test_utils.GetTempDir(),
- gtest_prog_name + 'out.xml')
+ xml_path = os.path.join(
+ gtest_test_utils.GetTempDir(), gtest_prog_name + 'out.xml'
+ )
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
- command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] +
- extra_args)
+ command = [
+ gtest_prog_path,
+ '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path),
+ ] + extra_args
environ_copy = os.environ.copy()
if extra_env:
environ_copy.update(extra_env)
p = gtest_test_utils.Subprocess(command, env=environ_copy)
if p.terminated_by_signal:
- self.assert_(False,
- '%s was killed by signal %d' % (gtest_prog_name, p.signal))
+ self.assertTrue(
+ False, '%s was killed by signal %d' % (gtest_prog_name, p.signal)
+ )
else:
- self.assert_(p.exited)
- self.assertEquals(expected_exit_code, p.exit_code,
- "'%s' exited with code %s, which doesn't match "
- 'the expected exit code %s.'
- % (command, p.exit_code, expected_exit_code))
+ self.assertTrue(p.exited)
+ self.assertEqual(
+ expected_exit_code,
+ p.exit_code,
+ "'%s' exited with code %s, which doesn't match "
+ 'the expected exit code %s.'
+ % (command, p.exit_code, expected_exit_code),
+ )
actual = minidom.parse(xml_path)
return actual
- def _TestXmlOutput(self, gtest_prog_name, expected_xml,
- expected_exit_code, extra_args=None, extra_env=None):
- """
+ def _TestXmlOutput(
+ self,
+ gtest_prog_name,
+ expected_xml,
+ expected_exit_code,
+ extra_args=None,
+ extra_env=None,
+ ):
+ """Asserts that the XML document matches.
+
Asserts that the XML document generated by running the program
gtest_prog_name matches expected_xml, a string containing another
XML document. Furthermore, the program's exit code must be
expected_exit_code.
+
+ Args:
+ gtest_prog_name: Program to run.
+ expected_xml: Path to XML document to match.
+ expected_exit_code: Expected exit code from running gtest_prog_name.
+ extra_args: Optional arguments to pass to program.
+ extra_env: Optional environment variables to set.
"""
- actual = self._GetXmlOutput(gtest_prog_name, extra_args or [],
- extra_env or {}, expected_exit_code)
+ actual = self._GetXmlOutput(
+ gtest_prog_name, extra_args or [], extra_env or {}, expected_exit_code
+ )
expected = minidom.parseString(expected_xml)
self.NormalizeXml(actual.documentElement)
- self.AssertEquivalentNodes(expected.documentElement,
- actual.documentElement)
+ self.AssertEquivalentNodes(expected.documentElement, actual.documentElement)
expected.unlink()
actual.unlink()
diff --git a/googletest/test/gtest_xml_output_unittest_.cc b/googletest/test/gtest_xml_output_unittest_.cc
index c95fd66cfaef..0ab33022e06a 100644
--- a/googletest/test/gtest_xml_output_unittest_.cc
+++ b/googletest/test/gtest_xml_output_unittest_.cc
@@ -35,18 +35,20 @@
//
// This program will be invoked from a Python unit test. Don't run it
// directly.
+// clang-format off
+
+#include <string>
#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.";
@@ -74,6 +76,15 @@ TEST_F(SkippedTest, Skipped) {
GTEST_SKIP();
}
+TEST_F(SkippedTest, SkippedWithMessage) {
+ GTEST_SKIP() << "It is good practice to tell why you skip a test.";
+}
+
+TEST_F(SkippedTest, SkippedAfterFailure) {
+ EXPECT_EQ(1, 2);
+ GTEST_SKIP() << "It is good practice to tell why you skip a test.";
+}
+
TEST(MixedResultTest, Succeeds) {
EXPECT_EQ(1, 1);
ASSERT_EQ(1, 1);
@@ -154,16 +165,13 @@ TEST_P(ValueParamTest, HasValueParamAttribute) {}
TEST_P(ValueParamTest, AnotherTestThatHasValueParamAttribute) {}
INSTANTIATE_TEST_SUITE_P(Single, ValueParamTest, Values(33, 42));
-#if GTEST_HAS_TYPED_TEST
// Verifies that the type parameter name is output in the 'type_param'
// XML attribute for typed tests.
template <typename T> class TypedTest : public Test {};
typedef testing::Types<int, long> TypedTestTypes;
TYPED_TEST_SUITE(TypedTest, TypedTestTypes);
TYPED_TEST(TypedTest, HasTypeParamAttribute) {}
-#endif
-#if GTEST_HAS_TYPED_TEST_P
// Verifies that the type parameter name is output in the 'type_param'
// XML attribute for type-parameterized tests.
template <typename T>
@@ -174,7 +182,6 @@ REGISTER_TYPED_TEST_SUITE_P(TypeParameterizedTestSuite, HasTypeParamAttribute);
typedef testing::Types<int, long> TypeParameterizedTestSuiteTypes; // NOLINT
INSTANTIATE_TYPED_TEST_SUITE_P(Single, TypeParameterizedTestSuite,
TypeParameterizedTestSuiteTypes);
-#endif
int main(int argc, char** argv) {
InitGoogleTest(&argc, argv);
@@ -186,3 +193,5 @@ int main(int argc, char** argv) {
testing::Test::RecordProperty("ad_hoc_property", "42");
return RUN_ALL_TESTS();
}
+
+// clang-format on
diff --git a/googletest/test/gtest_xml_test_utils.py b/googletest/test/gtest_xml_test_utils.py
index 9914a49ec188..74e0f4a0823b 100755
--- a/googletest/test/gtest_xml_test_utils.py
+++ b/googletest/test/gtest_xml_test_utils.py
@@ -31,18 +31,17 @@
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'
-class GTestXMLTestCase(gtest_test_utils.TestCase):
- """
- Base class for tests of Google Test's XML output functionality.
- """
+class GTestXMLTestCase(gtest_test_utils.TestCase):
+ """Base class for tests of Google Test's XML output functionality."""
def AssertEquivalentNodes(self, expected_node, actual_node):
- """
+ """Asserts that actual_node is equivalent to expected_node.
+
Asserts that actual_node (a DOM node object) is equivalent to
expected_node (another DOM node object), in that either both of
them are CDATA nodes and have the same value, or both are DOM
@@ -58,46 +57,66 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
CDATA sections) as expected_node. Note that we ignore the
order of the children as they are not guaranteed to be in any
particular order.
+
+ Args:
+ expected_node: expected DOM node object
+ actual_node: actual DOM node object
"""
if expected_node.nodeType == Node.CDATA_SECTION_NODE:
- self.assertEquals(Node.CDATA_SECTION_NODE, actual_node.nodeType)
- self.assertEquals(expected_node.nodeValue, actual_node.nodeValue)
+ self.assertEqual(Node.CDATA_SECTION_NODE, actual_node.nodeType)
+ self.assertEqual(expected_node.nodeValue, actual_node.nodeValue)
return
- self.assertEquals(Node.ELEMENT_NODE, actual_node.nodeType)
- self.assertEquals(Node.ELEMENT_NODE, expected_node.nodeType)
- self.assertEquals(expected_node.tagName, actual_node.tagName)
+ self.assertEqual(Node.ELEMENT_NODE, actual_node.nodeType)
+ self.assertEqual(Node.ELEMENT_NODE, expected_node.nodeType)
+ self.assertEqual(expected_node.tagName, actual_node.tagName)
expected_attributes = expected_node.attributes
- actual_attributes = actual_node .attributes
- self.assertEquals(
- expected_attributes.length, actual_attributes.length,
- 'attribute numbers differ in element %s:\nExpected: %r\nActual: %r' % (
- actual_node.tagName, expected_attributes.keys(),
- actual_attributes.keys()))
+ actual_attributes = actual_node.attributes
+ self.assertEqual(
+ expected_attributes.length,
+ actual_attributes.length,
+ 'attribute numbers differ in element %s:\nExpected: %r\nActual: %r'
+ % (
+ actual_node.tagName,
+ expected_attributes.keys(),
+ actual_attributes.keys(),
+ ),
+ )
for i in range(expected_attributes.length):
expected_attr = expected_attributes.item(i)
- actual_attr = actual_attributes.get(expected_attr.name)
- self.assert_(
+ actual_attr = actual_attributes.get(expected_attr.name)
+ self.assertTrue(
actual_attr is not None,
- 'expected attribute %s not found in element %s' %
- (expected_attr.name, actual_node.tagName))
- self.assertEquals(
- expected_attr.value, actual_attr.value,
- ' values of attribute %s in element %s differ: %s vs %s' %
- (expected_attr.name, actual_node.tagName,
- expected_attr.value, actual_attr.value))
+ 'expected attribute %s not found in element %s'
+ % (expected_attr.name, actual_node.tagName),
+ )
+ self.assertEqual(
+ expected_attr.value,
+ actual_attr.value,
+ ' values of attribute %s in element %s differ: %s vs %s'
+ % (
+ expected_attr.name,
+ actual_node.tagName,
+ expected_attr.value,
+ actual_attr.value,
+ ),
+ )
expected_children = self._GetChildren(expected_node)
actual_children = self._GetChildren(actual_node)
- self.assertEquals(
- len(expected_children), len(actual_children),
- 'number of child elements differ in element ' + actual_node.tagName)
+ self.assertEqual(
+ len(expected_children),
+ len(actual_children),
+ 'number of child elements differ in element ' + actual_node.tagName,
+ )
for child_id, child in expected_children.items():
- self.assert_(child_id in actual_children,
- '<%s> is not in <%s> (in element %s)' %
- (child_id, actual_children, actual_node.tagName))
+ self.assertTrue(
+ child_id in actual_children,
+ '<%s> is not in <%s> (in element %s)'
+ % (child_id, actual_children, actual_node.tagName),
+ )
self.AssertEquivalentNodes(child, actual_children[child_id])
identifying_attribute = {
@@ -105,44 +124,59 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
'testsuite': 'name',
'testcase': 'name',
'failure': 'message',
+ 'skipped': 'message',
'property': 'name',
}
def _GetChildren(self, element):
- """
- Fetches all of the child nodes of element, a DOM Element object.
- Returns them as the values of a dictionary keyed by the IDs of the
- children. For <testsuites>, <testsuite>, <testcase>, and <property>
- elements, the ID is the value of their "name" attribute; for <failure>
- elements, it is the value of the "message" attribute; for <properties>
- elements, it is the value of their parent's "name" attribute plus the
- literal string "properties"; CDATA sections and non-whitespace
- text nodes are concatenated into a single CDATA section with ID
- "detail". An exception is raised if any element other than the above
- four is encountered, if two child elements with the same identifying
- attributes are encountered, or if any other type of node is encountered.
+ """Fetches all of the child nodes of element, a DOM Element object.
+
+ Returns them as the values of a dictionary keyed by the IDs of the children.
+ For <testsuites>, <testsuite>, <testcase>, and <property> elements, the ID
+ is the value of their "name" attribute; for <failure> elements, it is the
+ value of the "message" attribute; for <properties> elements, it is the value
+ of their parent's "name" attribute plus the literal string "properties";
+ CDATA sections and non-whitespace text nodes are concatenated into a single
+ CDATA section with ID "detail". An exception is raised if any element other
+ than the above four is encountered, if two child elements with the same
+ identifying attributes are encountered, or if any other type of node is
+ encountered.
+
+ Args:
+ element: DOM Element object
+
+ Returns:
+ Dictionary where keys are the IDs of the children.
"""
children = {}
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
if child.tagName == 'properties':
- self.assert_(child.parentNode is not None,
- 'Encountered <properties> element without a parent')
+ self.assertTrue(
+ child.parentNode is not None,
+ 'Encountered <properties> element without a parent',
+ )
child_id = child.parentNode.getAttribute('name') + '-properties'
else:
- self.assert_(child.tagName in self.identifying_attribute,
- 'Encountered unknown element <%s>' % child.tagName)
+ self.assertTrue(
+ child.tagName in self.identifying_attribute,
+ 'Encountered unknown element <%s>' % child.tagName,
+ )
child_id = child.getAttribute(
- self.identifying_attribute[child.tagName])
- self.assert_(child_id not in children)
+ self.identifying_attribute[child.tagName]
+ )
+ self.assertNotIn(child_id, children)
children[child_id] = child
elif child.nodeType in [Node.TEXT_NODE, Node.CDATA_SECTION_NODE]:
if 'detail' not in children:
- if (child.nodeType == Node.CDATA_SECTION_NODE or
- not child.nodeValue.isspace()):
+ if (
+ child.nodeType == Node.CDATA_SECTION_NODE
+ or not child.nodeValue.isspace()
+ ):
children['detail'] = child.ownerDocument.createCDATASection(
- child.nodeValue)
+ child.nodeValue
+ )
else:
children['detail'].nodeValue += child.nodeValue
else:
@@ -150,7 +184,8 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
return children
def NormalizeXml(self, element):
- """
+ """Normalizes XML that may change from run to run.
+
Normalizes Google Test's XML output to eliminate references to transient
information that may change from run to run.
@@ -167,19 +202,29 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
file's basename and a single asterisk for the line number.
* The directory names in file paths are removed.
* The stack traces are removed.
+
+ Args:
+ element: DOM element to normalize
"""
+ 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$',
- '*', timestamp.value)
+ timestamp.value = re.sub(
+ r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d\d\d$', '*', timestamp.value
+ )
if element.tagName in ('testsuites', 'testsuite', 'testcase'):
time = element.getAttributeNode('time')
- time.value = re.sub(r'^\d+(\.\d+)?$', '*', time.value)
+ # The value for exact N seconds has a trailing decimal point (e.g., "10."
+ # instead of "10")
+ time.value = re.sub(r'^\d+\.(\d+)?$', '*', time.value)
type_param = element.getAttributeNode('type_param')
if type_param and type_param.value:
type_param.value = '*'
- elif element.tagName == 'failure':
+ elif element.tagName == 'failure' or element.tagName == 'skipped':
source_line_pat = r'^.*[/\\](.*:)\d+\n'
# Replaces the source line information with a normalized form.
message = element.getAttributeNode('message')
@@ -189,8 +234,9 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
# Replaces the source line information with a normalized form.
cdata = re.sub(source_line_pat, '\\1*\n', child.nodeValue)
# Removes the actual stack trace.
- child.nodeValue = re.sub(r'Stack trace:\n(.|\n)*',
- 'Stack trace:\n*', cdata)
+ child.nodeValue = re.sub(
+ r'Stack trace:\n(.|\n)*', 'Stack trace:\n*', cdata
+ )
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.NormalizeXml(child)
diff --git a/googletest/test/production.h b/googletest/test/production.h
index 542723b70873..4dec8d46e247 100644
--- a/googletest/test/production.h
+++ b/googletest/test/production.h
@@ -30,8 +30,8 @@
//
// This is part of the unit test for gtest_prod.h.
-#ifndef GTEST_TEST_PRODUCTION_H_
-#define GTEST_TEST_PRODUCTION_H_
+#ifndef GOOGLETEST_TEST_PRODUCTION_H_
+#define GOOGLETEST_TEST_PRODUCTION_H_
#include "gtest/gtest_prod.h"
@@ -46,9 +46,10 @@ class PrivateCode {
PrivateCode();
int x() const { return x_; }
+
private:
void set_x(int an_x) { x_ = an_x; }
int x_;
};
-#endif // GTEST_TEST_PRODUCTION_H_
+#endif // GOOGLETEST_TEST_PRODUCTION_H_
diff --git a/googletest_deps.bzl b/googletest_deps.bzl
new file mode 100644
index 000000000000..e25f5a1ada6d
--- /dev/null
+++ b/googletest_deps.bzl
@@ -0,0 +1,22 @@
+"""Load dependencies needed to use the googletest library as a 3rd-party consumer."""
+
+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
+
+def googletest_deps():
+ """Loads common dependencies needed to use the googletest library."""
+
+ if not native.existing_rule("com_googlesource_code_re2"):
+ http_archive(
+ name = "com_googlesource_code_re2", # 2023-03-17T11:36:51Z
+ sha256 = "cb8b5312a65f2598954545a76e8bce913f35fbb3a21a5c88797a4448e9f9b9d9",
+ strip_prefix = "re2-578843a516fd1da7084ae46209a75f3613b6065e",
+ urls = ["https://github.com/google/re2/archive/578843a516fd1da7084ae46209a75f3613b6065e.zip"],
+ )
+
+ if not native.existing_rule("com_google_absl"):
+ http_archive(
+ name = "com_google_absl", # 2023-08-01T14:59:13Z
+ sha256 = "d2c09bf3b3aba57ad87a56082020bee2948445407756e92ddaf3595396086853",
+ strip_prefix = "abseil-cpp-22091f4c0d6626b3ef40446ce3d4ccab19425ca3",
+ urls = ["https://github.com/abseil/abseil-cpp/archive/22091f4c0d6626b3ef40446ce3d4ccab19425ca3.zip"],
+ )
diff --git a/library.json b/library.json
deleted file mode 100644
index e46fcbdabced..000000000000
--- a/library.json
+++ /dev/null
@@ -1,59 +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.8.1",
- "frameworks": "arduino",
- "platforms": [
- "espressif32"
- ],
- "export": {
- "include": [
- "googlemock/include/*",
- "googlemock/src/*",
- "googletest/include/*",
- "googletest/src/*"
- ],
- "exclude": [
- "ci",
- "googlemock/build-aux",
- "googlemock/cmake",
- "googlemock/make",
- "googlemock/msvc",
- "googlemock/scripts",
- "googlemock/src/gmock-all.cc",
- "googlemock/src/gmock_main.cc",
- "googlemock/test",
- "googlemock/CMakeLists.txt",
- "googlemock/Makefile.am",
- "googlemock/configure.ac",
- "googletest/cmake",
- "googletest/codegear",
- "googletest/m4",
- "googletest/make",
- "googletest/msvc",
- "googletest/scripts",
- "googletest/src/gtest-all.cc",
- "googletest/src/gtest_main.cc",
- "googletest/test",
- "googletest/xcode",
- "googletest/CMakeLists.txt",
- "googletest/Makefile.am",
- "googletest/configure.ac"
- ]
- },
- "build": {
- "flags": [
- "-Igooglemock/include",
- "-Igooglemock",
- "-Igoogletest/include",
- "-Igoogletest"
- ]
- }
-}
diff --git a/platformio.ini b/platformio.ini
deleted file mode 100644
index 3910026be65f..000000000000
--- a/platformio.ini
+++ /dev/null
@@ -1,31 +0,0 @@
-; PlatformIO Project Configuration File
-;
-; Build options: build flags, source filter
-; Upload options: custom upload port, speed and extra flags
-; Library options: dependencies, extra library storages
-; Advanced options: extra scripting
-;
-; Please visit documentation for the other options and examples
-; http://docs.platformio.org/page/projectconf.html
-
-
-[platformio]
-#src_dir = ./googlemock
-#src_dir = ./googletest
-src_dir = .
-
-[env:googletest_esp32]
-platform = espressif32
-board = esp32dev
-framework = arduino
-build_flags = -I./googletest/include -I./googletest
-src_filter = +<*> -<.git/> -<googlemock> -<googletest/codegear/> -<googletest/samples> -<googletest/test/> -<googletest/xcode> -<googletest/src> +<googletest/src/gtest-all.cc> +<googletest/src/gtest_main.cc>
-upload_speed = 921600
-
-[env:googlemock_esp32]
-platform = espressif32
-board = esp32dev
-framework = arduino
-build_flags = -I./googlemock/include -I./googletest/include -I./googletest -I./googlemock
-src_filter = +<*> -<.git/> -<googletest> -<googlemock/test/> -<googlemock/src> +<googlemock/src/gmock-all.cc> +<googlemock/src/gmock_main.cc> +<googletest/src/gtest-all.cc>
-upload_speed = 921600