diff --git a/BUILD.bazel b/BUILD.bazel index 1df5ff5f..ac62251e 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -120,8 +120,14 @@ cc_library( linkopts = select({ ":qnx": ["-lregex"], ":windows": [], - ":freebsd": ["-lm", "-pthread"], - ":openbsd": ["-lm", "-pthread"], + ":freebsd": [ + "-lm", + "-pthread", + ], + ":openbsd": [ + "-lm", + "-pthread", + ], "//conditions:default": ["-pthread"], }), deps = select({ @@ -129,10 +135,15 @@ cc_library( "@com_google_absl//absl/debugging:failure_signal_handler", "@com_google_absl//absl/debugging:stacktrace", "@com_google_absl//absl/debugging:symbolize", + "@com_google_absl//absl/flags:flag", + "@com_google_absl//absl/flags:parse", + "@com_google_absl//absl/flags:reflection", + "@com_google_absl//absl/flags:usage", "@com_google_absl//absl/strings", "@com_google_absl//absl/types:any", "@com_google_absl//absl/types:optional", "@com_google_absl//absl/types:variant", + "@com_googlesource_code_re2//:re2", ], "//conditions:default": [], }), diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5bdead53..b3f50436 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,8 +21,8 @@ accept your pull requests. ## Are you a Googler? -If you are a Googler, please make an attempt to submit an internal change rather -than a GitHub Pull Request. If you are not able to submit an internal change a +If you are a Googler, please make an attempt to submit an internal contribution +rather than a GitHub Pull Request. If you are not able to submit internally, a PR is acceptable as an alternative. ## Contributing A Patch diff --git a/CONTRIBUTORS b/CONTRIBUTORS index d9bc587b..77397a5b 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -56,6 +56,7 @@ Russ Rufer Sean Mcafee Sigurður Ásgeirsson Sverre Sundsdal +Szymon Sobik Takeshi Yoshino Tracy Bialik Vadim Berman diff --git a/README.md b/README.md index 29e5a4ea..30edaecf 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,8 @@ GoogleTest now follows the [Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support). -We recommend using the latest commit in the `main` branch in your projects. +We recommend +[updating to the latest commit in the `main` branch as often as possible](https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-live-at-head-and-how-do-i-do-it). #### Documentation Updates @@ -121,11 +122,11 @@ result output. If your test runner understands TAP, you may find it useful. runs tests from your binary in parallel to provide significant speed-up. [GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter) -is a VS Code extension allowing to view GoogleTest in a tree view, and run/debug +is a VS Code extension allowing to view GoogleTest in a tree view and run/debug your tests. [C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS -Code extension allowing to view GoogleTest in a tree view, and run/debug your +Code extension allowing to view GoogleTest in a tree view and run/debug your tests. [Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser diff --git a/WORKSPACE b/WORKSPACE index 7eb18eb9..318b9088 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -4,9 +4,18 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "com_google_absl", - sha256 = "aeba534f7307e36fe084b452299e49b97420667a8d28102cf9a0daeed340b859", - strip_prefix = "abseil-cpp-7971fb358ae376e016d2d4fc9327aad95659b25e", - urls = ["https://github.com/abseil/abseil-cpp/archive/7971fb358ae376e016d2d4fc9327aad95659b25e.zip"], # 2021-05-20T02:59:16Z + sha256 = "f88c0030547281e8283ff183db61564ff08d3322a8c2e2de4c40e38c03c69aea", + strip_prefix = "abseil-cpp-c27ab06897f330267bed99061ed3e523e2606bf1", + urls = ["https://github.com/abseil/abseil-cpp/archive/c27ab06897f330267bed99061ed3e523e2606bf1.zip"], # 2022-04-18T19:51:27Z +) + +# Note this must use a commit from the `abseil` branch of the RE2 project. +# https://github.com/google/re2/tree/abseil +http_archive( + name = "com_googlesource_code_re2", + sha256 = "906d0df8ff48f8d3a00a808827f009a840190f404559f649cb8e4d7143255ef9", + strip_prefix = "re2-a276a8c738735a0fe45a6ee590fe2df69bcf4502", + urls = ["https://github.com/google/re2/archive/a276a8c738735a0fe45a6ee590fe2df69bcf4502.zip"], # 2022-04-08 ) http_archive( @@ -15,3 +24,16 @@ http_archive( strip_prefix = "rules_python-ed6cc8f2c3692a6a7f013ff8bc185ba77eb9b4d2", urls = ["https://github.com/bazelbuild/rules_python/archive/ed6cc8f2c3692a6a7f013ff8bc185ba77eb9b4d2.zip"], # 2021-05-17T00:24:16Z ) + +http_archive( + name = "bazel_skylib", + urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz"], + sha256 = "f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728", +) + +http_archive( + name = "platforms", + sha256 = "b601beaf841244de5c5a50d2b2eddd34839788000fa1be4260ce6603ca0d8eb7", + strip_prefix = "platforms-98939346da932eef0b54cf808622f5bb0928f00b", + urls = ["https://github.com/bazelbuild/platforms/archive/98939346da932eef0b54cf808622f5bb0928f00b.zip"], +) diff --git a/ci/linux-presubmit.sh b/ci/linux-presubmit.sh index 71471886..8d00bcaa 100644 --- a/ci/linux-presubmit.sh +++ b/ci/linux-presubmit.sh @@ -76,6 +76,7 @@ time docker run \ /usr/local/bin/bazel test ... \ --copt="-Wall" \ --copt="-Werror" \ + --copt="-Wuninitialized" \ --copt="-Wno-error=pragmas" \ --keep_going \ --show_timestamps \ @@ -94,6 +95,7 @@ for std in ${STD}; do /usr/local/bin/bazel test ... \ --copt="-Wall" \ --copt="-Werror" \ + --copt="-Wuninitialized" \ --define="absl=${absl}" \ --distdir="/bazel-distdir" \ --keep_going \ @@ -116,6 +118,7 @@ for std in ${STD}; do --copt="--gcc-toolchain=/usr/local" \ --copt="-Wall" \ --copt="-Werror" \ + --copt="-Wuninitialized" \ --define="absl=${absl}" \ --distdir="/bazel-distdir" \ --keep_going \ diff --git a/docs/advanced.md b/docs/advanced.md index f2f8854b..9a752b92 100644 --- a/docs/advanced.md +++ b/docs/advanced.md @@ -482,9 +482,11 @@ TEST_F(FooDeathTest, DoesThat) { ### Regular Expression Syntax -On POSIX systems (e.g. Linux, Cygwin, and Mac), googletest uses the +When built with Bazel and using Abseil, googletest uses the +[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX +systems (Linux, Cygwin, Mac), googletest uses the [POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) -syntax. To learn about this syntax, you may want to read this +syntax. To learn about POSIX syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). On Windows, googletest uses its own simple regular expression implementation. It @@ -839,7 +841,7 @@ will output XML like this: ```xml ... - + ... ``` @@ -1313,6 +1315,7 @@ First, define a fixture class template, as we did with typed tests: ```c++ template class FooTest : public testing::Test { + void DoSomethingInteresting(); ... }; ``` @@ -1330,6 +1333,9 @@ this as many times as you want: TYPED_TEST_P(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. TypeParam n = 0; + + // You will need to use `this` explicitly to refer to fixture members. + this->DoSomethingInteresting() ... } @@ -2082,15 +2088,15 @@ could generate this report: - + ... ... - + - + @@ -2108,6 +2114,9 @@ Things to note: * The `timestamp` attribute records the local date and time of the test execution. +* The `file` and `line` attributes record the source file location, where the + test was defined. + * Each `` element corresponds to a single failed googletest assertion. @@ -2147,6 +2156,8 @@ The report format conforms to the following JSON Schema: "type": "object", "properties": { "name": { "type": "string" }, + "file": { "type": "string" }, + "line": { "type": "integer" }, "status": { "type": "string", "enum": ["RUN", "NOTRUN"] @@ -2224,6 +2235,8 @@ message TestCase { message TestInfo { string name = 1; + string file = 6; + int32 line = 7; enum Status { RUN = 0; NOTRUN = 1; @@ -2267,6 +2280,8 @@ could generate this report: "testsuite": [ { "name": "Addition", + "file": "test.cpp", + "line": 1, "status": "RUN", "time": "0.007s", "classname": "", @@ -2283,6 +2298,8 @@ could generate this report: }, { "name": "Subtraction", + "file": "test.cpp", + "line": 2, "status": "RUN", "time": "0.005s", "classname": "" @@ -2298,6 +2315,8 @@ could generate this report: "testsuite": [ { "name": "NonContradiction", + "file": "test.cpp", + "line": 3, "status": "RUN", "time": "0.005s", "classname": "" diff --git a/docs/faq.md b/docs/faq.md index b2db186f..c849aff9 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -1,9 +1,9 @@ -# Googletest FAQ +# GoogleTest FAQ ## Why should test suite names and test names not contain underscore? {: .callout .note} -Note: Googletest reserves underscore (`_`) for special purpose keywords, such as +Note: GoogleTest reserves underscore (`_`) for special purpose keywords, such as [the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition to the following rationale. @@ -50,15 +50,15 @@ Now, the two `TEST`s will both generate the same class So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and `TestName`. The rule is more constraining than necessary, but it's simple and -easy to remember. It also gives googletest some wiggle room in case its +easy to remember. It also gives GoogleTest some wiggle room in case its implementation needs to change in the future. If you violate the rule, there may not be immediate consequences, but your test may (just may) break with a new compiler (or a new version of the compiler you -are using) or with a new version of googletest. Therefore it's best to follow +are using) or with a new version of GoogleTest. Therefore it's best to follow the rule. -## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`? +## Why does GoogleTest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`? First of all, you can use `nullptr` with each of these macros, e.g. `EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`, @@ -68,7 +68,7 @@ because `nullptr` does not have the type problems that `NULL` does. Due to some peculiarity of C++, it requires some non-trivial template meta programming tricks to support using `NULL` as an argument of the `EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where it's most needed -(otherwise we make the implementation of googletest harder to maintain and more +(otherwise we make the implementation of GoogleTest harder to maintain and more error-prone than necessary). Historically, the `EXPECT_EQ()` macro took the *expected* value as its first @@ -162,7 +162,7 @@ methods, the parent process will think the calls have never occurred. Therefore, you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH` macro. -## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug? +## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a GoogleTest bug? Actually, the bug is in `htonl()`. @@ -199,7 +199,7 @@ const int Foo::kBar; // No initializer here. ``` Otherwise your code is **invalid C++**, and may break in unexpected ways. In -particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will +particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc) will generate an "undefined reference" linker error. The fact that "it used to work" doesn't mean it's valid. It just means that you were lucky. :-) @@ -225,7 +225,7 @@ cases may want to use the same or slightly different fixtures. For example, you may want to make sure that all of a GUI library's test suites don't leak important system resources like fonts and brushes. -In googletest, you share a fixture among test suites by putting the shared logic +In GoogleTest, you share a fixture among test suites by putting the shared logic in a base test fixture, then deriving from that base a separate fixture for each test suite that wants to use this common logic. You then use `TEST_F()` to write tests using each derived fixture. @@ -264,7 +264,7 @@ TEST_F(FooTest, Baz) { ... } ``` If necessary, you can continue to derive test fixtures from a derived fixture. -googletest has no limit on how deep the hierarchy can be. +GoogleTest has no limit on how deep the hierarchy can be. For a complete example using derived test fixtures, see [sample5_unittest.cc](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc). @@ -278,7 +278,7 @@ disabled by our build system. Please see more details ## My death test hangs (or seg-faults). How do I fix it? -In googletest, death tests are run in a child process and the way they work is +In GoogleTest, death tests are run in a child process and the way they work is delicate. To write death tests you really need to understand how they work—see the details at [Death Assertions](reference/assertions.md#death) in the Assertions Reference. @@ -305,8 +305,8 @@ bullet - sorry! ## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp} -The first thing to remember is that googletest does **not** reuse the same test -fixture object across multiple tests. For each `TEST_F`, googletest will create +The first thing to remember is that GoogleTest does **not** reuse the same test +fixture object across multiple tests. For each `TEST_F`, GoogleTest will create a **fresh** test fixture object, immediately call `SetUp()`, run the test body, call `TearDown()`, and then delete the test fixture object. @@ -345,11 +345,11 @@ You may still want to use `SetUp()/TearDown()` in the following cases: that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions. -* The googletest team is considering making the assertion macros throw on +* The GoogleTest team is considering making the assertion macros throw on platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux client-side), which will eliminate the need for the user to propagate failures from a subroutine to its caller. Therefore, you shouldn't use - googletest assertions in a destructor if your code could run on such a + GoogleTest assertions in a destructor if your code could run on such a platform. ## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it? @@ -375,7 +375,7 @@ they write This is **wrong and dangerous**. The testing services needs to see the return value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()` function ignores it, your test will be considered successful even if it -has a googletest assertion failure. Very bad. +has a GoogleTest assertion failure. Very bad. We have decided to fix this (thanks to Michael Chastain for the idea). Now, your code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with @@ -440,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: @@ -520,7 +520,7 @@ TEST(MyDeathTest, CompoundStatement) { ## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why? -Googletest needs to be able to create objects of your test fixture class, so it +GoogleTest needs to be able to create objects of your test fixture class, so it must have a default constructor. Normally the compiler will define one for you. However, there are cases where you have to define your own: @@ -545,11 +545,11 @@ The new NPTL thread library doesn't suffer from this problem, as it doesn't create a manager thread. However, if you don't control which machine your test runs on, you shouldn't depend on this. -## Why does googletest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH? +## Why does GoogleTest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH? -googletest does not interleave tests from different test suites. That is, it +GoogleTest does not interleave tests from different test suites. That is, it runs all tests in one test suite first, and then runs all tests in the next test -suite, and so on. googletest does this because it needs to set up a test suite +suite, and so on. GoogleTest does this because it needs to set up a test suite before the first test in it is run, and tear it down afterwards. Splitting up the test case would require multiple set-up and tear-down processes, which is inefficient and makes the semantics unclean. @@ -588,11 +588,11 @@ TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } ``` -## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds? +## GoogleTest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds? Printing the LOG messages generated by the statement inside `EXPECT_DEATH()` makes it harder to search for real problems in the parent's log. Therefore, -googletest only prints them when the death test has failed. +GoogleTest only prints them when the death test has failed. If you really need to see such LOG messages, a workaround is to temporarily break the death test (e.g. by changing the regex pattern it is expected to @@ -611,7 +611,7 @@ needs to be defined in the *same* name space. See ## How do I suppress the memory leak messages on Windows? -Since the statically initialized googletest singleton requires allocations on +Since the statically initialized GoogleTest singleton requires allocations on the heap, the Visual C++ memory leak detector will report memory leaks at the end of the program run. The easiest way to avoid this is to use the `_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any @@ -625,7 +625,7 @@ things accordingly, you are leaking test-only logic into production code and there is no easy way to ensure that the test-only code paths aren't run by mistake in production. Such cleverness also leads to [Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly -advise against the practice, and googletest doesn't provide a way to do it. +advise against the practice, and GoogleTest doesn't provide a way to do it. In general, the recommended way to cause the code to behave differently under test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject @@ -672,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 index 3d164ad6..67d075dd 100644 --- a/docs/gmock_cheat_sheet.md +++ b/docs/gmock_cheat_sheet.md @@ -8,7 +8,7 @@ Given ```cpp class Foo { - ... + public: virtual ~Foo(); virtual int GetSize() const = 0; virtual string Describe(const char* name) = 0; @@ -23,7 +23,7 @@ class Foo { #include "gmock/gmock.h" class MockFoo : public Foo { - ... + public: MOCK_METHOD(int, GetSize, (), (const, override)); MOCK_METHOD(string, Describe, (const char* name), (override)); MOCK_METHOD(string, Describe, (int type), (override)); @@ -58,7 +58,7 @@ To mock ```cpp template class StackInterface { - ... + public: virtual ~StackInterface(); virtual int GetSize() const = 0; virtual void Push(const Elem& x) = 0; @@ -71,7 +71,7 @@ class StackInterface { ```cpp template class MockStack : public StackInterface { - ... + public: MOCK_METHOD(int, GetSize, (), (const, override)); MOCK_METHOD(void, Push, (const Elem& x), (override)); }; diff --git a/docs/gmock_cook_book.md b/docs/gmock_cook_book.md index 9494f122..b6abffae 100644 --- a/docs/gmock_cook_book.md +++ b/docs/gmock_cook_book.md @@ -1300,23 +1300,27 @@ What if you have a pointer to pointer? You guessed it - you can use nested `Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points to a number less than 3 (what a mouthful...). -### Testing a Certain Property of an Object +### Defining a Custom Matcher Class {#CustomMatcherClass} -Sometimes you want to specify that an object argument has a certain property, -but there is no existing matcher that does this. If you want good error -messages, you should [define a matcher](#NewMatchers). If you want to do it -quick and dirty, you could get away with writing an ordinary function. +Most matchers can be simply defined using [the MATCHER* macros](#NewMatchers), +which are terse and flexible, and produce good error messages. However, these +macros are not very explicit about the interfaces they create and are not always +suitable, especially for matchers that will be widely reused. -Let's say you have a mock function that takes an object of type `Foo`, which has -an `int bar()` method and an `int baz()` method, and you want to constrain that -the argument's `bar()` value plus its `baz()` value is a given number. Here's -how you can define a matcher to do it: +For more advanced cases, you may need to define your own matcher class. A custom +matcher allows you to test a specific invariant property of that object. Let's +take a look at how to do so. + +Imagine you have a mock function that takes an object of type `Foo`, which has +an `int bar()` method and an `int baz()` method. You want to constrain that the +argument's `bar()` value plus its `baz()` value is a given number. (This is an +invariant.) Here's how we can write and use a matcher class to do so: ```cpp -using ::testing::Matcher; - class BarPlusBazEqMatcher { public: + using is_gtest_matcher = void; + explicit BarPlusBazEqMatcher(int expected_sum) : expected_sum_(expected_sum) {} @@ -1325,23 +1329,24 @@ class BarPlusBazEqMatcher { return (foo.bar() + foo.baz()) == expected_sum_; } - void DescribeTo(std::ostream& os) const { - os << "bar() + baz() equals " << expected_sum_; + void DescribeTo(std::ostream* os) const { + *os << "bar() + baz() equals " << expected_sum_; } - void DescribeNegationTo(std::ostream& os) const { - os << "bar() + baz() does not equal " << expected_sum_; + void DescribeNegationTo(std::ostream* os) const { + *os << "bar() + baz() does not equal " << expected_sum_; } private: const int expected_sum_; }; -Matcher BarPlusBazEq(int expected_sum) { +::testing::Matcher BarPlusBazEq(int expected_sum) { return BarPlusBazEqMatcher(expected_sum); } ... - EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...; + Foo foo; + EXPECT_CALL(foo, BarPlusBazEq(5))...; ``` ### Matching Containers @@ -3807,22 +3812,19 @@ Cardinality EvenNumber() { .Times(EvenNumber()); ``` -### Writing New Actions Quickly {#QuickNewActions} +### Writing New Actions {#QuickNewActions} If the built-in actions don't work for you, you can easily define your own one. -Just define a functor class with a (possibly templated) call operator, matching -the signature of your action. +All you need is a call operator with a signature compatible with the mocked +function. So you can use a lambda: -```cpp -struct Increment { - template - T operator()(T* arg) { - return ++(*arg); - } -} +``` +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; }); +EXPECT_EQ(14, mock.AsStdFunction()(2)); ``` -The same approach works with stateful functors (or any callable, really): +Or a struct with a call operator (even a templated one): ``` struct MultiplyBy { @@ -3830,12 +3832,54 @@ struct MultiplyBy { T operator()(T arg) { return arg * multiplier; } int multiplier; -} +}; // Then use: // EXPECT_CALL(...).WillOnce(MultiplyBy{7}); ``` +It's also fine for the callable to take no arguments, ignoring the arguments +supplied to the mock function: + +``` +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([] { return 17; }); +EXPECT_EQ(17, mock.AsStdFunction()(0)); +``` + +When used with `WillOnce`, the callable can assume it will be called at most +once and is allowed to be a move-only type: + +``` +// An action that contains move-only types and has an &&-qualified operator, +// demanding in the type system that it be called at most once. This can be +// used with WillOnce, but the compiler will reject it if handed to +// WillRepeatedly. +struct MoveOnlyAction { + std::unique_ptr move_only_state; + std::unique_ptr operator()() && { return std::move(move_only_state); } +}; + +MockFunction()> mock; +EXPECT_CALL(mock, Call).WillOnce(MoveOnlyAction{std::make_unique(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` or +`Action. 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 diff --git a/docs/gmock_for_dummies.md b/docs/gmock_for_dummies.md index fa1296ee..b7264d35 100644 --- a/docs/gmock_for_dummies.md +++ b/docs/gmock_for_dummies.md @@ -190,12 +190,12 @@ 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?) -Generally, you should not define 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. +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. Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb diff --git a/docs/reference/matchers.md b/docs/reference/matchers.md index 0f57db47..9fb15927 100644 --- a/docs/reference/matchers.md +++ b/docs/reference/matchers.md @@ -8,9 +8,13 @@ A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or | `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. | | `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. | -{: .callout .note} -**Note:** Although equality matching via `EXPECT_THAT(actual_value, -expected_value)` is supported, prefer to make the comparison explicit via +{: .callout .warning} +**WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)` +is supported, however note that implicit conversions can cause surprising +results. For example, `EXPECT_THAT(some_bool, "some string")` will compile and +may pass unintentionally. + +**BEST PRACTICE:** Prefer to make the comparison explicit via `EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value, expected_value)`. diff --git a/docs/reference/mocking.md b/docs/reference/mocking.md index c29f7160..e414ffbd 100644 --- a/docs/reference/mocking.md +++ b/docs/reference/mocking.md @@ -248,7 +248,9 @@ EXPECT_CALL(my_mock, GetNumber()) .WillOnce(Return(3)); ``` -The `WillOnce` clause can be used any number of times on an expectation. +The `WillOnce` clause can be used any number of times on an expectation. Unlike +`WillRepeatedly`, the action fed to each `WillOnce` call will be called at most +once, so may be a move-only type and/or have an `&&`-qualified call operator. #### WillRepeatedly {#EXPECT_CALL.WillRepeatedly} diff --git a/docs/reference/testing.md b/docs/reference/testing.md index 554d6c95..dc479423 100644 --- a/docs/reference/testing.md +++ b/docs/reference/testing.md @@ -518,8 +518,8 @@ Logs a property for the current test, test suite, or entire invocation of the test program. Only the last value for a given key is logged. The key must be a valid XML attribute name, and cannot conflict with the ones -already used by GoogleTest (`name`, `status`, `time`, `classname`, `type_param`, -and `value_param`). +already used by GoogleTest (`name`, `file`, `line`, `status`, `time`, +`classname`, `type_param`, and `value_param`). `RecordProperty` is `public static` so it can be called from utility functions that are not members of the test fixture. diff --git a/googlemock/CMakeLists.txt b/googlemock/CMakeLists.txt index 3ab75a1b..5c1f0daf 100644 --- a/googlemock/CMakeLists.txt +++ b/googlemock/CMakeLists.txt @@ -151,7 +151,10 @@ if (gmock_build_tests) cxx_test(gmock_ex_test gmock_main) cxx_test(gmock-function-mocker_test gmock_main) cxx_test(gmock-internal-utils_test gmock_main) - cxx_test(gmock-matchers_test gmock_main) + cxx_test(gmock-matchers-arithmetic_test gmock_main) + cxx_test(gmock-matchers-comparisons_test gmock_main) + cxx_test(gmock-matchers-containers_test gmock_main) + cxx_test(gmock-matchers-misc_test gmock_main) cxx_test(gmock-more-actions_test gmock_main) cxx_test(gmock-nice-strict_test gmock_main) cxx_test(gmock-port_test gmock_main) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index 70c325a4..c785ad8a 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -131,7 +131,7 @@ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #ifndef _WIN32_WCE -# include +#include #endif #include @@ -147,8 +147,8 @@ #include "gmock/internal/gmock-pp.h" #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #endif namespace testing { @@ -196,9 +196,7 @@ class BuiltInDefaultValue { public: // This function returns true if and only if type T has a built-in default // value. - static bool Exists() { - return ::std::is_default_constructible::value; - } + static bool Exists() { return ::std::is_default_constructible::value; } static T Get() { return BuiltInDefaultValueGetter< @@ -227,11 +225,11 @@ class BuiltInDefaultValue { // 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 { \ - public: \ - static bool Exists() { return true; } \ - static type Get() { return value; } \ + template <> \ + class BuiltInDefaultValue { \ + public: \ + static bool Exists() { return true; } \ + static type Get() { return value; } \ } GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT @@ -255,21 +253,309 @@ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ -// Simple two-arg form of std::disjunction. -template -using disjunction = typename ::std::conditional::type; +// Partial implementations of metaprogramming types from the standard library +// not available in C++11. + +template +struct negation + // NOLINTNEXTLINE + : std::integral_constant {}; + +// Base case: with zero predicates the answer is always true. +template +struct conjunction : std::true_type {}; + +// With a single predicate, the answer is that predicate. +template +struct conjunction : P1 {}; + +// With multiple predicates the answer is the first predicate if that is false, +// and we recurse otherwise. +template +struct conjunction + : std::conditional, P1>::type {}; + +template +struct disjunction : std::false_type {}; + +template +struct disjunction : P1 {}; + +template +struct disjunction + // NOLINTNEXTLINE + : std::conditional, P1>::type {}; + +template +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(); +// } +// +// In particular, is_convertible doesn't give the correct answer when `To` and +// `From` are the same non-moveable type since `declval` will be an rvalue +// reference, defeating the guaranteed copy elision that would otherwise make +// this function work. +// +// REQUIRES: `From` is not cv void. +template +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 + static void Accept(T); + + // A function that creates a value of type T. + template + static T Make(); + + // An overload be selected when implicit conversion from T to To is possible. + template (Make()))> + static std::true_type TestImplicitConversion(int); + + // A fallback overload selected in all other cases. + template + static std::false_type TestImplicitConversion(...); + + public: + using type = decltype(TestImplicitConversion(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 +using call_result_t = decltype(std::declval()(std::declval()...)); + +template +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 +struct is_callable_r_impl>, R, F, Args...> + : std::conditional< + std::is_void::value, // + std::true_type, // + is_implicitly_convertible, 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 +using is_callable_r = is_callable_r_impl; + +// Like std::as_const from C++17. +template +typename std::add_const::type& as_const(T& t) { + return t; +} } // namespace internal +// Specialized for function types below. +template +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); +// +// // 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; +// +// void operator()() && { +// AcceptUniquePointer(std::move(Foo)); +// } +// }; +// +// // This action can be used with WillOnce. +// EXPECT_CALL(mock, Call) +// .WillOnce(ProvideFoo{std::make_unique(...)}); +// +// // 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(...)}); +// +// 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 +class OnceAction final { + private: + // True iff we can use the given callable type (or lvalue reference) directly + // via StdFunctionAdaptor. + template + using IsDirectlyCompatible = internal::conjunction< + // It must be possible to capture the callable in StdFunctionAdaptor. + std::is_constructible::type, Callable>, + // The callable must be compatible with our signature. + internal::is_callable_r::type, + Args...>>; + + // True iff we can use the given callable type via StdFunctionAdaptor once we + // ignore incoming arguments. + template + using IsCompatibleAfterIgnoringArguments = internal::conjunction< + // It must be possible to capture the callable in a lambda. + std::is_constructible::type, Callable>, + // The callable must be invocable with zero arguments, returning something + // convertible to Result. + internal::is_callable_r::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 ::type>>, + IsDirectlyCompatible> // + ::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + : function_(StdFunctionAdaptor::type>( + {}, std::forward(callable))) {} + + // As above, but for a callable that ignores the mocked function's arguments. + template ::type>>, + // Exclude callables for which the overload above works. + // We'd rather provide the arguments if possible. + internal::negation>, + IsCompatibleAfterIgnoringArguments>::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + // Call the constructor above with a callable + // that ignores the input arguments. + : OnceAction(IgnoreIncomingArguments::type>{ + std::forward(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)...); + } + + 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 + 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 + explicit StdFunctionAdaptor(CallableTag, F&& callable) + : callable_(std::make_shared(std::forward(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. 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 + internal::call_result_t operator()( + ArgRefs&&... args) const { + return std::move(*callable_)(std::forward(args)...); + } + + private: + // We must put the callable on the heap so that we are copyable, which + // std::function needs. + std::shared_ptr callable_; + }; + + // An adaptor that makes a callable that accepts zero arguments callable with + // our mocked arguments. + template + struct IgnoreIncomingArguments { + internal::call_result_t operator()(Args&&...) { + return std::move(callable)(); + } + + Callable callable; + }; + + std::function function_; +}; + // When an unexpected function call is encountered, Google Mock will // let it return a default value if the user has specified one for its // return type, or if the return type has a built-in default value; @@ -339,7 +625,8 @@ class DefaultValue { private: const T value_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer); + FixedValueProducer(const FixedValueProducer&) = delete; + FixedValueProducer& operator=(const FixedValueProducer&) = delete; }; class FactoryValueProducer : public ValueProducer { @@ -350,7 +637,8 @@ class DefaultValue { private: const FactoryFunction factory_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer); + FactoryValueProducer(const FactoryValueProducer&) = delete; + FactoryValueProducer& operator=(const FactoryValueProducer&) = delete; }; static ValueProducer* producer_; @@ -424,28 +712,34 @@ class ActionInterface { virtual Result Perform(const ArgumentTuple& args) = 0; private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface); + ActionInterface(const ActionInterface&) = delete; + ActionInterface& operator=(const ActionInterface&) = delete; }; -// An Action 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 is just a -// std::shared_ptr to const ActionInterface. Don't inherit from Action! -// You can view an object implementing ActionInterface as a -// concrete action (including its current state), and an Action -// object as a handle to it. template -class Action { +class Action; + +// An Action 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 is just a +// std::shared_ptr to const ActionInterface. Don't inherit from Action! You +// can view an object implementing ActionInterface as a concrete action +// (including its current state), and an Action object as a handle to it. +template +class Action { + 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> impl_; - template - typename internal::Function::Result operator()(Args&&... args) { + template + typename internal::Function::Result operator()(InArgs&&... args) { return impl_->Perform( - ::std::forward_as_tuple(::std::forward(args)...)); + ::std::forward_as_tuple(::std::forward(args)...)); } }; @@ -480,7 +774,8 @@ class Action { // Action, 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 - explicit Action(const Action& action) : fun_(action.fun_) {} + Action(const Action& action) // NOLINT + : fun_(action.fun_) {} // Returns true if and only if this is the DoDefault() action. bool IsDoDefault() const { return fun_ == nullptr; } @@ -498,6 +793,24 @@ class Action { return internal::Apply(fun_, ::std::move(args)); } + // An action can be used as a OnceAction, since it's obviously safe to call it + // once. + operator OnceAction() 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 action; + + R operator()(Args... args) && { + return action.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{*this}; + } + private: template friend class Action; @@ -514,8 +827,8 @@ class Action { template struct IgnoreArgs { - template - Result operator()(const Args&...) const { + template + Result operator()(const InArgs&...) const { return function_impl(); } @@ -606,118 +919,198 @@ struct ByMoveWrapper { T payload; }; -// Implements the polymorphic Return(x) action, which can be used in -// any function that returns the type of x, regardless of the argument -// types. -// -// Note: The value passed into Return must be converted into -// Function::Result when this action is cast to Action 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 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 -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)) {} - // This template type conversion operator allows Return(x) to be - // used in ANY function that returns x's type. - template - operator Action() 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::Result Result; - GTEST_COMPILE_ASSERT_( - !std::is_reference::value, - use_ReturnRef_instead_of_Return_to_return_a_reference); - static_assert(!std::is_void::value, - "Can't use Return() on an action expected to return `void`."); - return Action(new Impl(value_)); + template >, // + negation>, // + std::is_convertible, // + std::is_move_constructible>::value>::type> + operator OnceAction() && { // NOLINT + return Impl(std::move(value_)); + } + + template >, // + negation>, // + std::is_convertible, // + std::is_copy_constructible>::value>::type> + operator Action() const { // NOLINT + return Impl(value_); } private: - // Implements the Return(x) action for a particular function type F. - template - class Impl : public ActionInterface { + // Implements the Return(x) action for a mock function that returns type U. + template + class Impl final { public: - typedef typename Function::Result Result; - typedef typename Function::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) 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& value) - : value_before_cast_(*value), - value_(ImplicitCast_(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::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_; + // 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_(internal::as_const(input_value))) {} - GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); + // 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_(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 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::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& mock, + // const std::vector& 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 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()> mock; + // + // // Return the same vector twice, and then the empty vector + // // thereafter. + // auto action = Return(std::initializer_list{ + // "taco", "burrito", + // }); + // + // EXPECT_CALL(mock, Call) + // .WillOnce(action) + // .WillOnce(action) + // .WillRepeatedly(Return(std::vector{})); + // + // 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_; }; - // Partially specialize for ByMoveWrapper. This version of ReturnAction will - // move its contents instead. - template - class Impl, F> : public ActionInterface { - public: - typedef typename Function::Result Result; - typedef typename Function::ArgumentTuple ArgumentTuple; + R value_; +}; - explicit Impl(const std::shared_ptr& wrapper) - : performed_(false), wrapper_(wrapper) {} +// A specialization of ReturnAction when R is ByMoveWrapper 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 +class ReturnAction> final { + public: + explicit ReturnAction(ByMoveWrapper 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 wrapper_; + state_->called = true; + return std::move(state_->value); + } + + private: + // We store our state on the heap so that we are copyable as required by + // Action, despite the fact that we are stateful and T may not be copyable. + struct State { + explicit State(T&& value_in) : value(std::move(value_in)) {} + + T value; + bool called = false; }; - const std::shared_ptr value_; + const std::shared_ptr state_; }; // Implements the ReturnNull() action. @@ -759,8 +1152,8 @@ class ReturnRefAction { // Asserts that the function return type is a reference. This // catches the user error of using ReturnRef(x) when Return(x) // should be used, and generates some helpful error message. - GTEST_COMPILE_ASSERT_(std::is_reference::value, - use_Return_instead_of_ReturnRef_to_return_a_value); + static_assert(std::is_reference::value, + "use Return instead of ReturnRef to return a value"); return Action(new Impl(ref_)); } @@ -801,9 +1194,8 @@ class ReturnRefOfCopyAction { // Asserts that the function return type is a reference. This // catches the user error of using ReturnRefOfCopy(x) when Return(x) // should be used, and generates some helpful error message. - GTEST_COMPILE_ASSERT_( - std::is_reference::value, - use_Return_instead_of_ReturnRefOfCopy_to_return_a_value); + static_assert(std::is_reference::value, + "use Return instead of ReturnRefOfCopy to return a value"); return Action(new Impl(value_)); } @@ -839,7 +1231,7 @@ class ReturnRoundRobinAction { template T operator()(Args&&...) const { - return state_->Next(); + return state_->Next(); } private: @@ -862,7 +1254,9 @@ class DoDefaultAction { // This template type conversion operator allows DoDefault() to be // used in any function. template - operator Action() const { return Action(); } // NOLINT + operator Action() const { + return Action(); + } // NOLINT }; // Implements the Assign action to set a given pointer referent to a @@ -890,8 +1284,7 @@ template class SetErrnoAndReturnAction { public: SetErrnoAndReturnAction(int errno_value, T result) - : errno_(errno_value), - result_(result) {} + : errno_(errno_value), result_(result) {} template Result Perform(const ArgumentTuple& /* args */) const { errno = errno_; @@ -1002,8 +1395,8 @@ class IgnoreResultAction { private: // Type OriginalFunction is the same as F except that its return // type is IgnoredValue. - typedef typename internal::Function::MakeResultIgnoredValue - OriginalFunction; + typedef + typename internal::Function::MakeResultIgnoredValue OriginalFunction; const Action action_; }; @@ -1013,55 +1406,239 @@ class IgnoreResultAction { template struct WithArgsAction { - InnerAction action; + InnerAction inner_action; - // The inner action could be anything convertible to Action. - // 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 - operator Action() const { // NOLINT - using TupleType = std::tuple; - Action::type...)> - converted(action); + using InnerSignature = + R(typename std::tuple_element>::type...); - return [converted](Args... args) -> R { + // 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 >::type...)>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + struct OA { + OnceAction> inner_action; + + R operator()(Args&&... args) && { + return std::move(inner_action) + .Call(std::get( + std::forward_as_tuple(std::forward(args)...))...); + } + }; + + return OA{std::move(inner_action)}; + } + + template >::type...)>>::value, + int>::type = 0> + operator Action() const { // NOLINT + Action> converted(inner_action); + + return [converted](Args&&... args) -> R { return converted.Perform(std::forward_as_tuple( - std::get(std::forward_as_tuple(std::forward(args)...))...)); + std::get(std::forward_as_tuple(std::forward(args)...))...)); }; } }; template -struct DoAllAction { - private: +class DoAllAction; + +// Base case: only a single action. +template +class DoAllAction { + public: + struct UserConstructorTag {}; + template - using NonFinalType = + explicit DoAllAction(UserConstructorTag, T&& action) + : final_action_(std::forward(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 >::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + return std::move(final_action_); + } + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>::value, + int>::type = 0> + operator Action() 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 +class DoAllAction + : private DoAllAction { + private: + using Base = DoAllAction; + + // 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. 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 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 + // ------- ----------------------- + // 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 + using InitialActionArgType = typename std::conditional::value, T, const T&>::type; - template - std::vector Convert(IndexSequence) const { - return {ActionT(std::get(actions))...}; - } - public: - std::tuple actions; + struct UserConstructorTag {}; - template - operator Action() const { // NOLINT - struct Op { - std::vector...)>> converted; - Action last; - R operator()(Args... args) const { - auto tuple_args = std::forward_as_tuple(std::forward(args)...); - for (auto& a : converted) { - a.Perform(tuple_args); - } - return last.Perform(std::move(tuple_args)); + template + explicit DoAllAction(UserConstructorTag, T&& initial_action, + U&&... other_actions) + : Base({}, std::forward(other_actions)...), + initial_action_(std::forward(initial_action)) {} + + template ...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator OnceAction() && { // 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...)> initial_action; + OnceAction remaining_actions; + + R operator()(Args... args) && { + std::move(initial_action) + .Call(static_cast>(args)...); + + return std::move(remaining_actions).Call(std::forward(args)...); } }; - return Op{Convert...)>>( - MakeIndexSequence()), - std::get(actions)}; + + return OA{ + std::move(initial_action_), + std::move(static_cast(*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...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator Action() const { // 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 { + Action...)> initial_action; + Action remaining_actions; + + R operator()(Args... args) const { + initial_action.Perform(std::forward_as_tuple( + static_cast>(args)...)); + + return remaining_actions.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{ + initial_action_, + static_cast(*this), + }; + } + + private: + InitialAction initial_action_; }; template @@ -1078,7 +1655,8 @@ struct ReturnNewAction { template struct ReturnArgAction { - template + template ::type> auto operator()(Args&&... args) const -> decltype(std::get( std::forward_as_tuple(std::forward(args)...))) { return std::get(std::forward_as_tuple(std::forward(args)...)); @@ -1203,7 +1781,8 @@ typedef internal::IgnoredValue Unused; template internal::DoAllAction::type...> DoAll( Action&&... action) { - return {std::forward_as_tuple(std::forward(action)...)}; + return internal::DoAllAction::type...>( + {}, std::forward(action)...); } // WithArg(an_action) creates an action that passes the k-th @@ -1212,8 +1791,8 @@ internal::DoAllAction::type...> DoAll( // multiple arguments. For convenience, we also provide // WithArgs(an_action) (defined below) as a synonym. template -internal::WithArgsAction::type, k> -WithArg(InnerAction&& action) { +internal::WithArgsAction::type, k> WithArg( + InnerAction&& action) { return {std::forward(action)}; } @@ -1232,14 +1811,35 @@ WithArgs(InnerAction&& action) { // argument. In other words, it adapts an action accepting no // argument to one that accepts (and ignores) arguments. template -internal::WithArgsAction::type> -WithoutArgs(InnerAction&& action) { +internal::WithArgsAction::type> WithoutArgs( + InnerAction&& action) { return {std::forward(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 mock; +// EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco"))); +// const std::string_view result = mock.AsStdFunction()(); +// EXPECT_EQ("taco", result); +// template internal::ReturnAction Return(R value) { return internal::ReturnAction(std::move(value)); @@ -1273,6 +1873,8 @@ inline internal::ReturnRefOfCopyAction ReturnRefOfCopy(const R& x) { return internal::ReturnRefOfCopyAction(x); } +// DEPRECATED: use Return(x) directly with WillOnce. +// // Modifies the parent action (a Return() action) to perform a move of the // argument instead of a copy. // Return(ByMove()) actions can only be executed once and will assert this @@ -1319,7 +1921,7 @@ internal::SetArgumentPointeeAction SetArgumentPointee(T value) { // Creates an action that sets a pointer referent to a given value. template -PolymorphicAction > Assign(T1* ptr, T2 val) { +PolymorphicAction> Assign(T1* ptr, T2 val) { return MakePolymorphicAction(internal::AssignAction(ptr, val)); } @@ -1327,8 +1929,8 @@ PolymorphicAction > Assign(T1* ptr, T2 val) { // Creates an action that sets errno and returns the appropriate error. template -PolymorphicAction > -SetErrnoAndReturn(int errval, T result) { +PolymorphicAction> SetErrnoAndReturn( + int errval, T result) { return MakePolymorphicAction( internal::SetErrnoAndReturnAction(errval, result)); } @@ -1482,7 +2084,8 @@ struct ExcessiveArg {}; // Builds an implementation of an Action<> for some particular signature, using // a class defined by an ACTION* macro. -template struct ActionImpl; +template +struct ActionImpl; template struct ImplBase { @@ -1502,7 +2105,7 @@ struct ActionImpl : ImplBase::type { using args_type = std::tuple; ActionImpl() = default; // Only defined if appropriate for Base. - explicit ActionImpl(std::shared_ptr impl) : Base{std::move(impl)} { } + explicit ActionImpl(std::shared_ptr impl) : Base{std::move(impl)} {} R operator()(Args&&... arg) const { static constexpr size_t kMaxArgs = @@ -1521,12 +2124,14 @@ struct ActionImpl : ImplBase::type { // args_type get passed, followed by a dummy of unspecified type for the // remainder up to 10 explicit args. static constexpr ExcessiveArg kExcessArg{}; - return static_cast(*this).template gmock_PerformImpl< - /*function_type=*/function_type, /*return_type=*/R, - /*args_type=*/args_type, - /*argN_type=*/typename std::tuple_element::type...>( - /*args=*/args, std::get(args)..., - ((void)excess_id, kExcessArg)...); + return static_cast(*this) + .template gmock_PerformImpl< + /*function_type=*/function_type, /*return_type=*/R, + /*args_type=*/args_type, + /*argN_type=*/ + typename std::tuple_element::type...>( + /*args=*/args, std::get(args)..., + ((void)excess_id, kExcessArg)...); } }; @@ -1545,7 +2150,7 @@ template #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_ -#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \ GMOCK_INTERNAL_ARG_UNUSED, , 10) @@ -1584,42 +2189,47 @@ template #define GMOCK_ACTION_FIELD_PARAMS_(params) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params) -#define GMOCK_INTERNAL_ACTION(name, full_name, params) \ - template \ - class full_name { \ - public: \ - explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ - : impl_(std::make_shared( \ - GMOCK_ACTION_GVALUE_PARAMS_(params))) { } \ - full_name(const full_name&) = default; \ - full_name(full_name&&) noexcept = default; \ - template \ - operator ::testing::Action() const { \ - return ::testing::internal::MakeAction(impl_); \ - } \ - private: \ - class gmock_Impl { \ - public: \ - explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ - : GMOCK_ACTION_INIT_PARAMS_(params) {} \ - template \ - return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ - GMOCK_ACTION_FIELD_PARAMS_(params) \ - }; \ - std::shared_ptr impl_; \ - }; \ - template \ - inline full_name name( \ - GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ - return full_name( \ - GMOCK_ACTION_GVALUE_PARAMS_(params)); \ - } \ - template \ - template \ - return_type full_name::gmock_Impl:: \ - gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const +#define GMOCK_INTERNAL_ACTION(name, full_name, params) \ + template \ + class full_name { \ + public: \ + explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : impl_(std::make_shared( \ + GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \ + full_name(const full_name&) = default; \ + full_name(full_name&&) noexcept = default; \ + template \ + operator ::testing::Action() const { \ + return ::testing::internal::MakeAction(impl_); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : GMOCK_ACTION_INIT_PARAMS_(params) {} \ + template \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + GMOCK_ACTION_FIELD_PARAMS_(params) \ + }; \ + std::shared_ptr impl_; \ + }; \ + template \ + inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \ + template \ + inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ + return full_name( \ + GMOCK_ACTION_GVALUE_PARAMS_(params)); \ + } \ + template \ + template \ + return_type \ + full_name::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const } // namespace internal @@ -1627,12 +2237,13 @@ template #define ACTION(name) \ class name##Action { \ public: \ - explicit name##Action() noexcept {} \ - name##Action(const name##Action&) noexcept {} \ + explicit name##Action() noexcept {} \ + name##Action(const name##Action&) noexcept {} \ template \ operator ::testing::Action() const { \ return ::testing::internal::MakeAction(); \ } \ + \ private: \ class gmock_Impl { \ public: \ @@ -1681,7 +2292,7 @@ template } // namespace testing #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/googlemock/include/gmock/gmock-cardinalities.h b/googlemock/include/gmock/gmock-cardinalities.h index 48196dd2..b6ab648e 100644 --- a/googlemock/include/gmock/gmock-cardinalities.h +++ b/googlemock/include/gmock/gmock-cardinalities.h @@ -40,8 +40,10 @@ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #include + #include #include // NOLINT + #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" @@ -116,7 +118,7 @@ class GTEST_API_ Cardinality { // cardinality, i.e. exceed the maximum number of allowed calls. bool IsOverSaturatedByCallCount(int call_count) const { return impl_->IsSaturatedByCallCount(call_count) && - !impl_->IsSatisfiedByCallCount(call_count); + !impl_->IsSatisfiedByCallCount(call_count); } // Describes self to an ostream diff --git a/googlemock/include/gmock/gmock-function-mocker.h b/googlemock/include/gmock/gmock-function-mocker.h index 2de1d41b..f565d980 100644 --- a/googlemock/include/gmock/gmock-function-mocker.h +++ b/googlemock/include/gmock/gmock-function-mocker.h @@ -201,7 +201,7 @@ using internal::FunctionMocker; GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ } \ mutable ::testing::FunctionMocker \ - GMOCK_MOCKER_(_N, _Constness, _MethodName) + GMOCK_MOCKER_(_N, _Constness, _MethodName) #define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 95845864..62829011 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -313,7 +313,9 @@ class StringMatchResultListener : public MatchResultListener { private: ::std::stringstream ss_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener); + StringMatchResultListener(const StringMatchResultListener&) = delete; + StringMatchResultListener& operator=(const StringMatchResultListener&) = + delete; }; // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION @@ -533,19 +535,18 @@ inline Matcher SafeMatcherCast(const Matcher& matcher) { "T must be implicitly convertible to U"); // Enforce that we are not converting a non-reference type T to a reference // type U. - GTEST_COMPILE_ASSERT_( - std::is_reference::value || !std::is_reference::value, - cannot_convert_non_reference_arg_to_reference); + static_assert(std::is_reference::value || !std::is_reference::value, + "cannot convert non reference arg to reference"); // In case both T and U are arithmetic types, enforce that the // conversion is not lossy. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU; constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther; constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther; - GTEST_COMPILE_ASSERT_( + static_assert( kTIsOther || kUIsOther || (internal::LosslessArithmeticConvertible::value), - conversion_of_arithmetic_types_must_be_lossless); + "conversion of arithmetic types must be lossless"); return MatcherCast(matcher); } @@ -678,9 +679,9 @@ bool TupleMatches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { // Makes sure that matcher_tuple and value_tuple have the same // number of fields. - GTEST_COMPILE_ASSERT_(std::tuple_size::value == - std::tuple_size::value, - matcher_and_value_have_different_numbers_of_fields); + static_assert(std::tuple_size::value == + std::tuple_size::value, + "matcher and value have different numbers of fields"); return TuplePrefix::value>::Matches(matcher_tuple, value_tuple); } @@ -2258,7 +2259,11 @@ class ResultOfMatcher { } 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 @@ -2552,7 +2557,8 @@ class WhenSortedByMatcher { const Comparator comparator_; const Matcher&> matcher_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); + Impl(const Impl&) = delete; + Impl& operator=(const Impl&) = delete; }; private: @@ -2566,9 +2572,9 @@ class WhenSortedByMatcher { // container and the RHS container respectively. template class PointwiseMatcher { - GTEST_COMPILE_ASSERT_( + static_assert( !IsHashTable::value, - use_UnorderedPointwise_with_hash_tables); + "use UnorderedPointwise with hash tables"); public: typedef internal::StlContainerView RhsView; @@ -2587,9 +2593,9 @@ class PointwiseMatcher { template operator Matcher() const { - GTEST_COMPILE_ASSERT_( + static_assert( !IsHashTable::value, - use_UnorderedPointwise_with_hash_tables); + "use UnorderedPointwise with hash tables"); return Matcher( new Impl(tuple_matcher_, rhs_)); @@ -3721,10 +3727,10 @@ class ElementsAreMatcher { template operator Matcher() const { - GTEST_COMPILE_ASSERT_( + static_assert( !IsHashTable::value || ::std::tuple_size::value < 2, - use_UnorderedElementsAre_with_hash_tables); + "use UnorderedElementsAre with hash tables"); typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView::type View; @@ -3772,9 +3778,9 @@ class ElementsAreArrayMatcher { template operator Matcher() const { - GTEST_COMPILE_ASSERT_( + static_assert( !IsHashTable::value, - use_UnorderedElementsAreArray_with_hash_tables); + "use UnorderedElementsAreArray with hash tables"); return Matcher(new ElementsAreMatcherImpl( matchers_.begin(), matchers_.end())); @@ -5062,7 +5068,8 @@ inline bool ExplainMatchResult(M matcher, const T& value, // // MATCHER_P(XAndYThat, matcher, // "X that " + DescribeMatcher(matcher, negation) + -// " and Y that " + DescribeMatcher(matcher, negation)) { +// (negation ? " or" : " and") + " Y that " + +// DescribeMatcher(matcher, negation)) { // return ExplainMatchResult(matcher, arg.x(), result_listener) && // ExplainMatchResult(matcher, arg.y(), result_listener); // } diff --git a/googlemock/include/gmock/gmock-more-actions.h b/googlemock/include/gmock/gmock-more-actions.h index bf85ff51..148ac017 100644 --- a/googlemock/include/gmock/gmock-more-actions.h +++ b/googlemock/include/gmock/gmock-more-actions.h @@ -129,170 +129,207 @@ // Declares the template parameters. #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0 -#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1) kind0 name0, kind1 name1 +#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \ + kind0 name0, kind1 name1 #define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2) kind0 name0, kind1 name1, kind2 name2 + kind2, name2) \ + kind0 name0, kind1 name1, kind2 name2 #define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \ - kind3 name3 -#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \ - kind2 name2, kind3 name3, kind4 name4 + kind2, name2, kind3, name3) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3 +#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4 #define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \ - kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 -#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ - kind5 name5, kind6 name6 -#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \ - kind4 name4, kind5 name5, kind6 name6, kind7 name7 -#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \ - kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \ - kind8 name8 -#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \ - kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \ - kind6 name6, kind7 name7, kind8 name8, kind9 name9 + kind2, name2, kind3, name3, \ + kind4, name4, kind5, name5) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 +#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ + kind5 name5, kind6 name6 +#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ + kind5 name5, kind6 name6, kind7 name7 +#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7, kind8, name8) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ + kind5 name5, kind6 name6, kind7 name7, kind8 name8 +#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ + kind5 name5, kind6 name6, kind7 name7, kind8 name8, kind9 name9 // Lists the template parameters. #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0 -#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1) name0, name1 +#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \ + name0, name1 #define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2) name0, name1, name2 + kind2, name2) \ + name0, name1, name2 #define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3) name0, name1, name2, name3 -#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \ - name4 + kind2, name2, kind3, name3) \ + name0, name1, name2, name3 +#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \ + name0, name1, name2, name3, name4 #define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \ - name2, name3, name4, name5 -#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6) name0, name1, name2, name3, name4, name5, name6 -#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7 -#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \ - name6, name7, name8 -#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \ - name3, name4, name5, name6, name7, name8, name9 + kind2, name2, kind3, name3, \ + kind4, name4, kind5, name5) \ + name0, name1, name2, name3, name4, name5 +#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6) \ + name0, name1, name2, name3, name4, name5, name6 +#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7) \ + name0, name1, name2, name3, name4, name5, name6, name7 +#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7, kind8, name8) \ + name0, name1, name2, name3, name4, name5, name6, name7, name8 +#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \ + name0, name1, name2, name3, name4, name5, name6, name7, name8, name9 // Declares the types of value parameters. #define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \ - typename p0##_type, typename p1##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \ - typename p0##_type, typename p1##_type, typename p2##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) \ + , typename p0##_type, typename p1##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \ + , typename p0##_type, typename p1##_type, typename p2##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type + p6) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type, typename p7##_type + p6, p7) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type, typename p7##_type, typename p8##_type + p6, p7, p8) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \ - typename p2##_type, typename p3##_type, typename p4##_type, \ - typename p5##_type, typename p6##_type, typename p7##_type, \ - typename p8##_type, typename p9##_type + p6, p7, p8, p9) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type, \ + typename p9##_type // Initializes the value parameters. -#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\ - () -#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\ - (p0##_type gmock_p0) : p0(::std::move(gmock_p0)) -#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\ - (p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)) -#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\ - (p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)) -#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ +#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS() () +#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0) \ + (p0##_type gmock_p0) : p0(::std::move(gmock_p0)) +#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1) \ + (p0##_type gmock_p0, p1##_type gmock_p1) \ + : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)) +#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)) +#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)) -#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)) -#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ +#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)) +#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)) -#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)) -#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ +#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)), \ + p5(::std::move(gmock_p5)), \ + p6(::std::move(gmock_p6)) +#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)), \ + p5(::std::move(gmock_p5)), \ + p6(::std::move(gmock_p6)), \ p7(::std::move(gmock_p7)) -#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)) +#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ + p8) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)), \ + p5(::std::move(gmock_p5)), \ + p6(::std::move(gmock_p6)), \ + p7(::std::move(gmock_p7)), \ + p8(::std::move(gmock_p8)) #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \ + p7, p8, p9) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ + p9##_type gmock_p9) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)), \ + p5(::std::move(gmock_p5)), \ + p6(::std::move(gmock_p6)), \ + p7(::std::move(gmock_p7)), \ + p8(::std::move(gmock_p8)), \ p9(::std::move(gmock_p9)) // Defines the copy constructor #define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \ - {} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134 + {} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134 #define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default; @@ -307,30 +344,71 @@ // Declares the fields for storing the value parameters. #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0; -#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \ - p1##_type p1; -#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \ - p1##_type p1; p2##_type p2; -#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \ - p1##_type p1; p2##_type p2; p3##_type p3; -#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ - p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; -#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ - p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; -#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; p6##_type p6; -#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; p6##_type p6; p7##_type p7; -#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ - p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; +#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) \ + p0##_type p0; \ + p1##_type p1; +#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; +#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; +#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; +#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; +#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; +#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; +#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ + p8) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; #define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ - p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \ - p9##_type p9; + p7, p8, p9) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; \ + p9##_type p9; // Lists the value parameters. #define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS() @@ -338,72 +416,78 @@ #define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1 #define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2 #define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3 -#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \ - p2, p3, p4 -#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \ - p1, p2, p3, p4, p5 -#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0, p1, p2, p3, p4, p5, p6 -#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0, p1, p2, p3, p4, p5, p6, p7 -#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8 +#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + p0, p1, p2, p3, p4 +#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + p0, p1, p2, p3, p4, p5 +#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + p0, p1, p2, p3, p4, p5, p6 +#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + p0, p1, p2, p3, p4, p5, p6, p7 +#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ + p8) \ + p0, p1, p2, p3, p4, p5, p6, p7, p8 #define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 + p7, p8, p9) \ + p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 // Lists the value parameter types. #define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \ - p1##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \ - p1##_type, p2##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ - p0##_type, p1##_type, p2##_type, p3##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ - p0##_type, p1##_type, p2##_type, p3##_type, p4##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ - p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) \ + , p0##_type, p1##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \ + , p0##_type, p1##_type, p2##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + , p0##_type, p1##_type, p2##_type, p3##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ - p6##_type + p6) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type + p6, p7) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ + p6##_type, p7##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type, p8##_type + p6, p7, p8) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ + p6##_type, p7##_type, p8##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type, p8##_type, p9##_type + p6, p7, p8, p9) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ + p6##_type, p7##_type, p8##_type, p9##_type // Declares the value parameters. #define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0 -#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \ - p1##_type p1 -#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \ - p1##_type p1, p2##_type p2 -#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \ - p1##_type p1, p2##_type p2, p3##_type p3 -#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ - p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 -#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ - p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5 -#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5, p6##_type p6 -#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5, p6##_type p6, p7##_type p7 -#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8 +#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) \ + p0##_type p0, p1##_type p1 +#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) \ + p0##_type p0, p1##_type p1, p2##_type p2 +#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3 +#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 +#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5 +#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5, p6##_type p6 +#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5, p6##_type p6, p7##_type p7 +#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ + p8) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8 #define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ - p9##_type p9 + p7, p8, p9) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, p9##_type p9 // The suffix of the class template implementing the action template. #define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS() @@ -415,40 +499,43 @@ #define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6 #define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7 #define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) P8 + p7) \ + P8 #define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) P9 + p7, p8) \ + P9 #define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) P10 + p7, p8, p9) \ + P10 // The name of the class template implementing the action template. -#define GMOCK_ACTION_CLASS_(name, value_params)\ - GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) +#define GMOCK_ACTION_CLASS_(name, value_params) \ + GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) #define ACTION_TEMPLATE(name, template_params, value_params) \ template \ + GMOCK_INTERNAL_DECL_TYPE_##value_params> \ class GMOCK_ACTION_CLASS_(name, value_params) { \ public: \ explicit GMOCK_ACTION_CLASS_(name, value_params)( \ GMOCK_INTERNAL_DECL_##value_params) \ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ - = default; , \ + = default; \ + , \ : impl_(std::make_shared( \ - GMOCK_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 \ - operator ::testing::Action() const { \ + GMOCK_INTERNAL_LIST_##value_params)){}) \ + GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \ + name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_ \ + ##value_params GMOCK_ACTION_CLASS_(name, value_params)( \ + GMOCK_ACTION_CLASS_(name, value_params) &&) noexcept \ + GMOCK_INTERNAL_DEFN_COPY_##value_params template \ + operator ::testing::Action() const { \ return GMOCK_PP_IF( \ GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ - (::testing::internal::MakeAction()), \ - (::testing::internal::MakeAction(impl_))); \ + (::testing::internal::MakeAction()), \ + (::testing::internal::MakeAction(impl_))); \ } \ + \ private: \ class gmock_Impl { \ public: \ @@ -458,34 +545,35 @@ 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 impl_;) \ + GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), , \ + std::shared_ptr impl_;) \ }; \ template \ - GMOCK_ACTION_CLASS_(name, value_params)< \ - GMOCK_INTERNAL_LIST_##template_params \ - GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \ - GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \ + GMOCK_INTERNAL_DECL_TYPE_##value_params> \ + GMOCK_ACTION_CLASS_( \ + name, value_params) \ + name(GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \ template \ - inline GMOCK_ACTION_CLASS_(name, value_params)< \ - GMOCK_INTERNAL_LIST_##template_params \ - GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \ - GMOCK_INTERNAL_DECL_##value_params) { \ - return GMOCK_ACTION_CLASS_(name, value_params)< \ - GMOCK_INTERNAL_LIST_##template_params \ - GMOCK_INTERNAL_LIST_TYPE_##value_params>( \ - GMOCK_INTERNAL_LIST_##value_params); \ + GMOCK_INTERNAL_DECL_TYPE_##value_params> \ + inline GMOCK_ACTION_CLASS_( \ + name, value_params) \ + name(GMOCK_INTERNAL_DECL_##value_params) { \ + return GMOCK_ACTION_CLASS_( \ + name, value_params)( \ + GMOCK_INTERNAL_LIST_##value_params); \ } \ template \ + GMOCK_INTERNAL_DECL_TYPE_##value_params> \ template \ - return_type GMOCK_ACTION_CLASS_(name, value_params)< \ - GMOCK_INTERNAL_LIST_##template_params \ - GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + return_type GMOCK_ACTION_CLASS_( \ + name, value_params):: \ + gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) \ + const namespace testing { @@ -495,8 +583,8 @@ namespace testing { // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #endif namespace internal { @@ -512,7 +600,8 @@ auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) { template struct InvokeArgumentAction { - template + template ::type> auto operator()(Args&&... args) const -> decltype(internal::InvokeArgument( std::get(std::forward_as_tuple(std::forward(args)...)), std::declval()...)) { @@ -565,7 +654,7 @@ InvokeArgument(Params&&... params) { } #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif } // namespace testing diff --git a/googlemock/include/gmock/gmock-more-matchers.h b/googlemock/include/gmock/gmock-more-matchers.h index 6442d2fa..47aaf984 100644 --- a/googlemock/include/gmock/gmock-more-matchers.h +++ b/googlemock/include/gmock/gmock-more-matchers.h @@ -47,13 +47,13 @@ namespace testing { // Silence C4100 (unreferenced formal // parameter) for MSVC #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #if (_MSC_VER == 1900) // and silence C4800 (C4800: 'int *const ': forcing value // to bool 'true' or 'false') for MSVC 14 -# pragma warning(disable:4800) - #endif +#pragma warning(disable : 4800) +#endif #endif // Defines a matcher that matches an empty container. The container must @@ -83,10 +83,9 @@ MATCHER(IsFalse, negation ? "is true" : "is false") { } #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif - } // namespace testing #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-nice-strict.h b/googlemock/include/gmock/gmock-nice-strict.h index f421deaf..4f0eb35d 100644 --- a/googlemock/include/gmock/gmock-nice-strict.h +++ b/googlemock/include/gmock/gmock-nice-strict.h @@ -63,6 +63,7 @@ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ +#include #include #include "gmock/gmock-spec-builders.h" @@ -109,25 +110,37 @@ constexpr bool HasStrictnessModifier() { template class NiceMockImpl { public: - NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(this); } + NiceMockImpl() { + ::testing::Mock::AllowUninterestingCalls(reinterpret_cast(this)); + } - ~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(this); } + ~NiceMockImpl() { + ::testing::Mock::UnregisterCallReaction(reinterpret_cast(this)); + } }; template class NaggyMockImpl { public: - NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(this); } + NaggyMockImpl() { + ::testing::Mock::WarnUninterestingCalls(reinterpret_cast(this)); + } - ~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(this); } + ~NaggyMockImpl() { + ::testing::Mock::UnregisterCallReaction(reinterpret_cast(this)); + } }; template class StrictMockImpl { public: - StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(this); } + StrictMockImpl() { + ::testing::Mock::FailUninterestingCalls(reinterpret_cast(this)); + } - ~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(this); } + ~StrictMockImpl() { + ::testing::Mock::UnregisterCallReaction(reinterpret_cast(this)); + } }; } // namespace internal @@ -169,7 +182,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock } private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock); + NiceMock(const NiceMock&) = delete; + NiceMock& operator=(const NiceMock&) = delete; }; template @@ -210,7 +224,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock } private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock); + NaggyMock(const NaggyMock&) = delete; + NaggyMock& operator=(const NaggyMock&) = delete; }; template @@ -251,7 +266,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock } private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock); + StrictMock(const StrictMock&) = delete; + StrictMock& operator=(const StrictMock&) = delete; }; #undef GTEST_INTERNAL_EMPTY_BASE_CLASS diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index dfe642dc..45cc6051 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -61,6 +61,7 @@ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ +#include #include #include #include @@ -70,6 +71,7 @@ #include #include #include + #include "gmock/gmock-actions.h" #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-matchers.h" @@ -78,7 +80,7 @@ #include "gtest/gtest.h" #if GTEST_HAS_EXCEPTIONS -# include // NOLINT +#include // NOLINT #endif GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ @@ -97,13 +99,15 @@ class ExpectationSet; namespace internal { // Implements a mock function. -template class FunctionMocker; +template +class FunctionMocker; // Base class for expectations. class ExpectationBase; // Implements an expectation. -template class TypedExpectation; +template +class TypedExpectation; // Helper class for testing the Expectation class template. class ExpectationTester; @@ -129,9 +133,6 @@ class NaggyMockImpl; // calls to ensure the integrity of the mock objects' states. GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex); -// Untyped base class for ActionResultHolder. -class UntypedActionResultHolderBase; - // Abstract base class of FunctionMocker. This is the // type-agnostic part of the function mocker interface. Its pure // virtual methods are implemented by FunctionMocker. @@ -154,27 +155,12 @@ class GTEST_API_ UntypedFunctionMockerBase { // responsibility to guarantee the correctness of the arguments' // types. - // Performs the default action with the given arguments and returns - // the action's result. The call description string will be used in - // the error message to describe the call in the case the default - // action fails. - // L = * - virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( - void* untyped_args, const std::string& call_description) const = 0; - - // Performs the given action with the given arguments and returns - // the action's result. - // L = * - virtual UntypedActionResultHolderBase* UntypedPerformAction( - const void* untyped_action, void* untyped_args) const = 0; - // Writes a message that the call is uninteresting (i.e. neither // explicitly expected nor explicitly unexpected) to the given // ostream. - virtual void UntypedDescribeUninterestingCall( - const void* untyped_args, - ::std::ostream* os) const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; + virtual void UntypedDescribeUninterestingCall(const void* untyped_args, + ::std::ostream* os) const + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; // Returns the expectation that matches the given function arguments // (or NULL is there's no match); when a match is found, @@ -183,10 +169,9 @@ class GTEST_API_ UntypedFunctionMockerBase { // is_excessive is modified to indicate whether the call exceeds the // expected number. virtual const ExpectationBase* UntypedFindMatchingExpectation( - const void* untyped_args, - const void** untyped_action, bool* is_excessive, + const void* untyped_args, const void** untyped_action, bool* is_excessive, ::std::ostream* what, ::std::ostream* why) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; // Prints the given function arguments to the ostream. virtual void UntypedPrintArgs(const void* untyped_args, @@ -196,8 +181,7 @@ class GTEST_API_ UntypedFunctionMockerBase { // this information in the global mock registry. Will be called // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock // method. - void RegisterOwner(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Sets the mock object this mock method belongs to, and sets the // name of the mock function. Will be called upon each invocation @@ -208,20 +192,11 @@ class GTEST_API_ UntypedFunctionMockerBase { // Returns the mock object this mock method belongs to. Must be // called after RegisterOwner() or SetOwnerAndName() has been // called. - const void* MockObject() const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the name of this mock method. Must be called after // SetOwnerAndName() has been called. - const char* Name() const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); - - // Returns the result of invoking this mock function with the given - // arguments. This function can be safely called from multiple - // threads concurrently. The caller is responsible for deleting the - // result. - UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); protected: typedef std::vector UntypedOnCallSpecs; @@ -430,29 +405,28 @@ class GTEST_API_ Mock { // Tells Google Mock to allow uninteresting calls on the given mock // object. - static void AllowUninterestingCalls(const void* mock_obj) + static void AllowUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock to warn the user about uninteresting calls on // the given mock object. - static void WarnUninterestingCalls(const void* mock_obj) + static void WarnUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock to fail uninteresting calls on the given mock // object. - static void FailUninterestingCalls(const void* mock_obj) + static void FailUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock the given mock object is being destroyed and // its entry in the call-reaction table should be removed. - static void UnregisterCallReaction(const void* mock_obj) + static void UnregisterCallReaction(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Returns the reaction Google Mock will have on uninteresting calls // made on the given mock object. static internal::CallReaction GetReactionOnUninterestingCalls( - const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies that all expectations on the given mock object have been // satisfied. Reports one or more Google Test non-fatal failures @@ -465,17 +439,16 @@ class GTEST_API_ Mock { GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); // Registers a mock object and a mock method it owns. - static void Register( - const void* mock_obj, - internal::UntypedFunctionMockerBase* mocker) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static void Register(const void* mock_obj, + internal::UntypedFunctionMockerBase* mocker) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock where in the source code mock_obj is used in an // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this // information helps the user identify which object it is. - static void RegisterUseByOnCallOrExpectCall( - const void* mock_obj, const char* file, int line) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static void RegisterUseByOnCallOrExpectCall(const void* mock_obj, + const char* file, int line) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Unregisters a mock method; removes the owning mock object from // the registry when the last mock method associated with it has @@ -632,7 +605,6 @@ class ExpectationSet { Expectation::Set expectations_; }; - // Sequence objects are used by a user to specify the relative order // in which the expectations should match. They are copyable (we rely // on the compiler-defined copy constructor and assignment operator). @@ -678,10 +650,12 @@ class GTEST_API_ InSequence { public: InSequence(); ~InSequence(); + private: bool sequence_created_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT + InSequence(const InSequence&) = delete; + InSequence& operator=(const InSequence&) = delete; } GTEST_ATTRIBUTE_UNUSED_; namespace internal { @@ -784,40 +758,34 @@ class GTEST_API_ ExpectationBase { // the current thread. // Retires all pre-requisites of this expectation. - void RetireAllPreRequisites() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Returns true if and only if this expectation is retired. - bool is_retired() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return retired_; } // Retires this expectation. - void Retire() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); retired_ = true; } // Returns true if and only if this expectation is satisfied. - bool IsSatisfied() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSatisfiedByCallCount(call_count_); } // Returns true if and only if this expectation is saturated. - bool IsSaturated() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSaturatedByCallCount(call_count_); } // Returns true if and only if this expectation is over-saturated. - bool IsOverSaturated() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsOverSaturatedByCallCount(call_count_); } @@ -832,15 +800,13 @@ class GTEST_API_ ExpectationBase { GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Returns the number this expectation has been invoked. - int call_count() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return call_count_; } // Increments the number this expectation has been invoked. - void IncrementCallCount() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); call_count_++; } @@ -849,8 +815,7 @@ class GTEST_API_ ExpectationBase { // WillRepeatedly() clauses) against the cardinality if this hasn't // been done before. Prints a warning if there are too many or too // few actions. - void CheckActionCountIfNotDone() const - GTEST_LOCK_EXCLUDED_(mutex_); + void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_); friend class ::testing::Sequence; friend class ::testing::internal::ExpectationTester; @@ -863,12 +828,12 @@ class GTEST_API_ ExpectationBase { // This group of fields are part of the spec and won't change after // an EXPECT_CALL() statement finishes. - const char* file_; // The file that contains the expectation. - int line_; // The line number of the expectation. + const char* file_; // The file that contains the expectation. + int line_; // The line number of the expectation. const std::string source_text_; // The EXPECT_CALL(...) source text. // True if and only if the cardinality is specified explicitly. bool cardinality_specified_; - Cardinality cardinality_; // The cardinality of the expectation. + Cardinality cardinality_; // The cardinality of the expectation. // The immediate pre-requisites (i.e. expectations that must be // satisfied before this expectation can be matched) of this // expectation. We use std::shared_ptr in the set because we want an @@ -887,12 +852,18 @@ class GTEST_API_ ExpectationBase { bool retires_on_saturation_; Clause last_clause_; mutable bool action_count_checked_; // Under mutex_. - mutable Mutex mutex_; // Protects action_count_checked_. -}; // class ExpectationBase + mutable Mutex mutex_; // Protects action_count_checked_. +}; // class ExpectationBase + +template +class TypedExpectation; // Implements an expectation for the given function type. -template -class TypedExpectation : public ExpectationBase { +template +class TypedExpectation : public ExpectationBase { + private: + using F = R(Args...); + public: typedef typename Function::ArgumentTuple ArgumentTuple; typedef typename Function::ArgumentMatcherTuple ArgumentMatcherTuple; @@ -945,9 +916,7 @@ class TypedExpectation : public ExpectationBase { } // Implements the .Times() clause. - TypedExpectation& Times(int n) { - return Times(Exactly(n)); - } + TypedExpectation& Times(int n) { return Times(Exactly(n)); } // Implements the .InSequence() clause. TypedExpectation& InSequence(const Sequence& s) { @@ -1007,14 +976,31 @@ class TypedExpectation : public ExpectationBase { return After(s1, s2, s3, s4).After(s5); } - // Implements the .WillOnce() clause. - TypedExpectation& WillOnce(const Action& action) { + // Preferred, type-safe overload: consume anything that can be directly + // converted to a OnceAction, except for Action objects themselves. + TypedExpectation& WillOnce(OnceAction 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(ActionAdaptor{ + std::make_shared>(std::move(once_action)), + })); + } + + // Fallback overload: accept Action objects and those actions that define + // `operator Action` but not `operator OnceAction`. + // + // This is templated in order to cause the overload above to be preferred + // when the input is convertible to either type. + template + TypedExpectation& WillOnce(Action action) { ExpectSpecProperty(last_clause_ <= kWillOnce, ".WillOnce() cannot appear after " ".WillRepeatedly() or .RetiresOnSaturation()."); last_clause_ = kWillOnce; - untyped_actions_.push_back(new Action(action)); + untyped_actions_.push_back(new Action(std::move(action))); + if (!cardinality_specified()) { set_cardinality(Exactly(static_cast(untyped_actions_.size()))); } @@ -1062,9 +1048,7 @@ class TypedExpectation : public ExpectationBase { // Returns the matchers for the arguments as specified inside the // EXPECT_CALL() macro. - const ArgumentMatcherTuple& matchers() const { - return matchers_; - } + const ArgumentMatcherTuple& matchers() const { return matchers_; } // Returns the matcher specified by the .With() clause. const Matcher& extra_matcher() const { @@ -1088,6 +1072,16 @@ class TypedExpectation : public ExpectationBase { template friend class FunctionMocker; + // An adaptor that turns a OneAction into something compatible with + // Action. Must be called at most once. + struct ActionAdaptor { + std::shared_ptr> once_action; + + R operator()(Args&&... args) const { + return std::move(*once_action).Call(std::forward(args)...); + } + }; + // Returns an Expectation object that references and co-owns this // expectation. Expectation GetHandle() override { return owner_->GetHandleOf(this); } @@ -1119,10 +1113,8 @@ class TypedExpectation : public ExpectationBase { // Describes the result of matching the arguments against this // expectation to the given ostream. - void ExplainMatchResultTo( - const ArgumentTuple& args, - ::std::ostream* os) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void ExplainMatchResultTo(const ArgumentTuple& args, ::std::ostream* os) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); if (is_retired()) { @@ -1181,9 +1173,9 @@ class TypedExpectation : public ExpectationBase { ::std::stringstream ss; DescribeLocationTo(&ss); ss << "Actions ran out in " << source_text() << "...\n" - << "Called " << count << " times, but only " - << action_count << " WillOnce()" - << (action_count == 1 ? " is" : "s are") << " specified - "; + << "Called " << count << " times, but only " << action_count + << " WillOnce()" << (action_count == 1 ? " is" : "s are") + << " specified - "; mocker->DescribeDefaultActionTo(args, &ss); Log(kWarning, ss.str(), 1); } @@ -1225,7 +1217,7 @@ class TypedExpectation : public ExpectationBase { } // Must be done after IncrementCount()! - *what << "Mock function call matches " << source_text() <<"...\n"; + *what << "Mock function call matches " << source_text() << "...\n"; return &(GetCurrentAction(mocker, args)); } @@ -1236,7 +1228,8 @@ class TypedExpectation : public ExpectationBase { Matcher extra_matcher_; Action repeated_action_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation); + TypedExpectation(const TypedExpectation&) = delete; + TypedExpectation& operator=(const TypedExpectation&) = delete; }; // class TypedExpectation // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for @@ -1258,8 +1251,8 @@ template class MockSpec { public: typedef typename internal::Function::ArgumentTuple ArgumentTuple; - typedef typename internal::Function::ArgumentMatcherTuple - ArgumentMatcherTuple; + typedef + typename internal::Function::ArgumentMatcherTuple ArgumentMatcherTuple; // Constructs a MockSpec object, given the function mocker object // that the spec is associated with. @@ -1269,8 +1262,9 @@ class MockSpec { // Adds a new default action spec to the function mocker and returns // the newly created spec. - internal::OnCallSpec& InternalDefaultActionSetAt( - const char* file, int line, const char* obj, const char* call) { + internal::OnCallSpec& InternalDefaultActionSetAt(const char* file, + int line, const char* obj, + const char* call) { LogWithLocation(internal::kInfo, file, line, std::string("ON_CALL(") + obj + ", " + call + ") invoked"); return function_mocker_->AddNewOnCallSpec(file, line, matchers_); @@ -1278,13 +1272,14 @@ class MockSpec { // Adds a new expectation spec to the function mocker and returns // the newly created spec. - internal::TypedExpectation& InternalExpectedAt( - const char* file, int line, const char* obj, const char* call) { + internal::TypedExpectation& InternalExpectedAt(const char* file, int line, + const char* obj, + const char* call) { const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " + call + ")"); LogWithLocation(internal::kInfo, file, line, source_text + " invoked"); - return function_mocker_->AddNewExpectation( - file, line, source_text, matchers_); + return function_mocker_->AddNewExpectation(file, line, source_text, + matchers_); } // This operator overload is used to swallow the superfluous parameter list @@ -1317,9 +1312,7 @@ template class ReferenceOrValueWrapper { public: // Constructs a wrapper from the given value/reference. - explicit ReferenceOrValueWrapper(T value) - : value_(std::move(value)) { - } + explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {} // Unwraps and returns the underlying value/reference, exactly as // originally passed. The behavior of calling this more than once on @@ -1330,9 +1323,7 @@ class ReferenceOrValueWrapper { // Always returns a const reference (more precisely, // const std::add_lvalue_reference::type). The behavior of calling this // after calling Unwrap on the same object is unspecified. - const T& Peek() const { - return value_; - } + const T& Peek() const { return value_; } private: T value_; @@ -1346,8 +1337,7 @@ class ReferenceOrValueWrapper { // Workaround for debatable pass-by-reference lint warning (c-library-team // policy precludes NOLINT in this context) typedef T& reference; - explicit ReferenceOrValueWrapper(reference ref) - : value_ptr_(&ref) {} + explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {} T& Unwrap() { return *value_ptr_; } const T& Peek() const { return *value_ptr_; } @@ -1355,102 +1345,27 @@ class ReferenceOrValueWrapper { T* value_ptr_; }; -// C++ treats the void type specially. For example, you cannot define -// a void-typed variable or pass a void value to a function. -// ActionResultHolder 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. -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 -class ActionResultHolder : public UntypedActionResultHolderBase { +void PrintAsActionResult(const T& result, std::ostream& os) { + os << "\n Returns: "; + // T may be a reference type, so we don't use UniversalPrint(). + UniversalPrinter::Print(result, &os); +} + +// 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); + +// A generic RAII type that runs a user-provided function in its destructor. +class Cleanup final { 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::Print(result_.Peek(), os); - } - - // Performs the given mock function's default action and returns the - // result in a new-ed ActionResultHolder. - template - static ActionResultHolder* PerformDefaultAction( - const FunctionMocker* func_mocker, - typename Function::ArgumentTuple&& args, - const std::string& call_description) { - return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction( - std::move(args), call_description))); - } - - // Performs the given action and returns the result in a new-ed - // ActionResultHolder. - template - static ActionResultHolder* PerformAction( - const Action& action, typename Function::ArgumentTuple&& args) { - return new ActionResultHolder( - Wrapper(action.Perform(std::move(args)))); - } + explicit Cleanup(std::function f) : f_(std::move(f)) {} + ~Cleanup() { f_(); } private: - typedef ReferenceOrValueWrapper Wrapper; - - explicit ActionResultHolder(Wrapper result) - : result_(std::move(result)) { - } - - Wrapper result_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder); -}; - -// Specialization for T = void. -template <> -class ActionResultHolder : public UntypedActionResultHolderBase { - public: - void Unwrap() { } - - void PrintAsActionResult(::std::ostream* /* os */) const override {} - - // Performs the given mock function's default action and returns ownership - // of an empty ActionResultHolder*. - template - static ActionResultHolder* PerformDefaultAction( - const FunctionMocker* func_mocker, - typename Function::ArgumentTuple&& args, - const std::string& call_description) { - func_mocker->PerformDefaultAction(std::move(args), call_description); - return new ActionResultHolder; - } - - // Performs the given action and returns ownership of an empty - // ActionResultHolder*. - template - static ActionResultHolder* PerformAction( - const Action& action, typename Function::ArgumentTuple&& args) { - action.Perform(std::move(args)); - return new ActionResultHolder; - } - - private: - ActionResultHolder() {} - GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder); + std::function f_; }; template @@ -1495,14 +1410,12 @@ class FunctionMocker 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* FindOnCallSpec( - const ArgumentTuple& args) const { - for (UntypedOnCallSpecs::const_reverse_iterator it - = untyped_on_call_specs_.rbegin(); + const OnCallSpec* 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* spec = static_cast*>(*it); - if (spec->Matches(args)) - return spec; + if (spec->Matches(args)) return spec; } return nullptr; @@ -1517,8 +1430,7 @@ class FunctionMocker final : public UntypedFunctionMockerBase { // L = * Result PerformDefaultAction(ArgumentTuple&& args, const std::string& call_description) const { - const OnCallSpec* const spec = - this->FindOnCallSpec(args); + const OnCallSpec* const spec = this->FindOnCallSpec(args); if (spec != nullptr) { return spec->GetAction().Perform(std::move(args)); } @@ -1536,32 +1448,6 @@ class FunctionMocker final : public UntypedFunctionMockerBase { return DefaultValue::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(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 action = *static_cast*>(untyped_action); - ArgumentTuple* args = static_cast(untyped_args); - return ResultHolder::PerformAction(action, std::move(*args)); - } - // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked(): // clears the ON_CALL()s set on this mock function. void ClearDefaultActionsLocked() override @@ -1579,8 +1465,7 @@ class FunctionMocker 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*>(*it); } @@ -1594,10 +1479,7 @@ class FunctionMocker 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)...); - std::unique_ptr holder(DownCast_( - this->UntypedInvokeWith(static_cast(&tuple)))); - return holder->Unwrap(); + return InvokeWith(ArgumentTuple(std::forward(args)...)); } MockSpec With(Matcher... m) { @@ -1608,13 +1490,10 @@ class FunctionMocker final : public UntypedFunctionMockerBase { template friend class MockSpec; - typedef ActionResultHolder ResultHolder; - // Adds and returns a default action spec for this mock function. - OnCallSpec& AddNewOnCallSpec( - const char* file, int line, - const ArgumentMatcherTuple& m) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + OnCallSpec& AddNewOnCallSpec(const char* file, int line, + const ArgumentMatcherTuple& m) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); OnCallSpec* const on_call_spec = new OnCallSpec(file, line, m); untyped_on_call_specs_.push_back(on_call_spec); @@ -1644,7 +1523,8 @@ class FunctionMocker final : public UntypedFunctionMockerBase { } private: - template friend class TypedExpectation; + template + friend class TypedExpectation; // Some utilities needed for implementing UntypedInvokeWith(). @@ -1728,9 +1608,8 @@ class FunctionMocker final : public UntypedFunctionMockerBase { // Returns the expectation that matches the arguments, or NULL if no // expectation matches them. - TypedExpectation* FindMatchingExpectationLocked( - const ArgumentTuple& args) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + TypedExpectation* FindMatchingExpectationLocked(const ArgumentTuple& args) + const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // See the definition of untyped_expectations_ for why access to // it is unprotected here. @@ -1747,11 +1626,10 @@ class FunctionMocker final : public UntypedFunctionMockerBase { } // Returns a message that the arguments don't match any expectation. - void FormatUnexpectedCallMessageLocked( - const ArgumentTuple& args, - ::std::ostream* os, - ::std::ostream* why) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args, + ::std::ostream* os, + ::std::ostream* why) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); *os << "\nUnexpected mock function call - "; DescribeDefaultActionTo(args, os); @@ -1760,15 +1638,14 @@ class FunctionMocker 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* const expectation = @@ -1783,11 +1660,177 @@ class FunctionMocker 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 action = *static_cast*>(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 + 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>, + // 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>; + + // Perform the supplied action, printing the result to os. + template ::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(result); + } + + // An overload for when it's not possible to print the result. In this case we + // simply perform the action. + template >::value, int>::type = 0> + R PerformActionAndPrintResult(const void* const untyped_action, + ArgumentTuple&& args, + const std::string& call_description, + std::ostream&) { + return PerformAction(untyped_action, std::move(args), call_description); + } + + // Returns the result of invoking this mock function with the given + // arguments. This function can be safely called from multiple + // threads concurrently. + R InvokeWith(ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); }; // class FunctionMocker -// Reports an uninteresting call (whose description is in msg) in the -// manner specified by 'reaction'. -void ReportUninterestingCall(CallReaction reaction, const std::string& msg); +// Calculates the result of invoking this mock function with the given +// arguments, prints it, and returns it. +template +R FunctionMocker::InvokeWith(ArgumentTuple&& args) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + // See the definition of untyped_expectations_ for why access to it + // is unprotected here. + if (untyped_expectations_.size() == 0) { + // No expectation is set on this mock method - we have an + // uninteresting call. + + // We must get Google Mock's reaction on uninteresting calls + // made on this mock object BEFORE performing the action, + // because the action may DELETE the mock object and make the + // following expression meaningless. + const CallReaction reaction = + Mock::GetReactionOnUninterestingCalls(MockObject()); + + // True if and only if we need to print this call's arguments and return + // value. This definition must be kept in sync with + // the behavior of ReportUninterestingCall(). + const bool need_to_report_uninteresting_call = + // If the user allows this uninteresting call, we print it + // only when they want informational messages. + reaction == kAllow ? LogIsVisible(kInfo) : + // If the user wants this to be a warning, we print + // it only when they want to see warnings. + reaction == kWarn + ? LogIsVisible(kWarning) + : + // Otherwise, the user wants this to be an error, and we + // should always print detailed information in the error. + true; + + if (!need_to_report_uninteresting_call) { + // Perform the action without printing the call information. + return this->PerformDefaultAction( + std::move(args), "Function call: " + std::string(Name())); + } + + // Warns about the uninteresting call. + ::std::stringstream ss; + this->UntypedDescribeUninterestingCall(&args, &ss); + + // Perform the action, print the result, and then report the uninteresting + // call. + // + // We use RAII to do the latter in case R is void or a non-moveable type. In + // either case we can't assign it to a local variable. + const Cleanup report_uninteresting_call( + [&] { ReportUninterestingCall(reaction, ss.str()); }); + + return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss); + } + + bool is_excessive = false; + ::std::stringstream ss; + ::std::stringstream why; + ::std::stringstream loc; + const void* untyped_action = nullptr; + + // The UntypedFindMatchingExpectation() function acquires and + // releases g_gmock_mutex. + + const ExpectationBase* const untyped_expectation = + this->UntypedFindMatchingExpectation(&args, &untyped_action, + &is_excessive, &ss, &why); + const bool found = untyped_expectation != nullptr; + + // True if and only if we need to print the call's arguments + // and return value. + // This definition must be kept in sync with the uses of Expect() + // and Log() in this function. + const bool need_to_report_call = + !found || is_excessive || LogIsVisible(kInfo); + if (!need_to_report_call) { + // Perform the action without printing the call information. + return PerformAction(untyped_action, std::move(args), ""); + } + + ss << " Function call: " << Name(); + this->UntypedPrintArgs(&args, &ss); + + // In case the action deletes a piece of the expectation, we + // generate the message beforehand. + if (found && !is_excessive) { + untyped_expectation->DescribeLocationTo(&loc); + } + + // Perform the action, print the result, and then fail or log in whatever way + // is appropriate. + // + // We use RAII to do the latter in case R is void or a non-moveable type. In + // either case we can't assign it to a local variable. + const Cleanup handle_failures([&] { + ss << "\n" << why.str(); + + if (!found) { + // No expectation matches this call - reports a failure. + Expect(false, nullptr, -1, ss.str()); + } else if (is_excessive) { + // We had an upper-bound violation and the failure message is in ss. + Expect(false, untyped_expectation->file(), untyped_expectation->line(), + ss.str()); + } else { + // We had an expected call and the matching expectation is + // described in ss. + Log(kInfo, loc.str() + ss.str(), 2); + } + }); + + return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(), + ss); +} } // namespace internal @@ -1952,7 +1995,9 @@ using internal::MockSpec; // // Expects a call to const MockFoo::Bar(). // EXPECT_CALL(Const(foo), Bar()); template -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 diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index d9d812a3..b1343fdc 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -59,9 +59,9 @@ namespace internal { // Silence MSVC C4100 (unreferenced formal parameter) and // C4805('==': unsafe mix of type 'const int' and type 'const bool') #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) -# pragma warning(disable:4805) +#pragma warning(push) +#pragma warning(disable : 4100) +#pragma warning(disable : 4805) #endif // Joins a vector of strings as if they are fields of a tuple; returns @@ -91,7 +91,9 @@ inline const Element* GetRawPointer(const std::reference_wrapper& r) { // This overloaded version is for the raw pointer case. template -inline Element* GetRawPointer(Element* p) { return p; } +inline Element* GetRawPointer(Element* p) { + return p; +} // MSVC treats wchar_t as a native type usually, but treats it as the // same as unsigned short when the compiler option /Zc:wchar_t- is @@ -100,7 +102,7 @@ inline Element* GetRawPointer(Element* p) { return p; } #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) // wchar_t is a typedef. #else -# define GMOCK_WCHAR_T_IS_NATIVE_ 1 +#define GMOCK_WCHAR_T_IS_NATIVE_ 1 #endif // In what follows, we use the term "kind" to indicate whether a type @@ -108,18 +110,20 @@ inline Element* GetRawPointer(Element* p) { return p; } // or none of them. This categorization is useful for determining // when a matcher argument type can be safely converted to another // type in the implementation of SafeMatcherCast. -enum TypeKind { - kBool, kInteger, kFloatingPoint, kOther -}; +enum TypeKind { kBool, kInteger, kFloatingPoint, kOther }; // KindOf::value is the kind of type T. -template struct KindOf { +template +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 { enum { value = kind }; } + template <> \ + struct KindOf { \ + enum { value = kind }; \ + } GMOCK_DECLARE_KIND_(bool, kBool); @@ -127,13 +131,13 @@ GMOCK_DECLARE_KIND_(bool, kBool); GMOCK_DECLARE_KIND_(char, kInteger); GMOCK_DECLARE_KIND_(signed char, kInteger); GMOCK_DECLARE_KIND_(unsigned char, kInteger); -GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(int, kInteger); GMOCK_DECLARE_KIND_(unsigned int, kInteger); -GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT -GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT -GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT #if GMOCK_WCHAR_T_IS_NATIVE_ @@ -148,7 +152,7 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint); #undef GMOCK_DECLARE_KIND_ // Evaluates to the kind of 'type'. -#define GMOCK_KIND_OF_(type) \ +#define GMOCK_KIND_OF_(type) \ static_cast< ::testing::internal::TypeKind>( \ ::testing::internal::KindOf::value) @@ -204,9 +208,7 @@ using LosslessArithmeticConvertible = class FailureReporterInterface { public: // The type of a failure (either non-fatal or fatal). - enum FailureType { - kNonfatal, kFatal - }; + enum FailureType { kNonfatal, kFatal }; virtual ~FailureReporterInterface() {} @@ -226,8 +228,8 @@ GTEST_API_ FailureReporterInterface* GetFailureReporter(); inline void Assert(bool condition, const char* file, int line, const std::string& msg) { if (!condition) { - GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, - file, line, msg); + GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file, + line, msg); } } inline void Assert(bool condition, const char* file, int line) { @@ -248,10 +250,7 @@ inline void Expect(bool condition, const char* file, int line) { } // Severity level of a log. -enum LogSeverity { - kInfo = 0, - kWarning = 1 -}; +enum LogSeverity { kInfo = 0, kWarning = 1 }; // Valid values for the --gmock_verbose flag. @@ -294,8 +293,8 @@ GTEST_API_ WithoutMatchers GetWithoutMatchers(); // Disable MSVC warnings for infinite recursion, since in this case the // recursion is unreachable. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4717) +#pragma warning(push) +#pragma warning(disable : 4717) #endif // Invalid() is usable as an expression of type T, but will terminate @@ -306,14 +305,17 @@ GTEST_API_ WithoutMatchers GetWithoutMatchers(); template inline T Invalid() { Assert(false, "", -1, "Internal error: attempt to return invalid value"); - // This statement is unreachable, and would never terminate even if it - // could be reached. It is provided only to placate compiler warnings - // about missing return statements. +#if defined(__GNUC__) || defined(__clang__) + __builtin_unreachable(); +#elif defined(_MSC_VER) + __assume(0); +#else return Invalid(); +#endif } #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif // Given a raw type (i.e. having no top-level reference or const @@ -392,7 +394,8 @@ class StlContainerView< ::std::tuple > { // The following specialization prevents the user from instantiating // StlContainer with a reference type. -template class StlContainerView; +template +class StlContainerView; // 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, @@ -413,17 +416,18 @@ struct RemoveConstFromKey > { GTEST_API_ void IllegalDoDefault(const char* file, int line); template -auto ApplyImpl(F&& f, Tuple&& args, IndexSequence) -> decltype( - std::forward(f)(std::get(std::forward(args))...)) { +auto ApplyImpl(F&& f, Tuple&& args, IndexSequence) + -> decltype(std::forward(f)( + std::get(std::forward(args))...)) { return std::forward(f)(std::get(std::forward(args))...); } // Apply the function to a tuple of arguments. template -auto Apply(F&& f, Tuple&& args) -> decltype( - ApplyImpl(std::forward(f), std::forward(args), - MakeIndexSequence::type>::value>())) { +auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl( + std::forward(f), std::forward(args), + MakeIndexSequence::type>::value>())) { return ApplyImpl(std::forward(f), std::forward(args), MakeIndexSequence::type>::value>()); @@ -463,7 +467,7 @@ constexpr size_t Function::ArgumentCount; bool Base64Unescape(const std::string& encoded, std::string* decoded); #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif } // namespace internal diff --git a/googlemock/include/gmock/internal/gmock-port.h b/googlemock/include/gmock/internal/gmock-port.h index 998f6c79..bc18a25f 100644 --- a/googlemock/include/gmock/internal/gmock-port.h +++ b/googlemock/include/gmock/internal/gmock-port.h @@ -53,53 +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" + +#if GTEST_HAS_ABSL +#include "absl/flags/declare.h" +#include "absl/flags/flag.h" +#endif // For MS Visual C++, check the compiler version. At least VS 2015 is // required to compile Google Mock. #if defined(_MSC_VER) && _MSC_VER < 1900 -# error "At least Visual C++ 2015 (14.0) is required to compile Google Mock." +#error "At least Visual C++ 2015 (14.0) is required to compile Google Mock." #endif // Macro for referencing flags. This is public as we want the user to // use this syntax to reference Google Mock flags. +#define GMOCK_FLAG_NAME_(name) gmock_##name #define GMOCK_FLAG(name) FLAGS_gmock_##name -#if !defined(GMOCK_DECLARE_bool_) +// Pick a command line flags implementation. +#if GTEST_HAS_ABSL + +// Macros for defining flags. +#define GMOCK_DEFINE_bool_(name, default_val, doc) \ + ABSL_FLAG(bool, GMOCK_FLAG_NAME_(name), default_val, doc) +#define GMOCK_DEFINE_int32_(name, default_val, doc) \ + ABSL_FLAG(int32_t, GMOCK_FLAG_NAME_(name), default_val, doc) +#define GMOCK_DEFINE_string_(name, default_val, doc) \ + ABSL_FLAG(std::string, GMOCK_FLAG_NAME_(name), default_val, doc) // Macros for declaring flags. -#define GMOCK_DECLARE_bool_(name) \ - 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_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) \ namespace testing { \ GTEST_API_ bool GMOCK_FLAG(name) = (default_val); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + 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") + } \ + 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") -#endif // !defined(GMOCK_DECLARE_bool_) + } \ + 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") -#if !defined(GMOCK_FLAG_GET) #define GMOCK_FLAG_GET(name) ::testing::GMOCK_FLAG(name) #define GMOCK_FLAG_SET(name, value) (void)(::testing::GMOCK_FLAG(name) = value) -#endif // !defined(GMOCK_FLAG_GET) + +#endif // GTEST_HAS_ABSL #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ diff --git a/googlemock/src/gmock-cardinalities.cc b/googlemock/src/gmock-cardinalities.cc index 7463f438..92cde348 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 + #include // NOLINT #include #include + #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 6020736e..0a74841f 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 @@ -84,12 +83,11 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) { // We don't care about the current locale as the input is // guaranteed to be a valid C++ identifier name. const bool starts_new_word = IsUpper(*p) || - (!IsAlpha(prev_char) && IsLower(*p)) || - (!IsDigit(prev_char) && IsDigit(*p)); + (!IsAlpha(prev_char) && IsLower(*p)) || + (!IsDigit(prev_char) && IsDigit(*p)); if (IsAlNum(*p)) { - if (starts_new_word && result != "") - result += ' '; + if (starts_new_word && result != "") result += ' '; result += ToLower(*p); } } @@ -103,12 +101,9 @@ class GoogleTestFailureReporter : public FailureReporterInterface { public: void ReportFailure(FailureType type, const char* file, int line, const std::string& message) override { - AssertHelper(type == kFatal ? - TestPartResult::kFatalFailure : - TestPartResult::kNonFatalFailure, - file, - line, - message.c_str()) = Message(); + AssertHelper(type == kFatal ? TestPartResult::kFatalFailure + : TestPartResult::kNonFatalFailure, + file, line, message.c_str()) = Message(); if (type == kFatal) { posix::Abort(); } @@ -156,8 +151,7 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity) { // conservative. GTEST_API_ void Log(LogSeverity severity, const std::string& message, int stack_frames_to_skip) { - if (!LogIsVisible(severity)) - return; + if (!LogIsVisible(severity)) return; // Ensures that logs from different threads don't interleave. MutexLock l(&g_log_mutex); @@ -186,8 +180,8 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message, std::cout << "\n"; } std::cout << "Stack trace:\n" - << ::testing::internal::GetCurrentOsStackTraceExceptTop( - ::testing::UnitTest::GetInstance(), actual_to_skip); + << ::testing::internal::GetCurrentOsStackTraceExceptTop( + ::testing::UnitTest::GetInstance(), actual_to_skip); } std::cout << ::std::flush; } @@ -240,7 +234,7 @@ bool Base64Unescape(const std::string& encoded, std::string* decoded) { return false; } if (bit_pos == 0) { - dst |= src_bin << 2; + dst |= static_cast(src_bin << 2); bit_pos = 6; } else { dst |= static_cast(src_bin >> (bit_pos - 2)); diff --git a/googlemock/src/gmock-matchers.cc b/googlemock/src/gmock-matchers.cc index 873527b1..a8d04a6d 100644 --- a/googlemock/src/gmock-matchers.cc +++ b/googlemock/src/gmock-matchers.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 Matcher, Matcher, and diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index 4d7b83ed..f37a661e 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 @@ -42,6 +41,7 @@ #include #include #include +#include #include #include "gmock/gmock.h" @@ -49,15 +49,15 @@ #include "gtest/internal/gtest-port.h" #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC -# include // NOLINT +#include // NOLINT #endif // Silence C4800 (C4800: 'int *const ': forcing value // to bool 'true' or 'false') for MSVC 15 #ifdef _MSC_VER #if _MSC_VER == 1900 -# pragma warning(push) -# pragma warning(disable:4800) +#pragma warning(push) +#pragma warning(disable : 4800) #endif #endif @@ -195,11 +195,12 @@ void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const // Describes the state of the expectation (e.g. is it satisfied? // is it active?). - *os << " - " << (IsOverSaturated() ? "over-saturated" : - IsSaturated() ? "saturated" : - IsSatisfied() ? "satisfied" : "unsatisfied") - << " and " - << (is_retired() ? "retired" : "active"); + *os << " - " + << (IsOverSaturated() ? "over-saturated" + : IsSaturated() ? "saturated" + : IsSatisfied() ? "satisfied" + : "unsatisfied") + << " and " << (is_retired() ? "retired" : "active"); } // Checks the action count (i.e. the number of WillOnce() and @@ -242,13 +243,12 @@ void ExpectationBase::CheckActionCountIfNotDone() const ::std::stringstream ss; DescribeLocationTo(&ss); - ss << "Too " << (too_many ? "many" : "few") - << " actions specified in " << source_text() << "...\n" + ss << "Too " << (too_many ? "many" : "few") << " actions specified in " + << source_text() << "...\n" << "Expected to be "; cardinality().DescribeTo(&ss); - ss << ", but has " << (too_many ? "" : "only ") - << action_count << " WillOnce()" - << (action_count == 1 ? "" : "s"); + ss << ", but has " << (too_many ? "" : "only ") << action_count + << " WillOnce()" << (action_count == 1 ? "" : "s"); if (repeated_action_specified_) { ss << " and a WillRepeatedly()"; } @@ -372,143 +372,12 @@ const char* UntypedFunctionMockerBase::Name() const return name; } -// Calculates the result of invoking this mock function with the given -// arguments, prints it, and returns it. The caller is responsible -// for deleting the result. -UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith( - void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { - // See the definition of untyped_expectations_ for why access to it - // is unprotected here. - if (untyped_expectations_.size() == 0) { - // No expectation is set on this mock method - we have an - // uninteresting call. - - // We must get Google Mock's reaction on uninteresting calls - // made on this mock object BEFORE performing the action, - // because the action may DELETE the mock object and make the - // following expression meaningless. - const CallReaction reaction = - Mock::GetReactionOnUninterestingCalls(MockObject()); - - // True if and only if we need to print this call's arguments and return - // value. This definition must be kept in sync with - // the behavior of ReportUninterestingCall(). - const bool need_to_report_uninteresting_call = - // If the user allows this uninteresting call, we print it - // only when they want informational messages. - reaction == kAllow ? LogIsVisible(kInfo) : - // If the user wants this to be a warning, we print - // it only when they want to see warnings. - reaction == kWarn - ? LogIsVisible(kWarning) - : - // Otherwise, the user wants this to be an error, and we - // should always print detailed information in the error. - true; - - if (!need_to_report_uninteresting_call) { - // Perform the action without printing the call information. - return this->UntypedPerformDefaultAction( - untyped_args, "Function call: " + std::string(Name())); - } - - // Warns about the uninteresting call. - ::std::stringstream ss; - this->UntypedDescribeUninterestingCall(untyped_args, &ss); - - // Calculates the function result. - UntypedActionResultHolderBase* const result = - this->UntypedPerformDefaultAction(untyped_args, ss.str()); - - // Prints the function result. - if (result != nullptr) result->PrintAsActionResult(&ss); - - ReportUninterestingCall(reaction, ss.str()); - return result; - } - - bool is_excessive = false; - ::std::stringstream ss; - ::std::stringstream why; - ::std::stringstream loc; - const void* untyped_action = nullptr; - - // The UntypedFindMatchingExpectation() function acquires and - // releases g_gmock_mutex. - - const ExpectationBase* const untyped_expectation = - this->UntypedFindMatchingExpectation(untyped_args, &untyped_action, - &is_excessive, &ss, &why); - const bool found = untyped_expectation != nullptr; - - // True if and only if we need to print the call's arguments - // and return value. - // This definition must be kept in sync with the uses of Expect() - // and Log() in this function. - const bool need_to_report_call = - !found || is_excessive || LogIsVisible(kInfo); - if (!need_to_report_call) { - // Perform the action without printing the call information. - return untyped_action == nullptr - ? this->UntypedPerformDefaultAction(untyped_args, "") - : this->UntypedPerformAction(untyped_action, untyped_args); - } - - ss << " Function call: " << Name(); - this->UntypedPrintArgs(untyped_args, &ss); - - // In case the action deletes a piece of the expectation, we - // generate the message beforehand. - if (found && !is_excessive) { - untyped_expectation->DescribeLocationTo(&loc); - } - - UntypedActionResultHolderBase* result = nullptr; - - auto perform_action = [&] { - return untyped_action == nullptr - ? this->UntypedPerformDefaultAction(untyped_args, ss.str()) - : this->UntypedPerformAction(untyped_action, untyped_args); - }; - auto handle_failures = [&] { - ss << "\n" << why.str(); - - if (!found) { - // No expectation matches this call - reports a failure. - Expect(false, nullptr, -1, ss.str()); - } else if (is_excessive) { - // We had an upper-bound violation and the failure message is in ss. - Expect(false, untyped_expectation->file(), untyped_expectation->line(), - ss.str()); - } else { - // We had an expected call and the matching expectation is - // described in ss. - Log(kInfo, loc.str() + ss.str(), 2); - } - }; -#if GTEST_HAS_EXCEPTIONS - try { - result = perform_action(); - } catch (...) { - handle_failures(); - throw; - } -#else - result = perform_action(); -#endif - - if (result != nullptr) result->PrintAsActionResult(&ss); - handle_failures(); - return result; -} - // Returns an Expectation object that references and co-owns exp, // which must be an expectation on this mock function. Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { // See the definition of untyped_expectations_ for why access to it // is unprotected here. - for (UntypedExpectations::const_iterator it = - untyped_expectations_.begin(); + for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { if (it->get() == exp) { return Expectation(*it); @@ -528,8 +397,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()) { @@ -540,15 +408,15 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() } else if (!untyped_expectation->IsSatisfied()) { expectations_met = false; ::std::stringstream ss; - ss << "Actual function call count doesn't match " - << untyped_expectation->source_text() << "...\n"; + ss << "Actual function call count doesn't match " + << untyped_expectation->source_text() << "...\n"; // No need to show the source file location of the expectation // in the description, as the Expect() call that follows already // takes care of it. untyped_expectation->MaybeDescribeExtraMatcherTo(&ss); untyped_expectation->DescribeCallCountTo(&ss); - Expect(false, untyped_expectation->file(), - untyped_expectation->line(), ss.str()); + Expect(false, untyped_expectation->file(), untyped_expectation->line(), + ss.str()); } } @@ -635,7 +503,7 @@ class MockObjectRegistry { << state.first_used_test << ")"; } std::cout << " should be deleted but never is. Its address is @" - << it->first << "."; + << it->first << "."; leaked_count++; } if (leaked_count > 0) { @@ -669,58 +537,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 g_uninteresting_call_reaction; +std::unordered_map& +UninterestingCallReactionMap() { + static auto* map = new std::unordered_map; + 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(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) + return (UninterestingCallReactionMap().count( + reinterpret_cast(mock_obj)) == 0) ? internal::intToCallReaction( GMOCK_FLAG_GET(default_mock_behavior)) - : g_uninteresting_call_reaction[mock_obj]; + : UninterestingCallReactionMap()[reinterpret_cast( + mock_obj)]; } // Tells Google Mock to ignore mock_obj when checking for leaked mock @@ -875,8 +748,8 @@ Expectation::~Expectation() {} void Sequence::AddExpectation(const Expectation& expectation) const { if (*last_expectation_ != expectation) { if (last_expectation_->expectation_base() != nullptr) { - expectation.expectation_base()->immediate_prerequisites_ - += *last_expectation_; + expectation.expectation_base()->immediate_prerequisites_ += + *last_expectation_; } *last_expectation_ = expectation; } @@ -905,6 +778,6 @@ InSequence::~InSequence() { #ifdef _MSC_VER #if _MSC_VER == 1900 -# pragma warning(pop) +#pragma warning(pop) #endif #endif diff --git a/googlemock/src/gmock.cc b/googlemock/src/gmock.cc index a20aed80..5025656a 100644 --- a/googlemock/src/gmock.cc +++ b/googlemock/src/gmock.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 "gmock/gmock.h" + #include "gmock/internal/gmock-port.h" GMOCK_DEFINE_bool_(catch_leaked_mocks, true, diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index 18c500f6..b411c5ec 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.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 + #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -56,7 +56,7 @@ void loop() { RUN_ALL_TESTS(); } // https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library // // NOLINT #if GTEST_OS_WINDOWS_MOBILE -# include // NOLINT +#include // NOLINT GTEST_API_ int _tmain(int argc, TCHAR** argv) { #else diff --git a/googlemock/test/BUILD.bazel b/googlemock/test/BUILD.bazel index 004da12a..d4297c80 100644 --- a/googlemock/test/BUILD.bazel +++ b/googlemock/test/BUILD.bazel @@ -38,7 +38,7 @@ 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": [], diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index fc628937..215495ed 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -27,64 +27,230 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file tests the built-in actions. -// Silence C4100 (unreferenced formal parameter) for MSVC +// Silence C4100 (unreferenced formal parameter) and C4503 (decorated name +// length exceeded) for MSVC. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) +#pragma warning(disable : 4503) #if _MSC_VER == 1900 // and silence C4800 (C4800: 'int *const ': forcing value // to bool 'true' or 'false') for MSVC 15 -# pragma warning(disable:4800) +#pragma warning(disable : 4800) #endif #endif #include "gmock/gmock-actions.h" + #include +#include #include #include #include #include +#include + #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" +namespace testing { namespace { -using ::testing::_; -using ::testing::Action; -using ::testing::ActionInterface; -using ::testing::Assign; -using ::testing::ByMove; -using ::testing::ByRef; -using ::testing::DefaultValue; -using ::testing::DoAll; -using ::testing::DoDefault; -using ::testing::IgnoreResult; -using ::testing::Invoke; -using ::testing::InvokeWithoutArgs; -using ::testing::MakePolymorphicAction; -using ::testing::PolymorphicAction; -using ::testing::Return; -using ::testing::ReturnNew; -using ::testing::ReturnNull; -using ::testing::ReturnRef; -using ::testing::ReturnRefOfCopy; -using ::testing::ReturnRoundRobin; -using ::testing::SetArgPointee; -using ::testing::SetArgumentPointee; -using ::testing::Unused; -using ::testing::WithArgs; using ::testing::internal::BuiltInDefaultValue; -#if !GTEST_OS_WINDOWS_MOBILE -using ::testing::SetErrnoAndReturn; -#endif +TEST(TypeTraits, Negation) { + // Direct use with std types. + static_assert(std::is_base_of>::value, + ""); + + static_assert(std::is_base_of>::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>>::value, + ""); + + static_assert(std::is_base_of< + std::false_type, + internal::negation>>::value, + ""); + + static_assert(std::is_base_of< + std::false_type, + internal::negation>>::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 +struct MyFalse : std::integral_constant {}; + +template +struct MyTrue : std::integral_constant {}; + +TEST(TypeTraits, Conjunction) { + // Base case: always true. + static_assert(std::is_base_of>::value, + ""); + + // One predicate: inherits from that predicate, regardless of value. + static_assert( + std::is_base_of, internal::conjunction>>::value, + ""); + + static_assert( + std::is_base_of, internal::conjunction>>::value, ""); + + // Multiple predicates, with at least one false: inherits from that one. + static_assert( + std::is_base_of, internal::conjunction, MyFalse<1>, + MyTrue<2>>>::value, + ""); + + static_assert( + std::is_base_of, internal::conjunction, 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, internal::conjunction, MyFalse<1>, + Empty>>::value, + ""); + + // All predicates true: inherits from the last. + static_assert( + std::is_base_of, internal::conjunction, MyTrue<1>, + MyTrue<2>>>::value, + ""); +} + +TEST(TypeTraits, Disjunction) { + // Base case: always false. + static_assert( + std::is_base_of>::value, ""); + + // One predicate: inherits from that predicate, regardless of value. + static_assert( + std::is_base_of, internal::disjunction>>::value, + ""); + + static_assert( + std::is_base_of, internal::disjunction>>::value, ""); + + // Multiple predicates, with at least one true: inherits from that one. + static_assert( + std::is_base_of, internal::disjunction, MyTrue<1>, + MyFalse<2>>>::value, + ""); + + static_assert( + std::is_base_of, internal::disjunction, 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, internal::disjunction, MyTrue<1>, + Empty>>::value, + ""); + + // All predicates false: inherits from the last. + static_assert( + std::is_base_of, internal::disjunction, 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::value, ""); + static_assert(internal::is_callable_r::value, ""); + static_assert(internal::is_callable_r::value, ""); + static_assert(internal::is_callable_r::value, ""); + + static_assert(internal::is_callable_r::value, ""); + static_assert(internal::is_callable_r::value, ""); + static_assert(internal::is_callable_r::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::value, ""); + static_assert(!internal::is_callable_r::value, ""); + static_assert(!internal::is_callable_r::value, ""); + static_assert(!internal::is_callable_r::value, ""); + + static_assert(internal::is_callable_r::value, ""); + static_assert(internal::is_callable_r::value, ""); + static_assert(!internal::is_callable_r::value, ""); + + // It's not possible to provide other arguments. + static_assert(!internal::is_callable_r::value, ""); + static_assert(!internal::is_callable_r::value, ""); + + // In C++17 and above, where it's guaranteed that functions can return + // non-moveable objects, everything should work fine for non-moveable rsult + // types too. +#if defined(__cplusplus) && __cplusplus >= 201703L + { + struct NonMoveable { + NonMoveable() = default; + NonMoveable(NonMoveable&&) = delete; + }; + + static_assert(!std::is_move_constructible_v); + + struct Callable { + NonMoveable operator()() { return NonMoveable(); } + }; + + static_assert(internal::is_callable_r::value); + static_assert(internal::is_callable_r::value); + static_assert( + internal::is_callable_r::value); + + static_assert(!internal::is_callable_r::value); + static_assert(!internal::is_callable_r::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::value, ""); + static_assert(!internal::is_callable_r::value, ""); + static_assert(!internal::is_callable_r::value, ""); +} // Tests that BuiltInDefaultValue::Get() returns NULL. TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { @@ -114,17 +280,17 @@ TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) { #endif #endif EXPECT_EQ(0U, BuiltInDefaultValue::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT EXPECT_EQ(0U, BuiltInDefaultValue::Get()); EXPECT_EQ(0, BuiltInDefaultValue::Get()); EXPECT_EQ(0, BuiltInDefaultValue::Get()); - EXPECT_EQ(0U, BuiltInDefaultValue::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT + EXPECT_EQ(0U, BuiltInDefaultValue::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT EXPECT_EQ(0U, BuiltInDefaultValue::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue::Get()); EXPECT_EQ(0, BuiltInDefaultValue::Get()); } @@ -139,17 +305,17 @@ TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) { EXPECT_TRUE(BuiltInDefaultValue::Exists()); #endif EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue::Exists()); EXPECT_TRUE(BuiltInDefaultValue::Exists()); EXPECT_TRUE(BuiltInDefaultValue::Exists()); - EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue::Exists()); EXPECT_TRUE(BuiltInDefaultValue::Exists()); } @@ -167,13 +333,13 @@ TEST(BuiltInDefaultValueTest, BoolExists) { // Tests that BuiltInDefaultValue::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::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::Get() returns the same @@ -208,7 +374,6 @@ class MyNonDefaultConstructible { int value_; }; - TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) { EXPECT_TRUE(BuiltInDefaultValue::Exists()); } @@ -217,25 +382,19 @@ TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) { EXPECT_EQ(42, BuiltInDefaultValue::Get().value()); } - TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) { EXPECT_FALSE(BuiltInDefaultValue::Exists()); } // Tests that BuiltInDefaultValue::Get() aborts the program. TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) { - EXPECT_DEATH_IF_SUPPORTED({ - BuiltInDefaultValue::Get(); - }, ""); - EXPECT_DEATH_IF_SUPPORTED({ - BuiltInDefaultValue::Get(); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue::Get(); }, ""); + EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue::Get(); }, ""); } TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) { - EXPECT_DEATH_IF_SUPPORTED({ - BuiltInDefaultValue::Get(); - }, ""); + EXPECT_DEATH_IF_SUPPORTED( + { BuiltInDefaultValue::Get(); }, ""); } // Tests that DefaultValue::IsSet() is false initially. @@ -281,26 +440,22 @@ TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_EQ(0, DefaultValue::Get()); - EXPECT_DEATH_IF_SUPPORTED({ - DefaultValue::Get(); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ DefaultValue::Get(); }, + ""); } TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { EXPECT_TRUE(DefaultValue>::Exists()); EXPECT_TRUE(DefaultValue>::Get() == nullptr); - DefaultValue>::SetFactory([] { - return std::unique_ptr(new int(42)); - }); + DefaultValue>::SetFactory( + [] { return std::unique_ptr(new int(42)); }); EXPECT_TRUE(DefaultValue>::Exists()); std::unique_ptr i = DefaultValue>::Get(); EXPECT_EQ(42, *i); } // Tests that DefaultValue::Get() returns void. -TEST(DefaultValueTest, GetWorksForVoid) { - return DefaultValue::Get(); -} +TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue::Get(); } // Tests using DefaultValue with a reference type. @@ -348,12 +503,9 @@ TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_FALSE(DefaultValue::IsSet()); EXPECT_FALSE(DefaultValue::IsSet()); - EXPECT_DEATH_IF_SUPPORTED({ - DefaultValue::Get(); - }, ""); - EXPECT_DEATH_IF_SUPPORTED({ - DefaultValue::Get(); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ DefaultValue::Get(); }, ""); + EXPECT_DEATH_IF_SUPPORTED({ DefaultValue::Get(); }, + ""); } // Tests that ActionInterface can be implemented by defining the @@ -433,7 +585,7 @@ class IsNotZero : public ActionInterface { // NOLINT }; TEST(ActionTest, CanBeConvertedToOtherActionType) { - const Action a1(new IsNotZero); // NOLINT + const Action a1(new IsNotZero); // NOLINT const Action a2 = Action(a1); // NOLINT EXPECT_EQ(1, a2.Perform(std::make_tuple('a'))); EXPECT_EQ(0, a2.Perform(std::make_tuple('\0'))); @@ -525,24 +677,134 @@ TEST(ReturnTest, AcceptsStringLiteral) { EXPECT_EQ("world", a2.Perform(std::make_tuple())); } -// Test struct which wraps a vector of integers. Used in -// 'SupportsWrapperReturnType' test. -struct IntegerVectorWrapper { - std::vector * v; - IntegerVectorWrapper(std::vector& _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, implicitly convertible from it. + struct Result { + const std::vector* v; + Result(const std::vector& v) : v(&v) {} // NOLINT + }; -// Tests that Return() works when return type is a wrapper type. -TEST(ReturnTest, SupportsWrapperReturnType) { - // Initialize vector of integers. - std::vector v; - for (int i = 0; i < 5; ++i) v.push_back(i); + // 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 mock; + EXPECT_CALL(mock, Call) + .WillOnce(Return(std::vector{17, 19, 23})) + .WillRepeatedly(Return(std::vector{29, 31, 37})); - // 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 a = Return(v); - const std::vector& result = *(a.Perform(std::make_tuple()).v); - EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4)); + EXPECT_THAT(mock.AsStdFunction()(), + Field(&Result::v, Pointee(ElementsAre(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 x) : x(x) {} + explicit Out(const In&) : x(0) {} + }; + + struct In { + operator Out() const { return Out{19}; } // NOLINT + }; + + // Assumption check: the C++ language rules are such that a function that + // returns Out which uses In a return statement will use the implicit + // conversion path rather than the explicit constructor. + EXPECT_THAT([]() -> Out { return In(); }(), Field(&Out::x, 19)); + + // Return should work the same way: if the mock function's return type is Out + // and we feed Return an In value, then the Out should be created through the + // implicit conversion path rather than the explicit constructor. + MockFunction mock; + EXPECT_CALL(mock, Call).WillOnce(Return(In())); + EXPECT_THAT(mock.AsStdFunction()(), Field(&Out::x, 19)); +} + +// It should be possible to use Return(R) with a mock function result type U +// that is convertible from const R& but *not* R (such as +// std::reference_wrapper). This should work for both WillOnce and +// WillRepeatedly. +TEST(ReturnTest, ConversionRequiresConstLvalueReference) { + using R = int; + using U = std::reference_wrapper; + + static_assert(std::is_convertible::value, ""); + static_assert(!std::is_convertible::value, ""); + + MockFunction 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::value, ""); +#ifndef _MSC_VER + static_assert(!std::is_convertible::value, ""); +#endif + static_assert(!std::is_convertible::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>::value, ""); +#ifndef _MSC_VER + static_assert(!std::is_convertible>::value, ""); +#endif +} + +TEST(ReturnTest, MoveOnlyResultType) { + // Return should support move-only result types when used with WillOnce. + { + MockFunction()> mock; + EXPECT_CALL(mock, Call) + // NOLINTNEXTLINE + .WillOnce(Return(std::unique_ptr(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())), + Action()>>::value, + ""); } // Tests that Return(v) is covaraint. @@ -596,19 +858,6 @@ TEST(ReturnTest, ConvertsArgumentWhenConverted) { << "when performed."; } -class DestinationType {}; - -class SourceType { - public: - // Note: a non-const typecast operator. - operator DestinationType() { return DestinationType(); } -}; - -TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) { - SourceType s; - Action action(Return(s)); -} - // Tests that ReturnNull() returns NULL in a pointer-returning function. TEST(ReturnNullTest, WorksInPointerReturningFunction) { const Action a1 = ReturnNull(); @@ -648,7 +897,9 @@ TEST(ReturnRefTest, IsCovariant) { } template ()))> -bool CanCallReturnRef(T&&) { return true; } +bool CanCallReturnRef(T&&) { + return true; +} bool CanCallReturnRef(Unused) { return false; } // Tests that ReturnRef(v) is working with non-temporaries (T&) @@ -668,7 +919,7 @@ TEST(ReturnRefTest, WorksForNonTemporary) { // Tests that ReturnRef(v) is not working with temporaries (T&&) TEST(ReturnRefTest, DoesNotWorkForTemporary) { - auto scalar_value = []() -> int { return 123; }; + auto scalar_value = []() -> int { return 123; }; EXPECT_FALSE(CanCallReturnRef(scalar_value())); auto non_scalar_value = []() -> std::string { return "ABC"; }; @@ -747,15 +998,15 @@ class MockClass { int(const std::unique_ptr&, std::unique_ptr)); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass); + MockClass(const MockClass&) = delete; + MockClass& operator=(const MockClass&) = delete; }; // Tests that DoDefault() returns the built-in default value for the // return type by default. TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) { MockClass mock; - EXPECT_CALL(mock, IntFunc(_)) - .WillOnce(DoDefault()); + EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); EXPECT_EQ(0, mock.IntFunc(true)); } @@ -763,14 +1014,11 @@ TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) { // the process when there is no built-in default value for the return type. TEST(DoDefaultDeathTest, DiesForUnknowType) { MockClass mock; - EXPECT_CALL(mock, Foo()) - .WillRepeatedly(DoDefault()); + EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault()); #if GTEST_HAS_EXCEPTIONS EXPECT_ANY_THROW(mock.Foo()); #else - EXPECT_DEATH_IF_SUPPORTED({ - mock.Foo(); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, ""); #endif } @@ -782,16 +1030,13 @@ void VoidFunc(bool /* flag */) {} TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) { MockClass mock; EXPECT_CALL(mock, IntFunc(_)) - .WillRepeatedly(DoAll(Invoke(VoidFunc), - DoDefault())); + .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault())); // Ideally we should verify the error message as well. Sadly, // EXPECT_DEATH() can only capture stderr, while Google Mock's // errors are printed on stdout. Therefore we have to settle for // not verifying the message. - EXPECT_DEATH_IF_SUPPORTED({ - mock.IntFunc(true); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, ""); } // Tests that DoDefault() returns the default value set by @@ -799,8 +1044,7 @@ TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) { TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) { DefaultValue::Set(1); MockClass mock; - EXPECT_CALL(mock, IntFunc(_)) - .WillOnce(DoDefault()); + EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); EXPECT_EQ(1, mock.IntFunc(false)); DefaultValue::Clear(); } @@ -808,20 +1052,19 @@ TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) { // Tests that DoDefault() does the action specified by ON_CALL(). TEST(DoDefaultTest, DoesWhatOnCallSpecifies) { MockClass mock; - ON_CALL(mock, IntFunc(_)) - .WillByDefault(Return(2)); - EXPECT_CALL(mock, IntFunc(_)) - .WillOnce(DoDefault()); + ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2)); + EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); EXPECT_EQ(2, mock.IntFunc(false)); } // Tests that using DoDefault() in ON_CALL() leads to a run-time failure. TEST(DoDefaultTest, CannotBeUsedInOnCall) { MockClass mock; - EXPECT_NONFATAL_FAILURE({ // NOLINT - ON_CALL(mock, IntFunc(_)) - .WillByDefault(DoDefault()); - }, "DoDefault() cannot be used in ON_CALL()"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault()); + }, + "DoDefault() cannot be used in ON_CALL()"); } // Tests that SetArgPointee(v) sets the variable pointed to by @@ -868,7 +1111,7 @@ TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { a.Perform(std::make_tuple(&ptr)); EXPECT_STREQ(L"world", ptr); -# if GTEST_HAS_STD_WSTRING +#if GTEST_HAS_STD_WSTRING typedef void MyStringFunction(std::wstring*); Action a2 = SetArgPointee<0>(L"world"); @@ -876,7 +1119,7 @@ TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { a2.Perform(std::make_tuple(&str)); EXPECT_EQ(L"world", str); -# endif +#endif } // Tests that SetArgPointee() accepts a char pointer. @@ -907,7 +1150,7 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) { a.Perform(std::make_tuple(true, &ptr)); EXPECT_EQ(hi, ptr); -# if GTEST_HAS_STD_WSTRING +#if GTEST_HAS_STD_WSTRING typedef void MyStringFunction(bool, std::wstring*); wchar_t world_array[] = L"world"; @@ -916,7 +1159,7 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) { std::wstring str; a2.Perform(std::make_tuple(true, &str)); EXPECT_EQ(world_array, str); -# endif +#endif } // Tests that SetArgumentPointee(v) sets the variable pointed to by @@ -1079,6 +1322,159 @@ TEST(AssignTest, CompatibleTypes) { EXPECT_DOUBLE_EQ(5, x); } +// DoAll should support &&-qualified actions when used with WillOnce. +TEST(DoAll, SupportsRefQualifiedActions) { + struct InitialAction { + void operator()(const int arg) && { EXPECT_EQ(17, arg); } + }; + + struct FinalAction { + int operator()() && { return 19; } + }; + + MockFunction 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 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 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 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 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 mock; + EXPECT_CALL(mock, Call) + .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {})); + + Obj obj; + mock.AsStdFunction()(obj); + } + + { + struct InitialAction { + void operator()(Obj&) && {} + }; + + MockFunction 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 initial_action = [] {}; + const Action final_action = [] { return 17; }; + + MockFunction mock; + EXPECT_CALL(mock, Call) + .WillOnce(DoAll(initial_action, initial_action, final_action)) + .WillRepeatedly(DoAll(initial_action, initial_action, final_action)); + + EXPECT_EQ(17, mock.AsStdFunction()()); + + // With &&-qualified and move-only final action. + { + struct FinalAction { + FinalAction() = default; + FinalAction(FinalAction&&) = default; + + int operator()() && { return 17; } + }; + + EXPECT_CALL(mock, Call) + .WillOnce(DoAll(initial_action, initial_action, FinalAction{})); + + EXPECT_EQ(17, mock.AsStdFunction()()); + } +} // Tests using WithArgs and with an action that takes 1 argument. TEST(WithArgsTest, OneArg) { @@ -1175,8 +1571,29 @@ TEST(WithArgsTest, ReturnReference) { TEST(WithArgsTest, InnerActionWithConversion) { Action inner = [] { return nullptr; }; - Action a = testing::WithoutArgs(inner); - EXPECT_EQ(nullptr, a.Perform(std::make_tuple(1.1))); + + MockFunction 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 mock; + EXPECT_CALL(mock, Call).WillOnce(WithArg<1>(SomeAction{})); + EXPECT_EQ(19, mock.AsStdFunction()(0, 17)); } #if !GTEST_OS_WINDOWS_MOBILE @@ -1235,7 +1652,7 @@ TEST(ByRefTest, IsCopyable) { TEST(ByRefTest, ConstValue) { const int n = 0; // int& ref = ByRef(n); // This shouldn't compile - we have a - // negative compilation test to catch it. + // negative compilation test to catch it. const int& const_ref = ByRef(n); EXPECT_EQ(&n, &const_ref); } @@ -1260,7 +1677,7 @@ TEST(ByRefTest, ExplicitType) { EXPECT_EQ(&n, &r1); // ByRef(n); // This shouldn't compile - we have a negative - // compilation test to catch it. + // compilation test to catch it. Derived d; Derived& r2 = ByRef(d); @@ -1375,9 +1792,10 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) { MockClass mock; std::unique_ptr i(new int(19)); EXPECT_CALL(mock_function, Call()); - EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll( - InvokeWithoutArgs(&mock_function, &testing::MockFunction::Call), - Return(ByMove(std::move(i))))); + EXPECT_CALL(mock, MakeUnique()) + .WillOnce(DoAll(InvokeWithoutArgs(&mock_function, + &testing::MockFunction::Call), + Return(ByMove(std::move(i))))); std::unique_ptr result1 = mock.MakeUnique(); EXPECT_EQ(19, *result1); @@ -1387,9 +1805,8 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) { MockClass mock; // Check default value - DefaultValue>::SetFactory([] { - return std::unique_ptr(new int(42)); - }); + DefaultValue>::SetFactory( + [] { return std::unique_ptr(new int(42)); }); EXPECT_EQ(42, *mock.MakeUnique()); EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource)); @@ -1449,6 +1866,178 @@ TEST(MockMethodTest, CanTakeMoveOnlyValue) { EXPECT_EQ(42, *saved); } +// It should be possible to use callables with an &&-qualified call operator +// with WillOnce, since they will be called only once. This allows actions to +// contain and manipulate move-only types. +TEST(MockMethodTest, ActionHasRvalueRefQualifiedCallOperator) { + struct Return17 { + int operator()() && { return 17; } + }; + + // Action is directly compatible with mocked function type. + { + MockFunction mock; + EXPECT_CALL(mock, Call).WillOnce(Return17()); + + EXPECT_EQ(17, mock.AsStdFunction()()); + } + + // Action doesn't want mocked function arguments. + { + MockFunction 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 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 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 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 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 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 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 + static constexpr bool CheckArgs() { + static_assert(sizeof...(Args) == 1, ""); + return true; + } + + template ()> + 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 mock; + EXPECT_CALL(mock, Call) + .WillOnce(StaticAssertSingleArgument{}) + .WillRepeatedly(StaticAssertSingleArgument{}); + + EXPECT_EQ(17, mock.AsStdFunction()(0)); + EXPECT_EQ(17, mock.AsStdFunction()(0)); +} + +struct ActionWithTemplatedConversionOperators { + template + operator OnceAction() && { // NOLINT + return [] { return 17; }; + } + + template + operator Action() 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 mock; + EXPECT_CALL(mock, Call) + .WillOnce(ActionWithTemplatedConversionOperators{}) + .WillRepeatedly(ActionWithTemplatedConversionOperators{}); + + EXPECT_EQ(17, mock.AsStdFunction()()); + EXPECT_EQ(19, mock.AsStdFunction()()); +} // Tests for std::function based action. @@ -1463,7 +2052,9 @@ int Deref(std::unique_ptr ptr) { return *ptr; } struct Double { template - T operator()(T t) { return 2 * t; } + T operator()(T t) { + return 2 * t; + } }; std::unique_ptr UniqueInt(int i) { @@ -1532,8 +2123,9 @@ TEST(FunctorActionTest, TypeConversion) { TEST(FunctorActionTest, UnusedArguments) { // Verify that users can ignore uninteresting arguments. - Action a = - [](int i, Unused, Unused) { return 2 * i; }; + Action a = [](int i, Unused, Unused) { + return 2 * i; + }; std::tuple dummy = std::make_tuple(3, 7.3, 9.44); EXPECT_EQ(6, a.Perform(dummy)); } @@ -1552,9 +2144,7 @@ TEST(MoveOnlyArgumentsTest, ReturningActions) { EXPECT_EQ(x, 3); } -ACTION(ReturnArity) { - return std::tuple_size::value; -} +ACTION(ReturnArity) { return std::tuple_size::value; } TEST(ActionMacro, LargeArity) { EXPECT_EQ( @@ -1573,11 +2163,5 @@ TEST(ActionMacro, LargeArity) { 14, 15, 16, 17, 18, 19))); } -} // Unnamed namespace - -#ifdef _MSC_VER -#if _MSC_VER == 1900 -# pragma warning(pop) -#endif -#endif - +} // namespace +} // namespace testing diff --git a/googlemock/test/gmock-cardinalities_test.cc b/googlemock/test/gmock-cardinalities_test.cc index ca97cae2..cdd99563 100644 --- a/googlemock/test/gmock-cardinalities_test.cc +++ b/googlemock/test/gmock-cardinalities_test.cc @@ -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. - // Google Mock - a framework for writing C++ mock classes. // // This file tests the built-in cardinalities. #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" namespace { @@ -55,13 +54,12 @@ class MockFoo { MOCK_METHOD0(Bar, int()); // NOLINT private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); + MockFoo(const MockFoo&) = delete; + MockFoo& operator=(const MockFoo&) = delete; }; // Tests that Cardinality objects can be default constructed. -TEST(CardinalityTest, IsDefaultConstructable) { - Cardinality c; -} +TEST(CardinalityTest, IsDefaultConstructable) { Cardinality c; } // Tests that Cardinality objects are copyable. TEST(CardinalityTest, IsCopyable) { @@ -119,8 +117,7 @@ TEST(AnyNumber, Works) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", ss.str()); } TEST(AnyNumberTest, HasCorrectBounds) { @@ -132,9 +129,11 @@ TEST(AnyNumberTest, HasCorrectBounds) { // Tests AtLeast(n). TEST(AtLeastTest, OnNegativeNumber) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - AtLeast(-1); - }, "The invocation lower bound must be >= 0"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + AtLeast(-1); + }, + "The invocation lower bound must be >= 0"); } TEST(AtLeastTest, OnZero) { @@ -147,8 +146,7 @@ TEST(AtLeastTest, OnZero) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", ss.str()); } TEST(AtLeastTest, OnPositiveNumber) { @@ -164,18 +162,15 @@ TEST(AtLeastTest, OnPositiveNumber) { stringstream ss1; AtLeast(1).DescribeTo(&ss1); - EXPECT_PRED_FORMAT2(IsSubstring, "at least once", - ss1.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "at least once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); - EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", - ss2.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", ss2.str()); stringstream ss3; AtLeast(3).DescribeTo(&ss3); - EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", - ss3.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", ss3.str()); } TEST(AtLeastTest, HasCorrectBounds) { @@ -187,9 +182,11 @@ TEST(AtLeastTest, HasCorrectBounds) { // Tests AtMost(n). TEST(AtMostTest, OnNegativeNumber) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - AtMost(-1); - }, "The invocation upper bound must be >= 0"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + AtMost(-1); + }, + "The invocation upper bound must be >= 0"); } TEST(AtMostTest, OnZero) { @@ -202,8 +199,7 @@ TEST(AtMostTest, OnZero) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "never called", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(AtMostTest, OnPositiveNumber) { @@ -219,18 +215,15 @@ TEST(AtMostTest, OnPositiveNumber) { stringstream ss1; AtMost(1).DescribeTo(&ss1); - EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", - ss1.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); - EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", - ss2.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss2.str()); stringstream ss3; AtMost(3).DescribeTo(&ss3); - EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", - ss3.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", ss3.str()); } TEST(AtMostTest, HasCorrectBounds) { @@ -242,22 +235,28 @@ TEST(AtMostTest, HasCorrectBounds) { // Tests Between(m, n). TEST(BetweenTest, OnNegativeStart) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - Between(-1, 2); - }, "The invocation lower bound must be >= 0, but is actually -1"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + Between(-1, 2); + }, + "The invocation lower bound must be >= 0, but is actually -1"); } TEST(BetweenTest, OnNegativeEnd) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - Between(1, -2); - }, "The invocation upper bound must be >= 0, but is actually -2"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + Between(1, -2); + }, + "The invocation upper bound must be >= 0, but is actually -2"); } TEST(BetweenTest, OnStartBiggerThanEnd) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - Between(2, 1); - }, "The invocation upper bound (1) must be >= " - "the invocation lower bound (2)"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + Between(2, 1); + }, + "The invocation upper bound (1) must be >= " + "the invocation lower bound (2)"); } TEST(BetweenTest, OnZeroStartAndZeroEnd) { @@ -271,8 +270,7 @@ TEST(BetweenTest, OnZeroStartAndZeroEnd) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "never called", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(BetweenTest, OnZeroStartAndNonZeroEnd) { @@ -289,8 +287,7 @@ TEST(BetweenTest, OnZeroStartAndNonZeroEnd) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss.str()); } TEST(BetweenTest, OnSameStartAndEnd) { @@ -307,8 +304,7 @@ TEST(BetweenTest, OnSameStartAndEnd) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss.str()); } TEST(BetweenTest, OnDifferentStartAndEnd) { @@ -328,8 +324,7 @@ TEST(BetweenTest, OnDifferentStartAndEnd) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", ss.str()); } TEST(BetweenTest, HasCorrectBounds) { @@ -341,9 +336,11 @@ TEST(BetweenTest, HasCorrectBounds) { // Tests Exactly(n). TEST(ExactlyTest, OnNegativeNumber) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - Exactly(-1); - }, "The invocation lower bound must be >= 0"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + Exactly(-1); + }, + "The invocation lower bound must be >= 0"); } TEST(ExactlyTest, OnZero) { @@ -356,8 +353,7 @@ TEST(ExactlyTest, OnZero) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "never called", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(ExactlyTest, OnPositiveNumber) { @@ -370,18 +366,15 @@ TEST(ExactlyTest, OnPositiveNumber) { stringstream ss1; Exactly(1).DescribeTo(&ss1); - EXPECT_PRED_FORMAT2(IsSubstring, "called once", - ss1.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); - EXPECT_PRED_FORMAT2(IsSubstring, "called twice", - ss2.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called twice", ss2.str()); stringstream ss3; Exactly(3).DescribeTo(&ss3); - EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", - ss3.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss3.str()); } TEST(ExactlyTest, HasCorrectBounds) { diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index cf76fa99..286115fe 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -27,6 +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. +// Silence C4503 (decorated name length exceeded) for MSVC. +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4503) +#endif // Google Mock - a framework for writing C++ mock classes. // @@ -37,7 +42,7 @@ // MSDN says the header file to be included for STDMETHOD is BaseTyps.h but // we are getting compiler errors if we use basetyps.h, hence including // objbase.h for definition of STDMETHOD. -# include +#include #endif // GTEST_OS_WINDOWS #include @@ -65,7 +70,7 @@ using testing::Return; using testing::ReturnRef; using testing::TypedEq; -template +template class TemplatedCopyable { public: TemplatedCopyable() {} @@ -82,7 +87,7 @@ class FooInterface { virtual int Nullary() = 0; virtual bool Unary(int x) = 0; - virtual long Binary(short x, int y) = 0; // NOLINT + virtual long Binary(short x, int y) = 0; // NOLINT virtual int Decimal(bool b, char c, short d, int e, long f, // NOLINT float g, double h, unsigned i, char* j, const std::string& k) = 0; @@ -133,8 +138,8 @@ class FooInterface { // signature. This was fixed in Visual Studio 2008. However, the compiler // still emits a warning that alerts about this change in behavior. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable : 4373) +#pragma warning(push) +#pragma warning(disable : 4373) #endif class MockFoo : public FooInterface { public: @@ -203,7 +208,8 @@ class MockFoo : public FooInterface { MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&&), override)); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); + MockFoo(const MockFoo&) = delete; + MockFoo& operator=(const MockFoo&) = delete; }; class LegacyMockFoo : public FooInterface { @@ -275,11 +281,12 @@ class LegacyMockFoo : public FooInterface { int RefQualifiedOverloaded() && override { return 0; } private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockFoo); + LegacyMockFoo(const LegacyMockFoo&) = delete; + LegacyMockFoo& operator=(const LegacyMockFoo&) = delete; }; #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif template @@ -493,7 +500,8 @@ class MockB { MOCK_METHOD(void, DoB, ()); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB); + MockB(const MockB&) = delete; + MockB& operator=(const MockB&) = delete; }; class LegacyMockB { @@ -503,7 +511,8 @@ class LegacyMockB { MOCK_METHOD0(DoB, void()); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockB); + LegacyMockB(const LegacyMockB&) = delete; + LegacyMockB& operator=(const LegacyMockB&) = delete; }; template @@ -558,7 +567,8 @@ class MockStack : public StackInterface { MOCK_METHOD((std::map), ReturnTypeWithComma, (int), (const)); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack); + MockStack(const MockStack&) = delete; + MockStack& operator=(const MockStack&) = delete; }; template @@ -576,7 +586,8 @@ class LegacyMockStack : public StackInterface { MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map(int)); // NOLINT private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStack); + LegacyMockStack(const LegacyMockStack&) = delete; + LegacyMockStack& operator=(const LegacyMockStack&) = delete; }; template @@ -595,10 +606,8 @@ TYPED_TEST(TemplateMockTest, Works) { .WillOnce(Return(0)); EXPECT_CALL(mock, Push(_)); int n = 5; - EXPECT_CALL(mock, GetTop()) - .WillOnce(ReturnRef(n)); - EXPECT_CALL(mock, Pop()) - .Times(AnyNumber()); + EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n)); + EXPECT_CALL(mock, Pop()).Times(AnyNumber()); EXPECT_EQ(0, mock.GetSize()); mock.Push(5); @@ -612,10 +621,8 @@ TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) { TypeParam mock; const std::map a_map; - EXPECT_CALL(mock, ReturnTypeWithComma()) - .WillOnce(Return(a_map)); - EXPECT_CALL(mock, ReturnTypeWithComma(1)) - .WillOnce(Return(a_map)); + EXPECT_CALL(mock, ReturnTypeWithComma()).WillOnce(Return(a_map)); + EXPECT_CALL(mock, ReturnTypeWithComma(1)).WillOnce(Return(a_map)); EXPECT_EQ(a_map, mock.ReturnTypeWithComma()); EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1)); @@ -650,7 +657,8 @@ class MockStackWithCallType : public StackInterfaceWithCallType { (Calltype(STDMETHODCALLTYPE), override, const)); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType); + MockStackWithCallType(const MockStackWithCallType&) = delete; + MockStackWithCallType& operator=(const MockStackWithCallType&) = delete; }; template @@ -664,7 +672,9 @@ class LegacyMockStackWithCallType : public StackInterfaceWithCallType { MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&()); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStackWithCallType); + LegacyMockStackWithCallType(const LegacyMockStackWithCallType&) = delete; + LegacyMockStackWithCallType& operator=(const LegacyMockStackWithCallType&) = + delete; }; template @@ -685,10 +695,8 @@ TYPED_TEST(TemplateMockTestWithCallType, Works) { .WillOnce(Return(0)); EXPECT_CALL(mock, Push(_)); int n = 5; - EXPECT_CALL(mock, GetTop()) - .WillOnce(ReturnRef(n)); - EXPECT_CALL(mock, Pop()) - .Times(AnyNumber()); + EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n)); + EXPECT_CALL(mock, Pop()).Times(AnyNumber()); EXPECT_EQ(0, mock.GetSize()); mock.Push(5); @@ -716,7 +724,9 @@ class MockOverloadedOnArgNumber { MY_MOCK_METHODS1_; private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber); + MockOverloadedOnArgNumber(const MockOverloadedOnArgNumber&) = delete; + MockOverloadedOnArgNumber& operator=(const MockOverloadedOnArgNumber&) = + delete; }; class LegacyMockOverloadedOnArgNumber { @@ -726,7 +736,10 @@ class LegacyMockOverloadedOnArgNumber { LEGACY_MY_MOCK_METHODS1_; private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockOverloadedOnArgNumber); + LegacyMockOverloadedOnArgNumber(const LegacyMockOverloadedOnArgNumber&) = + delete; + LegacyMockOverloadedOnArgNumber& operator=( + const LegacyMockOverloadedOnArgNumber&) = delete; }; template @@ -747,9 +760,9 @@ TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) { EXPECT_TRUE(mock.Overloaded(true, 1)); } -#define MY_MOCK_METHODS2_ \ - MOCK_CONST_METHOD1(Overloaded, int(int n)); \ - MOCK_METHOD1(Overloaded, int(int n)) +#define MY_MOCK_METHODS2_ \ + MOCK_CONST_METHOD1(Overloaded, int(int n)); \ + MOCK_METHOD1(Overloaded, int(int n)) class MockOverloadedOnConstness { public: @@ -758,7 +771,9 @@ class MockOverloadedOnConstness { MY_MOCK_METHODS2_; private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnConstness); + MockOverloadedOnConstness(const MockOverloadedOnConstness&) = delete; + MockOverloadedOnConstness& operator=(const MockOverloadedOnConstness&) = + delete; }; TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) { @@ -779,9 +794,7 @@ TEST(MockMethodMockFunctionTest, WorksForVoidNullary) { TEST(MockMethodMockFunctionTest, WorksForNonVoidNullary) { MockFunction foo; - EXPECT_CALL(foo, Call()) - .WillOnce(Return(1)) - .WillOnce(Return(2)); + EXPECT_CALL(foo, Call()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, foo.Call()); EXPECT_EQ(2, foo.Call()); } @@ -794,19 +807,17 @@ TEST(MockMethodMockFunctionTest, WorksForVoidUnary) { TEST(MockMethodMockFunctionTest, WorksForNonVoidBinary) { MockFunction 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 foo; + MockFunction + foo; EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _)) .WillOnce(Return(1)) .WillOnce(Return(2)); @@ -816,9 +827,7 @@ TEST(MockMethodMockFunctionTest, WorksFor10Arguments) { TEST(MockMethodMockFunctionTest, AsStdFunction) { MockFunction foo; - auto call = [](const std::function &f, int i) { - return f(i); - }; + auto call = [](const std::function& f, int i) { return f(i); }; EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1)); EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2)); EXPECT_EQ(-1, call(foo.AsStdFunction(), 1)); @@ -836,10 +845,8 @@ TEST(MockMethodMockFunctionTest, AsStdFunctionReturnsReference) { } TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) { - MockFunction foo; - auto call = [](const std::function &f, int &i) { - return f(i); - }; + MockFunction foo; + auto call = [](const std::function& f, int& i) { return f(i); }; int i = 42; EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1)); EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); @@ -888,8 +895,7 @@ TYPED_TEST( } template -struct AlternateCallable { -}; +struct AlternateCallable {}; TYPED_TEST(MockMethodMockFunctionSignatureTest, IsMockFunctionTemplateArgumentDeducedForAlternateCallable) { @@ -898,16 +904,14 @@ TYPED_TEST(MockMethodMockFunctionSignatureTest, EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo(foo)); } -TYPED_TEST( - MockMethodMockFunctionSignatureTest, - IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) { +TYPED_TEST(MockMethodMockFunctionSignatureTest, + IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) { using ForRawSignature = decltype(&MockFunction::Call); using ForStdFunction = decltype(&MockFunction>::Call); EXPECT_TRUE((std::is_same::value)); } - struct MockMethodSizes0 { MOCK_METHOD(void, func, ()); }; @@ -925,22 +929,21 @@ struct MockMethodSizes4 { }; struct LegacyMockMethodSizes0 { - MOCK_METHOD0(func, void()); + MOCK_METHOD0(func, void()); }; struct LegacyMockMethodSizes1 { - MOCK_METHOD1(func, void(int)); + MOCK_METHOD1(func, void(int)); }; struct LegacyMockMethodSizes2 { - MOCK_METHOD2(func, void(int, int)); + MOCK_METHOD2(func, void(int, int)); }; struct LegacyMockMethodSizes3 { - MOCK_METHOD3(func, void(int, int, int)); + MOCK_METHOD3(func, void(int, int, int)); }; struct LegacyMockMethodSizes4 { - MOCK_METHOD4(func, void(int, int, int, int)); + MOCK_METHOD4(func, void(int, int, int, int)); }; - TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2)); diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc index 800ee8ad..932bece5 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. @@ -58,7 +57,7 @@ #undef GTEST_IMPLEMENTATION_ #if GTEST_OS_CYGWIN -# include // For ssize_t. NOLINT +#include // For ssize_t. NOLINT #endif namespace proto2 { @@ -155,19 +154,19 @@ TEST(KindOfTest, Bool) { } TEST(KindOfTest, Integer) { - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN // ssize_t is not defined on Windows and possibly some other OSes. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); // NOLINT @@ -175,15 +174,15 @@ TEST(KindOfTest, Integer) { } TEST(KindOfTest, FloatingPoint) { - EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float)); // NOLINT - EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double)); // NOLINT + EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float)); // NOLINT + EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double)); // NOLINT EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double)); // NOLINT } TEST(KindOfTest, Other) { - EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*)); // NOLINT + EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*)); // NOLINT EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**)); // NOLINT - EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base)); // NOLINT + EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base)); // NOLINT } // Tests LosslessArithmeticConvertible. @@ -214,26 +213,26 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) { EXPECT_TRUE((LosslessArithmeticConvertible::value)); // Unsigned => larger unsigned is fine. - EXPECT_TRUE((LosslessArithmeticConvertible< - unsigned short, uint64_t>::value)); // NOLINT + EXPECT_TRUE((LosslessArithmeticConvertible::value)); // NOLINT // Signed => unsigned is not fine. - EXPECT_FALSE((LosslessArithmeticConvertible< - short, uint64_t>::value)); // NOLINT - EXPECT_FALSE((LosslessArithmeticConvertible< - signed char, unsigned int>::value)); // NOLINT + EXPECT_FALSE( + (LosslessArithmeticConvertible::value)); // NOLINT + EXPECT_FALSE((LosslessArithmeticConvertible::value)); // NOLINT // Same size and same signedness: fine too. - EXPECT_TRUE((LosslessArithmeticConvertible< - unsigned char, unsigned char>::value)); + EXPECT_TRUE( + (LosslessArithmeticConvertible::value)); EXPECT_TRUE((LosslessArithmeticConvertible::value)); EXPECT_TRUE((LosslessArithmeticConvertible::value)); - EXPECT_TRUE((LosslessArithmeticConvertible< - unsigned long, unsigned long>::value)); // NOLINT + EXPECT_TRUE((LosslessArithmeticConvertible::value)); // NOLINT // Same size, different signedness: not fine. - EXPECT_FALSE((LosslessArithmeticConvertible< - unsigned char, signed char>::value)); + EXPECT_FALSE( + (LosslessArithmeticConvertible::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); @@ -248,8 +247,8 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) { // the format of the latter is implementation-defined. EXPECT_FALSE((LosslessArithmeticConvertible::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); - EXPECT_FALSE((LosslessArithmeticConvertible< - short, long double>::value)); // NOLINT + EXPECT_FALSE( + (LosslessArithmeticConvertible::value)); // NOLINT } TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) { @@ -277,7 +276,7 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) { EXPECT_FALSE((LosslessArithmeticConvertible::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::value)); @@ -296,7 +295,7 @@ TEST(TupleMatchesTest, WorksForSize0) { } TEST(TupleMatchesTest, WorksForSize1) { - std::tuple > matchers(Eq(1)); + std::tuple> matchers(Eq(1)); std::tuple values1(1), values2(2); EXPECT_TRUE(TupleMatches(matchers, values1)); @@ -304,7 +303,7 @@ TEST(TupleMatchesTest, WorksForSize1) { } TEST(TupleMatchesTest, WorksForSize2) { - std::tuple, Matcher > matchers(Eq(1), Eq('a')); + std::tuple, Matcher> matchers(Eq(1), Eq('a')); std::tuple values1(1, 'a'), values2(1, 'b'), values3(2, 'a'), values4(2, 'b'); @@ -317,7 +316,7 @@ TEST(TupleMatchesTest, WorksForSize2) { TEST(TupleMatchesTest, WorksForSize5) { std::tuple, Matcher, Matcher, Matcher, // NOLINT - Matcher > + Matcher> matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi")); std::tuple // NOLINT values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"), @@ -336,13 +335,10 @@ TEST(AssertTest, SucceedsOnTrue) { // Tests that Assert(false, ...) generates a fatal failure. TEST(AssertTest, FailsFatallyOnFalse) { - EXPECT_DEATH_IF_SUPPORTED({ - Assert(false, __FILE__, __LINE__, "This should fail."); - }, ""); + EXPECT_DEATH_IF_SUPPORTED( + { Assert(false, __FILE__, __LINE__, "This should fail."); }, ""); - EXPECT_DEATH_IF_SUPPORTED({ - Assert(false, __FILE__, __LINE__); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, ""); } // Tests that Expect(true, ...) succeeds. @@ -353,13 +349,17 @@ 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(). @@ -404,11 +404,11 @@ void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity, 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()); } @@ -455,13 +455,13 @@ TEST(LogTest, NoSkippingStackFrameInOptMode) { EXPECT_THAT(log, HasSubstr(expected_message)); int skip_count = atoi(log.substr(expected_message.size()).c_str()); -# if defined(NDEBUG) +#if defined(NDEBUG) // In opt mode, no stack frame should be skipped. const int expected_skip_count = 0; -# else +#else // In dbg mode, the stack frames should be skipped. const int expected_skip_count = 100; -# endif +#endif // Note that each inner implementation layer will +1 the number to remove // itself from the trace. This means that the value is a little higher than @@ -503,7 +503,7 @@ TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) { // Verifies that Log() behaves correctly for the given verbosity level // and log severity. -std::string GrabOutput(void(*logger)(), const char* verbosity) { +std::string GrabOutput(void (*logger)(), const char* verbosity) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, verbosity); CaptureStdout(); @@ -538,7 +538,7 @@ TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) { // Verifies that EXPECT_CALL doesn't log // if the --gmock_verbose flag is set to "error". -TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) { +TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) { EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str()); } @@ -582,9 +582,9 @@ TEST(OnCallTest, LogsAnythingArgument) { TEST(StlContainerViewTest, WorksForStlContainer) { StaticAssertTypeEq, - StlContainerView >::type>(); + StlContainerView>::type>(); StaticAssertTypeEq&, - StlContainerView >::const_reference>(); + StlContainerView>::const_reference>(); typedef std::vector Chars; Chars v1; @@ -597,17 +597,16 @@ TEST(StlContainerViewTest, WorksForStlContainer) { } TEST(StlContainerViewTest, WorksForStaticNativeArray) { - StaticAssertTypeEq, - StlContainerView::type>(); + StaticAssertTypeEq, StlContainerView::type>(); StaticAssertTypeEq, - StlContainerView::type>(); + StlContainerView::type>(); StaticAssertTypeEq, - StlContainerView::type>(); + StlContainerView::type>(); StaticAssertTypeEq, - StlContainerView::const_reference>(); + StlContainerView::const_reference>(); - int a1[3] = { 0, 1, 2 }; + int a1[3] = {0, 1, 2}; NativeArray a2 = StlContainerView::ConstReference(a1); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); @@ -625,24 +624,24 @@ TEST(StlContainerViewTest, WorksForStaticNativeArray) { TEST(StlContainerViewTest, WorksForDynamicNativeArray) { StaticAssertTypeEq, - StlContainerView >::type>(); + StlContainerView>::type>(); StaticAssertTypeEq< NativeArray, - StlContainerView, int> >::type>(); + StlContainerView, int>>::type>(); StaticAssertTypeEq< const NativeArray, - StlContainerView >::const_reference>(); + StlContainerView>::const_reference>(); - int a1[3] = { 0, 1, 2 }; + int a1[3] = {0, 1, 2}; const int* const p1 = a1; NativeArray a2 = - StlContainerView >::ConstReference( + StlContainerView>::ConstReference( std::make_tuple(p1, 3)); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); - const NativeArray a3 = StlContainerView >::Copy( + const NativeArray a3 = StlContainerView>::Copy( std::make_tuple(static_cast(a1), 3)); ASSERT_EQ(3U, a3.size()); EXPECT_EQ(0, a3.begin()[0]); diff --git a/googlemock/test/gmock-matchers-arithmetic_test.cc b/googlemock/test/gmock-matchers-arithmetic_test.cc new file mode 100644 index 00000000..a4c1def6 --- /dev/null +++ b/googlemock/test/gmock-matchers-arithmetic_test.cc @@ -0,0 +1,1517 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file tests some commonly used argument matchers. + +// Silence warning C4244: 'initializing': conversion from 'int' to 'short', +// possible loss of data and C4100, unreferenced local parameter +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4244) +#pragma warning(disable : 4100) +#endif + +#include "test/gmock-matchers_test.h" + +namespace testing { +namespace gmock_matchers_test { +namespace { + +typedef ::std::tuple Tuple2; // NOLINT + +// Tests that Eq() matches a 2-tuple where the first field == the +// second field. +TEST(Eq2Test, MatchesEqualArguments) { + Matcher 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 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 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 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 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 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 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 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 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 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 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 m = Ne(); + EXPECT_EQ("are an unequal pair", Describe(m)); +} + +TEST(PairMatchBaseTest, WorksWithMoveOnly) { + using Pointers = std::tuple, std::unique_ptr>; + Matcher 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::quiet_NaN(); + float other_nan = std::nanf("1"); + float real_value = 1.0f; + + Matcher m = IsNan(); + EXPECT_TRUE(m.Matches(quiet_nan)); + EXPECT_TRUE(m.Matches(other_nan)); + EXPECT_FALSE(m.Matches(real_value)); + + Matcher 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 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::quiet_NaN(); + double other_nan = std::nan("1"); + double real_value = 1.0; + + Matcher m = IsNan(); + EXPECT_TRUE(m.Matches(quiet_nan)); + EXPECT_TRUE(m.Matches(other_nan)); + EXPECT_FALSE(m.Matches(real_value)); + + Matcher 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 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::quiet_NaN(); + long double other_nan = std::nan("1"); + long double real_value = 1.0; + + Matcher m = IsNan(); + EXPECT_TRUE(m.Matches(quiet_nan)); + EXPECT_TRUE(m.Matches(other_nan)); + EXPECT_FALSE(m.Matches(real_value)); + + Matcher 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 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 mf = Not(IsNan()); + EXPECT_FALSE(mf.Matches(std::numeric_limits::quiet_NaN())); + EXPECT_FALSE(mf.Matches(std::nanf("1"))); + EXPECT_TRUE(mf.Matches(1.0)); + + Matcher md = Not(IsNan()); + EXPECT_FALSE(md.Matches(std::numeric_limits::quiet_NaN())); + EXPECT_FALSE(md.Matches(std::nan("1"))); + EXPECT_TRUE(md.Matches(1.0)); + + Matcher mld = Not(IsNan()); + EXPECT_FALSE(mld.Matches(std::numeric_limits::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 mf = IsNan(); + EXPECT_EQ("is NaN", Describe(mf)); + + Matcher md = IsNan(); + EXPECT_EQ("is NaN", Describe(md)); + + Matcher mld = IsNan(); + EXPECT_EQ("is NaN", Describe(mld)); +} + +// Tests that IsNan() can describe itself with Not. +TEST(IsNan, CanDescribeSelfWithNot) { + Matcher mf = Not(IsNan()); + EXPECT_EQ("isn't NaN", Describe(mf)); + + Matcher md = Not(IsNan()); + EXPECT_EQ("isn't NaN", Describe(md)); + + Matcher 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 Tpl; + Matcher 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&> 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 Tpl; + Matcher m = NanSensitiveFloatEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), + std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveFloatEq() describes itself properly. +TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) { + Matcher&> 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 Tpl; + Matcher 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&> 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 Tpl; + Matcher m = NanSensitiveDoubleEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), + std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); +} + +// Tests that DoubleEq() describes itself properly. +TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) { + Matcher&> 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 Tpl; + Matcher 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&> 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 Tpl; + Matcher 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::quiet_NaN(), + std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveFloatNear() describes itself properly. +TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) { + Matcher&> 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 Tpl; + Matcher 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&> 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 Tpl; + Matcher 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::quiet_NaN(), + std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveDoubleNear() describes itself properly. +TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) { + Matcher&> 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 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 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 greater_than_5 = Gt(5); + + Matcher m = Not(greater_than_5); + Matcher m2 = Not(greater_than_5); + Matcher m3 = Not(m); +} + +// Helper to allow easy testing of AllOf matchers with num parameters. +void AllOfMatches(int num, const Matcher& 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 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 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 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 greater_than_5 = Gt(5); + Matcher less_than_10 = Lt(10); + + Matcher m = AllOf(greater_than_5, less_than_10); + Matcher m2 = AllOf(greater_than_5, less_than_10); + Matcher m3 = AllOf(greater_than_5, m2); + + // Tests that BothOf works when composing itself. + Matcher m4 = AllOf(greater_than_5, less_than_10, less_than_10); + Matcher m5 = AllOf(greater_than_5, less_than_10, less_than_10); +} + +TEST_P(AllOfTestP, ExplainsResult) { + Matcher 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& 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& 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 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 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 eq_red = Eq("red"); + Matcher ne_red = Ne("red"); + Matcher 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 eq_red = Eq("red"); + Matcher ne_red = Ne("red"); + Matcher 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 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 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 greater_than_5 = Gt(5); + Matcher less_than_10 = Lt(10); + + Matcher m = AnyOf(greater_than_5, less_than_10); + Matcher m2 = AnyOf(greater_than_5, less_than_10); + Matcher m3 = AnyOf(greater_than_5, m2); + + // Tests that EitherOf works when composing itself. + Matcher m4 = AnyOf(greater_than_5, less_than_10, less_than_10); + Matcher m5 = AnyOf(greater_than_5, less_than_10, less_than_10); +} + +TEST_P(AnyOfTestP, ExplainsResult) { + Matcher 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 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 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 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 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 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 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 is_zero = Eq(0); + EXPECT_TRUE(Value(0, is_zero)); + EXPECT_FALSE(Value('a', is_zero)); + + int n = 0; + const Matcher ref_n = Ref(n); + EXPECT_TRUE(Value(n, ref_n)); + EXPECT_FALSE(Value(1, ref_n)); +} + +TEST(AllArgsTest, WorksForTuple) { + EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt())); + EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt()))); +} + +TEST(AllArgsTest, WorksForNonTuple) { + EXPECT_THAT(42, AllArgs(Gt(0))); + EXPECT_THAT('a', Not(AllArgs(Eq('b')))); +} + +class AllArgsHelper { + public: + AllArgsHelper() {} + + MOCK_METHOD2(Helper, int(char x, int y)); + + private: + AllArgsHelper(const AllArgsHelper&) = delete; + AllArgsHelper& operator=(const AllArgsHelper&) = delete; +}; + +TEST(AllArgsTest, WorksInWithClause) { + AllArgsHelper helper; + ON_CALL(helper, Helper(_, _)).With(AllArgs(Lt())).WillByDefault(Return(1)); + EXPECT_CALL(helper, Helper(_, _)); + EXPECT_CALL(helper, Helper(_, _)).With(AllArgs(Gt())).WillOnce(Return(2)); + + EXPECT_EQ(1, helper.Helper('\1', 2)); + EXPECT_EQ(2, helper.Helper('a', 1)); +} + +class OptionalMatchersHelper { + public: + OptionalMatchersHelper() {} + + MOCK_METHOD0(NoArgs, int()); + + MOCK_METHOD1(OneArg, int(int y)); + + MOCK_METHOD2(TwoArgs, int(char x, int y)); + + MOCK_METHOD1(Overloaded, int(char x)); + MOCK_METHOD2(Overloaded, int(char x, int y)); + + private: + OptionalMatchersHelper(const OptionalMatchersHelper&) = delete; + OptionalMatchersHelper& operator=(const OptionalMatchersHelper&) = delete; +}; + +TEST(AllArgsTest, WorksWithoutMatchers) { + OptionalMatchersHelper helper; + + ON_CALL(helper, NoArgs).WillByDefault(Return(10)); + ON_CALL(helper, OneArg).WillByDefault(Return(20)); + ON_CALL(helper, TwoArgs).WillByDefault(Return(30)); + + EXPECT_EQ(10, helper.NoArgs()); + EXPECT_EQ(20, helper.OneArg(1)); + EXPECT_EQ(30, helper.TwoArgs('\1', 2)); + + EXPECT_CALL(helper, NoArgs).Times(1); + EXPECT_CALL(helper, OneArg).WillOnce(Return(100)); + EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200)); + EXPECT_CALL(helper, TwoArgs).Times(0); + + EXPECT_EQ(10, helper.NoArgs()); + EXPECT_EQ(100, helper.OneArg(1)); + EXPECT_EQ(200, helper.OneArg(17)); +} + +// Tests floating-point matchers. +template +class FloatingPointTest : public testing::Test { + protected: + typedef testing::internal::FloatingPoint 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 (*matcher_maker)(RawType)) { + Matcher 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 m2 = matcher_maker(close_to_positive_zero_); + EXPECT_FALSE(m2.Matches(further_from_negative_zero_)); + + Matcher 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 m4 = matcher_maker(-infinity_); + EXPECT_TRUE(m4.Matches(-close_to_infinity_)); + + Matcher 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, which is needed in + // some cases. + Matcher 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, which is needed in some + // cases. + Matcher 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 +class FloatingPointNearTest : public FloatingPointTest { + protected: + typedef FloatingPointTest 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 ( + *matcher_maker)(RawType, RawType)) { + Matcher 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 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 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 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 m5 = matcher_maker(ParentType::max_, ParentType::max_); + EXPECT_TRUE(m5.Matches(ParentType::max_)); + EXPECT_FALSE(m5.Matches(-ParentType::max_)); + + Matcher m6 = matcher_maker(-ParentType::max_, ParentType::max_); + EXPECT_FALSE(m6.Matches(ParentType::max_)); + EXPECT_TRUE(m6.Matches(-ParentType::max_)); + + Matcher m7 = matcher_maker(ParentType::max_, 0); + EXPECT_TRUE(m7.Matches(ParentType::max_)); + EXPECT_FALSE(m7.Matches(-ParentType::max_)); + + Matcher 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 m9 = + matcher_maker(ParentType::max_, ParentType::infinity_); + EXPECT_TRUE(m8.Matches(-ParentType::max_)); + + // matcher_maker can produce a Matcher, which is needed in + // some cases. + Matcher 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, which is needed in some + // cases. + Matcher 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 FloatTest; + +TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) { TestMatches(&FloatEq); } + +TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) { + TestMatches(&NanSensitiveFloatEq); +} + +TEST_F(FloatTest, FloatEqCannotMatchNaN) { + // FloatEq never matches NaN. + Matcher 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 m = NanSensitiveFloatEq(nan1_); + EXPECT_TRUE(m.Matches(nan1_)); + EXPECT_TRUE(m.Matches(nan2_)); + EXPECT_FALSE(m.Matches(1.0)); +} + +TEST_F(FloatTest, FloatEqCanDescribeSelf) { + Matcher m1 = FloatEq(2.0f); + EXPECT_EQ("is approximately 2", Describe(m1)); + EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); + + Matcher m2 = FloatEq(0.5f); + EXPECT_EQ("is approximately 0.5", Describe(m2)); + EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); + + Matcher m3 = FloatEq(nan1_); + EXPECT_EQ("never matches", Describe(m3)); + EXPECT_EQ("is anything", DescribeNegation(m3)); +} + +TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) { + Matcher m1 = NanSensitiveFloatEq(2.0f); + EXPECT_EQ("is approximately 2", Describe(m1)); + EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); + + Matcher m2 = NanSensitiveFloatEq(0.5f); + EXPECT_EQ("is approximately 0.5", Describe(m2)); + EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); + + Matcher 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 FloatNearTest; + +TEST_F(FloatNearTest, FloatNearMatches) { TestNearMatches(&FloatNear); } + +TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) { + TestNearMatches(&NanSensitiveFloatNear); +} + +TEST_F(FloatNearTest, FloatNearCanDescribeSelf) { + Matcher 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 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 m3 = FloatNear(nan1_, 0.0); + EXPECT_EQ("never matches", Describe(m3)); + EXPECT_EQ("is anything", DescribeNegation(m3)); +} + +TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) { + Matcher 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 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 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 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 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 DoubleTest; + +TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) { + TestMatches(&DoubleEq); +} + +TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) { + TestMatches(&NanSensitiveDoubleEq); +} + +TEST_F(DoubleTest, DoubleEqCannotMatchNaN) { + // DoubleEq never matches NaN. + Matcher 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 m = NanSensitiveDoubleEq(nan1_); + EXPECT_TRUE(m.Matches(nan1_)); + EXPECT_TRUE(m.Matches(nan2_)); + EXPECT_FALSE(m.Matches(1.0)); +} + +TEST_F(DoubleTest, DoubleEqCanDescribeSelf) { + Matcher m1 = DoubleEq(2.0); + EXPECT_EQ("is approximately 2", Describe(m1)); + EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); + + Matcher m2 = DoubleEq(0.5); + EXPECT_EQ("is approximately 0.5", Describe(m2)); + EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); + + Matcher m3 = DoubleEq(nan1_); + EXPECT_EQ("never matches", Describe(m3)); + EXPECT_EQ("is anything", DescribeNegation(m3)); +} + +TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) { + Matcher m1 = NanSensitiveDoubleEq(2.0); + EXPECT_EQ("is approximately 2", Describe(m1)); + EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); + + Matcher m2 = NanSensitiveDoubleEq(0.5); + EXPECT_EQ("is approximately 0.5", Describe(m2)); + EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); + + Matcher 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 DoubleNearTest; + +TEST_F(DoubleNearTest, DoubleNearMatches) { TestNearMatches(&DoubleNear); } + +TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) { + TestNearMatches(&NanSensitiveDoubleNear); +} + +TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) { + Matcher 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 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 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 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 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 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 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 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 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 +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 +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 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 p(new int(3)); + EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5)))); + EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5))))); +} + +} // namespace +} // namespace gmock_matchers_test +} // namespace testing + +#ifdef _MSC_VER +#pragma warning(pop) +#endif diff --git a/googlemock/test/gmock-matchers-comparisons_test.cc b/googlemock/test/gmock-matchers-comparisons_test.cc new file mode 100644 index 00000000..eb8f3f63 --- /dev/null +++ b/googlemock/test/gmock-matchers-comparisons_test.cc @@ -0,0 +1,2318 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file tests some commonly used argument matchers. + +// Silence warning C4244: 'initializing': conversion from 'int' to 'short', +// possible loss of data and C4100, unreferenced local parameter +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4244) +#pragma warning(disable : 4100) +#endif + +#include "test/gmock-matchers_test.h" + +namespace testing { +namespace gmock_matchers_test { +namespace { + +INSTANTIATE_GTEST_MATCHER_TEST_P(MonotonicMatcherTest); + +TEST_P(MonotonicMatcherTestP, IsPrintable) { + stringstream ss; + ss << GreaterThan(5); + EXPECT_EQ("is > 5", ss.str()); +} + +TEST(MatchResultListenerTest, StreamingWorks) { + StringMatchResultListener listener; + listener << "hi" << 5; + EXPECT_EQ("hi5", listener.str()); + + listener.Clear(); + EXPECT_EQ("", listener.str()); + + listener << 42; + EXPECT_EQ("42", listener.str()); + + // Streaming shouldn't crash when the underlying ostream is NULL. + DummyMatchResultListener dummy; + dummy << "hi" << 5; +} + +TEST(MatchResultListenerTest, CanAccessUnderlyingStream) { + EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr); + EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr); + + EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream()); +} + +TEST(MatchResultListenerTest, IsInterestedWorks) { + EXPECT_TRUE(StringMatchResultListener().IsInterested()); + EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested()); + + EXPECT_FALSE(DummyMatchResultListener().IsInterested()); + EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested()); +} + +// Makes sure that the MatcherInterface interface doesn't +// change. +class EvenMatcherImpl : public MatcherInterface { + 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 { + 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 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 m; } + +// Tests that Matcher can be constructed from a MatcherInterface*. +TEST(MatcherTest, CanBeConstructedFromMatcherInterface) { + const MatcherInterface* impl = new EvenMatcherImpl; + Matcher 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 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 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 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 m = _; } + +// Tests that matchers are copyable. +TEST(MatcherTest, IsCopyable) { + // Tests the copy constructor. + Matcher 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::DescribeTo() calls +// MatcherInterface::DescribeTo(). +TEST(MatcherTest, CanDescribeItself) { + EXPECT_EQ("is an even number", Describe(Matcher(new EvenMatcherImpl))); +} + +// Tests Matcher::MatchAndExplain(). +TEST_P(MatcherTestP, MatchAndExplain) { + Matcher 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 or Matcher. +TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { + Matcher m1 = "hi"; + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher m2 = "hi"; + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} + +// Tests that a string object can be implicitly converted to a +// Matcher or Matcher. +TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) { + Matcher m1 = std::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher 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 or Matcher. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { + Matcher m1 = "cats"; + EXPECT_TRUE(m1.Matches("cats")); + EXPECT_FALSE(m1.Matches("dogs")); + + Matcher 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 or Matcher. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) { + Matcher m1 = std::string("cats"); + EXPECT_TRUE(m1.Matches("cats")); + EXPECT_FALSE(m1.Matches("dogs")); + + Matcher 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 or Matcher. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) { + Matcher m1 = internal::StringView("cats"); + EXPECT_TRUE(m1.Matches("cats")); + EXPECT_FALSE(m1.Matches("dogs")); + + Matcher 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 object can be implicitly +// converted to a Matcher or Matcher via Eq(). +TEST(StringMatcherTest, + CanBeImplicitlyConstructedFromEqReferenceWrapperString) { + std::string value = "cats"; + Matcher m1 = Eq(std::ref(value)); + EXPECT_TRUE(m1.Matches("cats")); + EXPECT_FALSE(m1.Matches("dogs")); + + Matcher m2 = Eq(std::ref(value)); + EXPECT_TRUE(m2.Matches("cats")); + EXPECT_FALSE(m2.Matches("dogs")); +} + +// Tests that MakeMatcher() constructs a Matcher from a +// MatcherInterface* without requiring the user to explicitly +// write the type. +TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) { + const MatcherInterface* dummy_impl = new EvenMatcherImpl; + Matcher 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 + 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 where T is the argument's type. +PolymorphicMatcher ReferencesBarOrIsZero() { + return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl()); +} + +TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) { + // Using a polymorphic matcher to match a reference type. + Matcher 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 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 + 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 PolymorphicIsEven() { + return MakePolymorphicMatcher(PolymorphicIsEvenImpl()); +} + +TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) { + // Using PolymorphicIsEven() as a Matcher. + const Matcher m1 = PolymorphicIsEven(); + EXPECT_TRUE(m1.Matches(42)); + EXPECT_FALSE(m1.Matches(43)); + EXPECT_EQ("is even", Describe(m1)); + + const Matcher not_m1 = Not(m1); + EXPECT_EQ("is odd", Describe(not_m1)); + + EXPECT_EQ("% 2 == 0", Explain(m1, 42)); + + // Using PolymorphicIsEven() as a Matcher. + const Matcher m2 = PolymorphicIsEven(); + EXPECT_TRUE(m2.Matches('\x42')); + EXPECT_FALSE(m2.Matches('\x43')); + EXPECT_EQ("is even", Describe(m2)); + + const Matcher 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(m) works when m is a polymorphic matcher. +TEST_P(MatcherCastTestP, FromPolymorphicMatcher) { + Matcher m; + if (use_gtest_matcher_) { + m = MatcherCast(GtestGreaterThan(int64_t{5})); + } else { + m = MatcherCast(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(m) works when m is a Matcher where T +// can be statically converted to U. +TEST(MatcherCastTest, FromCompatibleType) { + Matcher m1 = Eq(2.0); + Matcher m2 = MatcherCast(m1); + EXPECT_TRUE(m2.Matches(2)); + EXPECT_FALSE(m2.Matches(3)); + + Matcher m3 = Truly(IsPositiveIntValue); + Matcher m4 = MatcherCast(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(m) works when m is a Matcher. +TEST(MatcherCastTest, FromConstReferenceToNonReference) { + Matcher m1 = Eq(0); + Matcher m2 = MatcherCast(m1); + EXPECT_TRUE(m2.Matches(0)); + EXPECT_FALSE(m2.Matches(1)); +} + +// Tests that MatcherCast(m) works when m is a Matcher. +TEST(MatcherCastTest, FromReferenceToNonReference) { + Matcher m1 = Eq(0); + Matcher m2 = MatcherCast(m1); + EXPECT_TRUE(m2.Matches(0)); + EXPECT_FALSE(m2.Matches(1)); +} + +// Tests that MatcherCast(m) works when m is a Matcher. +TEST(MatcherCastTest, FromNonReferenceToConstReference) { + Matcher m1 = Eq(0); + Matcher m2 = MatcherCast(m1); + EXPECT_TRUE(m2.Matches(0)); + EXPECT_FALSE(m2.Matches(1)); +} + +// Tests that MatcherCast(m) works when m is a Matcher. +TEST(MatcherCastTest, FromNonReferenceToReference) { + Matcher m1 = Eq(0); + Matcher m2 = MatcherCast(m1); + int n = 0; + EXPECT_TRUE(m2.Matches(n)); + n = 1; + EXPECT_FALSE(m2.Matches(n)); +} + +// Tests that MatcherCast(m) works when m is a Matcher. +TEST(MatcherCastTest, FromSameType) { + Matcher m1 = Eq(0); + Matcher m2 = MatcherCast(m1); + EXPECT_TRUE(m2.Matches(0)); + EXPECT_FALSE(m2.Matches(1)); +} + +// Tests that MatcherCast(m) works when m is a value of the same type as the +// value type of the Matcher. +TEST(MatcherCastTest, FromAValue) { + Matcher m = MatcherCast(42); + EXPECT_TRUE(m.Matches(42)); + EXPECT_FALSE(m.Matches(239)); +} + +// Tests that MatcherCast(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 m = MatcherCast('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(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 m1 = + MatcherCast(42); + EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); + + Matcher m2 = + MatcherCast(239); + EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); + + // When updating the following lines please also change the comment to + // namespace convertible_from_any. + Matcher m3 = + MatcherCast(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 + 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 m = MatcherCast(1); + EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); + EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); +} + +TEST(MatcherCastTest, FromConvertibleFromAny) { + Matcher m = + MatcherCast(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 m = MatcherCast(n); + // Verify that the matcher holds a reference to n, not to its temporary copy. + EXPECT_TRUE(m.Matches(n)); +} + +class Base { + public: + virtual ~Base() {} + Base() {} + + private: + Base(const Base&) = delete; + Base& operator=(const Base&) = delete; +}; + +class Derived : public Base { + public: + Derived() : Base() {} + int i; +}; + +class OtherDerived : public Base {}; + +INSTANTIATE_GTEST_MATCHER_TEST_P(SafeMatcherCastTest); + +// Tests that SafeMatcherCast(m) works when m is a polymorphic matcher. +TEST_P(SafeMatcherCastTestP, FromPolymorphicMatcher) { + Matcher m2; + if (use_gtest_matcher_) { + m2 = SafeMatcherCast(GtestGreaterThan(32)); + } else { + m2 = SafeMatcherCast(Gt(32)); + } + EXPECT_TRUE(m2.Matches('A')); + EXPECT_FALSE(m2.Matches('\n')); +} + +// Tests that SafeMatcherCast(m) works when m is a Matcher where +// T and U are arithmetic types and T can be losslessly converted to +// U. +TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) { + Matcher m1 = DoubleEq(1.0); + Matcher m2 = SafeMatcherCast(m1); + EXPECT_TRUE(m2.Matches(1.0f)); + EXPECT_FALSE(m2.Matches(2.0f)); + + Matcher m3 = SafeMatcherCast(TypedEq('a')); + EXPECT_TRUE(m3.Matches('a')); + EXPECT_FALSE(m3.Matches('b')); +} + +// Tests that SafeMatcherCast(m) works when m is a Matcher where T and U +// are pointers or references to a derived and a base class, correspondingly. +TEST(SafeMatcherCastTest, FromBaseClass) { + Derived d, d2; + Matcher m1 = Eq(&d); + Matcher m2 = SafeMatcherCast(m1); + EXPECT_TRUE(m2.Matches(&d)); + EXPECT_FALSE(m2.Matches(&d2)); + + Matcher m3 = Ref(d); + Matcher m4 = SafeMatcherCast(m3); + EXPECT_TRUE(m4.Matches(d)); + EXPECT_FALSE(m4.Matches(d2)); +} + +// Tests that SafeMatcherCast(m) works when m is a Matcher. +TEST(SafeMatcherCastTest, FromConstReferenceToReference) { + int n = 0; + Matcher m1 = Ref(n); + Matcher m2 = SafeMatcherCast(m1); + int n1 = 0; + EXPECT_TRUE(m2.Matches(n)); + EXPECT_FALSE(m2.Matches(n1)); +} + +// Tests that MatcherCast(m) works when m is a Matcher. +TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) { + Matcher> m1 = IsNull(); + Matcher&> m2 = + SafeMatcherCast&>(m1); + EXPECT_TRUE(m2.Matches(std::unique_ptr())); + EXPECT_FALSE(m2.Matches(std::unique_ptr(new int))); +} + +// Tests that SafeMatcherCast(m) works when m is a Matcher. +TEST(SafeMatcherCastTest, FromNonReferenceToReference) { + Matcher m1 = Eq(0); + Matcher m2 = SafeMatcherCast(m1); + int n = 0; + EXPECT_TRUE(m2.Matches(n)); + n = 1; + EXPECT_FALSE(m2.Matches(n)); +} + +// Tests that SafeMatcherCast(m) works when m is a Matcher. +TEST(SafeMatcherCastTest, FromSameType) { + Matcher m1 = Eq(0); + Matcher m2 = SafeMatcherCast(m1); + EXPECT_TRUE(m2.Matches(0)); + EXPECT_FALSE(m2.Matches(1)); +} + +#if !defined _MSC_VER + +namespace convertible_from_any { +TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) { + Matcher m = SafeMatcherCast(1); + EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); + EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); +} + +TEST(SafeMatcherCastTest, FromConvertibleFromAny) { + Matcher m = + SafeMatcherCast(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 m = SafeMatcherCast(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() matches any value of type T. +TEST(ATest, MatchesAnyValue) { + // Tests a matcher for a value type. + Matcher m1 = A(); + 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 m2 = A(); + EXPECT_TRUE(m2.Matches(a)); + EXPECT_TRUE(m2.Matches(b)); +} + +TEST(ATest, WorksForDerivedClass) { + Base base; + Derived derived; + EXPECT_THAT(&base, A()); + // This shouldn't compile: EXPECT_THAT(&base, A()); + EXPECT_THAT(&derived, A()); + EXPECT_THAT(&derived, A()); +} + +// Tests that A() describes itself properly. +TEST(ATest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(A())); } + +// Tests that An() matches any value of type T. +TEST(AnTest, MatchesAnyValue) { + // Tests a matcher for a value type. + Matcher m1 = An(); + EXPECT_TRUE(m1.Matches(9143)); + EXPECT_TRUE(m1.Matches(-1532)); + + // Tests a matcher for a reference type. + int a = 2; + int b = -6; + Matcher m2 = An(); + EXPECT_TRUE(m2.Matches(a)); + EXPECT_TRUE(m2.Matches(b)); +} + +// Tests that An() describes itself properly. +TEST(AnTest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(An())); } + +// 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 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 m2 = _; + EXPECT_TRUE(m2.Matches(a)); + EXPECT_TRUE(m2.Matches(b)); +} + +// Tests that _ describes itself properly. +TEST(UnderscoreTest, CanDescribeSelf) { + Matcher 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 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 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 m1 = Eq(1); + EXPECT_TRUE(m1.Matches(1)); + EXPECT_FALSE(m1.Matches(2)); + + Matcher m2 = Eq(1); + EXPECT_TRUE(m2.Matches('\1')); + EXPECT_FALSE(m2.Matches('a')); +} + +// Tests that TypedEq(v) matches values of type T that's equal to v. +TEST(TypedEqTest, ChecksEqualityForGivenType) { + Matcher m1 = TypedEq('a'); + EXPECT_TRUE(m1.Matches('a')); + EXPECT_FALSE(m1.Matches('b')); + + Matcher m2 = TypedEq(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(2))); +} + +// Tests that TypedEq(v) has type Matcher. + +// Type::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 +struct Type { + static bool IsTypeOf(const T& /* v */) { return true; } + + template + static void IsTypeOf(T2 v); +}; + +TEST(TypedEqTest, HasSpecifiedType) { + // Verfies that the type of TypedEq(v) is Matcher. + Type>::IsTypeOf(TypedEq(5)); + Type>::IsTypeOf(TypedEq(5)); +} + +// Tests that Ge(v) matches anything >= v. +TEST(GeTest, ImplementsGreaterThanOrEqual) { + Matcher 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 m = Ge(5); + EXPECT_EQ("is >= 5", Describe(m)); +} + +// Tests that Gt(v) matches anything > v. +TEST(GtTest, ImplementsGreaterThan) { + Matcher 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 m = Gt(5); + EXPECT_EQ("is > 5", Describe(m)); +} + +// Tests that Le(v) matches anything <= v. +TEST(LeTest, ImplementsLessThanOrEqual) { + Matcher 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 m = Le(5); + EXPECT_EQ("is <= 5", Describe(m)); +} + +// Tests that Lt(v) matches anything < v. +TEST(LtTest, ImplementsLessThan) { + Matcher 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 m = Lt(5); + EXPECT_EQ("is < 5", Describe(m)); +} + +// Tests that Ne(v) matches anything != v. +TEST(NeTest, ImplementsNotEqual) { + Matcher 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 m = Ne(5); + EXPECT_EQ("isn't equal to 5", Describe(m)); +} + +class MoveOnly { + public: + explicit MoveOnly(int i) : i_(i) {} + MoveOnly(const MoveOnly&) = delete; + MoveOnly(MoveOnly&&) = default; + MoveOnly& operator=(const MoveOnly&) = delete; + MoveOnly& operator=(MoveOnly&&) = default; + + bool operator==(const MoveOnly& other) const { return i_ == other.i_; } + bool operator!=(const MoveOnly& other) const { return i_ != other.i_; } + bool operator<(const MoveOnly& other) const { return i_ < other.i_; } + bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; } + bool operator>(const MoveOnly& other) const { return i_ > other.i_; } + bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; } + + private: + int i_; +}; + +struct MoveHelper { + MOCK_METHOD1(Call, void(MoveOnly)); +}; + +// Disable this test in VS 2015 (version 14), where it fails when SEH is enabled +#if defined(_MSC_VER) && (_MSC_VER < 1910) +TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) { +#else +TEST(ComparisonBaseTest, WorksWithMoveOnly) { +#endif + MoveOnly m{0}; + MoveHelper helper; + + EXPECT_CALL(helper, Call(Eq(ByRef(m)))); + helper.Call(MoveOnly(0)); + EXPECT_CALL(helper, Call(Ne(ByRef(m)))); + helper.Call(MoveOnly(1)); + EXPECT_CALL(helper, Call(Le(ByRef(m)))); + helper.Call(MoveOnly(0)); + EXPECT_CALL(helper, Call(Lt(ByRef(m)))); + helper.Call(MoveOnly(-1)); + EXPECT_CALL(helper, Call(Ge(ByRef(m)))); + helper.Call(MoveOnly(0)); + EXPECT_CALL(helper, Call(Gt(ByRef(m)))); + helper.Call(MoveOnly(1)); +} + +// Tests that IsNull() matches any NULL pointer of any type. +TEST(IsNullTest, MatchesNullPointer) { + Matcher m1 = IsNull(); + int* p1 = nullptr; + int n = 0; + EXPECT_TRUE(m1.Matches(p1)); + EXPECT_FALSE(m1.Matches(&n)); + + Matcher m2 = IsNull(); + const char* p2 = nullptr; + EXPECT_TRUE(m2.Matches(p2)); + EXPECT_FALSE(m2.Matches("hi")); + + Matcher m3 = IsNull(); + void* p3 = nullptr; + EXPECT_TRUE(m3.Matches(p3)); + EXPECT_FALSE(m3.Matches(reinterpret_cast(0xbeef))); +} + +TEST(IsNullTest, StdFunction) { + const Matcher> m = IsNull(); + + EXPECT_TRUE(m.Matches(std::function())); + EXPECT_FALSE(m.Matches([] {})); +} + +// Tests that IsNull() describes itself properly. +TEST(IsNullTest, CanDescribeSelf) { + Matcher 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 m1 = NotNull(); + int* p1 = nullptr; + int n = 0; + EXPECT_FALSE(m1.Matches(p1)); + EXPECT_TRUE(m1.Matches(&n)); + + Matcher m2 = NotNull(); + const char* p2 = nullptr; + EXPECT_FALSE(m2.Matches(p2)); + EXPECT_TRUE(m2.Matches("hi")); +} + +TEST(NotNullTest, LinkedPtr) { + const Matcher> m = NotNull(); + const std::shared_ptr null_p; + const std::shared_ptr non_null_p(new int); + + EXPECT_FALSE(m.Matches(null_p)); + EXPECT_TRUE(m.Matches(non_null_p)); +} + +TEST(NotNullTest, ReferenceToConstLinkedPtr) { + const Matcher&> m = NotNull(); + const std::shared_ptr null_p; + const std::shared_ptr non_null_p(new double); + + EXPECT_FALSE(m.Matches(null_p)); + EXPECT_TRUE(m.Matches(non_null_p)); +} + +TEST(NotNullTest, StdFunction) { + const Matcher> m = NotNull(); + + EXPECT_TRUE(m.Matches([] {})); + EXPECT_FALSE(m.Matches(std::function())); +} + +// Tests that NotNull() describes itself properly. +TEST(NotNullTest, CanDescribeSelf) { + Matcher 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 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 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 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 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(Ref(n)), n), + StartsWith("which is located @")); + + int m = 0; + EXPECT_THAT(Explain(Matcher(Ref(n)), m), + StartsWith("which is located @")); +} + +// Tests string comparison matchers. + +template +std::string FromStringLike(internal::StringLike 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 m = StrEq(std::string("Hello")); + EXPECT_TRUE(m.Matches("Hello")); + EXPECT_FALSE(m.Matches("hello")); + EXPECT_FALSE(m.Matches(nullptr)); + + Matcher m2 = StrEq("Hello"); + EXPECT_TRUE(m2.Matches("Hello")); + EXPECT_FALSE(m2.Matches("Hi")); + +#if GTEST_INTERNAL_HAS_STRING_VIEW + Matcher 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 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 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 m2 = StrEq(str); + EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2)); + str[0] = str[6] = str[7] = str[9] = str[10] = '\0'; + Matcher m3 = StrEq(str); + EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3)); +} + +TEST(StrNeTest, MatchesUnequalString) { + Matcher m = StrNe("Hello"); + EXPECT_TRUE(m.Matches("")); + EXPECT_TRUE(m.Matches(nullptr)); + EXPECT_FALSE(m.Matches("Hello")); + + Matcher m2 = StrNe(std::string("Hello")); + EXPECT_TRUE(m2.Matches("hello")); + EXPECT_FALSE(m2.Matches("Hello")); + +#if GTEST_INTERNAL_HAS_STRING_VIEW + Matcher 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 m = StrNe("Hi"); + EXPECT_EQ("isn't equal to \"Hi\"", Describe(m)); +} + +TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) { + Matcher 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 m2 = StrCaseEq("Hello"); + EXPECT_TRUE(m2.Matches("hello")); + EXPECT_FALSE(m2.Matches("Hi")); + +#if GTEST_INTERNAL_HAS_STRING_VIEW + Matcher 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 m0 = StrCaseEq(str1); + EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0'))); + + str1[3] = str2[3] = '\0'; + Matcher 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 m2 = StrCaseEq(str1); + str1[9] = str2[9] = '\0'; + EXPECT_FALSE(m2.Matches(str2)); + + Matcher 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 m = StrCaseEq("Hi"); + EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m)); +} + +TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) { + Matcher m = StrCaseNe("Hello"); + EXPECT_TRUE(m.Matches("Hi")); + EXPECT_TRUE(m.Matches(nullptr)); + EXPECT_FALSE(m.Matches("Hello")); + EXPECT_FALSE(m.Matches("hello")); + + Matcher m2 = StrCaseNe(std::string("Hello")); + EXPECT_TRUE(m2.Matches("")); + EXPECT_FALSE(m2.Matches("Hello")); + +#if GTEST_INTERNAL_HAS_STRING_VIEW + Matcher 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 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 m1 = HasSubstr("foo"); + EXPECT_TRUE(m1.Matches(std::string("I love food."))); + EXPECT_FALSE(m1.Matches(std::string("tofo"))); + + const Matcher m2 = HasSubstr("foo"); + EXPECT_TRUE(m2.Matches(std::string("I love food."))); + EXPECT_FALSE(m2.Matches(std::string("tofo"))); + + const Matcher 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 m1 = HasSubstr("foo"); + EXPECT_TRUE(m1.Matches(const_cast("I love food."))); + EXPECT_FALSE(m1.Matches(const_cast("tofo"))); + EXPECT_FALSE(m1.Matches(nullptr)); + + const Matcher m2 = HasSubstr("foo"); + EXPECT_TRUE(m2.Matches("I love food.")); + EXPECT_FALSE(m2.Matches("tofo")); + EXPECT_FALSE(m2.Matches(nullptr)); + + const Matcher 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 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 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 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 m = HasSubstr("foo\n\""); + EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m)); +} + +INSTANTIATE_GTEST_MATCHER_TEST_P(KeyTest); + +TEST(KeyTest, CanDescribeSelf) { + Matcher&> 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> 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 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> p; + EXPECT_THAT(p, Key(Eq(nullptr))); +} + +INSTANTIATE_GTEST_MATCHER_TEST_P(PairTest); + +template +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 +auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag())) { + return value.GetImpl(Tag()); +} +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 v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; + EXPECT_THAT(v, Contains(Key(29))); +} + +TEST(KeyTest, SafelyCastsInnerMatcher) { + Matcher is_positive = Gt(0); + Matcher is_negative = Lt(0); + pair p('a', true); + EXPECT_THAT(p, Key(is_positive)); + EXPECT_THAT(p, Not(Key(is_negative))); +} + +TEST(KeyTest, InsideContainsUsingMap) { + map 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 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&> m1 = Pair("foo", 42); + Matcher> m2 = Pair("foo", 42); + Matcher> m3 = Pair("foo", 42); + + Matcher> m4 = Pair(25, "42"); + Matcher> m5 = Pair("25", 42); +} + +TEST(PairTest, CanDescribeSelf) { + Matcher&> 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&> 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> 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> 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> 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 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> p; + p.second.reset(new int(7)); + EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr))); +} + +TEST(PairTest, SafelyCastsInnerMatchers) { + Matcher is_positive = Gt(0); + Matcher is_negative = Lt(0); + pair 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 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 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&> 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> m = + FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0)); + + EXPECT_EQ("whose field #0 does not match, which is 1 less than 0", + Explain(m, std::make_tuple(-1, -2, -3))); + EXPECT_EQ("whose field #1 does not match, which is 2 less than 0", + Explain(m, std::make_tuple(1, -2, -3))); + EXPECT_EQ("whose field #2 does not match, which is 3 less than 0", + Explain(m, std::make_tuple(1, 2, -3))); + + // If they all match, we get a long explanation of success. + EXPECT_EQ( + "whose all elements match, " + "where field #0 is a value which is 1 more than 0" + ", and field #1 is a value which is 2 more than 0" + ", and field #2 is a value which is 3 more than 0", + Explain(m, std::make_tuple(1, 2, 3))); + + // Only print those that have an explanation. + m = FieldsAre(GreaterThan(0), 0, GreaterThan(0)); + EXPECT_EQ( + "whose all elements match, " + "where field #0 is a value which is 1 more than 0" + ", and field #2 is a value which is 3 more than 0", + Explain(m, std::make_tuple(1, 0, 3))); + + // If only one has an explanation, then print that one. + m = FieldsAre(0, GreaterThan(0), 0); + EXPECT_EQ( + "whose all elements match, " + "where field #1 is a value which is 1 more than 0", + Explain(m, std::make_tuple(0, 1, 0))); +} + +#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606 +TEST(FieldsAreTest, StructuredBindings) { + // testing::FieldsAre can also match aggregates and such with C++17 and up. + struct MyType { + int i; + std::string str; + }; + EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo"))); + + // Test all the supported arities. + struct MyVarType1 { + int a; + }; + EXPECT_THAT(MyVarType1{}, FieldsAre(0)); + struct MyVarType2 { + int a, b; + }; + EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0)); + struct MyVarType3 { + int a, b, c; + }; + EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0)); + struct MyVarType4 { + int a, b, c, d; + }; + EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0)); + struct MyVarType5 { + int a, b, c, d, e; + }; + EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0)); + struct MyVarType6 { + int a, b, c, d, e, f; + }; + EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0)); + struct MyVarType7 { + int a, b, c, d, e, f, g; + }; + EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0)); + struct MyVarType8 { + int a, b, c, d, e, f, g, h; + }; + EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0)); + struct MyVarType9 { + int a, b, c, d, e, f, g, h, i; + }; + EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0)); + struct MyVarType10 { + int a, b, c, d, e, f, g, h, i, j; + }; + EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); + struct MyVarType11 { + int a, b, c, d, e, f, g, h, i, j, k; + }; + EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); + struct MyVarType12 { + int a, b, c, d, e, f, g, h, i, j, k, l; + }; + EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); + struct MyVarType13 { + int a, b, c, d, e, f, g, h, i, j, k, l, m; + }; + EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); + struct MyVarType14 { + int a, b, c, d, e, f, g, h, i, j, k, l, m, n; + }; + EXPECT_THAT(MyVarType14{}, + FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); + struct MyVarType15 { + int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o; + }; + EXPECT_THAT(MyVarType15{}, + FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); + struct MyVarType16 { + int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p; + }; + EXPECT_THAT(MyVarType16{}, + FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); +} +#endif + +TEST(PairTest, UseGetInsteadOfMembers) { + PairWithGet pair{7, "ABC"}; + EXPECT_THAT(pair, Pair(7, "ABC")); + EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB"))); + EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC"))); + + std::vector 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 m1 = StartsWith(std::string("")); + EXPECT_TRUE(m1.Matches("Hi")); + EXPECT_TRUE(m1.Matches("")); + EXPECT_FALSE(m1.Matches(nullptr)); + + const Matcher 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 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 m = StartsWith("Hi"); + EXPECT_EQ("starts with \"Hi\"", Describe(m)); +} + +// Tests EndsWith(s). + +TEST(EndsWithTest, MatchesStringWithGivenSuffix) { + const Matcher m1 = EndsWith(""); + EXPECT_TRUE(m1.Matches("Hi")); + EXPECT_TRUE(m1.Matches("")); + EXPECT_FALSE(m1.Matches(nullptr)); + + const Matcher 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 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 m = EndsWith("Hi"); + EXPECT_EQ("ends with \"Hi\"", Describe(m)); +} + +// Tests WhenBase64Unescaped. + +TEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) { + const Matcher m1 = WhenBase64Unescaped(EndsWith("!")); + EXPECT_FALSE(m1.Matches("invalid base64")); + EXPECT_FALSE(m1.Matches("aGVsbG8gd29ybGQ=")); // hello world + EXPECT_TRUE(m1.Matches("aGVsbG8gd29ybGQh")); // hello world! + + const Matcher m2 = WhenBase64Unescaped(EndsWith("!")); + EXPECT_FALSE(m2.Matches("invalid base64")); + EXPECT_FALSE(m2.Matches("aGVsbG8gd29ybGQ=")); // hello world + EXPECT_TRUE(m2.Matches("aGVsbG8gd29ybGQh")); // hello world! + +#if GTEST_INTERNAL_HAS_STRING_VIEW + const Matcher m3 = + WhenBase64Unescaped(EndsWith("!")); + EXPECT_FALSE(m3.Matches("invalid base64")); + EXPECT_FALSE(m3.Matches("aGVsbG8gd29ybGQ=")); // hello world + EXPECT_TRUE(m3.Matches("aGVsbG8gd29ybGQh")); // hello world! +#endif // GTEST_INTERNAL_HAS_STRING_VIEW +} + +TEST(WhenBase64UnescapedTest, CanDescribeSelf) { + const Matcher m = WhenBase64Unescaped(EndsWith("!")); + EXPECT_EQ("matches after Base64Unescape ends with \"!\"", Describe(m)); +} + +// Tests MatchesRegex(). + +TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) { + const Matcher m1 = MatchesRegex("a.*z"); + EXPECT_TRUE(m1.Matches("az")); + EXPECT_TRUE(m1.Matches("abcz")); + EXPECT_FALSE(m1.Matches(nullptr)); + + const Matcher 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 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 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 m1 = MatchesRegex(std::string("Hi.*")); + EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1)); + + Matcher m2 = MatchesRegex(new RE("a.*")); + EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2)); + +#if GTEST_INTERNAL_HAS_STRING_VIEW + Matcher 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 m1 = ContainsRegex(std::string("a.*z")); + EXPECT_TRUE(m1.Matches("az")); + EXPECT_TRUE(m1.Matches("0abcz1")); + EXPECT_FALSE(m1.Matches(nullptr)); + + const Matcher 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 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 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 m1 = ContainsRegex("Hi.*"); + EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1)); + + Matcher m2 = ContainsRegex(new RE("a.*")); + EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2)); + +#if GTEST_INTERNAL_HAS_STRING_VIEW + Matcher 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 m = StrEq(::std::wstring(L"Hello")); + EXPECT_TRUE(m.Matches(L"Hello")); + EXPECT_FALSE(m.Matches(L"hello")); + EXPECT_FALSE(m.Matches(nullptr)); + + Matcher m2 = StrEq(L"Hello"); + EXPECT_TRUE(m2.Matches(L"Hello")); + EXPECT_FALSE(m2.Matches(L"Hi")); + + Matcher 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 m4 = StrEq(str); + EXPECT_TRUE(m4.Matches(str)); + str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; + Matcher 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 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 m5 = StrEq(str); + EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5)); +} + +TEST(StdWideStrNeTest, MatchesUnequalString) { + Matcher 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 m = StrNe(L"Hi"); + EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m)); +} + +TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { + Matcher 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 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 m0 = StrCaseEq(str1); + EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0'))); + + str1[3] = str2[3] = L'\0'; + Matcher 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 m2 = StrCaseEq(str1); + str1[9] = str2[9] = L'\0'; + EXPECT_FALSE(m2.Matches(str2)); + + Matcher 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 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 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 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 m1 = HasSubstr(L"foo"); + EXPECT_TRUE(m1.Matches(const_cast(L"I love food."))); + EXPECT_FALSE(m1.Matches(const_cast(L"tofo"))); + EXPECT_FALSE(m1.Matches(nullptr)); + + const Matcher 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 m1 = StartsWith(::std::wstring(L"")); + EXPECT_TRUE(m1.Matches(L"Hi")); + EXPECT_TRUE(m1.Matches(L"")); + EXPECT_FALSE(m1.Matches(nullptr)); + + const Matcher 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 m = StartsWith(L"Hi"); + EXPECT_EQ("starts with L\"Hi\"", Describe(m)); +} + +// Tests EndsWith(s). + +TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) { + const Matcher m1 = EndsWith(L""); + EXPECT_TRUE(m1.Matches(L"Hi")); + EXPECT_TRUE(m1.Matches(L"")); + EXPECT_FALSE(m1.Matches(nullptr)); + + const Matcher 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 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 is_even = PolymorphicIsEven(); + StringMatchResultListener listener1; + EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1)); + EXPECT_EQ("% 2 == 0", listener1.str()); + + const Matcher 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; + EXPECT_TRUE((std::is_constructible::value)); + EXPECT_FALSE((std::is_convertible::value)); + } + { + // Multiple arg matchers can be constructed with an implicit construction. + Construct2ArgsMatcherP2 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(42)); + EXPECT_EQ("isn't equal to 42", DescribeMatcher(42, true)); +} + +TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) { + const Matcher monomorphic = Le(0); + EXPECT_EQ("is <= 0", DescribeMatcher(monomorphic)); + EXPECT_EQ("isn't <= 0", DescribeMatcher(monomorphic, true)); +} + +TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) { + EXPECT_EQ("is even", DescribeMatcher(PolymorphicIsEven())); + EXPECT_EQ("is odd", DescribeMatcher(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(Not(IsNull()))); + EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(Pointee(FieldIIs(4)))); + EXPECT_THAT(as_base_ptr, + Not(WhenDynamicCastTo(Pointee(FieldIIs(5))))); +} + +TEST(WhenDynamicCastToTest, WrongTypes) { + Base base; + Derived derived; + OtherDerived other_derived; + + // Wrong types. NULL is passed. + EXPECT_THAT(&base, Not(WhenDynamicCastTo(Pointee(_)))); + EXPECT_THAT(&base, WhenDynamicCastTo(IsNull())); + Base* as_base_ptr = &derived; + EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo(Pointee(_)))); + EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(IsNull())); + as_base_ptr = &other_derived; + EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo(Pointee(_)))); + EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(IsNull())); +} + +TEST(WhenDynamicCastToTest, AlreadyNull) { + // Already NULL. + Base* as_base_ptr = nullptr; + EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(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(&many_derived); + EXPECT_THAT(as_base_ptr, + WhenDynamicCastTo(IsNull())); + as_base_ptr = &sub1; + EXPECT_THAT( + as_base_ptr, + WhenDynamicCastTo(Not(IsNull()))); +} + +TEST(WhenDynamicCastToTest, Describe) { + Matcher matcher = WhenDynamicCastTo(Pointee(_)); + const std::string prefix = + "when dynamic_cast to " + internal::GetTypeName() + ", "; + 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 matcher = WhenDynamicCastTo(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 ref_matcher = WhenDynamicCastTo(_); + 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(FieldIIs(4))); + EXPECT_THAT(as_base_ref, WhenDynamicCastTo(Not(FieldIIs(5)))); +} + +TEST(WhenDynamicCastToTest, BadReference) { + Derived derived; + Base& as_base_ref = derived; + EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo(_))); +} +#endif // GTEST_HAS_RTTI + +class DivisibleByImpl { + public: + explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {} + + // For testing using ExplainMatchResultTo() with polymorphic matchers. + template + 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 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 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 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 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 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 m = AllOf(Ge(2), Le(3)); + EXPECT_EQ("", Explain(m, 2)); +} + +INSTANTIATE_GTEST_MATCHER_TEST_P(ExplainmatcherResultTest); + +TEST_P(ExplainmatcherResultTestP, MonomorphicMatcher) { + const Matcher m = GreaterThan(5); + EXPECT_EQ("which is 1 more than 5", Explain(m, 6)); +} + +// Tests PolymorphicMatcher::mutable_impl(). +TEST(PolymorphicMatcherTest, CanAccessMutableImpl) { + PolymorphicMatcher 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 m(DivisibleByImpl(42)); + const DivisibleByImpl& impl = m.impl(); + EXPECT_EQ(42, impl.divider()); +} + +} // namespace +} // namespace gmock_matchers_test +} // namespace testing + +#ifdef _MSC_VER +#pragma warning(pop) +#endif diff --git a/googlemock/test/gmock-matchers-containers_test.cc b/googlemock/test/gmock-matchers-containers_test.cc new file mode 100644 index 00000000..f50159f8 --- /dev/null +++ b/googlemock/test/gmock-matchers-containers_test.cc @@ -0,0 +1,3129 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file tests some commonly used argument matchers. + +// Silence warning C4244: 'initializing': conversion from 'int' to 'short', +// possible loss of data and C4100, unreferenced local parameter +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4244) +#pragma warning(disable : 4100) +#endif + +#include "test/gmock-matchers_test.h" + +namespace testing { +namespace gmock_matchers_test { +namespace { + +std::vector> MakeUniquePtrs(const std::vector& ints) { + std::vector> 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 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 test_vector{ + "literal_string", "", "", "", "", "", "", "", "", "", "", ""}; + + EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _, + _, _, _, _, _, _)); +} + +// Tests the variadic version of the UnorderedElementsAreMatcher +TEST(ElementsAreTest, HugeMatcherUnordered) { + vector 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 starts_with_he = StartsWith("he"); + ASSERT_THAT("hello", starts_with_he); + + Matcher 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 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 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 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 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 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> m = Pointee(Ge(0)); + + std::unique_ptr n(new int(1)); + EXPECT_TRUE(m.Matches(n)); +} + +TEST(PointeeTest, SmartPointerToConst) { + const Matcher> m = Pointee(Ge(0)); + + // There's no implicit conversion from unique_ptr to const + // unique_ptr, so we must pass a unique_ptr into the + // matcher. + std::unique_ptr n(new int(1)); + EXPECT_TRUE(m.Matches(n)); +} + +TEST(PointerTest, RawPointer) { + int n = 1; + const Matcher 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 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 n(new int(10)); + int* raw_n = n.get(); + const Matcher> m = Pointer(Eq(raw_n)); + + EXPECT_TRUE(m.Matches(n)); +} + +TEST(PointerTest, SmartPointerToConst) { + std::unique_ptr n(new int(10)); + const int* raw_n = n.get(); + const Matcher> m = Pointer(Eq(raw_n)); + + // There's no implicit conversion from unique_ptr to const + // unique_ptr, so we must pass a unique_ptr into the + // matcher. + std::unique_ptr p(new int(10)); + EXPECT_FALSE(m.Matches(p)); +} + +// Minimal const-propagating pointer. +template +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> m = Pointee(Lt(5)); + int three = 3; + const ConstPropagatingPtr co(&three); + ConstPropagatingPtr o(&three); + EXPECT_TRUE(m.Matches(o)); + EXPECT_TRUE(m.Matches(co)); + *o = 6; + EXPECT_FALSE(m.Matches(o)); + EXPECT_FALSE(m.Matches(ConstPropagatingPtr())); +} + +TEST(PointeeTest, NeverMatchesNull) { + const Matcher m = Pointee(_); + EXPECT_FALSE(m.Matches(nullptr)); +} + +// Tests that we can write Pointee(value) instead of Pointee(Eq(value)). +TEST(PointeeTest, MatchesAgainstAValue) { + const Matcher 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 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 m = Pointee(StartsWith("Hi")); + + EXPECT_EQ("", Explain(m, static_cast(nullptr))); + + const Matcher 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 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 m = Field(&AStruct::x, Ge(0)); + Matcher 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 m = Field(&AStruct::y, Ge(0.0)); + Matcher 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 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 m = Field(&AStruct::p, static_cast(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 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 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 m = Field(&AStruct::x, Matcher(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 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 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 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 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 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 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 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 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 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 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 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 m = Field(&AStruct::x, Ge(0)); + + AStruct a; + a.x = 1; + EXPECT_EQ("", Explain(m, static_cast(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 m = Field("field_name", &AStruct::x, Ge(0)); + + AStruct a; + a.x = 1; + EXPECT_EQ("", Explain(m, static_cast(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 m = Property(&AClass::n, Ge(0)); + Matcher 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 m = Property(&AClass::s, StartsWith("hi")); + Matcher 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 m = Property(&AClass::s_ref, StartsWith("hi")); + Matcher 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 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 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 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 m = Property(&AClass::n, Matcher(Ge(0))); + + Matcher m_with_name = + Property("n", &AClass::n, Matcher(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 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 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 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 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 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 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 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 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 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 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 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 m = Property(&AClass::n, Ge(0)); + + AClass a; + a.set_n(1); + EXPECT_EQ("", Explain(m, static_cast(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 m = Property("fancy_name", &AClass::n, Ge(0)); + + AClass a; + a.set_n(1); + EXPECT_EQ("", Explain(m, static_cast(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 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 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 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 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 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 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 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 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 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 matcher = ResultOf(IntFunction, Matcher(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(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 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 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(strlen(s)); } + std::string operator()(int* p) { return p ? "good ptr" : "null"; } +}; + +TEST(ResultOfTest, WorksForPolymorphicFunctors) { + Matcher matcher_int = ResultOf(PolymorphicFunctor(), Ge(5)); + + EXPECT_TRUE(matcher_int.Matches(10)); + EXPECT_FALSE(matcher_int.Matches(2)); + + Matcher matcher_string = ResultOf(PolymorphicFunctor(), Ge(5)); + + EXPECT_TRUE(matcher_string.Matches("long string")); + EXPECT_FALSE(matcher_string.Matches("shrt")); +} + +TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) { + Matcher matcher = ResultOf(PolymorphicFunctor(), "good ptr"); + + int n = 0; + EXPECT_TRUE(matcher.Matches(&n)); + EXPECT_FALSE(matcher.Matches(nullptr)); +} + +TEST(ResultOfTest, WorksForLambdas) { + Matcher matcher = ResultOf( + [](int str_len) { + return std::string(static_cast(str_len), 'x'); + }, + "xxx"); + EXPECT_TRUE(matcher.Matches(3)); + EXPECT_FALSE(matcher.Matches(1)); +} + +TEST(ResultOfTest, WorksForNonCopyableArguments) { + Matcher> matcher = ResultOf( + [](const std::unique_ptr& str_len) { + return std::string(static_cast(*str_len), 'x'); + }, + "xxx"); + EXPECT_TRUE(matcher.Matches(std::unique_ptr(new int(3)))); + EXPECT_FALSE(matcher.Matches(std::unique_ptr(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 matcher2 = ResultOf(ReferencingFunction, Eq(&n)); + EXPECT_TRUE(matcher2.Matches(n)); + EXPECT_FALSE(matcher2.Matches(n2)); + + Matcher matcher3 = ResultOf(ReferencingFunctor(), Eq(&n)); + EXPECT_TRUE(matcher3.Matches(n)); + EXPECT_FALSE(matcher3.Matches(n2)); +} + +TEST(SizeIsTest, ImplementsSizeIs) { + vector 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 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 container; + Matcher&> 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> 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> m1 = SizeIs(2); + Matcher> m2 = SizeIs(Lt(2u)); + Matcher> m3 = SizeIs(AnyOf(0, 3)); + Matcher> m4 = SizeIs(Gt(1u)); + vector 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 numbers; + EXPECT_THAT(numbers, WhenSortedBy(less(), ElementsAre())); + EXPECT_THAT(numbers, Not(WhenSortedBy(less(), ElementsAre(1)))); +} + +TEST(WhenSortedByTest, WorksForNonEmptyContainer) { + vector numbers; + numbers.push_back(3); + numbers.push_back(1); + numbers.push_back(2); + numbers.push_back(2); + EXPECT_THAT(numbers, + WhenSortedBy(greater(), ElementsAre(3, 2, 2, 1))); + EXPECT_THAT(numbers, + Not(WhenSortedBy(greater(), ElementsAre(1, 2, 2, 3)))); +} + +TEST(WhenSortedByTest, WorksForNonVectorContainer) { + list words; + words.push_back("say"); + words.push_back("hello"); + words.push_back("world"); + EXPECT_THAT(words, WhenSortedBy(less(), + ElementsAre("hello", "say", "world"))); + EXPECT_THAT(words, Not(WhenSortedBy(less(), + 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(), ElementsAre(1, 2, 3, 4))); + EXPECT_THAT(numbers, + WhenSortedBy(less(), ElementsAreArray(sorted_numbers))); + EXPECT_THAT(numbers, Not(WhenSortedBy(less(), ElementsAre(1, 3, 2, 4)))); +} + +TEST(WhenSortedByTest, CanDescribeSelf) { + const Matcher> m = WhenSortedBy(less(), 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(), ElementsAre(2, 3)), a)); + EXPECT_EQ("which is { 1, 2 } when sorted", + Explain(WhenSortedBy(less(), 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 numbers; + EXPECT_THAT(numbers, WhenSorted(ElementsAre())); + EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1)))); +} + +TEST(WhenSortedTest, WorksForNonEmptyContainer) { + list 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 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 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 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 d; + d.push_back(2); + d.push_back(1); + Matcher&> vector_match = ElementsAre(1, 2); + EXPECT_THAT(d, WhenSorted(vector_match)); + Matcher&> 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 +class Streamlike { + private: + class ConstIter; + + public: + typedef ConstIter const_iterator; + typedef T value_type; + + template + 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::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::iterator pos_; + }; + + friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) { + os << "["; + typedef typename std::list::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 remainder_; // modified by iteration +}; + +TEST(StreamlikeTest, Iteration) { + const int a[5] = {2, 1, 4, 5, 3}; + Streamlike s(a, a + 5); + Streamlike::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 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 s(a, a + 5); + EXPECT_THAT(s, BeginEndDistanceIs(5)); +} + +TEST(BeginEndDistanceIsTest, CanDescribeSelf) { + Matcher> 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> m1 = BeginEndDistanceIs(2); + Matcher> m2 = BeginEndDistanceIs(Lt(2)); + Matcher> m3 = BeginEndDistanceIs(AnyOf(0, 3)); + Matcher> m4 = BeginEndDistanceIs(GreaterThan(1)); + vector 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 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 s(std::begin(a), std::end(a)); + Matcher&> 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 numbers; + vector 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 s(std::begin(a), std::end(a)); + + vector 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 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 IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + Describe(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 IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + DescribeNegation(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 v; + v.push_back(2); + v.push_back(3); + std::vector 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 numbers; + vector 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 s(std::begin(a), std::end(a)); + + vector 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 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 IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + + EXPECT_THAT( + Describe(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 IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + DescribeNegation(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 v; + v.push_back(2); + v.push_back(3); + std::vector 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 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 s(std::begin(a), std::end(a)); + + vector 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 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 s(std::begin(a), std::end(a)); + do { + StringMatchResultListener listener; + EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener)) + << listener.str(); + } while (std::next_permutation(s.begin(), s.end())); +} + +TEST(UnorderedElementsAreArrayTest, VectorBool) { + const bool a[] = {0, 1, 0, 1, 1}; + const bool b[] = {1, 0, 1, 1, 0}; + std::vector expected(std::begin(a), std::end(a)); + std::vector 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 s(std::begin(a), std::end(a)); + + ::std::vector 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 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>( + {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); + EXPECT_THAT(a, Not(UnorderedElementsAreArray>( + {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 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 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 s(std::begin(a), std::end(a)); + std::vector> 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 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 s; + std::vector> 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 s; + std::vector> 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 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 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 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 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 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 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(UnorderedElementsAre()), Eq("is empty")); + EXPECT_THAT(Describe(UnorderedElementsAre(345)), + Eq("has 1 element and that element is equal to 345")); + EXPECT_THAT(Describe(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(UnorderedElementsAre()), + Eq("isn't empty")); + EXPECT_THAT( + DescribeNegation(UnorderedElementsAre(345)), + Eq("doesn't have 1 element, or has 1 element that isn't equal to 345")); + EXPECT_THAT(DescribeNegation(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 a; // empty + + Matcher> m = Each(2); + EXPECT_EQ("", Explain(m, a)); + + Matcher 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> m = Each(1); + EXPECT_EQ("only contains elements that is equal to 1", Describe(m)); + + Matcher> m2 = Not(m); + EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2)); +} + +TEST(EachTest, MatchesVectorWhenAllElementsMatch) { + vector 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 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 my_map; + const char* bar = "a string"; + my_map[bar] = 2; + EXPECT_THAT(my_map, Each(make_pair(bar, 2))); + + map 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 + bool MatchAndExplain(const std::tuple& 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 IsHalfOf() { + return MakePolymorphicMatcher(IsHalfOfMatcher()); +} + +TEST(PointwiseTest, DescribesSelf) { + vector rhs; + rhs.push_back(1); + rhs.push_back(2); + rhs.push_back(3); + const Matcher&> 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 rhs; + rhs.push_back(2); + rhs.push_back(4); + + int lhs[] = {1, 2}; + const Matcher 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 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 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 rhs(3, false); + rhs[1] = true; + vector lhs = rhs; + EXPECT_THAT(lhs, Pointwise(Eq(), rhs)); + rhs[0] = true; + EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); +} + +TEST(PointwiseTest, WorksForRhsInitializerList) { + const vector 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> m1 = IsHalfOf(); + EXPECT_THAT(lhs, Pointwise(m1, rhs)); + EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs)); + + // This type works as a std::tuple can be + // implicitly cast to std::tuple. + const Matcher> 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{1, 2}))); + helper.Call(MakeUniquePtrs({1, 2})); +} + +TEST(UnorderedPointwiseTest, DescribesSelf) { + vector rhs; + rhs.push_back(1); + rhs.push_back(2); + rhs.push_back(3); + const Matcher&> 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 rhs; + rhs.push_back(2); + rhs.push_back(4); + + int lhs[] = {2, 1}; + const Matcher 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 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 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 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> m1 = IsHalfOf(); + EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs)); + + // This type works as a std::tuple can be + // implicitly cast to std::tuple. + const Matcher> m2 = IsHalfOf(); + EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs)); +} + +TEST(UnorderedPointwiseTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(), + std::vector{1, 2}))); + helper.Call(MakeUniquePtrs({2, 1})); +} + +TEST(PointeeTest, WorksOnMoveOnlyType) { + std::unique_ptr 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 { + 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> 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()) + ", [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()) + ", [MatchAndExplain]"; + EXPECT_EQ(expect, result.message()); +} + +// Tests for ElementsAre(). + +TEST(ElementsAreTest, CanDescribeExpectingNoElement) { + Matcher&> m = ElementsAre(); + EXPECT_EQ("is empty", Describe(m)); +} + +TEST(ElementsAreTest, CanDescribeExpectingOneElement) { + Matcher> m = ElementsAre(Gt(5)); + EXPECT_EQ("has 1 element that is > 5", Describe(m)); +} + +TEST(ElementsAreTest, CanDescribeExpectingManyElements) { + Matcher> 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> m = ElementsAre(); + EXPECT_EQ("isn't empty", DescribeNegation(m)); +} + +TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElement) { + Matcher&> m = ElementsAre(Gt(5)); + EXPECT_EQ( + "doesn't have 1 element, or\n" + "element #0 isn't > 5", + DescribeNegation(m)); +} + +TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) { + Matcher&> 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&> m = ElementsAre(1, Ne(2)); + + list 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&> m = + ElementsAre(GreaterThan(1), 0, GreaterThan(2)); + + const int a[] = {10, 0, 100}; + vector 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&> m = ElementsAre(1, 3); + + list 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&> m = ElementsAre(1, GreaterThan(5)); + + vector 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 test_vector; + test_vector.push_back("test string"); + + EXPECT_THAT(test_vector, ElementsAre(StrEq("test string"))); +} + +TEST(ElementsAreTest, MatchesOneElementList) { + list test_list; + test_list.push_back("test string"); + + EXPECT_THAT(test_list, ElementsAre("test string")); +} + +TEST(ElementsAreTest, MatchesThreeElementVector) { + vector 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 test_vector; + test_vector.push_back(4); + + EXPECT_THAT(test_vector, ElementsAre(Eq(4))); +} + +TEST(ElementsAreTest, MatchesOneElementAnyMatcher) { + vector test_vector; + test_vector.push_back(4); + + EXPECT_THAT(test_vector, ElementsAre(_)); +} + +TEST(ElementsAreTest, MatchesOneElementValue) { + vector test_vector; + test_vector.push_back(4); + + EXPECT_THAT(test_vector, ElementsAre(4)); +} + +TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) { + vector 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 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 test_vector; + test_vector.push_back("test string"); + test_vector.push_back("test string"); + + Matcher> m = ElementsAre(StrEq("test string")); + EXPECT_FALSE(m.Matches(test_vector)); +} + +TEST(ElementsAreTest, DoesNotMatchWrongValue) { + vector test_vector; + test_vector.push_back("other string"); + + Matcher> m = ElementsAre(StrEq("test string")); + EXPECT_FALSE(m.Matches(test_vector)); +} + +TEST(ElementsAreTest, DoesNotMatchWrongOrder) { + vector test_vector; + test_vector.push_back("one"); + test_vector.push_back("three"); + test_vector.push_back("two"); + + Matcher> m = + ElementsAre(StrEq("one"), StrEq("two"), StrEq("three")); + EXPECT_FALSE(m.Matches(test_vector)); +} + +TEST(ElementsAreTest, WorksForNestedContainer) { + constexpr std::array strings = {{"Hi", "world"}}; + + vector> 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 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 v(std::begin(a), std::end(a)); + + EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _))); + EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3)))); +} + +TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) { + int array[] = {0, 1, 2}; + EXPECT_THAT(array, ElementsAre(0, 1, _)); + EXPECT_THAT(array, Not(ElementsAre(1, _, _))); + EXPECT_THAT(array, Not(ElementsAre(0, _))); +} + +class NativeArrayPassedAsPointerAndSize { + public: + NativeArrayPassedAsPointerAndSize() {} + + MOCK_METHOD(void, Helper, (int* array, int size)); + + private: + NativeArrayPassedAsPointerAndSize(const NativeArrayPassedAsPointerAndSize&) = + delete; + NativeArrayPassedAsPointerAndSize& operator=( + const NativeArrayPassedAsPointerAndSize&) = delete; +}; + +TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) { + int array[] = {0, 1}; + ::std::tuple 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> + 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 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 a = {{"one", "two", "three"}}; + + vector 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 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 kMatcherArray[] = {StrEq("one"), StrEq("two"), + StrEq("three")}; + + vector 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 test_vector(std::begin(a), std::end(a)); + const vector 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>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); + EXPECT_THAT(a, Not(ElementsAreArray>( + {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)}))); +} + +TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) { + const int a[] = {1, 2, 3}; + const Matcher kMatchers[] = {Eq(1), Eq(2), Eq(3)}; + vector test_vector(std::begin(a), std::end(a)); + const vector> 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 test_vector(std::begin(a), std::end(a)); + const vector 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()), 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 test_vector(std::begin(a), std::end(a)); + vector expect(std::begin(a), std::end(a)); + ElementsAreArrayMatcher 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 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 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 some_list; + some_list.push_back(3); + some_list.push_back(1); + EXPECT_THAT(some_list, Not(Contains(4))); +} + +TEST(ContainsTest, SetMatchesWhenElementIsInContainer) { + set 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 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 some_set; + some_set.insert(3); + some_set.insert(1); + EXPECT_THAT(some_set, Not(Contains(4))); + + set 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 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> m = Contains(1); + EXPECT_EQ("contains at least one element that is equal to 1", Describe(m)); + + Matcher> m2 = Not(m); + EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2)); +} + +TEST(ContainsTest, MapMatchesWhenElementIsInContainer) { + map my_map; + const char* bar = "a string"; + my_map[bar] = 2; + EXPECT_THAT(my_map, Contains(pair(bar, 2))); + + map another_map; + another_map["fee"] = 1; + another_map["fie"] = 2; + another_map["foe"] = 3; + another_map["fum"] = 4; + EXPECT_THAT(another_map, + Contains(pair(std::string("fee"), 1))); + EXPECT_THAT(another_map, Contains(pair("fie", 2))); +} + +TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) { + map some_map; + some_map[1] = 11; + some_map[2] = 22; + EXPECT_THAT(some_map, Not(Contains(pair(2, 23)))); +} + +TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) { + const char* string_array[] = {"fee", "fie", "foe", "fum"}; + EXPECT_THAT(string_array, Contains(Eq(std::string("fum")))); +} + +TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) { + int int_array[] = {1, 2, 3, 4}; + EXPECT_THAT(int_array, Not(Contains(5))); +} + +TEST(ContainsTest, AcceptsMatcher) { + const int a[] = {1, 2, 3}; + EXPECT_THAT(a, Contains(Gt(2))); + EXPECT_THAT(a, Not(Contains(Gt(4)))); +} + +TEST(ContainsTest, WorksForNativeArrayAsTuple) { + const int a[] = {1, 2}; + const int* const pointer = a; + EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1)); + EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3)))); +} + +TEST(ContainsTest, WorksForTwoDimensionalNativeArray) { + int a[][3] = {{1, 2, 3}, {4, 5, 6}}; + EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6))); + EXPECT_THAT(a, Contains(Contains(5))); + EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5)))); + EXPECT_THAT(a, Contains(Not(Contains(5)))); +} + +} // namespace +} // namespace gmock_matchers_test +} // namespace testing + +#ifdef _MSC_VER +#pragma warning(pop) +#endif diff --git a/googlemock/test/gmock-matchers-misc_test.cc b/googlemock/test/gmock-matchers-misc_test.cc new file mode 100644 index 00000000..c68431c1 --- /dev/null +++ b/googlemock/test/gmock-matchers-misc_test.cc @@ -0,0 +1,1805 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file tests some commonly used argument matchers. + +// Silence warning C4244: 'initializing': conversion from 'int' to 'short', +// possible loss of data and C4100, unreferenced local parameter +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4244) +#pragma warning(disable : 4100) +#endif + +#include "test/gmock-matchers_test.h" + +namespace testing { +namespace gmock_matchers_test { +namespace { + +TEST(AddressTest, NonConst) { + int n = 1; + const Matcher 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 m = Address(Eq(&n)); + + EXPECT_TRUE(m.Matches(n)); + + int other = 5; + + EXPECT_FALSE(m.Matches(other)); +} + +TEST(AddressTest, MatcherDoesntCopy) { + std::unique_ptr n(new int(1)); + const Matcher> m = Address(Eq(&n)); + + EXPECT_TRUE(m.Matches(n)); +} + +TEST(AddressTest, Describe) { + Matcher 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 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 m = Ge(ByRef(value2)); + + NotCopyable n1(1), n2(2); + EXPECT_FALSE(m.Matches(n1)); + EXPECT_TRUE(m.Matches(n2)); +} + +TEST(IsEmptyTest, ImplementsIsEmpty) { + vector 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> m = IsEmpty(); + EXPECT_EQ("is empty", Describe(m)); + EXPECT_EQ("isn't empty", DescribeNegation(m)); +} + +TEST(IsEmptyTest, ExplainsResult) { + Matcher> m = IsEmpty(); + vector 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 null_unique; + std::unique_ptr nonnull_unique(new int(0)); + EXPECT_THAT(null_unique, Not(IsTrue())); + EXPECT_THAT(null_unique, IsFalse()); + EXPECT_THAT(nonnull_unique, IsTrue()); + EXPECT_THAT(nonnull_unique, Not(IsFalse())); +} + +#if GTEST_HAS_TYPED_TEST +// Tests ContainerEq with different container types, and +// different element types. + +template +class ContainerEqTest : public testing::Test {}; + +typedef testing::Types, vector, multiset, list> + 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 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 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 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 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 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 my_set(vals, vals + 6); + vector test_set(test_vals, test_vals + 3); + const Matcher> 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 my_set(vals, vals + 6); + list test_set(test_vals, test_vals + 7); + const Matcher&> 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 my_set(vals, vals + 6); + list test_set(test_vals, test_vals + 5); + const Matcher> 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 my_set(vals, vals + 6); + vector test_set(test_vals, test_vals + 5); + const Matcher> 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 my_map; + my_map[0] = "a"; + my_map[1] = "b"; + + map test_map; + test_map[0] = "aa"; + test_map[1] = "b"; + + const Matcher&> 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 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 +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(-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 lhs_used_; + std::vector rhs_used_; + ElementMatcherPairs matches_; + ElementMatcherPairs best_so_far_; +}; + +template +const size_t BacktrackingMaxBPMState::kUnused; + +} // namespace + +// Implement a simple backtracking algorithm to determine if it is possible +// to find one element per matcher, without reusing elements. +template +ElementMatcherPairs FindBacktrackingMaxBPM(const Graph& g) { + return BacktrackingMaxBPMState(&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 {}; + +// 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 seen_element(graph.LhsSize()); + std::vector 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> {}; + +TEST_F(BipartiteNonSquareTest, SimpleBacktracking) { + // ....... + // 0:-----\ : + // 1:---\ | : + // 2:---\ | : + // 3:-\ | | : + // :.......: + // 0 1 2 + MatchMatrix g(4, 3); + constexpr std::array, 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> {}; + +// Verifies a large sample of larger graphs. +TEST_P(BipartiteRandomTest, LargerNets) { + int nodes = GetParam().first; + int iters = GetParam().second; + MatchMatrix graph(static_cast(nodes), static_cast(nodes)); + + auto seed = static_cast(GTEST_FLAG_GET(random_seed)); + if (seed == 0) { + seed = static_cast(time(nullptr)); + } + + for (; iters > 0; --iters, ++seed) { + srand(static_cast(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 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")); + 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 >")); + EXPECT_FALSE(IsReadableTypeName("std::vector >")); +} + +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(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(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(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 +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> m = Optional(Eq(1)); + EXPECT_EQ("value is equal to 1", Describe(m)); +} + +TEST(OptionalTest, ExplainsSelf) { + const Matcher> m = Optional(Eq(1)); + EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional(1))); + EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional(2))); +} + +TEST(OptionalTest, MatchesNonEmptyOptional) { + const Matcher> m1 = Optional(1); + const Matcher> m2 = Optional(Eq(2)); + const Matcher> m3 = Optional(Lt(3)); + SampleOptional opt(1); + EXPECT_TRUE(m1.Matches(opt)); + EXPECT_FALSE(m2.Matches(opt)); + EXPECT_TRUE(m3.Matches(opt)); +} + +TEST(OptionalTest, DoesNotMatchNullopt) { + const Matcher> m = Optional(1); + SampleOptional empty; + EXPECT_FALSE(m.Matches(empty)); +} + +TEST(OptionalTest, WorksWithMoveOnly) { + Matcher>> m = Optional(Eq(nullptr)); + EXPECT_TRUE(m.Matches(SampleOptional>(nullptr))); +} + +class SampleVariantIntString { + public: + SampleVariantIntString(int i) : i_(i), has_int_(true) {} + SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {} + + template + friend bool holds_alternative(const SampleVariantIntString& value) { + return value.has_int_ == std::is_same::value; + } + + template + friend const T& get(const SampleVariantIntString& value) { + return value.get_impl(static_cast(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 m = VariantWith(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 m = VariantWith(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 m = VariantWith(Eq(1)); + EXPECT_TRUE(m.Matches(SampleVariantIntString(1))); + + m = VariantWith(Eq("1")); + EXPECT_TRUE(m.Matches(SampleVariantIntString("1"))); +} + +TEST(VariantTest, TypeDoesNotMatch) { + Matcher m = VariantWith(Eq(1)); + EXPECT_FALSE(m.Matches(SampleVariantIntString("1"))); + + m = VariantWith(Eq("1")); + EXPECT_FALSE(m.Matches(SampleVariantIntString(1))); +} + +TEST(VariantTest, InnerDoesNotMatch) { + Matcher m = VariantWith(Eq(1)); + EXPECT_FALSE(m.Matches(SampleVariantIntString(2))); + + m = VariantWith(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 + friend const T* any_cast(const SampleAnyType* any) { + return any->get_impl(static_cast(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 m = AnyWith(Eq(1)); + EXPECT_TRUE(m.Matches(SampleAnyType(1))); +} + +TEST(AnyWithTest, TestBadCastType) { + Matcher m = AnyWith(Eq("fail")); + EXPECT_FALSE(m.Matches(SampleAnyType(1))); +} + +TEST(AnyWithTest, TestUseInContainers) { + std::vector a; + a.emplace_back(1); + a.emplace_back(2); + a.emplace_back(3); + EXPECT_THAT( + a, ElementsAreArray({AnyWith(1), AnyWith(2), AnyWith(3)})); + + std::vector b; + b.emplace_back("hello"); + b.emplace_back("merhaba"); + b.emplace_back("salut"); + EXPECT_THAT(b, ElementsAreArray({AnyWith("hello"), + AnyWith("merhaba"), + AnyWith("salut")})); +} +TEST(AnyWithTest, TestCompare) { + EXPECT_THAT(SampleAnyType(1), AnyWith(Gt(0))); +} + +TEST(AnyWithTest, DescribesSelf) { + const Matcher m = AnyWith(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 m = AnyWith(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(m). + +TEST(ArgsTest, AcceptsZeroTemplateArg) { + const std::tuple t(5, true); + EXPECT_THAT(t, Args<>(Eq(std::tuple<>()))); + EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>())))); +} + +TEST(ArgsTest, AcceptsOneTemplateArg) { + const std::tuple 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 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 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 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 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 Tuple3; + const Matcher 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 Tuple3; + const Matcher 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> 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&> 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> 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> 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> { + public: + void DescribeTo(::std::ostream* /*os*/) const override {} + + bool MatchAndExplain(std::tuple 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> LessThan() { + return MakeMatcher(new LessThanMatcher); +} + +TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) { + const Matcher> 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 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 m1 = IsEven2(); + EXPECT_EQ("is even", Describe(m1)); + EXPECT_EQ("is odd", DescribeNegation(m1)); + + const Matcher 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 m1 = IsEven2(); + EXPECT_EQ("OK", Explain(m1, 4)); + EXPECT_EQ("% 2 == 1", Explain(m1, 5)); + + const Matcher 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(); + return arg.empty(); +} + +TEST(MatcherMacroTest, CanReferenceArgType) { + const Matcher<::std::string> m1 = IsEmptyString(); + EXPECT_TRUE(m1.Matches("")); + + const Matcher 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 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 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 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 m = + ReferencesUncopyable(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(); + StaticAssertTypeEq(); // NOLINT + StaticAssertTypeEq(); + 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_m = + ReferencesAnyOf(foo1, foo2); + + EXPECT_TRUE(const_m.Matches(foo1)); + EXPECT_TRUE(const_m.Matches(foo2)); + EXPECT_FALSE(const_m.Matches(foo3)); + + const Matcher m = + ReferencesAnyOf(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 m = + ReferencesAnyOf(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 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(3))); + EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d")); + + EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast(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(suffix); + return arg == prefix_str + suffix_char; +} + +TEST(MatcherPnMacroTest, SimpleTypePromotion) { + Matcher no_promo = EqConcat(std::string("foo"), 't'); + Matcher promo = EqConcat("foo", static_cast('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 a1 = EqualsSumOf(1); + + // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk + // variable, and so on. + EqualsSumOfMatcherP2 a2 = EqualsSumOf(1, '2'); + EqualsSumOfMatcherP3 a3 = EqualsSumOf(1, 2, '3'); + EqualsSumOfMatcherP4 a4 = EqualsSumOf(1, 2, 3, '4'); + EqualsSumOfMatcherP5 a5 = + EqualsSumOf(1, 2, 3, 4, '5'); + EqualsSumOfMatcherP6 a6 = + EqualsSumOf(1, 2, 3, 4, 5, '6'); + EqualsSumOfMatcherP7 a7 = + EqualsSumOf(1, 2, 3, 4, 5, 6, '7'); + EqualsSumOfMatcherP8 a8 = + EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8'); + EqualsSumOfMatcherP9 a9 = + EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9'); + EqualsSumOfMatcherP10 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(Value(arg, m1)) + + static_cast(Value(arg, m2)) + + static_cast(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 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{}, Not(Contains(_))); +} + +TEST_P(ContainsTimesP, ExplainsMatchResultCorrectly) { + const int a[2] = {1, 2}; + Matcher 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(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> m = Contains(1).Times(2); + EXPECT_EQ("quantity of elements that match is equal to 1 is equal to 2", + Describe(m)); + + Matcher> 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 v0{}; + std::vector v1{1}; + std::vector v2{2, 3}; + std::vector 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({})); // 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> 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 v0{}; + std::vector v1{1}; + std::vector 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({}))); // 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> matchers{Lt(1), Ge(2)}; + EXPECT_THAT(0, AnyOfArray(matchers)); + EXPECT_THAT(1, Not(AnyOfArray(matchers))); + EXPECT_THAT(2, AnyOfArray(matchers)); + // initializer_list + EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)})); + EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)}))); +} + +TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) { + // AnyOfArray and AllOfArry use the same underlying template-template, + // thus it is sufficient to test one here. + const std::vector v0{}; + const std::vector v1{1}; + const std::vector v2{2, 3}; + const Matcher m0 = AnyOfArray(v0); + const Matcher m1 = AnyOfArray(v1); + const Matcher 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 g1 = AnyOfArray({GreaterThan(1)}); + const Matcher 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 p(new int(3)); + EXPECT_THAT(p, IsNotNull()); + EXPECT_THAT(std::unique_ptr(), 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 p(new int(3)); + EXPECT_THAT(p, UniquePointee(3)); + EXPECT_THAT(p, Not(UniquePointee(2))); +} + +#if GTEST_HAS_EXCEPTIONS + +// std::function 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([]() { throw std::runtime_error("message"); }), + Throws()); + + EXPECT_THAT( + std::function([]() { throw std::runtime_error("message"); }), + ThrowsMessage(HasSubstr("message"))); +} + +TEST(ThrowsTest, PrintsExceptionWhat) { + EXPECT_THAT( + std::function([]() { throw std::runtime_error("ABC123XYZ"); }), + ThrowsMessage(HasSubstr("ABC123XYZ"))); +} + +TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) { + EXPECT_THAT(std::function([]() { throw std::exception(); }), + Throws()); +} + +TEST(ThrowsTest, CallableExecutedExactlyOnce) { + size_t a = 0; + + EXPECT_THAT(std::function([&a]() { + a++; + throw 10; + }), + Throws()); + EXPECT_EQ(a, 1u); + + EXPECT_THAT(std::function([&a]() { + a++; + throw std::runtime_error("message"); + }), + Throws()); + EXPECT_EQ(a, 2u); + + EXPECT_THAT(std::function([&a]() { + a++; + throw std::runtime_error("message"); + }), + ThrowsMessage(HasSubstr("message"))); + EXPECT_EQ(a, 3u); + + EXPECT_THAT(std::function([&a]() { + a++; + throw std::runtime_error("message"); + }), + Throws( + Property(&std::runtime_error::what, HasSubstr("message")))); + EXPECT_EQ(a, 4u); +} + +TEST(ThrowsTest, Describe) { + Matcher> matcher = Throws(); + std::stringstream ss; + matcher.DescribeTo(&ss); + auto explanation = ss.str(); + EXPECT_THAT(explanation, HasSubstr("std::runtime_error")); +} + +TEST(ThrowsTest, Success) { + Matcher> matcher = Throws(); + 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> matcher = Throws(); + 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> matcher = Throws(); + 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> matcher = Throws(); + StringMatchResultListener listener; + EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener)); + EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception")); +} + +class ThrowsPredicateTest + : public TestWithParam>> {}; + +TEST_P(ThrowsPredicateTest, Describe) { + Matcher> 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> 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> 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> 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> 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>( + ThrowsMessage(HasSubstr("error message"))))); + +// Tests that Throws(Matcher{}) compiles even when E2 != const E1&. +TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) { + { + Matcher> matcher = + ThrowsMessage(HasSubstr("error message")); + EXPECT_TRUE( + matcher.Matches([]() { throw std::runtime_error("error message"); })); + EXPECT_FALSE( + matcher.Matches([]() { throw std::runtime_error("wrong message"); })); + } + + { + Matcher inner = Eq(10); + Matcher> matcher = Throws(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("message")). +TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) { + Matcher> matcher = + ThrowsMessage("error message"); + EXPECT_TRUE( + matcher.Matches([]() { throw std::runtime_error("error message"); })); + EXPECT_FALSE(matcher.Matches( + []() { throw std::runtime_error("wrong error message"); })); +} + +#endif // GTEST_HAS_EXCEPTIONS + +} // namespace +} // namespace gmock_matchers_test +} // namespace testing + +#ifdef _MSC_VER +#pragma warning(pop) +#endif diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc deleted file mode 100644 index 6d480e0e..00000000 --- a/googlemock/test/gmock-matchers_test.cc +++ /dev/null @@ -1,8702 +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 -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "gmock/gmock-more-matchers.h" -#include "gmock/gmock.h" -#include "gtest/gtest-spi.h" -#include "gtest/gtest.h" - -namespace testing { -namespace gmock_matchers_test { -namespace { - -using std::greater; -using std::less; -using std::list; -using std::make_pair; -using std::map; -using std::multimap; -using std::multiset; -using std::ostream; -using std::pair; -using std::set; -using std::stringstream; -using std::vector; -using testing::internal::DummyMatchResultListener; -using testing::internal::ElementMatcherPair; -using testing::internal::ElementMatcherPairs; -using testing::internal::ElementsAreArrayMatcher; -using testing::internal::ExplainMatchFailureTupleTo; -using testing::internal::FloatingEqMatcher; -using testing::internal::FormatMatcherDescription; -using testing::internal::IsReadableTypeName; -using testing::internal::MatchMatrix; -using testing::internal::PredicateFormatterFromMatcher; -using testing::internal::RE; -using testing::internal::StreamMatchResultListener; -using testing::internal::Strings; - -// Helper for testing container-valued matchers in mock method context. It is -// important to test matchers in this context, since it requires additional type -// deduction beyond what EXPECT_THAT does, thus making it more restrictive. -struct ContainerHelper { - MOCK_METHOD1(Call, void(std::vector>)); -}; - -std::vector> MakeUniquePtrs(const std::vector& ints) { - std::vector> pointers; - for (int i : ints) pointers.emplace_back(new int(i)); - return pointers; -} - -// For testing ExplainMatchResultTo(). -template -class GreaterThanMatcher : public MatcherInterface { - public: - explicit GreaterThanMatcher(T rhs) : rhs_(rhs) {} - - void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; } - - bool MatchAndExplain(T lhs, MatchResultListener* listener) const override { - 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_; - } - - private: - const T rhs_; -}; - -template -Matcher GreaterThan(T n) { - return MakeMatcher(new GreaterThanMatcher(n)); -} - -std::string OfType(const std::string& type_name) { -#if GTEST_HAS_RTTI - return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : ""; -#else - return ""; -#endif -} - -// Returns the description of the given matcher. -template -std::string Describe(const Matcher& m) { - return DescribeMatcher(m); -} - -// Returns the description of the negation of the given matcher. -template -std::string DescribeNegation(const Matcher& m) { - return DescribeMatcher(m, true); -} - -// Returns the reason why x matches, or doesn't match, m. -template -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 interface doesn't -// change. -class EvenMatcherImpl : public MatcherInterface { - 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 { - 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 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 m; -} - -// Tests that Matcher can be constructed from a MatcherInterface*. -TEST(MatcherTest, CanBeConstructedFromMatcherInterface) { - const MatcherInterface* impl = new EvenMatcherImpl; - Matcher 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 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 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 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 m = _; } - -// Tests that matchers are copyable. -TEST(MatcherTest, IsCopyable) { - // Tests the copy constructor. - Matcher 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::DescribeTo() calls -// MatcherInterface::DescribeTo(). -TEST(MatcherTest, CanDescribeItself) { - EXPECT_EQ("is an even number", - Describe(Matcher(new EvenMatcherImpl))); -} - -// Tests Matcher::MatchAndExplain(). -TEST(MatcherTest, MatchAndExplain) { - Matcher 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 or Matcher. -TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { - Matcher m1 = "hi"; - EXPECT_TRUE(m1.Matches("hi")); - EXPECT_FALSE(m1.Matches("hello")); - - Matcher m2 = "hi"; - EXPECT_TRUE(m2.Matches("hi")); - EXPECT_FALSE(m2.Matches("hello")); -} - -// Tests that a string object can be implicitly converted to a -// Matcher or Matcher. -TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) { - Matcher m1 = std::string("hi"); - EXPECT_TRUE(m1.Matches("hi")); - EXPECT_FALSE(m1.Matches("hello")); - - Matcher 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 or Matcher. -TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { - Matcher m1 = "cats"; - EXPECT_TRUE(m1.Matches("cats")); - EXPECT_FALSE(m1.Matches("dogs")); - - Matcher 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 or Matcher. -TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) { - Matcher m1 = std::string("cats"); - EXPECT_TRUE(m1.Matches("cats")); - EXPECT_FALSE(m1.Matches("dogs")); - - Matcher 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 or Matcher. -TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) { - Matcher m1 = internal::StringView("cats"); - EXPECT_TRUE(m1.Matches("cats")); - EXPECT_FALSE(m1.Matches("dogs")); - - Matcher 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 object can be implicitly -// converted to a Matcher or Matcher via Eq(). -TEST(StringMatcherTest, - CanBeImplicitlyConstructedFromEqReferenceWrapperString) { - std::string value = "cats"; - Matcher m1 = Eq(std::ref(value)); - EXPECT_TRUE(m1.Matches("cats")); - EXPECT_FALSE(m1.Matches("dogs")); - - Matcher m2 = Eq(std::ref(value)); - EXPECT_TRUE(m2.Matches("cats")); - EXPECT_FALSE(m2.Matches("dogs")); -} - -// Tests that MakeMatcher() constructs a Matcher from a -// MatcherInterface* without requiring the user to explicitly -// write the type. -TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) { - const MatcherInterface* dummy_impl = new EvenMatcherImpl; - Matcher 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 - 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 where T is the argument's type. -PolymorphicMatcher ReferencesBarOrIsZero() { - return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl()); -} - -TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) { - // Using a polymorphic matcher to match a reference type. - Matcher 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 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 - 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 PolymorphicIsEven() { - return MakePolymorphicMatcher(PolymorphicIsEvenImpl()); -} - -TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) { - // Using PolymorphicIsEven() as a Matcher. - const Matcher m1 = PolymorphicIsEven(); - EXPECT_TRUE(m1.Matches(42)); - EXPECT_FALSE(m1.Matches(43)); - EXPECT_EQ("is even", Describe(m1)); - - const Matcher not_m1 = Not(m1); - EXPECT_EQ("is odd", Describe(not_m1)); - - EXPECT_EQ("% 2 == 0", Explain(m1, 42)); - - // Using PolymorphicIsEven() as a Matcher. - const Matcher m2 = PolymorphicIsEven(); - EXPECT_TRUE(m2.Matches('\x42')); - EXPECT_FALSE(m2.Matches('\x43')); - EXPECT_EQ("is even", Describe(m2)); - - const Matcher not_m2 = Not(m2); - EXPECT_EQ("is odd", Describe(not_m2)); - - EXPECT_EQ("% 2 == 0", Explain(m2, '\x42')); -} - -// Tests that MatcherCast(m) works when m is a polymorphic matcher. -TEST(MatcherCastTest, FromPolymorphicMatcher) { - Matcher m = MatcherCast(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(m) works when m is a Matcher where T -// can be statically converted to U. -TEST(MatcherCastTest, FromCompatibleType) { - Matcher m1 = Eq(2.0); - Matcher m2 = MatcherCast(m1); - EXPECT_TRUE(m2.Matches(2)); - EXPECT_FALSE(m2.Matches(3)); - - Matcher m3 = Truly(IsPositiveIntValue); - Matcher m4 = MatcherCast(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(m) works when m is a Matcher. -TEST(MatcherCastTest, FromConstReferenceToNonReference) { - Matcher m1 = Eq(0); - Matcher m2 = MatcherCast(m1); - EXPECT_TRUE(m2.Matches(0)); - EXPECT_FALSE(m2.Matches(1)); -} - -// Tests that MatcherCast(m) works when m is a Matcher. -TEST(MatcherCastTest, FromReferenceToNonReference) { - Matcher m1 = Eq(0); - Matcher m2 = MatcherCast(m1); - EXPECT_TRUE(m2.Matches(0)); - EXPECT_FALSE(m2.Matches(1)); -} - -// Tests that MatcherCast(m) works when m is a Matcher. -TEST(MatcherCastTest, FromNonReferenceToConstReference) { - Matcher m1 = Eq(0); - Matcher m2 = MatcherCast(m1); - EXPECT_TRUE(m2.Matches(0)); - EXPECT_FALSE(m2.Matches(1)); -} - -// Tests that MatcherCast(m) works when m is a Matcher. -TEST(MatcherCastTest, FromNonReferenceToReference) { - Matcher m1 = Eq(0); - Matcher m2 = MatcherCast(m1); - int n = 0; - EXPECT_TRUE(m2.Matches(n)); - n = 1; - EXPECT_FALSE(m2.Matches(n)); -} - -// Tests that MatcherCast(m) works when m is a Matcher. -TEST(MatcherCastTest, FromSameType) { - Matcher m1 = Eq(0); - Matcher m2 = MatcherCast(m1); - EXPECT_TRUE(m2.Matches(0)); - EXPECT_FALSE(m2.Matches(1)); -} - -// Tests that MatcherCast(m) works when m is a value of the same type as the -// value type of the Matcher. -TEST(MatcherCastTest, FromAValue) { - Matcher m = MatcherCast(42); - EXPECT_TRUE(m.Matches(42)); - EXPECT_FALSE(m.Matches(239)); -} - -// Tests that MatcherCast(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 m = MatcherCast('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(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 m1 = - MatcherCast(42); - EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); - - Matcher m2 = - MatcherCast(239); - EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); - - // When updating the following lines please also change the comment to - // namespace convertible_from_any. - Matcher m3 = - MatcherCast(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 - 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 m = MatcherCast(1); - EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); - EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); -} - -TEST(MatcherCastTest, FromConvertibleFromAny) { - Matcher m = - MatcherCast(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 m = MatcherCast(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(m) works when m is a polymorphic matcher. -TEST(SafeMatcherCastTest, FromPolymorphicMatcher) { - Matcher m2 = SafeMatcherCast(Eq(32)); - EXPECT_TRUE(m2.Matches(' ')); - EXPECT_FALSE(m2.Matches('\n')); -} - -// Tests that SafeMatcherCast(m) works when m is a Matcher where -// T and U are arithmetic types and T can be losslessly converted to -// U. -TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) { - Matcher m1 = DoubleEq(1.0); - Matcher m2 = SafeMatcherCast(m1); - EXPECT_TRUE(m2.Matches(1.0f)); - EXPECT_FALSE(m2.Matches(2.0f)); - - Matcher m3 = SafeMatcherCast(TypedEq('a')); - EXPECT_TRUE(m3.Matches('a')); - EXPECT_FALSE(m3.Matches('b')); -} - -// Tests that SafeMatcherCast(m) works when m is a Matcher where T and U -// are pointers or references to a derived and a base class, correspondingly. -TEST(SafeMatcherCastTest, FromBaseClass) { - Derived d, d2; - Matcher m1 = Eq(&d); - Matcher m2 = SafeMatcherCast(m1); - EXPECT_TRUE(m2.Matches(&d)); - EXPECT_FALSE(m2.Matches(&d2)); - - Matcher m3 = Ref(d); - Matcher m4 = SafeMatcherCast(m3); - EXPECT_TRUE(m4.Matches(d)); - EXPECT_FALSE(m4.Matches(d2)); -} - -// Tests that SafeMatcherCast(m) works when m is a Matcher. -TEST(SafeMatcherCastTest, FromConstReferenceToReference) { - int n = 0; - Matcher m1 = Ref(n); - Matcher m2 = SafeMatcherCast(m1); - int n1 = 0; - EXPECT_TRUE(m2.Matches(n)); - EXPECT_FALSE(m2.Matches(n1)); -} - -// Tests that MatcherCast(m) works when m is a Matcher. -TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) { - Matcher> m1 = IsNull(); - Matcher&> m2 = - SafeMatcherCast&>(m1); - EXPECT_TRUE(m2.Matches(std::unique_ptr())); - EXPECT_FALSE(m2.Matches(std::unique_ptr(new int))); -} - -// Tests that SafeMatcherCast(m) works when m is a Matcher. -TEST(SafeMatcherCastTest, FromNonReferenceToReference) { - Matcher m1 = Eq(0); - Matcher m2 = SafeMatcherCast(m1); - int n = 0; - EXPECT_TRUE(m2.Matches(n)); - n = 1; - EXPECT_FALSE(m2.Matches(n)); -} - -// Tests that SafeMatcherCast(m) works when m is a Matcher. -TEST(SafeMatcherCastTest, FromSameType) { - Matcher m1 = Eq(0); - Matcher m2 = SafeMatcherCast(m1); - EXPECT_TRUE(m2.Matches(0)); - EXPECT_FALSE(m2.Matches(1)); -} - -#if !defined _MSC_VER - -namespace convertible_from_any { -TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) { - Matcher m = SafeMatcherCast(1); - EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); - EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); -} - -TEST(SafeMatcherCastTest, FromConvertibleFromAny) { - Matcher m = - SafeMatcherCast(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 m = SafeMatcherCast(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() matches any value of type T. -TEST(ATest, MatchesAnyValue) { - // Tests a matcher for a value type. - Matcher m1 = A(); - 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 m2 = A(); - EXPECT_TRUE(m2.Matches(a)); - EXPECT_TRUE(m2.Matches(b)); -} - -TEST(ATest, WorksForDerivedClass) { - Base base; - Derived derived; - EXPECT_THAT(&base, A()); - // This shouldn't compile: EXPECT_THAT(&base, A()); - EXPECT_THAT(&derived, A()); - EXPECT_THAT(&derived, A()); -} - -// Tests that A() describes itself properly. -TEST(ATest, CanDescribeSelf) { - EXPECT_EQ("is anything", Describe(A())); -} - -// Tests that An() matches any value of type T. -TEST(AnTest, MatchesAnyValue) { - // Tests a matcher for a value type. - Matcher m1 = An(); - EXPECT_TRUE(m1.Matches(9143)); - EXPECT_TRUE(m1.Matches(-1532)); - - // Tests a matcher for a reference type. - int a = 2; - int b = -6; - Matcher m2 = An(); - EXPECT_TRUE(m2.Matches(a)); - EXPECT_TRUE(m2.Matches(b)); -} - -// Tests that An() describes itself properly. -TEST(AnTest, CanDescribeSelf) { - EXPECT_EQ("is anything", Describe(An())); -} - -// 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 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 m2 = _; - EXPECT_TRUE(m2.Matches(a)); - EXPECT_TRUE(m2.Matches(b)); -} - -// Tests that _ describes itself properly. -TEST(UnderscoreTest, CanDescribeSelf) { - Matcher 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 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 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 m1 = Eq(1); - EXPECT_TRUE(m1.Matches(1)); - EXPECT_FALSE(m1.Matches(2)); - - Matcher m2 = Eq(1); - EXPECT_TRUE(m2.Matches('\1')); - EXPECT_FALSE(m2.Matches('a')); -} - -// Tests that TypedEq(v) matches values of type T that's equal to v. -TEST(TypedEqTest, ChecksEqualityForGivenType) { - Matcher m1 = TypedEq('a'); - EXPECT_TRUE(m1.Matches('a')); - EXPECT_FALSE(m1.Matches('b')); - - Matcher m2 = TypedEq(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(2))); -} - -// Tests that TypedEq(v) has type Matcher. - -// Type::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 -struct Type { - static bool IsTypeOf(const T& /* v */) { return true; } - - template - static void IsTypeOf(T2 v); -}; - -TEST(TypedEqTest, HasSpecifiedType) { - // Verfies that the type of TypedEq(v) is Matcher. - Type >::IsTypeOf(TypedEq(5)); - Type >::IsTypeOf(TypedEq(5)); -} - -// Tests that Ge(v) matches anything >= v. -TEST(GeTest, ImplementsGreaterThanOrEqual) { - Matcher 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 m = Ge(5); - EXPECT_EQ("is >= 5", Describe(m)); -} - -// Tests that Gt(v) matches anything > v. -TEST(GtTest, ImplementsGreaterThan) { - Matcher 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 m = Gt(5); - EXPECT_EQ("is > 5", Describe(m)); -} - -// Tests that Le(v) matches anything <= v. -TEST(LeTest, ImplementsLessThanOrEqual) { - Matcher 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 m = Le(5); - EXPECT_EQ("is <= 5", Describe(m)); -} - -// Tests that Lt(v) matches anything < v. -TEST(LtTest, ImplementsLessThan) { - Matcher 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 m = Lt(5); - EXPECT_EQ("is < 5", Describe(m)); -} - -// Tests that Ne(v) matches anything != v. -TEST(NeTest, ImplementsNotEqual) { - Matcher 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 m = Ne(5); - EXPECT_EQ("isn't equal to 5", Describe(m)); -} - -class MoveOnly { - public: - explicit MoveOnly(int i) : i_(i) {} - MoveOnly(const MoveOnly&) = delete; - MoveOnly(MoveOnly&&) = default; - MoveOnly& operator=(const MoveOnly&) = delete; - MoveOnly& operator=(MoveOnly&&) = default; - - bool operator==(const MoveOnly& other) const { return i_ == other.i_; } - bool operator!=(const MoveOnly& other) const { return i_ != other.i_; } - bool operator<(const MoveOnly& other) const { return i_ < other.i_; } - bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; } - bool operator>(const MoveOnly& other) const { return i_ > other.i_; } - bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; } - - private: - int i_; -}; - -struct MoveHelper { - MOCK_METHOD1(Call, void(MoveOnly)); -}; - -// Disable this test in VS 2015 (version 14), where it fails when SEH is enabled -#if defined(_MSC_VER) && (_MSC_VER < 1910) -TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) { -#else -TEST(ComparisonBaseTest, WorksWithMoveOnly) { -#endif - MoveOnly m{0}; - MoveHelper helper; - - EXPECT_CALL(helper, Call(Eq(ByRef(m)))); - helper.Call(MoveOnly(0)); - EXPECT_CALL(helper, Call(Ne(ByRef(m)))); - helper.Call(MoveOnly(1)); - EXPECT_CALL(helper, Call(Le(ByRef(m)))); - helper.Call(MoveOnly(0)); - EXPECT_CALL(helper, Call(Lt(ByRef(m)))); - helper.Call(MoveOnly(-1)); - EXPECT_CALL(helper, Call(Ge(ByRef(m)))); - helper.Call(MoveOnly(0)); - EXPECT_CALL(helper, Call(Gt(ByRef(m)))); - helper.Call(MoveOnly(1)); -} - -// Tests that IsNull() matches any NULL pointer of any type. -TEST(IsNullTest, MatchesNullPointer) { - Matcher m1 = IsNull(); - int* p1 = nullptr; - int n = 0; - EXPECT_TRUE(m1.Matches(p1)); - EXPECT_FALSE(m1.Matches(&n)); - - Matcher m2 = IsNull(); - const char* p2 = nullptr; - EXPECT_TRUE(m2.Matches(p2)); - EXPECT_FALSE(m2.Matches("hi")); - - Matcher m3 = IsNull(); - void* p3 = nullptr; - EXPECT_TRUE(m3.Matches(p3)); - EXPECT_FALSE(m3.Matches(reinterpret_cast(0xbeef))); -} - -TEST(IsNullTest, StdFunction) { - const Matcher> m = IsNull(); - - EXPECT_TRUE(m.Matches(std::function())); - EXPECT_FALSE(m.Matches([]{})); -} - -// Tests that IsNull() describes itself properly. -TEST(IsNullTest, CanDescribeSelf) { - Matcher 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 m1 = NotNull(); - int* p1 = nullptr; - int n = 0; - EXPECT_FALSE(m1.Matches(p1)); - EXPECT_TRUE(m1.Matches(&n)); - - Matcher m2 = NotNull(); - const char* p2 = nullptr; - EXPECT_FALSE(m2.Matches(p2)); - EXPECT_TRUE(m2.Matches("hi")); -} - -TEST(NotNullTest, LinkedPtr) { - const Matcher> m = NotNull(); - const std::shared_ptr null_p; - const std::shared_ptr non_null_p(new int); - - EXPECT_FALSE(m.Matches(null_p)); - EXPECT_TRUE(m.Matches(non_null_p)); -} - -TEST(NotNullTest, ReferenceToConstLinkedPtr) { - const Matcher&> m = NotNull(); - const std::shared_ptr null_p; - const std::shared_ptr non_null_p(new double); - - EXPECT_FALSE(m.Matches(null_p)); - EXPECT_TRUE(m.Matches(non_null_p)); -} - -TEST(NotNullTest, StdFunction) { - const Matcher> m = NotNull(); - - EXPECT_TRUE(m.Matches([]{})); - EXPECT_FALSE(m.Matches(std::function())); -} - -// Tests that NotNull() describes itself properly. -TEST(NotNullTest, CanDescribeSelf) { - Matcher 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 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 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 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 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(Ref(n)), n), - StartsWith("which is located @")); - - int m = 0; - EXPECT_THAT(Explain(Matcher(Ref(n)), m), - StartsWith("which is located @")); -} - -// Tests string comparison matchers. - -template -std::string FromStringLike(internal::StringLike 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 m = StrEq(std::string("Hello")); - EXPECT_TRUE(m.Matches("Hello")); - EXPECT_FALSE(m.Matches("hello")); - EXPECT_FALSE(m.Matches(nullptr)); - - Matcher m2 = StrEq("Hello"); - EXPECT_TRUE(m2.Matches("Hello")); - EXPECT_FALSE(m2.Matches("Hi")); - -#if GTEST_INTERNAL_HAS_STRING_VIEW - Matcher 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 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 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 m2 = StrEq(str); - EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2)); - str[0] = str[6] = str[7] = str[9] = str[10] = '\0'; - Matcher m3 = StrEq(str); - EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3)); -} - -TEST(StrNeTest, MatchesUnequalString) { - Matcher m = StrNe("Hello"); - EXPECT_TRUE(m.Matches("")); - EXPECT_TRUE(m.Matches(nullptr)); - EXPECT_FALSE(m.Matches("Hello")); - - Matcher m2 = StrNe(std::string("Hello")); - EXPECT_TRUE(m2.Matches("hello")); - EXPECT_FALSE(m2.Matches("Hello")); - -#if GTEST_INTERNAL_HAS_STRING_VIEW - Matcher 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 m = StrNe("Hi"); - EXPECT_EQ("isn't equal to \"Hi\"", Describe(m)); -} - -TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) { - Matcher 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 m2 = StrCaseEq("Hello"); - EXPECT_TRUE(m2.Matches("hello")); - EXPECT_FALSE(m2.Matches("Hi")); - -#if GTEST_INTERNAL_HAS_STRING_VIEW - Matcher 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 m0 = StrCaseEq(str1); - EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0'))); - - str1[3] = str2[3] = '\0'; - Matcher 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 m2 = StrCaseEq(str1); - str1[9] = str2[9] = '\0'; - EXPECT_FALSE(m2.Matches(str2)); - - Matcher 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 m = StrCaseEq("Hi"); - EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m)); -} - -TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) { - Matcher m = StrCaseNe("Hello"); - EXPECT_TRUE(m.Matches("Hi")); - EXPECT_TRUE(m.Matches(nullptr)); - EXPECT_FALSE(m.Matches("Hello")); - EXPECT_FALSE(m.Matches("hello")); - - Matcher m2 = StrCaseNe(std::string("Hello")); - EXPECT_TRUE(m2.Matches("")); - EXPECT_FALSE(m2.Matches("Hello")); - -#if GTEST_INTERNAL_HAS_STRING_VIEW - Matcher 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 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 m1 = HasSubstr("foo"); - EXPECT_TRUE(m1.Matches(std::string("I love food."))); - EXPECT_FALSE(m1.Matches(std::string("tofo"))); - - const Matcher m2 = HasSubstr("foo"); - EXPECT_TRUE(m2.Matches(std::string("I love food."))); - EXPECT_FALSE(m2.Matches(std::string("tofo"))); - - const Matcher 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 m1 = HasSubstr("foo"); - EXPECT_TRUE(m1.Matches(const_cast("I love food."))); - EXPECT_FALSE(m1.Matches(const_cast("tofo"))); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher m2 = HasSubstr("foo"); - EXPECT_TRUE(m2.Matches("I love food.")); - EXPECT_FALSE(m2.Matches("tofo")); - EXPECT_FALSE(m2.Matches(nullptr)); - - const Matcher 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 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 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 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 m = HasSubstr("foo\n\""); - EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m)); -} - -TEST(KeyTest, CanDescribeSelf) { - Matcher&> 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 > 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 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> p; - EXPECT_THAT(p, Key(Eq(nullptr))); -} - -template -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 -auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag())) { - return value.GetImpl(Tag()); -} -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 v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; - EXPECT_THAT(v, Contains(Key(29))); -} - -TEST(KeyTest, SafelyCastsInnerMatcher) { - Matcher is_positive = Gt(0); - Matcher is_negative = Lt(0); - pair p('a', true); - EXPECT_THAT(p, Key(is_positive)); - EXPECT_THAT(p, Not(Key(is_negative))); -} - -TEST(KeyTest, InsideContainsUsingMap) { - map 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 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&> m1 = Pair("foo", 42); - Matcher > m2 = Pair("foo", 42); - Matcher > m3 = Pair("foo", 42); - - Matcher > m4 = Pair(25, "42"); - Matcher > m5 = Pair("25", 42); -} - -TEST(PairTest, CanDescribeSelf) { - Matcher&> 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&> 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 > 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 > 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 > 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 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> p; - p.second.reset(new int(7)); - EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr))); -} - -TEST(PairTest, SafelyCastsInnerMatchers) { - Matcher is_positive = Gt(0); - Matcher is_negative = Lt(0); - pair 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 container; - container.insert(make_pair(1, 'a')); - container.insert(make_pair(2, 'b')); - container.insert(make_pair(4, 'c')); - EXPECT_THAT(container, Contains(Pair(1, 'a'))); - EXPECT_THAT(container, Contains(Pair(1, _))); - EXPECT_THAT(container, Contains(Pair(_, 'a'))); - EXPECT_THAT(container, Not(Contains(Pair(3, _)))); -} - -TEST(FieldsAreTest, MatchesCorrectly) { - std::tuple 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&> m1 = FieldsAre("foo", 42); - EXPECT_EQ( - "has field #0 that is equal to \"foo\"" - ", and has field #1 that is equal to 42", - Describe(m1)); - EXPECT_EQ( - "has field #0 that isn't equal to \"foo\"" - ", or has field #1 that isn't equal to 42", - DescribeNegation(m1)); -} - -TEST(FieldsAreTest, CanExplainMatchResultTo) { - // The first one that fails is the one that gives the error. - Matcher> m = - FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0)); - - EXPECT_EQ("whose field #0 does not match, which is 1 less than 0", - Explain(m, std::make_tuple(-1, -2, -3))); - EXPECT_EQ("whose field #1 does not match, which is 2 less than 0", - Explain(m, std::make_tuple(1, -2, -3))); - EXPECT_EQ("whose field #2 does not match, which is 3 less than 0", - Explain(m, std::make_tuple(1, 2, -3))); - - // If they all match, we get a long explanation of success. - EXPECT_EQ( - "whose all elements match, " - "where field #0 is a value which is 1 more than 0" - ", and field #1 is a value which is 2 more than 0" - ", and field #2 is a value which is 3 more than 0", - Explain(m, std::make_tuple(1, 2, 3))); - - // Only print those that have an explanation. - m = FieldsAre(GreaterThan(0), 0, GreaterThan(0)); - EXPECT_EQ( - "whose all elements match, " - "where field #0 is a value which is 1 more than 0" - ", and field #2 is a value which is 3 more than 0", - Explain(m, std::make_tuple(1, 0, 3))); - - // If only one has an explanation, then print that one. - m = FieldsAre(0, GreaterThan(0), 0); - EXPECT_EQ( - "whose all elements match, " - "where field #1 is a value which is 1 more than 0", - Explain(m, std::make_tuple(0, 1, 0))); -} - -#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606 -TEST(FieldsAreTest, StructuredBindings) { - // testing::FieldsAre can also match aggregates and such with C++17 and up. - struct MyType { - int i; - std::string str; - }; - EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo"))); - - // Test all the supported arities. - struct MyVarType1 { - int a; - }; - EXPECT_THAT(MyVarType1{}, FieldsAre(0)); - struct MyVarType2 { - int a, b; - }; - EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0)); - struct MyVarType3 { - int a, b, c; - }; - EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0)); - struct MyVarType4 { - int a, b, c, d; - }; - EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0)); - struct MyVarType5 { - int a, b, c, d, e; - }; - EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0)); - struct MyVarType6 { - int a, b, c, d, e, f; - }; - EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0)); - struct MyVarType7 { - int a, b, c, d, e, f, g; - }; - EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0)); - struct MyVarType8 { - int a, b, c, d, e, f, g, h; - }; - EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0)); - struct MyVarType9 { - int a, b, c, d, e, f, g, h, i; - }; - EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0)); - struct MyVarType10 { - int a, b, c, d, e, f, g, h, i, j; - }; - EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); - struct MyVarType11 { - int a, b, c, d, e, f, g, h, i, j, k; - }; - EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); - struct MyVarType12 { - int a, b, c, d, e, f, g, h, i, j, k, l; - }; - EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); - struct MyVarType13 { - int a, b, c, d, e, f, g, h, i, j, k, l, m; - }; - EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); - struct MyVarType14 { - int a, b, c, d, e, f, g, h, i, j, k, l, m, n; - }; - EXPECT_THAT(MyVarType14{}, - FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); - struct MyVarType15 { - int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o; - }; - EXPECT_THAT(MyVarType15{}, - FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); - struct MyVarType16 { - int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p; - }; - EXPECT_THAT(MyVarType16{}, - FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); -} -#endif - -TEST(ContainsTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(Contains(Pointee(2)))); - helper.Call(MakeUniquePtrs({1, 2})); -} - -TEST(PairTest, UseGetInsteadOfMembers) { - PairWithGet pair{7, "ABC"}; - EXPECT_THAT(pair, Pair(7, "ABC")); - EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB"))); - EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC"))); - - std::vector 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 m1 = StartsWith(std::string("")); - EXPECT_TRUE(m1.Matches("Hi")); - EXPECT_TRUE(m1.Matches("")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher 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 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 m = StartsWith("Hi"); - EXPECT_EQ("starts with \"Hi\"", Describe(m)); -} - -// Tests EndsWith(s). - -TEST(EndsWithTest, MatchesStringWithGivenSuffix) { - const Matcher m1 = EndsWith(""); - EXPECT_TRUE(m1.Matches("Hi")); - EXPECT_TRUE(m1.Matches("")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher 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 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 m = EndsWith("Hi"); - EXPECT_EQ("ends with \"Hi\"", Describe(m)); -} - -// Tests WhenBase64Unescaped. - -TEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) { - const Matcher m1 = WhenBase64Unescaped(EndsWith("!")); - EXPECT_FALSE(m1.Matches("invalid base64")); - EXPECT_FALSE(m1.Matches("aGVsbG8gd29ybGQ=")); // hello world - EXPECT_TRUE(m1.Matches("aGVsbG8gd29ybGQh")); // hello world! - - const Matcher m2 = WhenBase64Unescaped(EndsWith("!")); - EXPECT_FALSE(m2.Matches("invalid base64")); - EXPECT_FALSE(m2.Matches("aGVsbG8gd29ybGQ=")); // hello world - EXPECT_TRUE(m2.Matches("aGVsbG8gd29ybGQh")); // hello world! - -#if GTEST_INTERNAL_HAS_STRING_VIEW - const Matcher m3 = - WhenBase64Unescaped(EndsWith("!")); - EXPECT_FALSE(m3.Matches("invalid base64")); - EXPECT_FALSE(m3.Matches("aGVsbG8gd29ybGQ=")); // hello world - EXPECT_TRUE(m3.Matches("aGVsbG8gd29ybGQh")); // hello world! -#endif // GTEST_INTERNAL_HAS_STRING_VIEW -} - -TEST(WhenBase64UnescapedTest, CanDescribeSelf) { - const Matcher m = WhenBase64Unescaped(EndsWith("!")); - EXPECT_EQ("matches after Base64Unescape ends with \"!\"", Describe(m)); -} - -// Tests MatchesRegex(). - -TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) { - const Matcher m1 = MatchesRegex("a.*z"); - EXPECT_TRUE(m1.Matches("az")); - EXPECT_TRUE(m1.Matches("abcz")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher 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 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 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 m1 = MatchesRegex(std::string("Hi.*")); - EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1)); - - Matcher m2 = MatchesRegex(new RE("a.*")); - EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2)); - -#if GTEST_INTERNAL_HAS_STRING_VIEW - Matcher 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 m1 = ContainsRegex(std::string("a.*z")); - EXPECT_TRUE(m1.Matches("az")); - EXPECT_TRUE(m1.Matches("0abcz1")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher 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 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 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 m1 = ContainsRegex("Hi.*"); - EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1)); - - Matcher m2 = ContainsRegex(new RE("a.*")); - EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2)); - -#if GTEST_INTERNAL_HAS_STRING_VIEW - Matcher 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 m = StrEq(::std::wstring(L"Hello")); - EXPECT_TRUE(m.Matches(L"Hello")); - EXPECT_FALSE(m.Matches(L"hello")); - EXPECT_FALSE(m.Matches(nullptr)); - - Matcher m2 = StrEq(L"Hello"); - EXPECT_TRUE(m2.Matches(L"Hello")); - EXPECT_FALSE(m2.Matches(L"Hi")); - - Matcher 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 m4 = StrEq(str); - EXPECT_TRUE(m4.Matches(str)); - str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; - Matcher 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 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 m5 = StrEq(str); - EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5)); -} - -TEST(StdWideStrNeTest, MatchesUnequalString) { - Matcher 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 m = StrNe(L"Hi"); - EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m)); -} - -TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { - Matcher 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 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 m0 = StrCaseEq(str1); - EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0'))); - - str1[3] = str2[3] = L'\0'; - Matcher 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 m2 = StrCaseEq(str1); - str1[9] = str2[9] = L'\0'; - EXPECT_FALSE(m2.Matches(str2)); - - Matcher 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 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 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 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 m1 = HasSubstr(L"foo"); - EXPECT_TRUE(m1.Matches(const_cast(L"I love food."))); - EXPECT_FALSE(m1.Matches(const_cast(L"tofo"))); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher 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 m1 = StartsWith(::std::wstring(L"")); - EXPECT_TRUE(m1.Matches(L"Hi")); - EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher 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 m = StartsWith(L"Hi"); - EXPECT_EQ("starts with L\"Hi\"", Describe(m)); -} - -// Tests EndsWith(s). - -TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) { - const Matcher m1 = EndsWith(L""); - EXPECT_TRUE(m1.Matches(L"Hi")); - EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher 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 m = EndsWith(L"Hi"); - EXPECT_EQ("ends with L\"Hi\"", Describe(m)); -} - -#endif // GTEST_HAS_STD_WSTRING - -typedef ::std::tuple Tuple2; // NOLINT - -// Tests that Eq() matches a 2-tuple where the first field == the -// second field. -TEST(Eq2Test, MatchesEqualArguments) { - Matcher 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 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 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 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 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 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 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 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 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 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 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 m = Ne(); - EXPECT_EQ("are an unequal pair", Describe(m)); -} - -TEST(PairMatchBaseTest, WorksWithMoveOnly) { - using Pointers = std::tuple, std::unique_ptr>; - Matcher 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::quiet_NaN(); - float other_nan = std::nanf("1"); - float real_value = 1.0f; - - Matcher m = IsNan(); - EXPECT_TRUE(m.Matches(quiet_nan)); - EXPECT_TRUE(m.Matches(other_nan)); - EXPECT_FALSE(m.Matches(real_value)); - - Matcher 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 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::quiet_NaN(); - double other_nan = std::nan("1"); - double real_value = 1.0; - - Matcher m = IsNan(); - EXPECT_TRUE(m.Matches(quiet_nan)); - EXPECT_TRUE(m.Matches(other_nan)); - EXPECT_FALSE(m.Matches(real_value)); - - Matcher 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 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::quiet_NaN(); - long double other_nan = std::nan("1"); - long double real_value = 1.0; - - Matcher m = IsNan(); - EXPECT_TRUE(m.Matches(quiet_nan)); - EXPECT_TRUE(m.Matches(other_nan)); - EXPECT_FALSE(m.Matches(real_value)); - - Matcher 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 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 mf = Not(IsNan()); - EXPECT_FALSE(mf.Matches(std::numeric_limits::quiet_NaN())); - EXPECT_FALSE(mf.Matches(std::nanf("1"))); - EXPECT_TRUE(mf.Matches(1.0)); - - Matcher md = Not(IsNan()); - EXPECT_FALSE(md.Matches(std::numeric_limits::quiet_NaN())); - EXPECT_FALSE(md.Matches(std::nan("1"))); - EXPECT_TRUE(md.Matches(1.0)); - - Matcher mld = Not(IsNan()); - EXPECT_FALSE(mld.Matches(std::numeric_limits::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 mf = IsNan(); - EXPECT_EQ("is NaN", Describe(mf)); - - Matcher md = IsNan(); - EXPECT_EQ("is NaN", Describe(md)); - - Matcher mld = IsNan(); - EXPECT_EQ("is NaN", Describe(mld)); -} - -// Tests that IsNan() can describe itself with Not. -TEST(IsNan, CanDescribeSelfWithNot) { - Matcher mf = Not(IsNan()); - EXPECT_EQ("isn't NaN", Describe(mf)); - - Matcher md = Not(IsNan()); - EXPECT_EQ("isn't NaN", Describe(md)); - - Matcher 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 Tpl; - Matcher 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&> 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 Tpl; - Matcher m = NanSensitiveFloatEq(); - EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); - EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), - std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); - EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); -} - -// Tests that NanSensitiveFloatEq() describes itself properly. -TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) { - Matcher&> 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 Tpl; - Matcher 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&> 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 Tpl; - Matcher m = NanSensitiveDoubleEq(); - EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); - EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), - std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); - EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); -} - -// Tests that DoubleEq() describes itself properly. -TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) { - Matcher&> 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 Tpl; - Matcher 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&> 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 Tpl; - Matcher 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::quiet_NaN(), - std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); - EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); -} - -// Tests that NanSensitiveFloatNear() describes itself properly. -TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) { - Matcher&> 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 Tpl; - Matcher 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&> 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 Tpl; - Matcher 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::quiet_NaN(), - std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); - EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); -} - -// Tests that NanSensitiveDoubleNear() describes itself properly. -TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) { - Matcher&> 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 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 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 greater_than_5 = Gt(5); - - Matcher m = Not(greater_than_5); - Matcher m2 = Not(greater_than_5); - Matcher m3 = Not(m); -} - -// Helper to allow easy testing of AllOf matchers with num parameters. -void AllOfMatches(int num, const Matcher& 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 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 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 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 greater_than_5 = Gt(5); - Matcher less_than_10 = Lt(10); - - Matcher m = AllOf(greater_than_5, less_than_10); - Matcher m2 = AllOf(greater_than_5, less_than_10); - Matcher m3 = AllOf(greater_than_5, m2); - - // Tests that BothOf works when composing itself. - Matcher m4 = AllOf(greater_than_5, less_than_10, less_than_10); - Matcher m5 = AllOf(greater_than_5, less_than_10, less_than_10); -} - -TEST(AllOfTest, ExplainsResult) { - Matcher 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& 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& 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 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 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 eq_red = Eq("red"); - Matcher ne_red = Ne("red"); - Matcher 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 eq_red = Eq("red"); - Matcher ne_red = Ne("red"); - Matcher 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 the variadic version of the ElementsAreMatcher -TEST(ElementsAreTest, HugeMatcher) { - vector 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 test_vector{ - "literal_string", "", "", "", "", "", "", "", "", "", "", ""}; - - EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _, - _, _, _, _, _, _)); -} - -// Tests the variadic version of the UnorderedElementsAreMatcher -TEST(ElementsAreTest, HugeMatcherUnordered) { - vector 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 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 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 greater_than_5 = Gt(5); - Matcher less_than_10 = Lt(10); - - Matcher m = AnyOf(greater_than_5, less_than_10); - Matcher m2 = AnyOf(greater_than_5, less_than_10); - Matcher m3 = AnyOf(greater_than_5, m2); - - // Tests that EitherOf works when composing itself. - Matcher m4 = AnyOf(greater_than_5, less_than_10, less_than_10); - Matcher m5 = AnyOf(greater_than_5, less_than_10, less_than_10); -} - -TEST(AnyOfTest, ExplainsResult) { - Matcher 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 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 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 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 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 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 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 is_zero = Eq(0); - EXPECT_TRUE(Value(0, is_zero)); - EXPECT_FALSE(Value('a', is_zero)); - - int n = 0; - const Matcher 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 is_even = PolymorphicIsEven(); - StringMatchResultListener listener1; - EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1)); - EXPECT_EQ("% 2 == 0", listener1.str()); - - const Matcher 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; - EXPECT_TRUE((std::is_constructible::value)); - EXPECT_FALSE((std::is_convertible::value)); - } - { - // Multiple arg matchers can be constructed with an implicit construction. - Construct2ArgsMatcherP2 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(42)); - EXPECT_EQ("isn't equal to 42", DescribeMatcher(42, true)); -} - -TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) { - const Matcher monomorphic = Le(0); - EXPECT_EQ("is <= 0", DescribeMatcher(monomorphic)); - EXPECT_EQ("isn't <= 0", DescribeMatcher(monomorphic, true)); -} - -TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) { - EXPECT_EQ("is even", DescribeMatcher(PolymorphicIsEven())); - EXPECT_EQ("is odd", DescribeMatcher(PolymorphicIsEven(), true)); -} - -TEST(AllArgsTest, WorksForTuple) { - EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt())); - EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt()))); -} - -TEST(AllArgsTest, WorksForNonTuple) { - EXPECT_THAT(42, AllArgs(Gt(0))); - EXPECT_THAT('a', Not(AllArgs(Eq('b')))); -} - -class AllArgsHelper { - public: - AllArgsHelper() {} - - MOCK_METHOD2(Helper, int(char x, int y)); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper); -}; - -TEST(AllArgsTest, WorksInWithClause) { - AllArgsHelper helper; - ON_CALL(helper, Helper(_, _)) - .With(AllArgs(Lt())) - .WillByDefault(Return(1)); - EXPECT_CALL(helper, Helper(_, _)); - EXPECT_CALL(helper, Helper(_, _)) - .With(AllArgs(Gt())) - .WillOnce(Return(2)); - - EXPECT_EQ(1, helper.Helper('\1', 2)); - EXPECT_EQ(2, helper.Helper('a', 1)); -} - -class OptionalMatchersHelper { - public: - OptionalMatchersHelper() {} - - MOCK_METHOD0(NoArgs, int()); - - MOCK_METHOD1(OneArg, int(int y)); - - MOCK_METHOD2(TwoArgs, int(char x, int y)); - - MOCK_METHOD1(Overloaded, int(char x)); - MOCK_METHOD2(Overloaded, int(char x, int y)); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper); -}; - -TEST(AllArgsTest, WorksWithoutMatchers) { - OptionalMatchersHelper helper; - - ON_CALL(helper, NoArgs).WillByDefault(Return(10)); - ON_CALL(helper, OneArg).WillByDefault(Return(20)); - ON_CALL(helper, TwoArgs).WillByDefault(Return(30)); - - EXPECT_EQ(10, helper.NoArgs()); - EXPECT_EQ(20, helper.OneArg(1)); - EXPECT_EQ(30, helper.TwoArgs('\1', 2)); - - EXPECT_CALL(helper, NoArgs).Times(1); - EXPECT_CALL(helper, OneArg).WillOnce(Return(100)); - EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200)); - EXPECT_CALL(helper, TwoArgs).Times(0); - - EXPECT_EQ(10, helper.NoArgs()); - EXPECT_EQ(100, helper.OneArg(1)); - EXPECT_EQ(200, helper.OneArg(17)); -} - -// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value -// matches the matcher. -TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) { - ASSERT_THAT(5, Ge(2)) << "This should succeed."; - ASSERT_THAT("Foo", EndsWith("oo")); - EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too."; - EXPECT_THAT("Hello", StartsWith("Hell")); -} - -// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value -// doesn't match the matcher. -TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) { - // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(), - // which cannot reference auto variables. - static unsigned short n; // NOLINT - n = 5; - - EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)), - "Value of: n\n" - "Expected: is > 10\n" - " Actual: 5" + OfType("unsigned short")); - n = 0; - EXPECT_NONFATAL_FAILURE( - EXPECT_THAT(n, AllOf(Le(7), Ge(5))), - "Value of: n\n" - "Expected: (is <= 7) and (is >= 5)\n" - " Actual: 0" + OfType("unsigned short")); -} - -// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument -// has a reference type. -TEST(MatcherAssertionTest, WorksForByRefArguments) { - // We use a static variable here as EXPECT_FATAL_FAILURE() cannot - // reference auto variables. - static int n; - n = 0; - EXPECT_THAT(n, AllOf(Le(7), Ref(n))); - EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))), - "Value of: n\n" - "Expected: does not reference the variable @"); - // Tests the "Actual" part. - EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))), - "Actual: 0" + OfType("int") + ", which is located @"); -} - -// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is -// monomorphic. -TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { - Matcher starts_with_he = StartsWith("he"); - ASSERT_THAT("hello", starts_with_he); - - Matcher 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 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 -class FloatingPointTest : public testing::Test { - protected: - typedef testing::internal::FloatingPoint 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 (*matcher_maker)(RawType)) { - Matcher 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 m2 = matcher_maker(close_to_positive_zero_); - EXPECT_FALSE(m2.Matches(further_from_negative_zero_)); - - Matcher 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 m4 = matcher_maker(-infinity_); - EXPECT_TRUE(m4.Matches(-close_to_infinity_)); - - Matcher 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, which is needed in - // some cases. - Matcher 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, which is needed in some - // cases. - Matcher 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 -class FloatingPointNearTest : public FloatingPointTest { - protected: - typedef FloatingPointTest 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 - (*matcher_maker)(RawType, RawType)) { - Matcher 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 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 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 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 m5 = matcher_maker(ParentType::max_, ParentType::max_); - EXPECT_TRUE(m5.Matches(ParentType::max_)); - EXPECT_FALSE(m5.Matches(-ParentType::max_)); - - Matcher m6 = matcher_maker(-ParentType::max_, ParentType::max_); - EXPECT_FALSE(m6.Matches(ParentType::max_)); - EXPECT_TRUE(m6.Matches(-ParentType::max_)); - - Matcher m7 = matcher_maker(ParentType::max_, 0); - EXPECT_TRUE(m7.Matches(ParentType::max_)); - EXPECT_FALSE(m7.Matches(-ParentType::max_)); - - Matcher 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 m9 = matcher_maker( - ParentType::max_, ParentType::infinity_); - EXPECT_TRUE(m8.Matches(-ParentType::max_)); - - // matcher_maker can produce a Matcher, which is needed in - // some cases. - Matcher 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, which is needed in some - // cases. - Matcher 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 FloatTest; - -TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) { - TestMatches(&FloatEq); -} - -TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) { - TestMatches(&NanSensitiveFloatEq); -} - -TEST_F(FloatTest, FloatEqCannotMatchNaN) { - // FloatEq never matches NaN. - Matcher 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 m = NanSensitiveFloatEq(nan1_); - EXPECT_TRUE(m.Matches(nan1_)); - EXPECT_TRUE(m.Matches(nan2_)); - EXPECT_FALSE(m.Matches(1.0)); -} - -TEST_F(FloatTest, FloatEqCanDescribeSelf) { - Matcher m1 = FloatEq(2.0f); - EXPECT_EQ("is approximately 2", Describe(m1)); - EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); - - Matcher m2 = FloatEq(0.5f); - EXPECT_EQ("is approximately 0.5", Describe(m2)); - EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); - - Matcher m3 = FloatEq(nan1_); - EXPECT_EQ("never matches", Describe(m3)); - EXPECT_EQ("is anything", DescribeNegation(m3)); -} - -TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) { - Matcher m1 = NanSensitiveFloatEq(2.0f); - EXPECT_EQ("is approximately 2", Describe(m1)); - EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); - - Matcher m2 = NanSensitiveFloatEq(0.5f); - EXPECT_EQ("is approximately 0.5", Describe(m2)); - EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); - - Matcher 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 FloatNearTest; - -TEST_F(FloatNearTest, FloatNearMatches) { - TestNearMatches(&FloatNear); -} - -TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) { - TestNearMatches(&NanSensitiveFloatNear); -} - -TEST_F(FloatNearTest, FloatNearCanDescribeSelf) { - Matcher 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 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 m3 = FloatNear(nan1_, 0.0); - EXPECT_EQ("never matches", Describe(m3)); - EXPECT_EQ("is anything", DescribeNegation(m3)); -} - -TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) { - Matcher 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 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 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 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 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 DoubleTest; - -TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) { - TestMatches(&DoubleEq); -} - -TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) { - TestMatches(&NanSensitiveDoubleEq); -} - -TEST_F(DoubleTest, DoubleEqCannotMatchNaN) { - // DoubleEq never matches NaN. - Matcher 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 m = NanSensitiveDoubleEq(nan1_); - EXPECT_TRUE(m.Matches(nan1_)); - EXPECT_TRUE(m.Matches(nan2_)); - EXPECT_FALSE(m.Matches(1.0)); -} - -TEST_F(DoubleTest, DoubleEqCanDescribeSelf) { - Matcher m1 = DoubleEq(2.0); - EXPECT_EQ("is approximately 2", Describe(m1)); - EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); - - Matcher m2 = DoubleEq(0.5); - EXPECT_EQ("is approximately 0.5", Describe(m2)); - EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); - - Matcher m3 = DoubleEq(nan1_); - EXPECT_EQ("never matches", Describe(m3)); - EXPECT_EQ("is anything", DescribeNegation(m3)); -} - -TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) { - Matcher m1 = NanSensitiveDoubleEq(2.0); - EXPECT_EQ("is approximately 2", Describe(m1)); - EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); - - Matcher m2 = NanSensitiveDoubleEq(0.5); - EXPECT_EQ("is approximately 0.5", Describe(m2)); - EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); - - Matcher 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 DoubleNearTest; - -TEST_F(DoubleNearTest, DoubleNearMatches) { - TestNearMatches(&DoubleNear); -} - -TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) { - TestNearMatches(&NanSensitiveDoubleNear); -} - -TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) { - Matcher 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 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 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 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 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 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 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 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 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 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 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 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> m = Pointee(Ge(0)); - - std::unique_ptr n(new int(1)); - EXPECT_TRUE(m.Matches(n)); -} - -TEST(PointeeTest, SmartPointerToConst) { - const Matcher> m = Pointee(Ge(0)); - - // There's no implicit conversion from unique_ptr to const - // unique_ptr, so we must pass a unique_ptr into the - // matcher. - std::unique_ptr n(new int(1)); - EXPECT_TRUE(m.Matches(n)); -} - -TEST(PointerTest, RawPointer) { - int n = 1; - const Matcher 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 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 n(new int(10)); - int* raw_n = n.get(); - const Matcher> m = Pointer(Eq(raw_n)); - - EXPECT_TRUE(m.Matches(n)); -} - -TEST(PointerTest, SmartPointerToConst) { - std::unique_ptr n(new int(10)); - const int* raw_n = n.get(); - const Matcher> m = Pointer(Eq(raw_n)); - - // There's no implicit conversion from unique_ptr to const - // unique_ptr, so we must pass a unique_ptr into the - // matcher. - std::unique_ptr p(new int(10)); - EXPECT_FALSE(m.Matches(p)); -} - -TEST(AddressTest, NonConst) { - int n = 1; - const Matcher 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 m = Address(Eq(&n)); - - EXPECT_TRUE(m.Matches(n)); - - int other = 5; - - EXPECT_FALSE(m.Matches(other)); -} - -TEST(AddressTest, MatcherDoesntCopy) { - std::unique_ptr n(new int(1)); - const Matcher> m = Address(Eq(&n)); - - EXPECT_TRUE(m.Matches(n)); -} - -TEST(AddressTest, Describe) { - Matcher matcher = Address(_); - EXPECT_EQ("has address that is anything", Describe(matcher)); - EXPECT_EQ("does not have address that is anything", - DescribeNegation(matcher)); -} - -MATCHER_P(FieldIIs, inner_matcher, "") { - return ExplainMatchResult(inner_matcher, arg.i, result_listener); -} - -#if GTEST_HAS_RTTI -TEST(WhenDynamicCastToTest, SameType) { - Derived derived; - derived.i = 4; - - // Right type. A pointer is passed down. - Base* as_base_ptr = &derived; - EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(Not(IsNull()))); - EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(Pointee(FieldIIs(4)))); - EXPECT_THAT(as_base_ptr, - Not(WhenDynamicCastTo(Pointee(FieldIIs(5))))); -} - -TEST(WhenDynamicCastToTest, WrongTypes) { - Base base; - Derived derived; - OtherDerived other_derived; - - // Wrong types. NULL is passed. - EXPECT_THAT(&base, Not(WhenDynamicCastTo(Pointee(_)))); - EXPECT_THAT(&base, WhenDynamicCastTo(IsNull())); - Base* as_base_ptr = &derived; - EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo(Pointee(_)))); - EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(IsNull())); - as_base_ptr = &other_derived; - EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo(Pointee(_)))); - EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(IsNull())); -} - -TEST(WhenDynamicCastToTest, AlreadyNull) { - // Already NULL. - Base* as_base_ptr = nullptr; - EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(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(&many_derived); - EXPECT_THAT(as_base_ptr, - WhenDynamicCastTo(IsNull())); - as_base_ptr = &sub1; - EXPECT_THAT( - as_base_ptr, - WhenDynamicCastTo(Not(IsNull()))); -} - -TEST(WhenDynamicCastToTest, Describe) { - Matcher matcher = WhenDynamicCastTo(Pointee(_)); - const std::string prefix = - "when dynamic_cast to " + internal::GetTypeName() + ", "; - 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 matcher = WhenDynamicCastTo(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 ref_matcher = WhenDynamicCastTo(_); - 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(FieldIIs(4))); - EXPECT_THAT(as_base_ref, WhenDynamicCastTo(Not(FieldIIs(5)))); -} - -TEST(WhenDynamicCastToTest, BadReference) { - Derived derived; - Base& as_base_ref = derived; - EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo(_))); -} -#endif // GTEST_HAS_RTTI - -// Minimal const-propagating pointer. -template -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 > m = Pointee(Lt(5)); - int three = 3; - const ConstPropagatingPtr co(&three); - ConstPropagatingPtr o(&three); - EXPECT_TRUE(m.Matches(o)); - EXPECT_TRUE(m.Matches(co)); - *o = 6; - EXPECT_FALSE(m.Matches(o)); - EXPECT_FALSE(m.Matches(ConstPropagatingPtr())); -} - -TEST(PointeeTest, NeverMatchesNull) { - const Matcher m = Pointee(_); - EXPECT_FALSE(m.Matches(nullptr)); -} - -// Tests that we can write Pointee(value) instead of Pointee(Eq(value)). -TEST(PointeeTest, MatchesAgainstAValue) { - const Matcher 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 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 m = Pointee(StartsWith("Hi")); - - EXPECT_EQ("", Explain(m, static_cast(nullptr))); - - const Matcher 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 m = Pointee(0); - int n = 42; - EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n)); -} - -// An uncopyable class. -class Uncopyable { - public: - Uncopyable() : value_(-1) {} - explicit Uncopyable(int a_value) : value_(a_value) {} - - int value() const { return value_; } - void set_value(int i) { value_ = i; } - - private: - int value_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable); -}; - -// Returns true if and only if x.value() is positive. -bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; } - -MATCHER_P(UncopyableIs, inner_matcher, "") { - return ExplainMatchResult(inner_matcher, arg.value(), result_listener); -} - -// A user-defined struct for testing Field(). -struct AStruct { - AStruct() : x(0), y(1.0), z(5), p(nullptr) {} - AStruct(const AStruct& rhs) - : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {} - - int x; // A non-const field. - const double y; // A const field. - Uncopyable z; // An uncopyable field. - const char* p; // A pointer field. -}; - -// A derived struct for testing Field(). -struct DerivedStruct : public AStruct { - char ch; -}; - -// Tests that Field(&Foo::field, ...) works when field is non-const. -TEST(FieldTest, WorksForNonConstField) { - Matcher m = Field(&AStruct::x, Ge(0)); - Matcher 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 m = Field(&AStruct::y, Ge(0.0)); - Matcher 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 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 m = Field(&AStruct::p, static_cast(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 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 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 m = Field(&AStruct::x, - Matcher(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 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 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 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 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 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 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 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 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 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 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 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 m = Field(&AStruct::x, Ge(0)); - - AStruct a; - a.x = 1; - EXPECT_EQ("", Explain(m, static_cast(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 m = Field("field_name", &AStruct::x, Ge(0)); - - AStruct a; - a.x = 1; - EXPECT_EQ("", Explain(m, static_cast(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 m = Property(&AClass::n, Ge(0)); - Matcher 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 m = Property(&AClass::s, StartsWith("hi")); - Matcher 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 m = Property(&AClass::s_ref, StartsWith("hi")); - Matcher 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 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 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 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 m = Property(&AClass::n, - Matcher(Ge(0))); - - Matcher m_with_name = - Property("n", &AClass::n, Matcher(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 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 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 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 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 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 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 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 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 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 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 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 m = Property(&AClass::n, Ge(0)); - - AClass a; - a.set_n(1); - EXPECT_EQ("", Explain(m, static_cast(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 m = Property("fancy_name", &AClass::n, Ge(0)); - - AClass a; - a.set_n(1); - EXPECT_EQ("", Explain(m, static_cast(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 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 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 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(ResultOfTest, CanExplainMatchResult) { - Matcher 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 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 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 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 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 matcher = ResultOf(IntFunction, Matcher(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(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 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 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(strlen(s)); } - std::string operator()(int *p) { return p ? "good ptr" : "null"; } -}; - -TEST(ResultOfTest, WorksForPolymorphicFunctors) { - Matcher matcher_int = ResultOf(PolymorphicFunctor(), Ge(5)); - - EXPECT_TRUE(matcher_int.Matches(10)); - EXPECT_FALSE(matcher_int.Matches(2)); - - Matcher matcher_string = ResultOf(PolymorphicFunctor(), Ge(5)); - - EXPECT_TRUE(matcher_string.Matches("long string")); - EXPECT_FALSE(matcher_string.Matches("shrt")); -} - -TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) { - Matcher matcher = ResultOf(PolymorphicFunctor(), "good ptr"); - - int n = 0; - EXPECT_TRUE(matcher.Matches(&n)); - EXPECT_FALSE(matcher.Matches(nullptr)); -} - -TEST(ResultOfTest, WorksForLambdas) { - Matcher matcher = ResultOf( - [](int str_len) { - return std::string(static_cast(str_len), 'x'); - }, - "xxx"); - EXPECT_TRUE(matcher.Matches(3)); - EXPECT_FALSE(matcher.Matches(1)); -} - -TEST(ResultOfTest, WorksForNonCopyableArguments) { - Matcher> matcher = ResultOf( - [](const std::unique_ptr& str_len) { - return std::string(static_cast(*str_len), 'x'); - }, - "xxx"); - EXPECT_TRUE(matcher.Matches(std::unique_ptr(new int(3)))); - EXPECT_FALSE(matcher.Matches(std::unique_ptr(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 matcher2 = ResultOf(ReferencingFunction, Eq(&n)); - EXPECT_TRUE(matcher2.Matches(n)); - EXPECT_FALSE(matcher2.Matches(n2)); - - Matcher 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 - 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 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 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 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 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 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 m = AllOf(Ge(2), Le(3)); - EXPECT_EQ("", Explain(m, 2)); -} - -TEST(ExplainmatcherResultTest, MonomorphicMatcher) { - const Matcher 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 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 m = Ge(ByRef(value2)); - - NotCopyable n1(1), n2(2); - EXPECT_FALSE(m.Matches(n1)); - EXPECT_TRUE(m.Matches(n2)); -} - -TEST(IsEmptyTest, ImplementsIsEmpty) { - vector 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 > m = IsEmpty(); - EXPECT_EQ("is empty", Describe(m)); - EXPECT_EQ("isn't empty", DescribeNegation(m)); -} - -TEST(IsEmptyTest, ExplainsResult) { - Matcher > m = IsEmpty(); - vector 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 null_unique; - std::unique_ptr 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 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 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 container; - Matcher&> 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 > 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 > m1 = SizeIs(2); - Matcher > m2 = SizeIs(Lt(2u)); - Matcher > m3 = SizeIs(AnyOf(0, 3)); - Matcher > m4 = SizeIs(Gt(1u)); - vector container; - EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container)); - EXPECT_EQ("whose size 0 matches", Explain(m2, container)); - EXPECT_EQ("whose size 0 matches", Explain(m3, container)); - EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container)); - container.push_back(0); - container.push_back(0); - EXPECT_EQ("whose size 2 matches", Explain(m1, container)); - EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container)); - EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container)); - EXPECT_EQ("whose size 2 matches", Explain(m4, container)); -} - -#if GTEST_HAS_TYPED_TEST -// Tests ContainerEq with different container types, and -// different element types. - -template -class ContainerEqTest : public testing::Test {}; - -typedef testing::Types< - set, - vector, - multiset, - list > - 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 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 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 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 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 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 my_set(vals, vals + 6); - vector test_set(test_vals, test_vals + 3); - const Matcher > 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 my_set(vals, vals + 6); - list test_set(test_vals, test_vals + 7); - const Matcher&> 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 my_set(vals, vals + 6); - list test_set(test_vals, test_vals + 5); - const Matcher > 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 my_set(vals, vals + 6); - vector test_set(test_vals, test_vals + 5); - const Matcher > 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 my_map; - my_map[0] = "a"; - my_map[1] = "b"; - - map test_map; - test_map[0] = "aa"; - test_map[1] = "b"; - - const Matcher&> 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 m = ContainerEq(a2); - EXPECT_THAT(a1, m); - - a2[0][0] = "ha"; - EXPECT_THAT(a1, m); -} - -TEST(WhenSortedByTest, WorksForEmptyContainer) { - const vector numbers; - EXPECT_THAT(numbers, WhenSortedBy(less(), ElementsAre())); - EXPECT_THAT(numbers, Not(WhenSortedBy(less(), ElementsAre(1)))); -} - -TEST(WhenSortedByTest, WorksForNonEmptyContainer) { - vector numbers; - numbers.push_back(3); - numbers.push_back(1); - numbers.push_back(2); - numbers.push_back(2); - EXPECT_THAT(numbers, WhenSortedBy(greater(), - ElementsAre(3, 2, 2, 1))); - EXPECT_THAT(numbers, Not(WhenSortedBy(greater(), - ElementsAre(1, 2, 2, 3)))); -} - -TEST(WhenSortedByTest, WorksForNonVectorContainer) { - list words; - words.push_back("say"); - words.push_back("hello"); - words.push_back("world"); - EXPECT_THAT(words, WhenSortedBy(less(), - ElementsAre("hello", "say", "world"))); - EXPECT_THAT(words, Not(WhenSortedBy(less(), - 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(), ElementsAre(1, 2, 3, 4))); - EXPECT_THAT(numbers, WhenSortedBy(less(), - ElementsAreArray(sorted_numbers))); - EXPECT_THAT(numbers, Not(WhenSortedBy(less(), ElementsAre(1, 3, 2, 4)))); -} - -TEST(WhenSortedByTest, CanDescribeSelf) { - const Matcher > m = WhenSortedBy(less(), 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(), ElementsAre(2, 3)), a)); - EXPECT_EQ("which is { 1, 2 } when sorted", - Explain(WhenSortedBy(less(), 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 numbers; - EXPECT_THAT(numbers, WhenSorted(ElementsAre())); - EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1)))); -} - -TEST(WhenSortedTest, WorksForNonEmptyContainer) { - list 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 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 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 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 d; - d.push_back(2); - d.push_back(1); - Matcher&> vector_match = ElementsAre(1, 2); - EXPECT_THAT(d, WhenSorted(vector_match)); - Matcher&> 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 -class Streamlike { - private: - class ConstIter; - public: - typedef ConstIter const_iterator; - typedef T value_type; - - template - 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::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::iterator pos_; - }; - - friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) { - os << "["; - typedef typename std::list::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 remainder_; // modified by iteration -}; - -TEST(StreamlikeTest, Iteration) { - const int a[5] = {2, 1, 4, 5, 3}; - Streamlike s(a, a + 5); - Streamlike::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 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 s(a, a + 5); - EXPECT_THAT(s, BeginEndDistanceIs(5)); -} - -TEST(BeginEndDistanceIsTest, CanDescribeSelf) { - Matcher > 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 > m1 = BeginEndDistanceIs(2); - Matcher > m2 = BeginEndDistanceIs(Lt(2)); - Matcher > m3 = BeginEndDistanceIs(AnyOf(0, 3)); - Matcher > m4 = BeginEndDistanceIs(GreaterThan(1)); - vector 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 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 s(std::begin(a), std::end(a)); - Matcher&> 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 numbers; - vector 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 s(std::begin(a), std::end(a)); - - vector 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 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 IntVec; - IntVec expected; - expected.push_back(111); - expected.push_back(222); - expected.push_back(333); - EXPECT_THAT( - Describe(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 IntVec; - IntVec expected; - expected.push_back(111); - expected.push_back(222); - expected.push_back(333); - EXPECT_THAT( - DescribeNegation(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 v; - v.push_back(2); - v.push_back(3); - std::vector 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 numbers; - vector 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 s(std::begin(a), std::end(a)); - - vector 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 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 IntVec; - IntVec expected; - expected.push_back(111); - expected.push_back(222); - expected.push_back(333); - - EXPECT_THAT( - Describe(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 IntVec; - IntVec expected; - expected.push_back(111); - expected.push_back(222); - expected.push_back(333); - EXPECT_THAT( - DescribeNegation(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 v; - v.push_back(2); - v.push_back(3); - std::vector 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 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 s(std::begin(a), std::end(a)); - - vector 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 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 s(std::begin(a), std::end(a)); - do { - StringMatchResultListener listener; - EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), - s, &listener)) << listener.str(); - } while (std::next_permutation(s.begin(), s.end())); -} - -TEST(UnorderedElementsAreArrayTest, VectorBool) { - const bool a[] = {0, 1, 0, 1, 1}; - const bool b[] = {1, 0, 1, 1, 0}; - std::vector expected(std::begin(a), std::end(a)); - std::vector 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 s(std::begin(a), std::end(a)); - - ::std::vector 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 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 >( - {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); - EXPECT_THAT(a, Not(UnorderedElementsAreArray >( - {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 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 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 s(std::begin(a), std::end(a)); - std::vector > 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 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 s; - std::vector > 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 s; - std::vector > 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 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 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 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 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 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 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(UnorderedElementsAre()), - Eq("is empty")); - EXPECT_THAT( - Describe(UnorderedElementsAre(345)), - Eq("has 1 element and that element is equal to 345")); - EXPECT_THAT( - Describe(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(UnorderedElementsAre()), - Eq("isn't empty")); - EXPECT_THAT( - DescribeNegation(UnorderedElementsAre(345)), - Eq("doesn't have 1 element, or has 1 element that isn't equal to 345")); - EXPECT_THAT( - DescribeNegation(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 -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(-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 lhs_used_; - std::vector rhs_used_; - ElementMatcherPairs matches_; - ElementMatcherPairs best_so_far_; -}; - -template -const size_t BacktrackingMaxBPMState::kUnused; - -} // namespace - -// Implement a simple backtracking algorithm to determine if it is possible -// to find one element per matcher, without reusing elements. -template -ElementMatcherPairs -FindBacktrackingMaxBPM(const Graph& g) { - return BacktrackingMaxBPMState(&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 {}; - -// 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 seen_element(graph.LhsSize()); - std::vector 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 > { -}; - -TEST_F(BipartiteNonSquareTest, SimpleBacktracking) { - // ....... - // 0:-----\ : - // 1:---\ | : - // 2:---\ | : - // 3:-\ | | : - // :.......: - // 0 1 2 - MatchMatrix g(4, 3); - constexpr std::array, 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 > { -}; - -// Verifies a large sample of larger graphs. -TEST_P(BipartiteRandomTest, LargerNets) { - int nodes = GetParam().first; - int iters = GetParam().second; - MatchMatrix graph(static_cast(nodes), static_cast(nodes)); - - auto seed = static_cast(GTEST_FLAG_GET(random_seed)); - if (seed == 0) { - seed = static_cast(time(nullptr)); - } - - for (; iters > 0; --iters, ++seed) { - srand(static_cast(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 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")); - 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 >")); - EXPECT_FALSE(IsReadableTypeName("std::vector >")); -} - -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"})); -} - -// Tests PolymorphicMatcher::mutable_impl(). -TEST(PolymorphicMatcherTest, CanAccessMutableImpl) { - PolymorphicMatcher 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 m(DivisibleByImpl(42)); - const DivisibleByImpl& impl = m.impl(); - EXPECT_EQ(42, impl.divider()); -} - -TEST(MatcherTupleTest, ExplainsMatchFailure) { - stringstream ss1; - ExplainMatchFailureTupleTo( - std::make_tuple(Matcher(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(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(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 a; // empty - - Matcher > m = Each(2); - EXPECT_EQ("", Explain(m, a)); - - Matcher 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 > m = Each(1); - EXPECT_EQ("only contains elements that is equal to 1", Describe(m)); - - Matcher > m2 = Not(m); - EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2)); -} - -TEST(EachTest, MatchesVectorWhenAllElementsMatch) { - vector 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 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 my_map; - const char* bar = "a string"; - my_map[bar] = 2; - EXPECT_THAT(my_map, Each(make_pair(bar, 2))); - - map 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 - bool MatchAndExplain(const std::tuple& 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 IsHalfOf() { - return MakePolymorphicMatcher(IsHalfOfMatcher()); -} - -TEST(PointwiseTest, DescribesSelf) { - vector rhs; - rhs.push_back(1); - rhs.push_back(2); - rhs.push_back(3); - const Matcher&> 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 rhs; - rhs.push_back(2); - rhs.push_back(4); - - int lhs[] = {1, 2}; - const Matcher 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 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 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 rhs(3, false); - rhs[1] = true; - vector lhs = rhs; - EXPECT_THAT(lhs, Pointwise(Eq(), rhs)); - rhs[0] = true; - EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); -} - - -TEST(PointwiseTest, WorksForRhsInitializerList) { - const vector 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> m1 = IsHalfOf(); - EXPECT_THAT(lhs, Pointwise(m1, rhs)); - EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs)); - - // This type works as a std::tuple can be - // implicitly cast to std::tuple. - const Matcher> 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{1, 2}))); - helper.Call(MakeUniquePtrs({1, 2})); -} - -TEST(UnorderedPointwiseTest, DescribesSelf) { - vector rhs; - rhs.push_back(1); - rhs.push_back(2); - rhs.push_back(3); - const Matcher&> 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 rhs; - rhs.push_back(2); - rhs.push_back(4); - - int lhs[] = {2, 1}; - const Matcher 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 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 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 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> m1 = IsHalfOf(); - EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs)); - - // This type works as a std::tuple can be - // implicitly cast to std::tuple. - const Matcher> m2 = IsHalfOf(); - EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs)); -} - -TEST(UnorderedPointwiseTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(), - std::vector{1, 2}))); - helper.Call(MakeUniquePtrs({2, 1})); -} - -// Sample optional type implementation with minimal requirements for use with -// Optional matcher. -template -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> m = Optional(Eq(1)); - EXPECT_EQ("value is equal to 1", Describe(m)); -} - -TEST(OptionalTest, ExplainsSelf) { - const Matcher> m = Optional(Eq(1)); - EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional(1))); - EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional(2))); -} - -TEST(OptionalTest, MatchesNonEmptyOptional) { - const Matcher> m1 = Optional(1); - const Matcher> m2 = Optional(Eq(2)); - const Matcher> m3 = Optional(Lt(3)); - SampleOptional opt(1); - EXPECT_TRUE(m1.Matches(opt)); - EXPECT_FALSE(m2.Matches(opt)); - EXPECT_TRUE(m3.Matches(opt)); -} - -TEST(OptionalTest, DoesNotMatchNullopt) { - const Matcher> m = Optional(1); - SampleOptional empty; - EXPECT_FALSE(m.Matches(empty)); -} - -TEST(OptionalTest, WorksWithMoveOnly) { - Matcher>> m = Optional(Eq(nullptr)); - EXPECT_TRUE(m.Matches(SampleOptional>(nullptr))); -} - -class SampleVariantIntString { - public: - SampleVariantIntString(int i) : i_(i), has_int_(true) {} - SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {} - - template - friend bool holds_alternative(const SampleVariantIntString& value) { - return value.has_int_ == std::is_same::value; - } - - template - friend const T& get(const SampleVariantIntString& value) { - return value.get_impl(static_cast(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 m = VariantWith(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 m = VariantWith(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 m = VariantWith(Eq(1)); - EXPECT_TRUE(m.Matches(SampleVariantIntString(1))); - - m = VariantWith(Eq("1")); - EXPECT_TRUE(m.Matches(SampleVariantIntString("1"))); -} - -TEST(VariantTest, TypeDoesNotMatch) { - Matcher m = VariantWith(Eq(1)); - EXPECT_FALSE(m.Matches(SampleVariantIntString("1"))); - - m = VariantWith(Eq("1")); - EXPECT_FALSE(m.Matches(SampleVariantIntString(1))); -} - -TEST(VariantTest, InnerDoesNotMatch) { - Matcher m = VariantWith(Eq(1)); - EXPECT_FALSE(m.Matches(SampleVariantIntString(2))); - - m = VariantWith(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 - friend const T* any_cast(const SampleAnyType* any) { - return any->get_impl(static_cast(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 m = AnyWith(Eq(1)); - EXPECT_TRUE(m.Matches(SampleAnyType(1))); -} - -TEST(AnyWithTest, TestBadCastType) { - Matcher m = AnyWith(Eq("fail")); - EXPECT_FALSE(m.Matches(SampleAnyType(1))); -} - -TEST(AnyWithTest, TestUseInContainers) { - std::vector a; - a.emplace_back(1); - a.emplace_back(2); - a.emplace_back(3); - EXPECT_THAT( - a, ElementsAreArray({AnyWith(1), AnyWith(2), AnyWith(3)})); - - std::vector b; - b.emplace_back("hello"); - b.emplace_back("merhaba"); - b.emplace_back("salut"); - EXPECT_THAT(b, ElementsAreArray({AnyWith("hello"), - AnyWith("merhaba"), - AnyWith("salut")})); -} -TEST(AnyWithTest, TestCompare) { - EXPECT_THAT(SampleAnyType(1), AnyWith(Gt(0))); -} - -TEST(AnyWithTest, DescribesSelf) { - const Matcher m = AnyWith(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 m = AnyWith(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 p(new int(3)); - EXPECT_THAT(p, Pointee(Eq(3))); - EXPECT_THAT(p, Not(Pointee(Eq(2)))); -} - -TEST(NotTest, WorksOnMoveOnlyType) { - std::unique_ptr p(new int(3)); - EXPECT_THAT(p, Pointee(Eq(3))); - EXPECT_THAT(p, Not(Pointee(Eq(2)))); -} - -// Tests Args(m). - -TEST(ArgsTest, AcceptsZeroTemplateArg) { - const std::tuple t(5, true); - EXPECT_THAT(t, Args<>(Eq(std::tuple<>()))); - EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>())))); -} - -TEST(ArgsTest, AcceptsOneTemplateArg) { - const std::tuple 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 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 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 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 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 Tuple3; - const Matcher 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 Tuple3; - const Matcher 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 > 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&> 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 > 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 > 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 > { - public: - void DescribeTo(::std::ostream* /*os*/) const override {} - - bool MatchAndExplain(std::tuple 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 > LessThan() { - return MakeMatcher(new LessThanMatcher); -} - -TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) { - const Matcher > 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 { - 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> 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()) + ", [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()) + ", [MatchAndExplain]"; - EXPECT_EQ(expect, result.message()); -} - -// Tests for ElementsAre(). - -TEST(ElementsAreTest, CanDescribeExpectingNoElement) { - Matcher&> m = ElementsAre(); - EXPECT_EQ("is empty", Describe(m)); -} - -TEST(ElementsAreTest, CanDescribeExpectingOneElement) { - Matcher> m = ElementsAre(Gt(5)); - EXPECT_EQ("has 1 element that is > 5", Describe(m)); -} - -TEST(ElementsAreTest, CanDescribeExpectingManyElements) { - Matcher> 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> m = ElementsAre(); - EXPECT_EQ("isn't empty", DescribeNegation(m)); -} - -TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElement) { - Matcher&> m = ElementsAre(Gt(5)); - EXPECT_EQ( - "doesn't have 1 element, or\n" - "element #0 isn't > 5", - DescribeNegation(m)); -} - -TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) { - Matcher&> 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&> m = ElementsAre(1, Ne(2)); - - list 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&> m = - ElementsAre(GreaterThan(1), 0, GreaterThan(2)); - - const int a[] = {10, 0, 100}; - vector 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&> m = ElementsAre(1, 3); - - list 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&> m = ElementsAre(1, GreaterThan(5)); - - vector 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 test_vector; - test_vector.push_back("test string"); - - EXPECT_THAT(test_vector, ElementsAre(StrEq("test string"))); -} - -TEST(ElementsAreTest, MatchesOneElementList) { - list test_list; - test_list.push_back("test string"); - - EXPECT_THAT(test_list, ElementsAre("test string")); -} - -TEST(ElementsAreTest, MatchesThreeElementVector) { - vector 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 test_vector; - test_vector.push_back(4); - - EXPECT_THAT(test_vector, ElementsAre(Eq(4))); -} - -TEST(ElementsAreTest, MatchesOneElementAnyMatcher) { - vector test_vector; - test_vector.push_back(4); - - EXPECT_THAT(test_vector, ElementsAre(_)); -} - -TEST(ElementsAreTest, MatchesOneElementValue) { - vector test_vector; - test_vector.push_back(4); - - EXPECT_THAT(test_vector, ElementsAre(4)); -} - -TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) { - vector 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 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 test_vector; - test_vector.push_back("test string"); - test_vector.push_back("test string"); - - Matcher> m = ElementsAre(StrEq("test string")); - EXPECT_FALSE(m.Matches(test_vector)); -} - -TEST(ElementsAreTest, DoesNotMatchWrongValue) { - vector test_vector; - test_vector.push_back("other string"); - - Matcher> m = ElementsAre(StrEq("test string")); - EXPECT_FALSE(m.Matches(test_vector)); -} - -TEST(ElementsAreTest, DoesNotMatchWrongOrder) { - vector test_vector; - test_vector.push_back("one"); - test_vector.push_back("three"); - test_vector.push_back("two"); - - Matcher> m = - ElementsAre(StrEq("one"), StrEq("two"), StrEq("three")); - EXPECT_FALSE(m.Matches(test_vector)); -} - -TEST(ElementsAreTest, WorksForNestedContainer) { - constexpr std::array strings = {{"Hi", "world"}}; - - vector> 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 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 v(std::begin(a), std::end(a)); - - EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _))); - EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3)))); -} - -TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) { - int array[] = {0, 1, 2}; - EXPECT_THAT(array, ElementsAre(0, 1, _)); - EXPECT_THAT(array, Not(ElementsAre(1, _, _))); - EXPECT_THAT(array, Not(ElementsAre(0, _))); -} - -class NativeArrayPassedAsPointerAndSize { - public: - NativeArrayPassedAsPointerAndSize() {} - - MOCK_METHOD(void, Helper, (int* array, int size)); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize); -}; - -TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) { - int array[] = {0, 1}; - ::std::tuple 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> - 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 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 a = {{"one", "two", "three"}}; - - vector 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 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 kMatcherArray[] = {StrEq("one"), StrEq("two"), - StrEq("three")}; - - vector 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 test_vector(std::begin(a), std::end(a)); - const vector 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>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); - EXPECT_THAT(a, Not(ElementsAreArray>( - {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)}))); -} - -TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) { - const int a[] = {1, 2, 3}; - const Matcher kMatchers[] = {Eq(1), Eq(2), Eq(3)}; - vector test_vector(std::begin(a), std::end(a)); - const vector> 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 test_vector(std::begin(a), std::end(a)); - const vector 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()), 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 test_vector(std::begin(a), std::end(a)); - vector expect(std::begin(a), std::end(a)); - ElementsAreArrayMatcher matcher_maker = - ElementsAreArray(expect.begin(), expect.end()); - EXPECT_THAT(test_vector, matcher_maker); - // Changing in place the values that initialized matcher_maker should not - // affect matcher_maker anymore. It should have made its own copy of them. - for (int& i : expect) { - i += 10; - } - EXPECT_THAT(test_vector, matcher_maker); - test_vector.push_back(3); - EXPECT_THAT(test_vector, Not(matcher_maker)); -} - -// Tests for the MATCHER*() macro family. - -// Tests that a simple MATCHER() definition works. - -MATCHER(IsEven, "") { return (arg % 2) == 0; } - -TEST(MatcherMacroTest, Works) { - const Matcher 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 m1 = IsEven2(); - EXPECT_EQ("is even", Describe(m1)); - EXPECT_EQ("is odd", DescribeNegation(m1)); - - const Matcher 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 m1 = IsEven2(); - EXPECT_EQ("OK", Explain(m1, 4)); - EXPECT_EQ("% 2 == 1", Explain(m1, 5)); - - const Matcher 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(); - return arg.empty(); -} - -TEST(MatcherMacroTest, CanReferenceArgType) { - const Matcher<::std::string> m1 = IsEmptyString(); - EXPECT_TRUE(m1.Matches("")); - - const Matcher 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 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 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 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 m = - ReferencesUncopyable(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(); - StaticAssertTypeEq(); // NOLINT - StaticAssertTypeEq(); - 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_m = - ReferencesAnyOf(foo1, foo2); - - EXPECT_TRUE(const_m.Matches(foo1)); - EXPECT_TRUE(const_m.Matches(foo2)); - EXPECT_FALSE(const_m.Matches(foo3)); - - const Matcher m = - ReferencesAnyOf(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 m = - ReferencesAnyOf(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 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(3))); - EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d")); - - EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast(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(suffix); - return arg == prefix_str + suffix_char; -} - -TEST(MatcherPnMacroTest, SimpleTypePromotion) { - Matcher no_promo = EqConcat(std::string("foo"), 't'); - Matcher promo = EqConcat("foo", static_cast('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 a1 = EqualsSumOf(1); - - // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk - // variable, and so on. - EqualsSumOfMatcherP2 a2 = EqualsSumOf(1, '2'); - EqualsSumOfMatcherP3 a3 = EqualsSumOf(1, 2, '3'); - EqualsSumOfMatcherP4 a4 = EqualsSumOf(1, 2, 3, '4'); - EqualsSumOfMatcherP5 a5 = - EqualsSumOf(1, 2, 3, 4, '5'); - EqualsSumOfMatcherP6 a6 = - EqualsSumOf(1, 2, 3, 4, 5, '6'); - EqualsSumOfMatcherP7 a7 = - EqualsSumOf(1, 2, 3, 4, 5, 6, '7'); - EqualsSumOfMatcherP8 a8 = - EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8'); - EqualsSumOfMatcherP9 a9 = - EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9'); - EqualsSumOfMatcherP10 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(Value(arg, m1)) + - static_cast(Value(arg, m2)) + - static_cast(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 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 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 some_list; - some_list.push_back(3); - some_list.push_back(1); - EXPECT_THAT(some_list, Not(Contains(4))); -} - -TEST(ContainsTest, SetMatchesWhenElementIsInContainer) { - set 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 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 some_set; - some_set.insert(3); - some_set.insert(1); - EXPECT_THAT(some_set, Not(Contains(4))); - - set c_string_set; - c_string_set.insert("hello"); - EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye")))); -} - -TEST(ContainsTest, ExplainsMatchResultCorrectly) { - const int a[2] = {1, 2}; - Matcher 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> m = Contains(1); - EXPECT_EQ("contains at least one element that is equal to 1", Describe(m)); - - Matcher> m2 = Not(m); - EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2)); -} - -TEST(ContainsTest, MapMatchesWhenElementIsInContainer) { - map my_map; - const char* bar = "a string"; - my_map[bar] = 2; - EXPECT_THAT(my_map, Contains(pair(bar, 2))); - - map another_map; - another_map["fee"] = 1; - another_map["fie"] = 2; - another_map["foe"] = 3; - another_map["fum"] = 4; - EXPECT_THAT(another_map, - Contains(pair(std::string("fee"), 1))); - EXPECT_THAT(another_map, Contains(pair("fie", 2))); -} - -TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) { - map some_map; - some_map[1] = 11; - some_map[2] = 22; - EXPECT_THAT(some_map, Not(Contains(pair(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)))); -} - -// Tests Contains().Times(). - -TEST(ContainsTimes, ListMatchesWhenElementQuantityMatches) { - list 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{}, Not(Contains(_))); -} - -TEST(ContainsTimes, ExplainsMatchResultCorrectly) { - const int a[2] = {1, 2}; - Matcher 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(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> m = Contains(1).Times(2); - EXPECT_EQ("quantity of elements that match is equal to 1 is equal to 2", - Describe(m)); - - Matcher> 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 v0{}; - std::vector v1{1}; - std::vector v2{2, 3}; - std::vector 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({})); // 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> 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 v0{}; - std::vector v1{1}; - std::vector 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({}))); // 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> 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 v0{}; - const std::vector v1{1}; - const std::vector v2{2, 3}; - const Matcher m0 = AnyOfArray(v0); - const Matcher m1 = AnyOfArray(v1); - const Matcher 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 g1 = AnyOfArray({GreaterThan(1)}); - const Matcher 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)); -} - -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 -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 -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 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 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 p(new int(3)); - EXPECT_THAT(p, IsNotNull()); - EXPECT_THAT(std::unique_ptr(), 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 p(new int(3)); - EXPECT_THAT(p, UniquePointee(3)); - EXPECT_THAT(p, Not(UniquePointee(2))); -} - -#if GTEST_HAS_EXCEPTIONS - -// std::function 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([]() { throw std::runtime_error("message"); }), - Throws()); - - EXPECT_THAT( - std::function([]() { throw std::runtime_error("message"); }), - ThrowsMessage(HasSubstr("message"))); -} - -TEST(ThrowsTest, PrintsExceptionWhat) { - EXPECT_THAT( - std::function([]() { throw std::runtime_error("ABC123XYZ"); }), - ThrowsMessage(HasSubstr("ABC123XYZ"))); -} - -TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) { - EXPECT_THAT(std::function([]() { throw std::exception(); }), - Throws()); -} - -TEST(ThrowsTest, CallableExecutedExactlyOnce) { - size_t a = 0; - - EXPECT_THAT(std::function([&a]() { - a++; - throw 10; - }), - Throws()); - EXPECT_EQ(a, 1u); - - EXPECT_THAT(std::function([&a]() { - a++; - throw std::runtime_error("message"); - }), - Throws()); - EXPECT_EQ(a, 2u); - - EXPECT_THAT(std::function([&a]() { - a++; - throw std::runtime_error("message"); - }), - ThrowsMessage(HasSubstr("message"))); - EXPECT_EQ(a, 3u); - - EXPECT_THAT(std::function([&a]() { - a++; - throw std::runtime_error("message"); - }), - Throws( - Property(&std::runtime_error::what, HasSubstr("message")))); - EXPECT_EQ(a, 4u); -} - -TEST(ThrowsTest, Describe) { - Matcher> matcher = Throws(); - std::stringstream ss; - matcher.DescribeTo(&ss); - auto explanation = ss.str(); - EXPECT_THAT(explanation, HasSubstr("std::runtime_error")); -} - -TEST(ThrowsTest, Success) { - Matcher> matcher = Throws(); - 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> matcher = Throws(); - 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> matcher = Throws(); - 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> matcher = Throws(); - StringMatchResultListener listener; - EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener)); - EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception")); -} - -class ThrowsPredicateTest - : public TestWithParam>> {}; - -TEST_P(ThrowsPredicateTest, Describe) { - Matcher> 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> 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> 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> 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> 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>( - ThrowsMessage(HasSubstr("error message"))))); - -// Tests that Throws(Matcher{}) compiles even when E2 != const E1&. -TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) { - { - Matcher> matcher = - ThrowsMessage(HasSubstr("error message")); - EXPECT_TRUE( - matcher.Matches([]() { throw std::runtime_error("error message"); })); - EXPECT_FALSE( - matcher.Matches([]() { throw std::runtime_error("wrong message"); })); - } - - { - Matcher inner = Eq(10); - Matcher> matcher = Throws(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("message")). -TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) { - Matcher> matcher = - ThrowsMessage("error message"); - EXPECT_TRUE( - matcher.Matches([]() { throw std::runtime_error("error message"); })); - EXPECT_FALSE(matcher.Matches( - []() { throw std::runtime_error("wrong error message"); })); -} - -#endif // GTEST_HAS_EXCEPTIONS - -} // namespace -} // namespace gmock_matchers_test -} // namespace testing - -#ifdef _MSC_VER -# pragma warning(pop) -#endif diff --git a/googlemock/test/gmock-matchers_test.h b/googlemock/test/gmock-matchers_test.h new file mode 100644 index 00000000..6c986e9f --- /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 +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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>)); +}; + +// For testing ExplainMatchResultTo(). +template +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 +GtestGreaterThanMatcher::type> GtestGreaterThan( + T&& rhs) { + return {rhs}; +} + +// As the matcher above, but using the base class with virtual functions. +template +class GreaterThanMatcher : public MatcherInterface { + 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 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 { + public: + template + Matcher GreaterThan(T n) { + if (use_gtest_matcher_) { + return GtestGreaterThan(n); + } else { + return MakeMatcher(new GreaterThanMatcher(n)); + } + } + const bool use_gtest_matcher_ = GetParam(); +}; + +// Returns the description of the given matcher. +template +std::string Describe(const Matcher& m) { + return DescribeMatcher(m); +} + +// Returns the description of the negation of the given matcher. +template +std::string DescribeNegation(const Matcher& m) { + return DescribeMatcher(m, true); +} + +// Returns the reason why x matches, or doesn't match, m. +template +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 fdc8c709..b9b66bf9 100644 --- a/googlemock/test/gmock-more-actions_test.cc +++ b/googlemock/test/gmock-more-actions_test.cc @@ -145,7 +145,7 @@ class Foo { std::string Binary(const std::string& str, char c) const { return str + c; } - int Ternary(int x, bool y, char z) { return value_ + x + y*z; } + int Ternary(int x, bool y, char z) { return value_ + x + y * z; } int SumOf4(int a, int b, int c, int d) const { return a + b + c + d + value_; @@ -291,8 +291,7 @@ TEST(InvokeTest, FunctionWithUnusedParameters) { std::make_tuple(10, 2, 5.6, std::string("hi")); EXPECT_EQ(12, a1.Perform(dummy)); - Action a2 = - Invoke(SumOfFirst2); + Action a2 = Invoke(SumOfFirst2); EXPECT_EQ( 23, a2.Perform(std::make_tuple(20, 3, true, static_cast(nullptr)))); } @@ -303,8 +302,7 @@ TEST(InvokeTest, MethodWithUnusedParameters) { Action a1 = Invoke(&foo, &Foo::SumOfLast2); EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2))); - Action a2 = - Invoke(&foo, &Foo::SumOfLast2); + Action a2 = Invoke(&foo, &Foo::SumOfLast2); EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3))); } @@ -362,7 +360,8 @@ TEST(InvokeMethodTest, MethodThatTakes4Arguments) { // Tests using Invoke() with a 5-argument method. TEST(InvokeMethodTest, MethodThatTakes5Arguments) { Foo foo; - Action a = Invoke(&foo, &Foo::SumOf5); // NOLINT + Action a = + Invoke(&foo, &Foo::SumOf5); // NOLINT EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); } @@ -523,15 +522,12 @@ TEST(SetArgRefereeActionTest, WorksWithExtraArguments) { // the bool provided to the constructor to true when destroyed. class DeletionTester { public: - explicit DeletionTester(bool* is_deleted) - : is_deleted_(is_deleted) { + explicit DeletionTester(bool* is_deleted) : is_deleted_(is_deleted) { // Make sure the bit is set to false. *is_deleted_ = false; } - ~DeletionTester() { - *is_deleted_ = true; - } + ~DeletionTester() { *is_deleted_ = true; } private: bool* is_deleted_; @@ -540,7 +536,7 @@ class DeletionTester { TEST(DeleteArgActionTest, OneArg) { bool is_deleted = false; DeletionTester* t = new DeletionTester(&is_deleted); - const Action a1 = DeleteArg<0>(); // NOLINT + const Action a1 = DeleteArg<0>(); // NOLINT EXPECT_FALSE(is_deleted); a1.Perform(std::make_tuple(t)); EXPECT_TRUE(is_deleted); @@ -549,8 +545,9 @@ TEST(DeleteArgActionTest, OneArg) { TEST(DeleteArgActionTest, TenArgs) { bool is_deleted = false; DeletionTester* t = new DeletionTester(&is_deleted); - const Action a1 = DeleteArg<9>(); + const Action + 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); @@ -608,7 +605,7 @@ TEST(ThrowActionTest, Times0) { // pointed to by the N-th (0-based) argument to values in range [first, last). TEST(SetArrayArgumentTest, SetsTheNthArray) { using MyFunction = void(bool, int*, char*); - int numbers[] = { 1, 2, 3 }; + int numbers[] = {1, 2, 3}; Action a = SetArrayArgument<1>(numbers, numbers + 3); int n[4] = {}; @@ -644,7 +641,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) { // Tests SetArrayArgument(first, last) where first == last. TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { using MyFunction = void(bool, int*); - int numbers[] = { 1, 2, 3 }; + int numbers[] = {1, 2, 3}; Action a = SetArrayArgument<1>(numbers, numbers); int n[4] = {}; @@ -660,10 +657,10 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { // (but not equal) to the argument type. TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) { using MyFunction = void(bool, int*); - char chars[] = { 97, 98, 99 }; + char chars[] = {97, 98, 99}; Action 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]); diff --git a/googlemock/test/gmock-nice-strict_test.cc b/googlemock/test/gmock-nice-strict_test.cc index 319b18d8..08254e1a 100644 --- a/googlemock/test/gmock-nice-strict_test.cc +++ b/googlemock/test/gmock-nice-strict_test.cc @@ -31,6 +31,7 @@ #include #include + #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" @@ -44,7 +45,8 @@ class Mock { MOCK_METHOD0(DoThis, void()); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(Mock); + Mock(const Mock&) = delete; + Mock& operator=(const Mock&) = delete; }; namespace testing { @@ -92,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 { @@ -102,7 +105,8 @@ class MockBar { MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6, const std::string& a7, const std::string& a8, bool a9, bool a10) { str_ = std::string() + a1 + a2 + a3 + a4 + static_cast(a5) + - static_cast(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F'); + static_cast(a6) + a7 + a8 + (a9 ? 'T' : 'F') + + (a10 ? 'T' : 'F'); } virtual ~MockBar() {} @@ -115,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 { @@ -161,8 +165,7 @@ TEST(RawMockTest, WarningForUninterestingCallAfterDeath) { 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(); @@ -280,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 nice_bar('a', 'b', "c", "d", 'e', 'f', - "g", "h", true, false); + NiceMock nice_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true, + false); EXPECT_EQ("abcdefghTF", nice_bar.str()); nice_bar.This(); @@ -390,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 naggy_bar('0', '1', "2", "3", '4', '5', - "6", "7", true, false); + NaggyMock naggy_bar('0', '1', "2", "3", '4', '5', "6", "7", true, + false); EXPECT_EQ("01234567TF", naggy_bar.str()); naggy_bar.This(); @@ -490,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 strict_bar('a', 'b', "c", "d", 'e', 'f', - "g", "h", true, false); + StrictMock 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), diff --git a/googlemock/test/gmock-port_test.cc b/googlemock/test/gmock-port_test.cc index a2c2be24..c31af821 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 6f66cf15..53c80f4e 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 #include "gmock/gmock.h" +#include "gmock/internal/gmock-pp.h" namespace testing { namespace { diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc index 7f29b612..122d5b94 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,73 +37,28 @@ #include // NOLINT #include #include +#include #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" #include "gtest/internal/gtest-port.h" namespace testing { -namespace internal { - -// Helper class for testing the Expectation class template. -class ExpectationTester { - public: - // Sets the call count of the given expectation to the given number. - void SetCallCount(int n, ExpectationBase* exp) { - exp->call_count_ = n; - } -}; - -} // namespace internal -} // namespace testing - namespace { -using testing::_; -using testing::AnyNumber; -using testing::AtLeast; -using testing::AtMost; -using testing::Between; -using testing::Cardinality; -using testing::CardinalityInterface; -using testing::Const; -using testing::ContainsRegex; -using testing::DoAll; -using testing::DoDefault; -using testing::Eq; -using testing::Expectation; -using testing::ExpectationSet; -using testing::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; @@ -125,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 @@ -154,7 +107,8 @@ class MockA { MOCK_METHOD2(ReturnInt, int(int x, int y)); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA); + MockA(const MockA&) = delete; + MockA& operator=(const MockA&) = delete; }; class MockB { @@ -162,10 +116,11 @@ class MockB { MockB() {} MOCK_CONST_METHOD0(DoB, int()); // NOLINT - MOCK_METHOD1(DoB, int(int n)); // NOLINT + MOCK_METHOD1(DoB, int(int n)); // NOLINT private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB); + MockB(const MockB&) = delete; + MockB& operator=(const MockB&) = delete; }; class ReferenceHoldingMock { @@ -175,7 +130,8 @@ class ReferenceHoldingMock { MOCK_METHOD1(AcceptReference, void(std::shared_ptr*)); 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 @@ -197,7 +153,8 @@ class MockCC : public CC { MOCK_METHOD0(Method, int()); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC); + MockCC(const MockCC&) = delete; + MockCC& operator=(const MockCC&) = delete; }; // Tests that a method with expanded name compiles. @@ -253,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 @@ -315,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); } @@ -337,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); } @@ -357,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); @@ -372,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); @@ -386,11 +338,11 @@ TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) { MockA a; Sequence s; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(1)) - .InSequence(s) - .Times(1); - }, ".Times() may only appear *before* "); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1); + }, + ".Times() may only appear *before* "); a.DoA(1); } @@ -400,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); @@ -411,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); } @@ -422,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); } @@ -437,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); } @@ -450,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); @@ -464,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); @@ -484,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); } @@ -496,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); @@ -510,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); @@ -542,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); } @@ -557,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 @@ -579,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)) @@ -595,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); @@ -615,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)) @@ -630,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" @@ -678,19 +607,16 @@ 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(); } @@ -718,10 +644,12 @@ TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) { warning_output); GMOCK_FLAG_SET(default_mock_behavior, kFail); - EXPECT_NONFATAL_FAILURE({ - MockA a; - a.DoA(0); - }, "Uninteresting mock function call"); + EXPECT_NONFATAL_FAILURE( + { + MockA a; + a.DoA(0); + }, + "Uninteresting mock function call"); // Out of bounds values are converted to kWarn GMOCK_FLAG_SET(default_mock_behavior, -1); @@ -765,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)); @@ -775,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)); @@ -804,25 +728,24 @@ TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) { // Tests that the last matching EXPECT_CALL() fires. TEST(ExpectCallTest, PicksLastMatchingExpectCall) { MockB b; - EXPECT_CALL(b, DoB(_)) - .WillRepeatedly(Return(2)); - EXPECT_CALL(b, DoB(1)) - .WillRepeatedly(Return(1)); + EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2)); + EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1)); EXPECT_EQ(1, b.DoB(1)); } // Tests lower-bound violation. TEST(ExpectCallTest, CatchesTooFewCalls) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - MockB b; - EXPECT_CALL(b, DoB(5)) - .Times(AtLeast(2)); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + MockB b; + EXPECT_CALL(b, DoB(5)).Times(AtLeast(2)); - b.DoB(5); - }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n" - " Expected: to be called at least twice\n" - " Actual: called once - unsatisfied and active"); + b.DoB(5); + }, + "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n" + " Expected: to be called at least twice\n" + " Actual: called once - unsatisfied and active"); } // Tests that the cardinality can be inferred when no Times(...) is @@ -830,28 +753,24 @@ TEST(ExpectCallTest, CatchesTooFewCalls) { TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) { { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillOnce(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); } - EXPECT_NONFATAL_FAILURE({ // NOLINT - MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillOnce(Return(2)); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + MockB b; + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); - EXPECT_EQ(1, b.DoB()); - }, "to be called twice"); + EXPECT_EQ(1, b.DoB()); + }, + "to be called twice"); { // NOLINT MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillOnce(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); @@ -862,40 +781,78 @@ TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) { TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) { { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillRepeatedly(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); } { // NOLINT MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillRepeatedly(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB()); } - EXPECT_NONFATAL_FAILURE({ // NOLINT - MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillRepeatedly(Return(2)); - }, "to be called at least once"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + MockB b; + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); + }, + "to be called at least once"); } +#if defined(__cplusplus) && __cplusplus >= 201703L + +// It should be possible to return a non-moveable type from a mock action in +// C++17 and above, where it's guaranteed that such a type can be initialized +// from a prvalue returned from a function. +TEST(ExpectCallTest, NonMoveableType) { + // Define a non-moveable result type. + struct Result { + explicit Result(int x_in) : x(x_in) {} + Result(Result&&) = delete; + + int x; + }; + + static_assert(!std::is_move_constructible_v); + static_assert(!std::is_copy_constructible_v); + + static_assert(!std::is_move_assignable_v); + static_assert(!std::is_copy_assignable_v); + + // We should be able to use a callable that returns that result as both a + // OnceAction and an Action, whether the callable ignores arguments or not. + const auto return_17 = [] { return Result(17); }; + + static_cast(OnceAction{return_17}); + static_cast(Action{return_17}); + + static_cast(OnceAction{return_17}); + static_cast(Action{return_17}); + + // It should be possible to return the result end to end through an + // EXPECT_CALL statement, with both WillOnce and WillRepeatedly. + MockFunction 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()); @@ -906,9 +863,7 @@ TEST(ExpectCallTest, NthMatchTakesNthAction) { // list is exhausted. TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillRepeatedly(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); @@ -921,8 +876,7 @@ TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) { // exhausted and there is no WillRepeatedly(). TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) { MockB b; - EXPECT_CALL(b, DoB(_)) - .Times(1); + EXPECT_CALL(b, DoB(_)).Times(1); EXPECT_CALL(b, DoB()) .Times(AnyNumber()) .WillOnce(Return(1)) @@ -984,8 +938,7 @@ TEST(UninterestingCallTest, DoesDefaultAction) { // When there is an ON_CALL() statement, the action specified by it // should be taken. MockA a; - ON_CALL(a, Binary(_, _)) - .WillByDefault(Return(true)); + ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_TRUE(a.Binary(1, 2)); // When there is no ON_CALL(), the default value for the return type @@ -999,8 +952,7 @@ TEST(UnexpectedCallTest, DoesDefaultAction) { // When there is an ON_CALL() statement, the action specified by it // should be taken. MockA a; - ON_CALL(a, Binary(_, _)) - .WillByDefault(Return(true)); + ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_CALL(a, Binary(0, 0)); a.Binary(0, 0); bool result = false; @@ -1011,11 +963,9 @@ TEST(UnexpectedCallTest, DoesDefaultAction) { // When there is no ON_CALL(), the default value for the return type // should be returned. MockB b; - EXPECT_CALL(b, DoB(0)) - .Times(0); + EXPECT_CALL(b, DoB(0)).Times(0); int n = -1; - EXPECT_NONFATAL_FAILURE(n = b.DoB(1), - "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call"); EXPECT_EQ(0, n); } @@ -1092,14 +1042,12 @@ TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) { // match the call. TEST(UnexpectedCallTest, RetiredExpectation) { MockB b; - EXPECT_CALL(b, DoB(1)) - .RetiresOnSaturation(); + EXPECT_CALL(b, DoB(1)).RetiresOnSaturation(); b.DoB(1); - EXPECT_NONFATAL_FAILURE( - b.DoB(1), - " Expected: the expectation is active\n" - " Actual: it is retired"); + EXPECT_NONFATAL_FAILURE(b.DoB(1), + " Expected: the expectation is active\n" + " Actual: it is retired"); } // Tests that Google Mock explains that an expectation that doesn't @@ -1108,10 +1056,9 @@ TEST(UnexpectedCallTest, UnmatchedArguments) { MockB b; EXPECT_CALL(b, DoB(1)); - EXPECT_NONFATAL_FAILURE( - b.DoB(2), - " Expected arg #0: is equal to 1\n" - " Actual: 2\n"); + EXPECT_NONFATAL_FAILURE(b.DoB(2), + " Expected arg #0: is equal to 1\n" + " Actual: 2\n"); b.DoB(1); } @@ -1120,15 +1067,10 @@ TEST(UnexpectedCallTest, UnmatchedArguments) { TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) { Sequence s1, s2; MockB b; - EXPECT_CALL(b, DoB(1)) - .InSequence(s1); - EXPECT_CALL(b, DoB(2)) - .Times(AnyNumber()) - .InSequence(s1); - EXPECT_CALL(b, DoB(3)) - .InSequence(s2); - EXPECT_CALL(b, DoB(4)) - .InSequence(s1, s2); + EXPECT_CALL(b, DoB(1)).InSequence(s1); + EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1); + EXPECT_CALL(b, DoB(3)).InSequence(s2); + EXPECT_CALL(b, DoB(4)).InSequence(s1, s2); ::testing::TestPartResultArray failures; { @@ -1146,23 +1088,27 @@ TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) { // Verifies that the failure message contains the two unsatisfied // pre-requisites but not the satisfied one. #if GTEST_USES_PCRE - EXPECT_THAT(r.message(), ContainsRegex( - // PCRE has trouble using (.|\n) to match any character, but - // supports the (?s) prefix for using . to match any character. - "(?s)the following immediate pre-requisites are not satisfied:\n" - ".*: pre-requisite #0\n" - ".*: pre-requisite #1")); + EXPECT_THAT( + r.message(), + ContainsRegex( + // PCRE has trouble using (.|\n) to match any character, but + // supports the (?s) prefix for using . to match any character. + "(?s)the following immediate pre-requisites are not satisfied:\n" + ".*: pre-requisite #0\n" + ".*: pre-requisite #1")); #elif GTEST_USES_POSIX_RE - EXPECT_THAT(r.message(), ContainsRegex( - // POSIX RE doesn't understand the (?s) prefix, but has no trouble - // with (.|\n). - "the following immediate pre-requisites are not satisfied:\n" - "(.|\n)*: pre-requisite #0\n" - "(.|\n)*: pre-requisite #1")); + EXPECT_THAT(r.message(), + ContainsRegex( + // POSIX RE doesn't understand the (?s) prefix, but has no + // trouble with (.|\n). + "the following immediate pre-requisites are not satisfied:\n" + "(.|\n)*: pre-requisite #0\n" + "(.|\n)*: pre-requisite #1")); #else // We can only use Google Test's own simple regex. - EXPECT_THAT(r.message(), ContainsRegex( - "the following immediate pre-requisites are not satisfied:")); + EXPECT_THAT(r.message(), + ContainsRegex( + "the following immediate pre-requisites are not satisfied:")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1")); #endif // GTEST_USES_PCRE @@ -1191,8 +1137,7 @@ TEST(ExcessiveCallTest, DoesDefaultAction) { // When there is an ON_CALL() statement, the action specified by it // should be taken. MockA a; - ON_CALL(a, Binary(_, _)) - .WillByDefault(Return(true)); + ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_CALL(a, Binary(0, 0)); a.Binary(0, 0); bool result = false; @@ -1203,8 +1148,7 @@ TEST(ExcessiveCallTest, DoesDefaultAction) { // When there is no ON_CALL(), the default value for the return type // should be returned. MockB b; - EXPECT_CALL(b, DoB(0)) - .Times(0); + EXPECT_CALL(b, DoB(0)).Times(0); int n = -1; EXPECT_NONFATAL_FAILURE(n = b.DoB(0), "Mock function called more times than expected"); @@ -1215,8 +1159,7 @@ TEST(ExcessiveCallTest, DoesDefaultAction) { // the failure message contains the argument values. TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) { MockA a; - EXPECT_CALL(a, DoA(_)) - .Times(0); + EXPECT_CALL(a, DoA(_)).Times(0); EXPECT_NONFATAL_FAILURE( a.DoA(9), "Mock function called more times than expected - returning directly.\n" @@ -1252,9 +1195,11 @@ TEST(InSequenceTest, AllExpectationInScopeAreInSequence) { EXPECT_CALL(a, DoA(2)); } - EXPECT_NONFATAL_FAILURE({ // NOLINT - a.DoA(2); - }, "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + a.DoA(2); + }, + "Unexpected mock function call"); a.DoA(1); a.DoA(2); @@ -1274,10 +1219,12 @@ TEST(InSequenceTest, NestedInSequence) { } } - EXPECT_NONFATAL_FAILURE({ // NOLINT - a.DoA(1); - a.DoA(3); - }, "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + a.DoA(1); + a.DoA(3); + }, + "Unexpected mock function call"); a.DoA(2); a.DoA(3); @@ -1293,9 +1240,11 @@ TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) { } EXPECT_CALL(a, DoA(3)); - EXPECT_NONFATAL_FAILURE({ // NOLINT - a.DoA(2); - }, "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + a.DoA(2); + }, + "Unexpected mock function call"); a.DoA(3); a.DoA(1); @@ -1309,8 +1258,7 @@ TEST(SequenceTest, AnyOrderIsOkByDefault) { MockB b; EXPECT_CALL(a, DoA(1)); - EXPECT_CALL(b, DoB()) - .Times(AnyNumber()); + EXPECT_CALL(b, DoB()).Times(AnyNumber()); a.DoA(1); b.DoB(); @@ -1321,8 +1269,7 @@ TEST(SequenceTest, AnyOrderIsOkByDefault) { MockB b; EXPECT_CALL(a, DoA(1)); - EXPECT_CALL(b, DoB()) - .Times(AnyNumber()); + EXPECT_CALL(b, DoB()).Times(AnyNumber()); b.DoB(); a.DoA(1); @@ -1333,16 +1280,12 @@ TEST(SequenceTest, AnyOrderIsOkByDefault) { // is specified. TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) { MockA a; - ON_CALL(a, ReturnResult(_)) - .WillByDefault(Return(Result())); + ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); Sequence s; - EXPECT_CALL(a, ReturnResult(1)) - .InSequence(s); - EXPECT_CALL(a, ReturnResult(2)) - .InSequence(s); - EXPECT_CALL(a, ReturnResult(3)) - .InSequence(s); + EXPECT_CALL(a, ReturnResult(1)).InSequence(s); + EXPECT_CALL(a, ReturnResult(2)).InSequence(s); + EXPECT_CALL(a, ReturnResult(3)).InSequence(s); a.ReturnResult(1); @@ -1357,14 +1300,11 @@ TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) { // is specified. TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) { MockA a; - ON_CALL(a, ReturnResult(_)) - .WillByDefault(Return(Result())); + ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); Sequence s; - EXPECT_CALL(a, ReturnResult(1)) - .InSequence(s); - EXPECT_CALL(a, ReturnResult(2)) - .InSequence(s); + EXPECT_CALL(a, ReturnResult(1)).InSequence(s); + EXPECT_CALL(a, ReturnResult(2)).InSequence(s); // May only be called after a.ReturnResult(1). EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call"); @@ -1377,8 +1317,7 @@ TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) { class PartialOrderTest : public testing::Test { protected: PartialOrderTest() { - ON_CALL(a_, ReturnResult(_)) - .WillByDefault(Return(Result())); + ON_CALL(a_, ReturnResult(_)).WillByDefault(Return(Result())); // Specifies this partial ordering: // @@ -1386,16 +1325,10 @@ class PartialOrderTest : public testing::Test { // a.ReturnResult(2) * n ==> a.ReturnResult(3) // b.DoB() * 2 ==> Sequence x, y; - EXPECT_CALL(a_, ReturnResult(1)) - .InSequence(x); - EXPECT_CALL(b_, DoB()) - .Times(2) - .InSequence(y); - EXPECT_CALL(a_, ReturnResult(2)) - .Times(AnyNumber()) - .InSequence(x, y); - EXPECT_CALL(a_, ReturnResult(3)) - .InSequence(x); + EXPECT_CALL(a_, ReturnResult(1)).InSequence(x); + EXPECT_CALL(b_, DoB()).Times(2).InSequence(y); + EXPECT_CALL(a_, ReturnResult(2)).Times(AnyNumber()).InSequence(x, y); + EXPECT_CALL(a_, ReturnResult(3)).InSequence(x); } MockA a_; @@ -1447,13 +1380,9 @@ TEST(SequenceTest, Retirement) { MockA a; Sequence s; - EXPECT_CALL(a, DoA(1)) - .InSequence(s); - EXPECT_CALL(a, DoA(_)) - .InSequence(s) - .RetiresOnSaturation(); - EXPECT_CALL(a, DoA(1)) - .InSequence(s); + EXPECT_CALL(a, DoA(1)).InSequence(s); + EXPECT_CALL(a, DoA(_)).InSequence(s).RetiresOnSaturation(); + EXPECT_CALL(a, DoA(1)).InSequence(s); a.DoA(1); a.DoA(2); @@ -1518,12 +1447,12 @@ TEST(ExpectationSetTest, ConstructorsWork) { Expectation e1; const Expectation e2; - ExpectationSet es1; // Default ctor. + ExpectationSet es1; // Default ctor. ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL. - ExpectationSet es3 = e1; // Ctor from Expectation. - ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax. - ExpectationSet es5 = e2; // Ctor from const Expectation. - ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax. + ExpectationSet es3 = e1; // Ctor from Expectation. + ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax. + ExpectationSet es5 = e2; // Ctor from const Expectation. + ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax. ExpectationSet es7 = es2; // Copy ctor. EXPECT_EQ(0, es1.size()); @@ -1595,7 +1524,7 @@ TEST(ExpectationSetTest, IsEnumerable) { EXPECT_TRUE(it != es.end()); EXPECT_THAT(*it, Eq(Expectation())); ++it; - EXPECT_TRUE(it== es.end()); + EXPECT_TRUE(it == es.end()); } // Tests the .After() clause. @@ -1605,8 +1534,7 @@ TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) { ExpectationSet es; es += EXPECT_CALL(a, DoA(1)); es += EXPECT_CALL(a, DoA(2)); - EXPECT_CALL(a, DoA(3)) - .After(es); + EXPECT_CALL(a, DoA(3)).After(es); a.DoA(1); a.DoA(2); @@ -1619,9 +1547,7 @@ TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) { // The following also verifies that const Expectation objects work // too. Do not remove the const modifiers. const Expectation e1 = EXPECT_CALL(a, DoA(1)); - const Expectation e2 = EXPECT_CALL(b, DoB()) - .Times(2) - .After(e1); + const Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1); EXPECT_CALL(a, DoA(2)).After(e2); a.DoA(1); @@ -1638,10 +1564,8 @@ TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) { // Define ordering: // a.DoA(1) ==> b.DoB() ==> a.DoA(2) Expectation e1 = EXPECT_CALL(a, DoA(1)); - Expectation e2 = EXPECT_CALL(b, DoB()) - .After(e1); - EXPECT_CALL(a, DoA(2)) - .After(e2); + Expectation e2 = EXPECT_CALL(b, DoB()).After(e1); + EXPECT_CALL(a, DoA(2)).After(e2); a.DoA(1); @@ -1660,11 +1584,8 @@ TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) { // Define ordering: // a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2) Expectation e1 = EXPECT_CALL(a, DoA(1)); - Expectation e2 = EXPECT_CALL(b, DoB()) - .Times(2) - .After(e1); - EXPECT_CALL(a, DoA(2)) - .After(e2); + Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1); + EXPECT_CALL(a, DoA(2)).After(e2); a.DoA(1); b.DoB(); @@ -1679,16 +1600,14 @@ TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) { // Calls must satisfy the partial order when specified so. TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) { MockA a; - ON_CALL(a, ReturnResult(_)) - .WillByDefault(Return(Result())); + ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); // Define ordering: // a.DoA(1) ==> // a.DoA(2) ==> a.ReturnResult(3) Expectation e = EXPECT_CALL(a, DoA(1)); const ExpectationSet es = EXPECT_CALL(a, DoA(2)); - EXPECT_CALL(a, ReturnResult(3)) - .After(e, es); + EXPECT_CALL(a, ReturnResult(3)).After(e, es); // May only be called last. EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call"); @@ -1707,8 +1626,7 @@ TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) { // a.DoA(2) ==> a.DoA(3) Expectation e = EXPECT_CALL(a, DoA(1)); const ExpectationSet es = EXPECT_CALL(a, DoA(2)); - EXPECT_CALL(a, DoA(3)) - .After(e, es); + EXPECT_CALL(a, DoA(3)).After(e, es); a.DoA(2); @@ -1725,9 +1643,7 @@ TEST(AfterTest, CanBeUsedWithInSequence) { Sequence s; Expectation e = EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(2)).InSequence(s); - EXPECT_CALL(a, DoA(3)) - .InSequence(s) - .After(e); + EXPECT_CALL(a, DoA(3)).InSequence(s).After(e); a.DoA(1); @@ -1744,10 +1660,7 @@ TEST(AfterTest, CanBeCalledManyTimes) { Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e2 = EXPECT_CALL(a, DoA(2)); Expectation e3 = EXPECT_CALL(a, DoA(3)); - EXPECT_CALL(a, DoA(4)) - .After(e1) - .After(e2) - .After(e3); + EXPECT_CALL(a, DoA(4)).After(e1).After(e2).After(e3); a.DoA(3); a.DoA(1); @@ -1763,8 +1676,7 @@ TEST(AfterTest, AcceptsUpToFiveArguments) { Expectation e3 = EXPECT_CALL(a, DoA(3)); ExpectationSet es1 = EXPECT_CALL(a, DoA(4)); ExpectationSet es2 = EXPECT_CALL(a, DoA(5)); - EXPECT_CALL(a, DoA(6)) - .After(e1, e2, e3, es1, es2); + EXPECT_CALL(a, DoA(6)).After(e1, e2, e3, es1, es2); a.DoA(5); a.DoA(2); @@ -1777,8 +1689,7 @@ TEST(AfterTest, AcceptsUpToFiveArguments) { // .After() allows input to contain duplicated Expectations. TEST(AfterTest, AcceptsDuplicatedInput) { MockA a; - ON_CALL(a, ReturnResult(_)) - .WillByDefault(Return(Result())); + ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); // Define ordering: // DoA(1) ==> @@ -1788,8 +1699,7 @@ TEST(AfterTest, AcceptsDuplicatedInput) { ExpectationSet es; es += e1; es += e2; - EXPECT_CALL(a, ReturnResult(3)) - .After(e1, e2, es, e1); + EXPECT_CALL(a, ReturnResult(3)).After(e1, e2, es, e1); a.DoA(1); @@ -1806,8 +1716,7 @@ TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) { MockA a; ExpectationSet es1 = EXPECT_CALL(a, DoA(1)); Expectation e2 = EXPECT_CALL(a, DoA(2)); - EXPECT_CALL(a, DoA(3)) - .After(es1); + EXPECT_CALL(a, DoA(3)).After(es1); es1 += e2; a.DoA(1); @@ -1826,14 +1735,11 @@ TEST(DeletingMockEarlyTest, Success1) { { InSequence dummy; - EXPECT_CALL(*b1, DoB(_)) - .WillOnce(Return(1)); + EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1)); EXPECT_CALL(*a, Binary(_, _)) .Times(AnyNumber()) .WillRepeatedly(Return(true)); - EXPECT_CALL(*b2, DoB(_)) - .Times(AnyNumber()) - .WillRepeatedly(Return(2)); + EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2)); } EXPECT_EQ(1, b1->DoB(1)); @@ -1854,13 +1760,9 @@ TEST(DeletingMockEarlyTest, Success2) { { InSequence dummy; - EXPECT_CALL(*b1, DoB(_)) - .WillOnce(Return(1)); - EXPECT_CALL(*a, Binary(_, _)) - .Times(AnyNumber()); - EXPECT_CALL(*b2, DoB(_)) - .Times(AnyNumber()) - .WillRepeatedly(Return(2)); + EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1)); + EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber()); + EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2)); } delete a; // a is trivially satisfied. @@ -1875,14 +1777,14 @@ TEST(DeletingMockEarlyTest, Success2) { // Suppresses warning on unreferenced formal parameter in MSVC with // -W4. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #endif ACTION_P(Delete, ptr) { delete ptr; } #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) { @@ -1893,8 +1795,7 @@ TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) { TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) { MockA* const a = new MockA; - EXPECT_CALL(*a, ReturnResult(_)) - .WillOnce(DoAll(Delete(a), Return(Result()))); + EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result()))); a->ReturnResult(42); // This will cause a to be deleted. } @@ -1906,19 +1807,13 @@ TEST(DeletingMockEarlyTest, Failure1) { { InSequence dummy; - EXPECT_CALL(*b1, DoB(_)) - .WillOnce(Return(1)); - EXPECT_CALL(*a, Binary(_, _)) - .Times(AnyNumber()); - EXPECT_CALL(*b2, DoB(_)) - .Times(AnyNumber()) - .WillRepeatedly(Return(2)); + EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1)); + EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber()); + EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2)); } delete a; // a is trivially satisfied. - EXPECT_NONFATAL_FAILURE({ - b2->DoB(2); - }, "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, "Unexpected mock function call"); EXPECT_EQ(1, b1->DoB(1)); delete b1; delete b2; @@ -1933,18 +1828,13 @@ TEST(DeletingMockEarlyTest, Failure2) { { InSequence dummy; EXPECT_CALL(*b1, DoB(_)); - EXPECT_CALL(*a, Binary(_, _)) - .Times(AnyNumber()); - EXPECT_CALL(*b2, DoB(_)) - .Times(AnyNumber()); + EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber()); + EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()); } - EXPECT_NONFATAL_FAILURE(delete b1, - "Actual: never called"); - EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), - "Unexpected mock function call"); - EXPECT_NONFATAL_FAILURE(b2->DoB(1), - "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE(delete b1, "Actual: never called"); + EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE(b2->DoB(1), "Unexpected mock function call"); delete a; delete b2; } @@ -1969,23 +1859,16 @@ class EvenNumberCardinality : public CardinalityInterface { } }; -Cardinality EvenNumber() { - return Cardinality(new EvenNumberCardinality); -} +Cardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); } TEST(ExpectationBaseTest, AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) { MockA* a = new MockA; Sequence s; - EXPECT_CALL(*a, DoA(1)) - .Times(EvenNumber()) - .InSequence(s); - EXPECT_CALL(*a, DoA(2)) - .Times(AnyNumber()) - .InSequence(s); - EXPECT_CALL(*a, DoA(3)) - .Times(AnyNumber()); + EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s); + EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s); + EXPECT_CALL(*a, DoA(3)).Times(AnyNumber()); a->DoA(3); a->DoA(1); @@ -1996,8 +1879,7 @@ TEST(ExpectationBaseTest, // The following tests verify the message generated when a mock // function is called. -struct Printable { -}; +struct Printable {}; inline void operator<<(::std::ostream& os, const Printable&) { os << "Printable"; @@ -2017,7 +1899,8 @@ class MockC { MOCK_METHOD0(NonVoidMethod, int()); // NOLINT private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC); + MockC(const MockC&) = delete; + MockC& operator=(const MockC&) = delete; }; class VerboseFlagPreservingFixture : public testing::Test { @@ -2032,7 +1915,9 @@ class VerboseFlagPreservingFixture : public testing::Test { 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 @@ -2064,7 +1949,7 @@ TEST(FunctionCallMessageTest, EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output); -# ifndef NDEBUG +#ifndef NDEBUG // We check the stack trace content in dbg-mode only, as opt-mode // may inline the call we are interested in seeing. @@ -2080,7 +1965,7 @@ TEST(FunctionCallMessageTest, const std::string output2 = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2); -# endif // NDEBUG +#endif // NDEBUG } // Tests that an uninteresting mock function call on a naggy mock @@ -2096,7 +1981,8 @@ TEST(FunctionCallMessageTest, IsSubstring, "Uninteresting mock function call - returning default value.\n" " Function call: DoB()\n" - " Returns: 0\n", output1.c_str()); + " Returns: 0\n", + output1.c_str()); // Makes sure the return value is printed. // A void mock function. @@ -2104,12 +1990,12 @@ TEST(FunctionCallMessageTest, CaptureStdout(); c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); const std::string output2 = GetCapturedStdout(); - EXPECT_THAT(output2.c_str(), - ContainsRegex( - "Uninteresting mock function call - returning directly\\.\n" - " Function call: VoidMethod" - "\\(false, 5, \"Hi\", NULL, @.+ " - "Printable, 4-byte object <00-00 00-00>\\)")); + EXPECT_THAT( + output2.c_str(), + ContainsRegex("Uninteresting mock function call - returning directly\\.\n" + " Function call: VoidMethod" + "\\(false, 5, \"Hi\", NULL, @.+ " + "Printable, 4-byte object <00-00 00-00>\\)")); // A void function has no return value to print. } @@ -2126,14 +2012,14 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { const std::string& function_name) { if (should_print) { EXPECT_THAT(output.c_str(), HasSubstr(expected_substring)); -# ifndef NDEBUG +#ifndef NDEBUG // We check the stack trace content in dbg-mode only, as opt-mode // may inline the call we are interested in seeing. EXPECT_THAT(output.c_str(), HasSubstr(function_name)); -# else +#else // Suppresses 'unused function parameter' warnings. static_cast(function_name); -# endif // NDEBUG +#endif // NDEBUG } else { EXPECT_STREQ("", output.c_str()); } @@ -2143,31 +2029,26 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { void TestExpectedCall(bool should_print) { MockA a; EXPECT_CALL(a, DoA(5)); - EXPECT_CALL(a, Binary(_, 1)) - .WillOnce(Return(true)); + EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true)); // A void-returning function. CaptureStdout(); a.DoA(5); - VerifyOutput( - GetCapturedStdout(), - should_print, - "Mock function call matches EXPECT_CALL(a, DoA(5))...\n" - " Function call: DoA(5)\n" - "Stack trace:\n", - "DoA"); + VerifyOutput(GetCapturedStdout(), should_print, + "Mock function call matches EXPECT_CALL(a, DoA(5))...\n" + " Function call: DoA(5)\n" + "Stack trace:\n", + "DoA"); // A non-void-returning function. CaptureStdout(); a.Binary(2, 1); - VerifyOutput( - GetCapturedStdout(), - should_print, - "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n" - " Function call: Binary(2, 1)\n" - " Returns: true\n" - "Stack trace:\n", - "Binary"); + VerifyOutput(GetCapturedStdout(), should_print, + "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n" + " Function call: Binary(2, 1)\n" + " Returns: true\n" + "Stack trace:\n", + "Binary"); } // Tests how the flag affects uninteresting calls on a naggy mock. @@ -2185,27 +2066,23 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { // A void-returning function. CaptureStdout(); a.DoA(5); - VerifyOutput( - GetCapturedStdout(), - should_print, - "\nGMOCK WARNING:\n" - "Uninteresting mock function call - returning directly.\n" - " Function call: DoA(5)\n" + - note, - "DoA"); + VerifyOutput(GetCapturedStdout(), should_print, + "\nGMOCK WARNING:\n" + "Uninteresting mock function call - returning directly.\n" + " Function call: DoA(5)\n" + + note, + "DoA"); // A non-void-returning function. CaptureStdout(); a.Binary(2, 1); - VerifyOutput( - GetCapturedStdout(), - should_print, - "\nGMOCK WARNING:\n" - "Uninteresting mock function call - returning default value.\n" - " Function call: Binary(2, 1)\n" - " Returns: false\n" + - note, - "Binary"); + VerifyOutput(GetCapturedStdout(), should_print, + "\nGMOCK WARNING:\n" + "Uninteresting mock function call - returning default value.\n" + " Function call: Binary(2, 1)\n" + " Returns: false\n" + + note, + "Binary"); } }; @@ -2260,7 +2137,8 @@ class LogTestHelper { MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot)); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper); + LogTestHelper(const LogTestHelper&) = delete; + LogTestHelper& operator=(const LogTestHelper&) = delete; }; class GMockLogTest : public VerboseFlagPreservingFixture { @@ -2270,22 +2148,19 @@ class GMockLogTest : public VerboseFlagPreservingFixture { TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) { GMOCK_FLAG_SET(verbose, kWarningVerbosity); - EXPECT_CALL(helper_, Foo(_)) - .WillOnce(Return(PrintMeNot())); + EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot())); helper_.Foo(PrintMeNot()); // This is an expected call. } TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) { GMOCK_FLAG_SET(verbose, kErrorVerbosity); - EXPECT_CALL(helper_, Foo(_)) - .WillOnce(Return(PrintMeNot())); + EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot())); helper_.Foo(PrintMeNot()); // This is an expected call. } TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) { GMOCK_FLAG_SET(verbose, kErrorVerbosity); - ON_CALL(helper_, Foo(_)) - .WillByDefault(Return(PrintMeNot())); + ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot())); helper_.Foo(PrintMeNot()); // This should generate a warning. } @@ -2346,8 +2221,7 @@ TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) { // verification succeeds. TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)); b.DoB(); ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); @@ -2362,8 +2236,7 @@ TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) { // verification fails. TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)); bool result = true; EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), "Actual: never called"); @@ -2379,10 +2252,8 @@ TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) { // when all of its methods have expectations. TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)); - EXPECT_CALL(b, DoB(_)) - .WillOnce(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)); + EXPECT_CALL(b, DoB(_)).WillOnce(Return(2)); b.DoB(); b.DoB(1); ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); @@ -2397,10 +2268,8 @@ TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) { // when a method has more than one expectation. TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) { MockB b; - EXPECT_CALL(b, DoB(0)) - .WillOnce(Return(1)); - EXPECT_CALL(b, DoB(_)) - .WillOnce(Return(2)); + EXPECT_CALL(b, DoB(0)).WillOnce(Return(1)); + EXPECT_CALL(b, DoB(_)).WillOnce(Return(2)); b.DoB(1); bool result = true; EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), @@ -2421,8 +2290,7 @@ TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) { b.DoB(); Mock::VerifyAndClearExpectations(&b); - EXPECT_CALL(b, DoB(_)) - .WillOnce(Return(1)); + EXPECT_CALL(b, DoB(_)).WillOnce(Return(1)); b.DoB(1); Mock::VerifyAndClearExpectations(&b); Mock::VerifyAndClearExpectations(&b); @@ -2446,8 +2314,7 @@ TEST(VerifyAndClearTest, NoMethodHasDefaultActions) { // but not all of its methods have default actions. TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) { MockB b; - ON_CALL(b, DoB()) - .WillByDefault(Return(1)); + ON_CALL(b, DoB()).WillByDefault(Return(1)); Mock::VerifyAndClear(&b); @@ -2459,10 +2326,8 @@ TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) { // its methods have default actions. TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) { MockB b; - ON_CALL(b, DoB()) - .WillByDefault(Return(1)); - ON_CALL(b, DoB(_)) - .WillByDefault(Return(2)); + ON_CALL(b, DoB()).WillByDefault(Return(1)); + ON_CALL(b, DoB(_)).WillByDefault(Return(2)); Mock::VerifyAndClear(&b); @@ -2477,10 +2342,8 @@ TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) { // method has more than one ON_CALL() set on it. TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) { MockB b; - ON_CALL(b, DoB(0)) - .WillByDefault(Return(1)); - ON_CALL(b, DoB(_)) - .WillByDefault(Return(2)); + ON_CALL(b, DoB(0)).WillByDefault(Return(1)); + ON_CALL(b, DoB(_)).WillByDefault(Return(2)); Mock::VerifyAndClear(&b); @@ -2494,13 +2357,11 @@ TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) { // times. TEST(VerifyAndClearTest, CanCallManyTimes) { MockB b; - ON_CALL(b, DoB()) - .WillByDefault(Return(1)); + ON_CALL(b, DoB()).WillByDefault(Return(1)); Mock::VerifyAndClear(&b); Mock::VerifyAndClear(&b); - ON_CALL(b, DoB(_)) - .WillByDefault(Return(1)); + ON_CALL(b, DoB(_)).WillByDefault(Return(1)); Mock::VerifyAndClear(&b); EXPECT_EQ(0, b.DoB()); @@ -2510,10 +2371,8 @@ TEST(VerifyAndClearTest, CanCallManyTimes) { // Tests that VerifyAndClear() works when the verification succeeds. TEST(VerifyAndClearTest, Success) { MockB b; - ON_CALL(b, DoB()) - .WillByDefault(Return(1)); - EXPECT_CALL(b, DoB(1)) - .WillOnce(Return(2)); + ON_CALL(b, DoB()).WillByDefault(Return(1)); + EXPECT_CALL(b, DoB(1)).WillOnce(Return(2)); b.DoB(); b.DoB(1); @@ -2528,10 +2387,8 @@ TEST(VerifyAndClearTest, Success) { // Tests that VerifyAndClear() works when the verification fails. TEST(VerifyAndClearTest, Failure) { MockB b; - ON_CALL(b, DoB(_)) - .WillByDefault(Return(1)); - EXPECT_CALL(b, DoB()) - .WillOnce(Return(2)); + ON_CALL(b, DoB(_)).WillByDefault(Return(1)); + EXPECT_CALL(b, DoB()).WillOnce(Return(2)); b.DoB(1); bool result = true; @@ -2549,12 +2406,9 @@ TEST(VerifyAndClearTest, Failure) { // expectations are set on a const mock object. TEST(VerifyAndClearTest, Const) { MockB b; - ON_CALL(Const(b), DoB()) - .WillByDefault(Return(1)); + ON_CALL(Const(b), DoB()).WillByDefault(Return(1)); - EXPECT_CALL(Const(b), DoB()) - .WillOnce(DoDefault()) - .WillOnce(Return(2)); + EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2)); b.DoB(); b.DoB(); @@ -2570,18 +2424,14 @@ TEST(VerifyAndClearTest, Const) { // object after VerifyAndClear() has been called on it. TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) { MockB b; - ON_CALL(b, DoB()) - .WillByDefault(Return(1)); - EXPECT_CALL(b, DoB(_)) - .WillOnce(Return(2)); + ON_CALL(b, DoB()).WillByDefault(Return(1)); + EXPECT_CALL(b, DoB(_)).WillOnce(Return(2)); b.DoB(1); Mock::VerifyAndClear(&b); - EXPECT_CALL(b, DoB()) - .WillOnce(Return(3)); - ON_CALL(b, DoB(_)) - .WillByDefault(Return(4)); + EXPECT_CALL(b, DoB()).WillOnce(Return(3)); + ON_CALL(b, DoB(_)).WillByDefault(Return(4)); EXPECT_EQ(3, b.DoB()); EXPECT_EQ(4, b.DoB(1)); @@ -2594,19 +2444,13 @@ TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) { MockB b1; MockB b2; - ON_CALL(a, Binary(_, _)) - .WillByDefault(Return(true)); - EXPECT_CALL(a, Binary(_, _)) - .WillOnce(DoDefault()) - .WillOnce(Return(false)); + ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); + EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false)); - ON_CALL(b1, DoB()) - .WillByDefault(Return(1)); - EXPECT_CALL(b1, DoB(_)) - .WillOnce(Return(2)); + ON_CALL(b1, DoB()).WillByDefault(Return(1)); + EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2)); - ON_CALL(b2, DoB()) - .WillByDefault(Return(3)); + ON_CALL(b2, DoB()).WillByDefault(Return(3)); EXPECT_CALL(b2, DoB(_)); b2.DoB(0); @@ -2647,8 +2491,7 @@ TEST(VerifyAndClearTest, ReferenceHoldingMock test_mock; // ON_CALL stores a reference to a inside test_mock. - ON_CALL(test_mock, AcceptReference(_)) - .WillByDefault(SetArgPointee<0>(a)); + ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a)); // Throw away the reference to the mock that we have in a. After this, the // only reference to it is stored by test_mock. @@ -2669,9 +2512,8 @@ TEST(VerifyAndClearTest, TEST(SynchronizationTest, CanCallMockMethodInAction) { MockA a; MockC c; - ON_CALL(a, DoA(_)) - .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c, - &MockC::NonVoidMethod))); + ON_CALL(a, DoA(_)).WillByDefault( + IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod))); EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1)) .WillOnce(Invoke(&a, &MockA::DoA)) @@ -2755,14 +2597,15 @@ TEST(ParameterlessExpectationsTest, } } // namespace +} // namespace testing // Allows the user to define their own main and then invoke gmock_main // from it. This might be necessary on some platforms which require // specific setup and teardown. #if GMOCK_RENAME_MAIN -int gmock_main(int argc, char **argv) { +int gmock_main(int argc, char** argv) { #else -int main(int argc, char **argv) { +int main(int argc, char** argv) { #endif // GMOCK_RENAME_MAIN testing::InitGoogleMock(&argc, argv); // Ensures that the tests pass no matter what value of diff --git a/googlemock/test/gmock_all_test.cc b/googlemock/test/gmock_all_test.cc index fffbb8b6..6db0086b 100644 --- a/googlemock/test/gmock_all_test.cc +++ b/googlemock/test/gmock_all_test.cc @@ -38,7 +38,10 @@ #include "test/gmock-actions_test.cc" #include "test/gmock-cardinalities_test.cc" #include "test/gmock-internal-utils_test.cc" -#include "test/gmock-matchers_test.cc" +#include "test/gmock-matchers-arithmetic_test.cc" +#include "test/gmock-matchers-comparisons_test.cc" +#include "test/gmock-matchers-containers_test.cc" +#include "test/gmock-matchers-misc_test.cc" #include "test/gmock-more-actions_test.cc" #include "test/gmock-nice-strict_test.cc" #include "test/gmock-port_test.cc" diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 72eb43f7..44e5e35f 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_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 Google Mock's functionality that depends on exceptions. #include "gmock/gmock.h" @@ -75,6 +74,5 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { } } - } // unnamed namespace #endif diff --git a/googlemock/test/gmock_leak_test_.cc b/googlemock/test/gmock_leak_test_.cc index 2e095abc..fa645916 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 @@ -52,7 +51,8 @@ class MockFoo : public FooInterface { MOCK_METHOD0(DoThis, void()); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); + MockFoo(const MockFoo&) = delete; + MockFoo& operator=(const MockFoo&) = delete; }; TEST(LeakTest, LeakedMockWithExpectCallCausesFailureWhenLeakCheckingIsEnabled) { diff --git a/googlemock/test/gmock_link2_test.cc b/googlemock/test/gmock_link2_test.cc index d27ce176..cd3d6908 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 e7c54cc2..f51e3988 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 5734b2e1..eaf18e9d 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: @@ -118,7 +117,7 @@ #include "gmock/gmock.h" #if !GTEST_OS_WINDOWS_MOBILE -# include +#include #endif #include @@ -200,14 +199,14 @@ class Interface { virtual char* StringFromString(char* str) = 0; virtual int IntFromString(char* str) = 0; virtual int& IntRefFromString(char* str) = 0; - virtual void VoidFromFunc(void(*func)(char* str)) = 0; + virtual void VoidFromFunc(void (*func)(char* str)) = 0; virtual void VoidFromIntRef(int& n) = 0; // NOLINT virtual void VoidFromFloat(float n) = 0; virtual void VoidFromDouble(double n) = 0; virtual void VoidFromVector(const std::vector& v) = 0; }; -class Mock: public Interface { +class Mock : public Interface { public: Mock() {} @@ -215,14 +214,15 @@ class Mock: public Interface { MOCK_METHOD1(StringFromString, char*(char* str)); MOCK_METHOD1(IntFromString, int(char* str)); MOCK_METHOD1(IntRefFromString, int&(char* str)); - MOCK_METHOD1(VoidFromFunc, void(void(*func)(char* str))); + MOCK_METHOD1(VoidFromFunc, void(void (*func)(char* str))); MOCK_METHOD1(VoidFromIntRef, void(int& n)); // NOLINT MOCK_METHOD1(VoidFromFloat, void(float n)); MOCK_METHOD1(VoidFromDouble, void(double n)); MOCK_METHOD1(VoidFromVector, void(const std::vector& v)); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(Mock); + Mock(const Mock&) = delete; + Mock& operator=(const Mock&) = delete; }; class InvokeHelper { @@ -301,8 +301,8 @@ TEST(LinkTest, TestSetArrayArgument) { char ch = 'x'; char ch2 = 'y'; - EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArrayArgument<0>(&ch2, - &ch2 + 1)); + EXPECT_CALL(mock, VoidFromString(_)) + .WillOnce(SetArrayArgument<0>(&ch2, &ch2 + 1)); mock.VoidFromString(&ch); } @@ -339,8 +339,8 @@ TEST(LinkTest, TestInvokeWithoutArgs) { EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid)) - .WillOnce(InvokeWithoutArgs(&test_invoke_helper, - &InvokeHelper::VoidFromVoid)); + .WillOnce( + InvokeWithoutArgs(&test_invoke_helper, &InvokeHelper::VoidFromVoid)); mock.VoidFromString(nullptr); mock.VoidFromString(nullptr); } @@ -424,14 +424,14 @@ TEST(LinkTest, TestThrow) { // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #endif // Tests the linkage of actions created using ACTION macro. namespace { ACTION(Return1) { return 1; } -} +} // namespace TEST(LinkTest, TestActionMacro) { Mock mock; @@ -443,7 +443,7 @@ TEST(LinkTest, TestActionMacro) { // Tests the linkage of actions created using ACTION_P macro. namespace { ACTION_P(ReturnArgument, ret_value) { return ret_value; } -} +} // namespace TEST(LinkTest, TestActionPMacro) { Mock mock; @@ -457,10 +457,10 @@ namespace { ACTION_P2(ReturnEqualsEitherOf, first, second) { return arg0 == first || arg0 == second; } -} +} // namespace #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif TEST(LinkTest, TestActionP2Macro) { @@ -492,8 +492,7 @@ TEST(LinkTest, TestMatchersEq) { const char* p = "x"; ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return()); - ON_CALL(mock, VoidFromString(const_cast("y"))) - .WillByDefault(Return()); + ON_CALL(mock, VoidFromString(const_cast("y"))).WillByDefault(Return()); } // Tests the linkage of the Lt, Gt, Le, Ge, and Ne matchers. @@ -592,7 +591,7 @@ TEST(LinkTest, TestMatcherElementsAre) { // Tests the linkage of the ElementsAreArray matcher. TEST(LinkTest, TestMatcherElementsAreArray) { Mock mock; - char arr[] = { 'a', 'b' }; + char arr[] = {'a', 'b'}; ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return()); } diff --git a/googlemock/test/gmock_output_test.py b/googlemock/test/gmock_output_test.py index 71532c55..6b4ab901 100755 --- a/googlemock/test/gmock_output_test.py +++ b/googlemock/test/gmock_output_test.py @@ -161,13 +161,13 @@ class GMockOutputTest(gmock_test_utils.TestCase): golden_file.close() # The normalized output should match the golden file. - self.assertEquals(golden, output) + self.assertEqual(golden, output) # The raw output should contain 2 leaked mock object errors for # test GMockOutputTest.CatchesLeakedMocks. - self.assertEquals(['GMockOutputTest.CatchesLeakedMocks', - 'GMockOutputTest.CatchesLeakedMocks'], - leaky_tests) + self.assertEqual(['GMockOutputTest.CatchesLeakedMocks', + 'GMockOutputTest.CatchesLeakedMocks'], + leaky_tests) if __name__ == '__main__': diff --git a/googlemock/test/gmock_output_test_.cc b/googlemock/test/gmock_output_test_.cc index b1dac459..a1786915 100644 --- a/googlemock/test/gmock_output_test_.cc +++ b/googlemock/test/gmock_output_test_.cc @@ -27,21 +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. - // Tests Google Mock's output in various scenarios. This ensures that // Google Mock's messages are readable and useful. -#include "gmock/gmock.h" - #include + #include +#include "gmock/gmock.h" #include "gtest/gtest.h" // Silence C4100 (unreferenced formal parameter) #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #endif using testing::_; @@ -63,7 +62,8 @@ class MockFoo { MOCK_METHOD2(Bar3, void(int x, int y)); private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); + MockFoo(const MockFoo&) = delete; + MockFoo& operator=(const MockFoo&) = delete; }; class GMockOutputTest : public testing::Test { @@ -90,9 +90,7 @@ TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) { } TEST_F(GMockOutputTest, ExplicitActionsRunOut) { - EXPECT_CALL(foo_, Bar2(_, _)) - .Times(2) - .WillOnce(Return(false)); + EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false)); foo_.Bar2(2, 2); foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. } @@ -134,8 +132,7 @@ TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) { } TEST_F(GMockOutputTest, RetiredExpectation) { - EXPECT_CALL(foo_, Bar2(_, _)) - .RetiresOnSaturation(); + EXPECT_CALL(foo_, Bar2(_, _)).RetiresOnSaturation(); EXPECT_CALL(foo_, Bar2(0, 0)); foo_.Bar2(1, 1); @@ -160,12 +157,9 @@ TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) { TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) { Sequence s1, s2; - EXPECT_CALL(foo_, Bar(_, 0, _)) - .InSequence(s1); - EXPECT_CALL(foo_, Bar2(0, 0)) - .InSequence(s2); - EXPECT_CALL(foo_, Bar2(1, _)) - .InSequence(s1, s2); + EXPECT_CALL(foo_, Bar(_, 0, _)).InSequence(s1); + EXPECT_CALL(foo_, Bar2(0, 0)).InSequence(s2); + EXPECT_CALL(foo_, Bar2(1, _)).InSequence(s1, s2); foo_.Bar2(1, 0); // Has two immediate unsatisfied pre-requisites foo_.Bar("Hi", 0, 0); @@ -179,8 +173,7 @@ TEST_F(GMockOutputTest, UnsatisfiedWith) { TEST_F(GMockOutputTest, UnsatisfiedExpectation) { EXPECT_CALL(foo_, Bar(_, _, _)); - EXPECT_CALL(foo_, Bar2(0, _)) - .Times(2); + EXPECT_CALL(foo_, Bar2(0, _)).Times(2); foo_.Bar2(0, 1); } @@ -194,26 +187,22 @@ TEST_F(GMockOutputTest, MismatchArguments) { } TEST_F(GMockOutputTest, MismatchWith) { - EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) - .With(Ge()); + EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge()); foo_.Bar2(2, 3); // Mismatch With() foo_.Bar2(2, 1); } TEST_F(GMockOutputTest, MismatchArgumentsAndWith) { - EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) - .With(Ge()); + EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge()); foo_.Bar2(1, 3); // Mismatch arguments and mismatch With() foo_.Bar2(2, 1); } TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) { - ON_CALL(foo_, Bar2(_, _)) - .WillByDefault(Return(true)); // Default action #1 - ON_CALL(foo_, Bar2(1, _)) - .WillByDefault(Return(false)); // Default action #2 + ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1 + ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2 EXPECT_CALL(foo_, Bar2(2, 2)); foo_.Bar2(1, 0); // Unexpected call, takes default action #2. @@ -222,10 +211,8 @@ TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) { } TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) { - ON_CALL(foo_, Bar2(_, _)) - .WillByDefault(Return(true)); // Default action #1 - ON_CALL(foo_, Bar2(1, _)) - .WillByDefault(Return(false)); // Default action #2 + ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1 + ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2 EXPECT_CALL(foo_, Bar2(2, 2)); EXPECT_CALL(foo_, Bar2(1, 1)); @@ -237,22 +224,17 @@ TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) { } TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) { - ON_CALL(foo_, Bar2(_, _)) - .WillByDefault(Return(true)); // Default action #1 - ON_CALL(foo_, Bar2(1, _)) - .WillByDefault(Return(false)); // Default action #2 + ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1 + ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2 foo_.Bar2(2, 2); // Uninteresting call, takes default action #1. foo_.Bar2(1, 1); // Uninteresting call, takes default action #2. } TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) { - ON_CALL(foo_, Bar2(_, _)) - .WillByDefault(Return(true)); // Default action #1 + ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1 - EXPECT_CALL(foo_, Bar2(_, _)) - .Times(2) - .WillOnce(Return(false)); + EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false)); foo_.Bar2(2, 2); foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. } @@ -293,7 +275,7 @@ 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. @@ -305,5 +287,5 @@ int main(int argc, char **argv) { } #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif diff --git a/googlemock/test/gmock_stress_test.cc b/googlemock/test/gmock_stress_test.cc index 20725d69..9e42cd93 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) { 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')); + 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, 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* const t = new ThreadWithParam(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* 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 9a2bd93f..8f1bd5d0 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,6 +34,7 @@ #include "gmock/gmock.h" #include + #include "gtest/gtest.h" #include "gtest/internal/custom/gtest.h" diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index cd34e1f2..84e5a5bb 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -170,24 +170,24 @@ GTEST_API_ bool InDeathTestChild(); // Asserts that a given `statement` causes the program to exit, with an // integer exit status that satisfies `predicate`, and emitting error output // that matches `matcher`. -# define ASSERT_EXIT(statement, predicate, matcher) \ - GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_) +#define ASSERT_EXIT(statement, predicate, matcher) \ + GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_) // Like `ASSERT_EXIT`, but continues on to successive tests in the // test suite, if any: -# define EXPECT_EXIT(statement, predicate, matcher) \ - GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_) +#define EXPECT_EXIT(statement, predicate, matcher) \ + GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_) // Asserts that a given `statement` causes the program to exit, either by // explicitly exiting with a nonzero exit code or being killed by a // signal, and emitting error output that matches `matcher`. -# define ASSERT_DEATH(statement, matcher) \ - ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) +#define ASSERT_DEATH(statement, matcher) \ + ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) // Like `ASSERT_DEATH`, but continues on to successive tests in the // test suite, if any: -# define EXPECT_DEATH(statement, matcher) \ - EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) +#define EXPECT_DEATH(statement, matcher) \ + EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: @@ -198,21 +198,23 @@ class GTEST_API_ ExitedWithCode { ExitedWithCode(const ExitedWithCode&) = default; void operator=(const ExitedWithCode& other) = delete; bool operator()(int exit_status) const; + private: const int exit_code_; }; -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Tests that an exit code describes an exit due to termination by a // given signal. class GTEST_API_ KilledBySignal { public: explicit KilledBySignal(int signum); bool operator()(int exit_status) const; + private: const int signum_; }; -# endif // !GTEST_OS_WINDOWS +#endif // !GTEST_OS_WINDOWS // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. // The death testing framework causes this to have interesting semantics, @@ -257,23 +259,21 @@ class GTEST_API_ KilledBySignal { // EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); // }, "death"); // -# ifdef NDEBUG +#ifdef NDEBUG -# define EXPECT_DEBUG_DEATH(statement, regex) \ +#define EXPECT_DEBUG_DEATH(statement, regex) \ GTEST_EXECUTE_STATEMENT_(statement, regex) -# define ASSERT_DEBUG_DEATH(statement, regex) \ +#define ASSERT_DEBUG_DEATH(statement, regex) \ GTEST_EXECUTE_STATEMENT_(statement, regex) -# else +#else -# define EXPECT_DEBUG_DEATH(statement, regex) \ - EXPECT_DEATH(statement, regex) +#define EXPECT_DEBUG_DEATH(statement, regex) EXPECT_DEATH(statement, regex) -# define ASSERT_DEBUG_DEATH(statement, regex) \ - ASSERT_DEATH(statement, regex) +#define ASSERT_DEBUG_DEATH(statement, regex) ASSERT_DEATH(statement, regex) -# endif // NDEBUG for EXPECT_DEBUG_DEATH +#endif // NDEBUG for EXPECT_DEBUG_DEATH #endif // GTEST_HAS_DEATH_TEST // This macro is used for implementing macros such as @@ -311,18 +311,17 @@ class GTEST_API_ KilledBySignal { // statement unconditionally returns or throws. The Message constructor at // the end allows the syntax of streaming additional messages into the // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. -# define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - GTEST_LOG_(WARNING) \ - << "Death tests are not supported on this platform.\n" \ - << "Statement '" #statement "' cannot be verified."; \ - } else if (::testing::internal::AlwaysFalse()) { \ - ::testing::internal::RE::PartialMatch(".*", (regex)); \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - terminator; \ - } else \ - ::testing::Message() +#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \ + << "Statement '" #statement "' cannot be verified."; \ + } else if (::testing::internal::AlwaysFalse()) { \ + ::testing::internal::RE::PartialMatch(".*", (regex)); \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + terminator; \ + } else \ + ::testing::Message() // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if @@ -330,15 +329,15 @@ class GTEST_API_ KilledBySignal { // useful when you are combining death test assertions with normal test // assertions in one test. #if GTEST_HAS_DEATH_TEST -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - EXPECT_DEATH(statement, regex) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - ASSERT_DEATH(statement, regex) +#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ + EXPECT_DEATH(statement, regex) +#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ + ASSERT_DEATH(statement, regex) #else -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, ) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return) +#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ + GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, ) +#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ + GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return) #endif } // namespace testing diff --git a/googletest/include/gtest/gtest-matchers.h b/googletest/include/gtest/gtest-matchers.h index 3472db7e..bffa00c5 100644 --- a/googletest/include/gtest/gtest-matchers.h +++ b/googletest/include/gtest/gtest-matchers.h @@ -102,11 +102,11 @@ class MatchResultListener { private: ::std::ostream* const stream_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener); + MatchResultListener(const MatchResultListener&) = delete; + MatchResultListener& operator=(const MatchResultListener&) = delete; }; -inline MatchResultListener::~MatchResultListener() { -} +inline MatchResultListener::~MatchResultListener() {} // An instance of a subclass of this knows how to describe itself as a // matcher. @@ -180,27 +180,39 @@ namespace internal { struct AnyEq { template - bool operator()(const A& a, const B& b) const { return a == b; } + bool operator()(const A& a, const B& b) const { + return a == b; + } }; struct AnyNe { template - bool operator()(const A& a, const B& b) const { return a != b; } + bool operator()(const A& a, const B& b) const { + return a != b; + } }; struct AnyLt { template - bool operator()(const A& a, const B& b) const { return a < b; } + bool operator()(const A& a, const B& b) const { + return a < b; + } }; struct AnyGt { template - bool operator()(const A& a, const B& b) const { return a > b; } + bool operator()(const A& a, const B& b) const { + return a > b; + } }; struct AnyLe { template - bool operator()(const A& a, const B& b) const { return a <= b; } + bool operator()(const A& a, const B& b) const { + return a <= b; + } }; struct AnyGe { template - bool operator()(const A& a, const B& b) const { return a >= b; } + bool operator()(const A& a, const B& b) const { + return a >= b; + } }; // A match result listener that ignores the explanation. @@ -209,7 +221,8 @@ class DummyMatchResultListener : public MatchResultListener { DummyMatchResultListener() : MatchResultListener(nullptr) {} private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener); + DummyMatchResultListener(const DummyMatchResultListener&) = delete; + DummyMatchResultListener& operator=(const DummyMatchResultListener&) = delete; }; // A match result listener that forwards the explanation to a given @@ -221,7 +234,9 @@ class StreamMatchResultListener : public MatchResultListener { : MatchResultListener(os) {} private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener); + StreamMatchResultListener(const StreamMatchResultListener&) = delete; + StreamMatchResultListener& operator=(const StreamMatchResultListener&) = + delete; }; struct SharedPayloadBase { @@ -288,17 +303,18 @@ class MatcherBase : private MatcherDescriberInterface { } protected: - MatcherBase() : vtable_(nullptr) {} + MatcherBase() : vtable_(nullptr), buffer_() {} // Constructs a matcher from its implementation. template - explicit MatcherBase(const MatcherInterface* impl) { + explicit MatcherBase(const MatcherInterface* impl) + : vtable_(nullptr), buffer_() { Init(impl); } template ::type::is_gtest_matcher> - MatcherBase(M&& m) { // NOLINT + MatcherBase(M&& m) : vtable_(nullptr), buffer_() { // NOLINT Init(std::forward(m)); } @@ -424,8 +440,8 @@ class MatcherBase : private MatcherDescriberInterface { static const M& Get(const MatcherBase& m) { // When inlined along with Init, need to be explicit to avoid violating // strict aliasing rules. - const M *ptr = static_cast( - static_cast(&m.buffer_)); + const M* ptr = + static_cast(static_cast(&m.buffer_)); return *ptr; } static void Init(MatcherBase& m, M impl) { @@ -745,7 +761,7 @@ template class EqMatcher : public ComparisonBase, Rhs, AnyEq> { public: explicit EqMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyEq>(rhs) { } + : ComparisonBase, Rhs, AnyEq>(rhs) {} static const char* Desc() { return "is equal to"; } static const char* NegatedDesc() { return "isn't equal to"; } }; @@ -753,7 +769,7 @@ template class NeMatcher : public ComparisonBase, Rhs, AnyNe> { public: explicit NeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyNe>(rhs) { } + : ComparisonBase, Rhs, AnyNe>(rhs) {} static const char* Desc() { return "isn't equal to"; } static const char* NegatedDesc() { return "is equal to"; } }; @@ -761,7 +777,7 @@ template class LtMatcher : public ComparisonBase, Rhs, AnyLt> { public: explicit LtMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyLt>(rhs) { } + : ComparisonBase, Rhs, AnyLt>(rhs) {} static const char* Desc() { return "is <"; } static const char* NegatedDesc() { return "isn't <"; } }; @@ -769,7 +785,7 @@ template class GtMatcher : public ComparisonBase, Rhs, AnyGt> { public: explicit GtMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyGt>(rhs) { } + : ComparisonBase, Rhs, AnyGt>(rhs) {} static const char* Desc() { return "is >"; } static const char* NegatedDesc() { return "isn't >"; } }; @@ -777,7 +793,7 @@ template class LeMatcher : public ComparisonBase, Rhs, AnyLe> { public: explicit LeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyLe>(rhs) { } + : ComparisonBase, Rhs, AnyLe>(rhs) {} static const char* Desc() { return "is <="; } static const char* NegatedDesc() { return "isn't <="; } }; @@ -785,7 +801,7 @@ template class GeMatcher : public ComparisonBase, Rhs, AnyGe> { public: explicit GeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyGe>(rhs) { } + : ComparisonBase, Rhs, AnyGe>(rhs) {} static const char* Desc() { return "is >="; } static const char* NegatedDesc() { return "isn't >="; } }; @@ -876,12 +892,16 @@ PolymorphicMatcher ContainsRegex( // Note: if the parameter of Eq() were declared as const T&, Eq("foo") // wouldn't compile. template -inline internal::EqMatcher Eq(T x) { return internal::EqMatcher(x); } +inline internal::EqMatcher Eq(T x) { + return internal::EqMatcher(x); +} // Constructs a Matcher from a 'value' of type T. The constructed // matcher matches any value that's equal to 'value'. template -Matcher::Matcher(T value) { *this = Eq(value); } +Matcher::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(...) @@ -896,7 +916,9 @@ Matcher::Matcher(T value) { *this = Eq(value); } // can always write Matcher(Lt(5)) to be explicit about the type, // for example. template -inline Matcher TypedEq(const Rhs& rhs) { return Eq(rhs); } +inline Matcher TypedEq(const Rhs& rhs) { + return Eq(rhs); +} // Creates a polymorphic matcher that matches anything >= x. template diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h index 9419229f..6c8bf900 100644 --- a/googletest/include/gtest/gtest-message.h +++ b/googletest/include/gtest/gtest-message.h @@ -111,8 +111,8 @@ class GTEST_API_ Message { // Streams a non-pointer value to this object. template - inline Message& operator <<(const T& val) { - // Some libraries overload << for STL containers. These + inline Message& operator<<(const T& val) { + // Some libraries overload << for STL containers. These // overloads are defined in the global namespace instead of ::std. // // C++'s symbol lookup rule (i.e. Koenig lookup) says that these @@ -126,7 +126,7 @@ class GTEST_API_ Message { // from the global namespace. With this using declaration, // overloads of << defined in the global namespace and those // visible via Koenig lookup are both exposed in this function. - using ::operator <<; + using ::operator<<; *ss_ << val; return *this; } @@ -145,7 +145,7 @@ class GTEST_API_ Message { // ensure consistent result across compilers, we always treat NULL // as "(null)". template - inline Message& operator <<(T* const& pointer) { // NOLINT + inline Message& operator<<(T* const& pointer) { // NOLINT if (pointer == nullptr) { *ss_ << "(null)"; } else { @@ -160,25 +160,23 @@ class GTEST_API_ Message { // templatized version above. Without this definition, streaming // endl or other basic IO manipulators to Message will confuse the // compiler. - Message& operator <<(BasicNarrowIoManip val) { + Message& operator<<(BasicNarrowIoManip val) { *ss_ << val; return *this; } // Instead of 1/0, we want to see true/false for bool values. - Message& operator <<(bool b) { - return *this << (b ? "true" : "false"); - } + Message& operator<<(bool b) { return *this << (b ? "true" : "false"); } // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. - Message& operator <<(const wchar_t* wide_c_str); - Message& operator <<(wchar_t* wide_c_str); + Message& operator<<(const wchar_t* wide_c_str); + Message& operator<<(wchar_t* wide_c_str); #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. - Message& operator <<(const ::std::wstring& wstr); + Message& operator<<(const ::std::wstring& wstr); #endif // GTEST_HAS_STD_WSTRING // Gets the text streamed to this object so far as an std::string. @@ -197,7 +195,7 @@ class GTEST_API_ Message { }; // Streams a Message to an ostream. -inline std::ostream& operator <<(std::ostream& os, const Message& sb) { +inline std::ostream& operator<<(std::ostream& os, const Message& sb) { return os << sb.GetString(); } diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index 96c1c722..b55119ac 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -356,9 +356,7 @@ internal::ValueArray Values(T... v) { // } // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool()); // -inline internal::ParamGenerator Bool() { - return Values(false, true); -} +inline internal::ParamGenerator 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. @@ -431,8 +429,11 @@ internal::CartesianProductHolder Combine(const Generator&... g) { return 0; \ } \ static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ - test_name)); \ + GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ + (const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete; \ + GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \ + const GTEST_TEST_CLASS_NAME_(test_suite_name, \ + test_name) &) = delete; /* NOLINT */ \ }; \ int GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)::gtest_registering_dummy_ = \ @@ -456,43 +457,42 @@ internal::CartesianProductHolder 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 \ - 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& info) { \ - if (::testing::internal::AlwaysFalse()) { \ - ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \ - __VA_ARGS__, \ - ::testing::internal::DefaultParamName, \ - DUMMY_PARAM_))); \ - auto t = std::make_tuple(__VA_ARGS__); \ - static_assert(std::tuple_size::value <= 2, \ - "Too Many Args!"); \ - } \ - return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \ - __VA_ARGS__, \ - ::testing::internal::DefaultParamName, \ - DUMMY_PARAM_))))(info); \ - } \ - static int gtest_##prefix##test_suite_name##_dummy_ \ - GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::UnitTest::GetInstance() \ - ->parameterized_test_registry() \ - .GetTestSuitePatternHolder( \ - GTEST_STRINGIFY_(test_suite_name), \ - ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ - ->AddTestSuiteInstantiation( \ - GTEST_STRINGIFY_(prefix), \ - >est_##prefix##test_suite_name##_EvalGenerator_, \ - >est_##prefix##test_suite_name##_EvalGenerateName_, \ +#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \ + static ::testing::internal::ParamGenerator \ + 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& info) { \ + if (::testing::internal::AlwaysFalse()) { \ + ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \ + __VA_ARGS__, \ + ::testing::internal::DefaultParamName, \ + DUMMY_PARAM_))); \ + auto t = std::make_tuple(__VA_ARGS__); \ + static_assert(std::tuple_size::value <= 2, \ + "Too Many Args!"); \ + } \ + return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \ + __VA_ARGS__, \ + ::testing::internal::DefaultParamName, \ + DUMMY_PARAM_))))(info); \ + } \ + static int gtest_##prefix##test_suite_name##_dummy_ \ + GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::UnitTest::GetInstance() \ + ->parameterized_test_registry() \ + .GetTestSuitePatternHolder( \ + GTEST_STRINGIFY_(test_suite_name), \ + ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ + ->AddTestSuiteInstantiation( \ + GTEST_STRINGIFY_(prefix), \ + >est_##prefix##test_suite_name##_EvalGenerator_, \ + >est_##prefix##test_suite_name##_EvalGenerateName_, \ __FILE__, __LINE__) - // Allow Marking a Parameterized test class as not needing to be instantiated. -#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \ +#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \ namespace gtest_do_not_use_outside_namespace_scope {} \ static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \ GTEST_STRINGIFY_(T)) diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index b097e988..a91e8b8b 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -258,12 +258,10 @@ struct ConvertibleToStringViewPrinter { #endif }; - // Prints the given number of bytes in the given object to the given // ostream. GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, - size_t count, - ::std::ostream* os); + size_t count, ::std::ostream* os); struct RawBytesPrinter { // SFINAE on `sizeof` to make sure we have a complete type. template @@ -376,12 +374,12 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t); // to point to a NUL-terminated string, and thus can print it as a string. #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \ - template <> \ - class FormatForComparison { \ - public: \ - static ::std::string Format(CharType* value) { \ - return ::testing::PrintToString(value); \ - } \ + template <> \ + class FormatForComparison { \ + public: \ + static ::std::string Format(CharType* value) { \ + return ::testing::PrintToString(value); \ + } \ } GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); @@ -411,8 +409,8 @@ GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring); // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. template -std::string FormatForComparisonFailureMessage( - const T1& value, const T2& /* other_operand */) { +std::string FormatForComparisonFailureMessage(const T1& value, + const T2& /* other_operand */) { return FormatForComparison::Format(value); } @@ -552,7 +550,7 @@ void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { } // Overloads for ::std::string. -GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); +GTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os); inline void PrintTo(const ::std::string& s, ::std::ostream* os) { PrintStringTo(s, os); } @@ -579,7 +577,7 @@ inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) { // Overloads for ::std::wstring. #if GTEST_HAS_STD_WSTRING -GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); +GTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os); inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { PrintWideStringTo(s, os); } @@ -823,8 +821,8 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { } } // This overload prints a (const) char array compactly. -GTEST_API_ void UniversalPrintArray( - const char* begin, size_t len, ::std::ostream* os); +GTEST_API_ void UniversalPrintArray(const char* begin, size_t len, + ::std::ostream* os); #ifdef __cpp_char8_t // This overload prints a (const) char8_t array compactly. @@ -841,8 +839,8 @@ GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len, ::std::ostream* os); // This overload prints a (const) wchar_t array compactly. -GTEST_API_ void UniversalPrintArray( - const wchar_t* begin, size_t len, ::std::ostream* os); +GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len, + ::std::ostream* os); // Implements printing an array type T[N]. template @@ -1001,10 +999,10 @@ void UniversalPrint(const T& value, ::std::ostream* os) { UniversalPrinter::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 void TersePrintPrefixToStrings(const Tuple&, std::integral_constant, Strings*) {} diff --git a/googletest/include/gtest/gtest-spi.h b/googletest/include/gtest/gtest-spi.h index 12c94e4a..bec8c481 100644 --- a/googletest/include/gtest/gtest-spi.h +++ b/googletest/include/gtest/gtest-spi.h @@ -85,7 +85,10 @@ class GTEST_API_ ScopedFakeTestPartResultReporter TestPartResultReporterInterface* old_reporter_; TestPartResultArray* const result_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); + ScopedFakeTestPartResultReporter(const ScopedFakeTestPartResultReporter&) = + delete; + ScopedFakeTestPartResultReporter& operator=( + const ScopedFakeTestPartResultReporter&) = delete; }; namespace internal { @@ -101,12 +104,14 @@ class GTEST_API_ SingleFailureChecker { SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const std::string& substr); ~SingleFailureChecker(); + private: const TestPartResultArray* const results_; const TestPartResult::Type type_; const std::string substr_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); + SingleFailureChecker(const SingleFailureChecker&) = delete; + SingleFailureChecker& operator=(const SingleFailureChecker&) = delete; }; } // namespace internal @@ -116,7 +121,8 @@ class GTEST_API_ SingleFailureChecker { GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // A set of macros for testing Google Test assertions or code that's expected -// to generate Google Test fatal failures. It verifies that the given +// to generate Google Test fatal failures (e.g. a failure from an ASSERT_EQ, but +// not a non-fatal failure, as from EXPECT_EQ). It verifies that the given // statement will cause exactly one fatal Google Test failure with 'substr' // being part of the failure message. // @@ -138,44 +144,46 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // helper macro, due to some peculiarity in how the preprocessor // works. The AcceptsMacroThatExpandsToUnprotectedComma test in // gtest_unittest.cc will fail to compile if we do that. -#define EXPECT_FATAL_FAILURE(statement, substr) \ - do { \ - class GTestExpectFatalFailureHelper {\ - public:\ - static void Execute() { statement; }\ - };\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ONLY_CURRENT_THREAD, >est_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( \ + >est_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ONLY_CURRENT_THREAD, \ + >est_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(\ - >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ALL_THREADS, >est_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( \ + >est_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ + ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ + >est_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 @@ -204,32 +212,37 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // instead of // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) // to avoid an MSVC warning on unreachable code. -#define EXPECT_NONFATAL_FAILURE(statement, substr) \ - do {\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ +#define EXPECT_NONFATAL_FAILURE(statement, substr) \ + do { \ + ::testing::TestPartResultArray gtest_failures; \ + ::testing::internal::SingleFailureChecker gtest_checker( \ >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ - (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ - if (::testing::internal::AlwaysTrue()) { statement; }\ - }\ + (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ONLY_CURRENT_THREAD, \ + >est_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(\ - >est_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( \ + >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ + (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ - >est_failures);\ - if (::testing::internal::AlwaysTrue()) { statement; }\ - }\ + >est_failures); \ + if (::testing::internal::AlwaysTrue()) { \ + statement; \ + } \ + } \ } while (::testing::internal::AlwaysFalse()) #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 39393b21..09cc8c34 100644 --- a/googletest/include/gtest/gtest-test-part.h +++ b/googletest/include/gtest/gtest-test-part.h @@ -36,6 +36,7 @@ #include #include + #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" @@ -144,7 +145,8 @@ class GTEST_API_ TestPartResultArray { private: std::vector 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. @@ -170,11 +172,13 @@ class GTEST_API_ HasNewFatalFailureHelper ~HasNewFatalFailureHelper() override; void ReportTestPartResult(const TestPartResult& result) override; bool has_new_fatal_failure() const { return has_new_fatal_failure_; } + private: bool has_new_fatal_failure_; TestPartResultReporterInterface* original_reporter_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper); + HasNewFatalFailureHelper(const HasNewFatalFailureHelper&) = delete; + HasNewFatalFailureHelper& operator=(const HasNewFatalFailureHelper&) = delete; }; } // namespace internal diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 343bf6fe..bd35a326 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -192,7 +192,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); typedef ::testing::internal::GenerateTypeList::type \ GTEST_TYPE_PARAMS_(CaseName); \ typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ - GTEST_NAME_GENERATOR_(CaseName) + GTEST_NAME_GENERATOR_(CaseName) #define TYPED_TEST(CaseName, TestName) \ static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \ @@ -258,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_ @@ -303,21 +303,21 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); REGISTER_TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ - static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ - "test-suit-prefix must not be empty"); \ - static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTestSuite< \ - SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ - ::testing::internal::GenerateTypeList::type>:: \ - Register(GTEST_STRINGIFY_(Prefix), \ - ::testing::internal::CodeLocation(__FILE__, __LINE__), \ - >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ - GTEST_STRINGIFY_(SuiteName), \ - GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ - ::testing::internal::GenerateNames< \ - ::testing::internal::NameGeneratorSelector< \ - __VA_ARGS__>::type, \ +#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ + static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ + "test-suit-prefix must not be empty"); \ + static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::internal::TypeParameterizedTestSuite< \ + SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ + ::testing::internal::GenerateTypeList::type>:: \ + Register(GTEST_STRINGIFY_(Prefix), \ + ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + >EST_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::type>()) // Legacy API is deprecated but still available diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index a4174cd4..d19a587a 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -339,7 +339,8 @@ class GTEST_API_ Test { virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; } // We disallow copying Tests. - GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); + Test(const Test&) = delete; + Test& operator=(const Test&) = delete; }; typedef internal::TimeInMillis TimeInMillis; @@ -353,24 +354,17 @@ class TestProperty { // C'tor. TestProperty does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestProperty object. - TestProperty(const std::string& a_key, const std::string& a_value) : - key_(a_key), value_(a_value) { - } + TestProperty(const std::string& a_key, const std::string& a_value) + : key_(a_key), value_(a_value) {} // Gets the user supplied key. - const char* key() const { - return key_.c_str(); - } + const char* key() const { return key_.c_str(); } // Gets the user supplied value. - const char* value() const { - return value_.c_str(); - } + const char* value() const { return value_.c_str(); } // Sets a new value, overriding the one supplied in the constructor. - void SetValue(const std::string& new_value) { - value_ = new_value; - } + void SetValue(const std::string& new_value) { value_ = new_value; } private: // The key supplied by the user. @@ -504,7 +498,8 @@ class GTEST_API_ TestResult { TimeInMillis elapsed_time_; // We disallow copying TestResult. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); + TestResult(const TestResult&) = delete; + TestResult& operator=(const TestResult&) = delete; }; // class TestResult // A TestInfo object stores the following information about a test: @@ -628,8 +623,8 @@ class GTEST_API_ TestInfo { } // These fields are immutable properties of the test. - const std::string test_suite_name_; // test suite name - const std::string name_; // Test name + const std::string test_suite_name_; // test suite name + const std::string name_; // Test name // Name of the parameter type, or NULL if this is not a typed or a // type-parameterized test. const std::unique_ptr type_param_; @@ -650,7 +645,8 @@ class GTEST_API_ TestInfo { // test for the second time. TestResult result_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); + TestInfo(const TestInfo&) = delete; + TestInfo& operator=(const TestInfo&) = delete; }; // A test suite, which consists of a vector of TestInfos. @@ -758,7 +754,7 @@ class GTEST_API_ TestSuite { // Adds a TestInfo to this test suite. Will delete the TestInfo upon // destruction of the TestSuite object. - void AddTestInfo(TestInfo * test_info); + void AddTestInfo(TestInfo* test_info); // Clears the results of all tests in this test suite. void ClearResult(); @@ -859,7 +855,8 @@ class GTEST_API_ TestSuite { TestResult ad_hoc_test_result_; // We disallow copying TestSuites. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite); + TestSuite(const TestSuite&) = delete; + TestSuite& operator=(const TestSuite&) = delete; }; // An Environment object is capable of setting up and tearing down an @@ -886,6 +883,7 @@ class Environment { // Override this to define how to tear down the environment. virtual void TearDown() {} + private: // If you see an error about overriding the following function or // about it being private, you have mis-spelled SetUp() as Setup(). @@ -963,8 +961,7 @@ class TestEventListener { virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; // Fired after each iteration of tests finishes. - virtual void OnTestIterationEnd(const UnitTest& unit_test, - int iteration) = 0; + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0; // Fired after all test activities have ended. virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; @@ -1079,7 +1076,8 @@ class GTEST_API_ TestEventListeners { TestEventListener* default_xml_generator_; // We disallow copying TestEventListeners. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); + TestEventListeners(const TestEventListeners&) = delete; + TestEventListeners& operator=(const TestEventListeners&) = delete; }; // A UnitTest consists of a vector of TestSuites. @@ -1122,8 +1120,7 @@ class GTEST_API_ UnitTest { // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. - const TestInfo* current_test_info() const - GTEST_LOCK_EXCLUDED_(mutex_); + const TestInfo* current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_); // Returns the random seed used at the start of the current test run. int random_seed() const; @@ -1229,8 +1226,7 @@ class GTEST_API_ UnitTest { // eventually call this to report their results. The user code // should use the assertion macros instead of calling this directly. void AddTestPartResult(TestPartResult::Type result_type, - const char* file_name, - int line_number, + const char* file_name, int line_number, const std::string& message, const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_); @@ -1261,8 +1257,7 @@ class GTEST_API_ UnitTest { friend std::set* 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(); @@ -1276,8 +1271,7 @@ class GTEST_API_ UnitTest { GTEST_LOCK_EXCLUDED_(mutex_); // Pops a trace from the per-thread Google Test trace stack. - void PopGTestTrace() - GTEST_LOCK_EXCLUDED_(mutex_); + void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_); // Protects mutable state in *impl_. This is mutable as some const // methods need to lock it too. @@ -1290,7 +1284,8 @@ class GTEST_API_ UnitTest { internal::UnitTestImpl* impl_; // We disallow copying UnitTest. - GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); + UnitTest(const UnitTest&) = delete; + UnitTest& operator=(const UnitTest&) = delete; }; // A convenient wrapper for adding an environment for the test @@ -1341,13 +1336,11 @@ namespace internal { // when calling EXPECT_* in a tight loop. template 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==/!= @@ -1360,8 +1353,7 @@ inline bool operator!=(faketype, faketype) { return false; } // The helper function for {ASSERT|EXPECT}_EQ. template 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(); @@ -1392,8 +1384,7 @@ class EqHelper { // Even though its body looks the same as the above version, we // cannot merge the two, as it will make anonymous enums unhappy. static AssertionResult Compare(const char* lhs_expression, - const char* rhs_expression, - BiggestInt lhs, + const char* rhs_expression, BiggestInt lhs, BiggestInt rhs) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } @@ -1428,16 +1419,16 @@ AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ -template \ -AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ - const T1& val1, const T2& val2) {\ - if (val1 op val2) {\ - return AssertionSuccess();\ - } else {\ - return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\ - }\ -} +#define GTEST_IMPL_CMP_HELPER_(op_name, op) \ + template \ + 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. @@ -1459,49 +1450,42 @@ GTEST_IMPL_CMP_HELPER_(GT, >) // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, const char* s2_expression, - const char* s1, - const char* s2); + const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASEEQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression, const char* s2_expression, - const char* s1, - const char* s2); + const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRNE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, - const char* s1, - const char* s2); + const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASENE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, - const char* s1, - const char* s2); - + const char* s1, const char* s2); // Helper function for *_STREQ on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, const char* s2_expression, - const wchar_t* s1, - const wchar_t* s2); + const wchar_t* s1, const wchar_t* s2); // Helper function for *_STRNE on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, - const wchar_t* s1, - const wchar_t* s2); + const wchar_t* s1, const wchar_t* s2); } // namespace internal @@ -1513,32 +1497,40 @@ GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, // // The {needle,haystack}_expr arguments are the stringified // expressions that generated the two real arguments. -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, + const char* haystack_expr, + const char* needle, + const char* haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, + const char* haystack_expr, + const wchar_t* needle, + const wchar_t* haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const char* needle, + const char* haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const wchar_t* needle, + const wchar_t* haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::string& needle, + const ::std::string& haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::string& needle, + const ::std::string& haystack); #if GTEST_HAS_STD_WSTRING -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::wstring& needle, + const ::std::wstring& haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::wstring& needle, + const ::std::wstring& haystack); #endif // GTEST_HAS_STD_WSTRING namespace internal { @@ -1553,8 +1545,7 @@ namespace internal { template AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, const char* rhs_expression, - RawType lhs_value, - RawType rhs_value) { + RawType lhs_value, RawType rhs_value) { const FloatingPoint lhs(lhs_value), rhs(rhs_value); if (lhs.AlmostEquals(rhs)) { @@ -1569,10 +1560,8 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, rhs_ss << std::setprecision(std::numeric_limits::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); } @@ -1582,8 +1571,7 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, - double val1, - double val2, + double val1, double val2, double abs_error); // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. @@ -1591,9 +1579,7 @@ GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, class GTEST_API_ AssertHelper { public: // Constructor. - AssertHelper(TestPartResult::Type type, - const char* file, - int line, + AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message); ~AssertHelper(); @@ -1607,11 +1593,9 @@ class GTEST_API_ AssertHelper { // re-using stack space even for temporary variables, so every EXPECT_EQ // reserves stack space for another AssertHelper. struct AssertHelperData { - AssertHelperData(TestPartResult::Type t, - const char* srcfile, - int line_num, + AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num, const char* msg) - : type(t), file(srcfile), line(line_num), message(msg) { } + : type(t), file(srcfile), line(line_num), message(msg) {} TestPartResult::Type const type; const char* const file; @@ -1619,12 +1603,14 @@ class GTEST_API_ AssertHelper { std::string const message; private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); + AssertHelperData(const AssertHelperData&) = delete; + AssertHelperData& operator=(const AssertHelperData&) = delete; }; AssertHelperData* const data_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); + AssertHelper(const AssertHelper&) = delete; + AssertHelper& operator=(const AssertHelper&) = delete; }; } // namespace internal @@ -1681,15 +1667,14 @@ class WithParamInterface { private: // Sets parameter value. The caller is responsible for making sure the value // remains alive and unchanged throughout the current test. - static void SetParam(const ParamType* parameter) { - parameter_ = parameter; - } + static void SetParam(const ParamType* parameter) { parameter_ = parameter; } // Static value used for accessing parameter during a test lifetime. static const ParamType* parameter_; // TestClass must be a subclass of WithParamInterface and Test. - template friend class internal::ParameterizedTestFactory; + template + friend class internal::ParameterizedTestFactory; }; template @@ -1699,8 +1684,7 @@ const T* WithParamInterface::parameter_ = nullptr; // WithParamInterface, and can just inherit from ::testing::TestWithParam. template -class TestWithParam : public Test, public WithParamInterface { -}; +class TestWithParam : public Test, public WithParamInterface {}; // Macros for indicating success/failure in test code. @@ -1731,7 +1715,7 @@ class TestWithParam : public Test, public WithParamInterface { // 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) @@ -1746,7 +1730,7 @@ class TestWithParam : public Test, public WithParamInterface { // Define this macro to 1 to omit the definition of FAIL(), which is a // generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_FAIL -# define FAIL() GTEST_FAIL() +#define FAIL() GTEST_FAIL() #endif // Generates a success with a generic message. @@ -1755,7 +1739,7 @@ class TestWithParam : public Test, public WithParamInterface { // Define this macro to 1 to omit the definition of SUCCEED(), which // is a generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_SUCCEED -# define SUCCEED() GTEST_SUCCEED() +#define SUCCEED() GTEST_SUCCEED() #endif // Macros for testing exceptions. @@ -1783,16 +1767,15 @@ class TestWithParam : public Test, public WithParamInterface { // Boolean assertions. Condition can be either a Boolean expression or an // AssertionResult. For more information on how to use AssertionResult with // these macros see comments on that class. -#define GTEST_EXPECT_TRUE(condition) \ +#define GTEST_EXPECT_TRUE(condition) \ GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ GTEST_NONFATAL_FAILURE_) -#define GTEST_EXPECT_FALSE(condition) \ +#define GTEST_EXPECT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_NONFATAL_FAILURE_) #define GTEST_ASSERT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ - GTEST_FATAL_FAILURE_) -#define GTEST_ASSERT_FALSE(condition) \ + GTEST_TEST_BOOLEAN_(condition, #condition, false, true, GTEST_FATAL_FAILURE_) +#define GTEST_ASSERT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_FATAL_FAILURE_) @@ -1891,27 +1874,27 @@ class TestWithParam : public Test, public WithParamInterface { // ASSERT_XY(), which clashes with some users' own code. #if !GTEST_DONT_DEFINE_ASSERT_EQ -# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) +#define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_NE -# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) +#define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LE -# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) +#define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LT -# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) +#define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GE -# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) +#define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GT -# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) +#define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) #endif // C-string Comparisons. All tests treat NULL and any non-NULL string @@ -1936,7 +1919,7 @@ class TestWithParam : public Test, public WithParamInterface { 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) \ @@ -1945,7 +1928,7 @@ class TestWithParam : public Test, public WithParamInterface { 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. @@ -1962,29 +1945,29 @@ class TestWithParam : public Test, public WithParamInterface { // 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, \ val1, val2) -#define EXPECT_DOUBLE_EQ(val1, val2)\ +#define EXPECT_DOUBLE_EQ(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ val1, val2) -#define ASSERT_FLOAT_EQ(val1, val2)\ +#define ASSERT_FLOAT_EQ(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ val1, val2) -#define ASSERT_DOUBLE_EQ(val1, val2)\ +#define ASSERT_DOUBLE_EQ(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ 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. @@ -1998,7 +1981,6 @@ GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2); - #if GTEST_OS_WINDOWS // Macros that test for HRESULT failure and success, these are only useful @@ -2010,17 +1992,17 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, // expected result and the actual result with both a human-readable // string representation of the error, if available, as well as the // hex result code. -# define EXPECT_HRESULT_SUCCEEDED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) +#define EXPECT_HRESULT_SUCCEEDED(expr) \ + EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) -# define ASSERT_HRESULT_SUCCEEDED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) +#define ASSERT_HRESULT_SUCCEEDED(expr) \ + ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) -# define EXPECT_HRESULT_FAILED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) +#define EXPECT_HRESULT_FAILED(expr) \ + EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) -# define ASSERT_HRESULT_FAILED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) +#define ASSERT_HRESULT_FAILED(expr) \ + ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) #endif // GTEST_OS_WINDOWS @@ -2035,9 +2017,9 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; // #define ASSERT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) + GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) #define EXPECT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) + GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) // Causes a trace (including the given source file path and line number, // and the given message) to be included in every test failure message generated @@ -2079,7 +2061,8 @@ class GTEST_API_ ScopedTrace { private: void PushTrace(const char* file, int line, std::string message); - GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace); + ScopedTrace(const ScopedTrace&) = delete; + ScopedTrace& operator=(const ScopedTrace&) = delete; } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its // c'tor and d'tor. Therefore it doesn't // need to be used otherwise. @@ -2099,9 +2082,9 @@ class GTEST_API_ ScopedTrace { // Assuming that each thread maintains its own stack of traces. // Therefore, a SCOPED_TRACE() would (correctly) only affect the // assertions in its own thread. -#define SCOPED_TRACE(message) \ - ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ - __FILE__, __LINE__, (message)) +#define SCOPED_TRACE(message) \ + ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \ + __FILE__, __LINE__, (message)) // Compile-time assertion for type equality. // StaticAssertTypeEq() compiles if and only if type1 and type2 @@ -2199,7 +2182,7 @@ constexpr bool StaticAssertTypeEq() noexcept { // EXPECT_EQ(a_.size(), 0); // EXPECT_EQ(b_.size(), 1); // } -#define GTEST_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()) #if !GTEST_DONT_DEFINE_TEST_F @@ -2211,7 +2194,7 @@ constexpr bool StaticAssertTypeEq() noexcept { GTEST_API_ std::string TempDir(); #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif // Dynamically registers a test with the framework. @@ -2307,9 +2290,7 @@ TestInfo* RegisterTest(const char* test_suite_name, const char* test_name, // namespace and has an all-caps name. int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; -inline int RUN_ALL_TESTS() { - return ::testing::UnitTest::GetInstance()->Run(); -} +inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); } GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 diff --git a/googletest/include/gtest/gtest_pred_impl.h b/googletest/include/gtest/gtest_pred_impl.h index 96b36fab..47a24aa6 100644 --- a/googletest/include/gtest/gtest_pred_impl.h +++ b/googletest/include/gtest/gtest_pred_impl.h @@ -26,9 +26,6 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is AUTOMATICALLY GENERATED on 07/21/2021 by command -// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // // Implements a family of generic predicate assertion macros. @@ -77,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 -AssertionResult AssertPred1Helper(const char* pred_text, - const char* e1, - Pred pred, - const T1& v1) { +template +AssertionResult AssertPred1Helper(const char* pred_text, const char* e1, + Pred pred, const T1& v1) { if (pred(v1)) return AssertionSuccess(); return AssertionFailure() @@ -103,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 -AssertionResult AssertPred2Helper(const char* pred_text, - const char* e1, - const char* e2, - Pred pred, - const T1& v1, +template +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(); @@ -150,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) \ @@ -174,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 -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 +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() @@ -203,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) \ @@ -229,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 -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 +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() @@ -262,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) \ @@ -290,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 -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() @@ -327,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) \ @@ -357,8 +274,6 @@ AssertionResult AssertPred5Helper(const char* pred_text, #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) - - } // namespace testing #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ diff --git a/googletest/include/gtest/gtest_prod.h b/googletest/include/gtest/gtest_prod.h index b22030a8..1f37dc31 100644 --- a/googletest/include/gtest/gtest_prod.h +++ b/googletest/include/gtest/gtest_prod.h @@ -54,7 +54,7 @@ // Note: The test class must be in the same namespace as the class being tested. // For example, putting MyClassTest in an anonymous namespace will not work. -#define FRIEND_TEST(test_case_name, test_name)\ -friend class test_case_name##_##test_name##_Test +#define FRIEND_TEST(test_case_name, test_name) \ + friend class test_case_name##_##test_name##_Test #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_ diff --git a/googletest/include/gtest/internal/custom/README.md b/googletest/include/gtest/internal/custom/README.md index 0af3539a..cb49e2c7 100644 --- a/googletest/include/gtest/internal/custom/README.md +++ b/googletest/include/gtest/internal/custom/README.md @@ -15,20 +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)` -* `GTEST_FLAG_GET(flag_name)` -* `GTEST_FLAG_SET(flag_name, value)` - ### Logging: * `GTEST_LOG_(severity)` diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h index 128e0f4c..45580ae8 100644 --- a/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -39,12 +39,13 @@ #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ +#include + +#include + #include "gtest/gtest-matchers.h" #include "gtest/internal/gtest-internal.h" -#include -#include - GTEST_DECLARE_string_(internal_run_death_test); namespace testing { @@ -86,16 +87,18 @@ class GTEST_API_ DeathTest { static bool Create(const char* statement, Matcher matcher, const char* file, int line, DeathTest** test); DeathTest(); - virtual ~DeathTest() { } + virtual ~DeathTest() {} // A helper class that aborts a death test when it's deleted. class ReturnSentinel { public: - explicit ReturnSentinel(DeathTest* test) : test_(test) { } + explicit ReturnSentinel(DeathTest* test) : test_(test) {} ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } + private: DeathTest* const test_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); + ReturnSentinel(const ReturnSentinel&) = delete; + ReturnSentinel& operator=(const ReturnSentinel&) = delete; } GTEST_ATTRIBUTE_UNUSED_; // An enumeration of possible roles that may be taken when a death @@ -140,7 +143,8 @@ class GTEST_API_ DeathTest { // A string containing a description of the outcome of the last death test. static std::string last_death_test_message_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); + DeathTest(const DeathTest&) = delete; + DeathTest& operator=(const DeathTest&) = delete; }; GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 @@ -148,7 +152,7 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // Factory interface for death tests. May be mocked out for testing. class DeathTestFactory { public: - virtual ~DeathTestFactory() { } + virtual ~DeathTestFactory() {} virtual bool Create(const char* statement, Matcher matcher, const char* file, int line, DeathTest** test) = 0; @@ -189,28 +193,28 @@ inline Matcher 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*. @@ -266,16 +270,12 @@ inline Matcher 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_; } @@ -289,7 +289,8 @@ class InternalRunDeathTestFlag { int index_; int write_fd_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag); + InternalRunDeathTestFlag(const InternalRunDeathTestFlag&) = delete; + InternalRunDeathTestFlag& operator=(const InternalRunDeathTestFlag&) = delete; }; // Returns a newly created InternalRunDeathTestFlag object with fields diff --git a/googletest/include/gtest/internal/gtest-filepath.h b/googletest/include/gtest/internal/gtest-filepath.h index 4dfe2e22..a2a60a96 100644 --- a/googletest/include/gtest/internal/gtest-filepath.h +++ b/googletest/include/gtest/internal/gtest-filepath.h @@ -63,8 +63,8 @@ namespace internal { class GTEST_API_ FilePath { public: - FilePath() : pathname_("") { } - FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } + FilePath() : pathname_("") {} + FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {} explicit FilePath(const std::string& pathname) : pathname_(pathname) { Normalize(); @@ -75,9 +75,7 @@ class GTEST_API_ FilePath { return *this; } - void Set(const FilePath& rhs) { - pathname_ = rhs.pathname_; - } + void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; } const std::string& string() const { return pathname_; } const char* c_str() const { return pathname_.c_str(); } @@ -90,8 +88,7 @@ class GTEST_API_ FilePath { // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. static FilePath MakeFileName(const FilePath& directory, - const FilePath& base_name, - int number, + const FilePath& base_name, int number, const char* extension); // Given directory = "dir", relative_path = "test.xml", diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index fc15e947..9b04e4c8 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -42,19 +42,20 @@ #include "gtest/internal/gtest-port.h" #if GTEST_OS_LINUX -# include -# include -# include -# include +#include +#include +#include +#include #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS -# include +#include #endif #include #include #include + #include #include #include @@ -78,7 +79,7 @@ // the current line number. For more details, see // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) -#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar +#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar // Stringifies its argument. // Work around a bug in visual studio which doesn't accept code like this: @@ -100,21 +101,21 @@ namespace testing { // Forward declarations. -class AssertionResult; // Result of an assertion. -class Message; // Represents a failure message. -class Test; // Represents a test. -class TestInfo; // Information about a test. -class TestPartResult; // Result of a test part. -class UnitTest; // A collection of test suites. +class AssertionResult; // Result of an assertion. +class Message; // Represents a failure message. +class Test; // Represents a test. +class TestInfo; // Information about a test. +class TestPartResult; // Result of a test part. +class UnitTest; // A collection of test suites. template ::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. @@ -123,6 +124,7 @@ GTEST_API_ extern const char kStackTraceMarker[]; // An IgnoredValue object can be implicitly constructed from ANY value. class IgnoredValue { struct Sink {}; + public: // This constructor template allows any value to be implicitly // converted to IgnoredValue. The object has no data member and @@ -138,13 +140,13 @@ class IgnoredValue { }; // Appends the user-supplied message to the Google-Test-generated message. -GTEST_API_ std::string AppendUserMessage( - const std::string& gtest_msg, const Message& user_msg); +GTEST_API_ std::string AppendUserMessage(const std::string& gtest_msg, + const Message& user_msg); #if GTEST_HAS_EXCEPTIONS -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \ -/* an exported class was derived from a class that was not exported */) +GTEST_DISABLE_MSC_WARNINGS_PUSH_( + 4275 /* an exported class was derived from a class that was not exported */) // This exception is thrown by (and only by) a failed Google Test // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions @@ -183,14 +185,6 @@ GTEST_API_ std::string CreateUnifiedDiff(const std::vector& 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. // @@ -214,10 +208,8 @@ GTEST_API_ AssertionResult EqFailure(const char* expected_expression, // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. GTEST_API_ std::string GetBoolAssertionFailureMessage( - const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value); + const AssertionResult& assertion_result, const char* expression_text, + const char* actual_predicate_value, const char* expected_predicate_value); // This template class represents an IEEE floating-point number // (either single-precision or double-precision, depending on the @@ -258,11 +250,11 @@ class FloatingPoint { // Constants. // # of bits in a number. - static const size_t kBitCount = 8*sizeof(RawType); + static const size_t kBitCount = 8 * sizeof(RawType); // # of fraction bits in a number. static const size_t kFractionBitCount = - std::numeric_limits::digits - 1; + std::numeric_limits::digits - 1; // # of exponent bits in a number. static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; @@ -271,8 +263,8 @@ class FloatingPoint { static const Bits kSignBitMask = static_cast(1) << (kBitCount - 1); // The mask for the fraction bits. - static const Bits kFractionBitMask = - ~static_cast(0) >> (kExponentBitCount + 1); + static const Bits kFractionBitMask = ~static_cast(0) >> + (kExponentBitCount + 1); // The mask for the exponent bits. static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); @@ -311,9 +303,7 @@ class FloatingPoint { } // Returns the floating-point number that represent positive infinity. - static RawType Infinity() { - return ReinterpretBits(kExponentBitMask); - } + static RawType Infinity() { return ReinterpretBits(kExponentBitMask); } // Returns the maximum representable finite floating-point number. static RawType Max(); @@ -321,7 +311,7 @@ class FloatingPoint { // 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_; } @@ -350,8 +340,8 @@ class FloatingPoint { // a NAN must return false. if (is_nan() || rhs.is_nan()) return false; - return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) - <= kMaxUlps; + return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <= + kMaxUlps; } private: @@ -376,7 +366,7 @@ class FloatingPoint { // // Read http://en.wikipedia.org/wiki/Signed_number_representations // for more details on signed number representations. - static Bits SignAndMagnitudeToBiased(const Bits &sam) { + static Bits SignAndMagnitudeToBiased(const Bits& sam) { if (kSignBitMask & sam) { // sam represents a negative number. return ~sam + 1; @@ -388,8 +378,8 @@ class FloatingPoint { // Given two numbers in the sign-and-magnitude representation, // returns the distance between them as an unsigned number. - static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, - const Bits &sam2) { + static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits& sam1, + const Bits& sam2) { const Bits biased1 = SignAndMagnitudeToBiased(sam1); const Bits biased2 = SignAndMagnitudeToBiased(sam2); return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); @@ -401,9 +391,13 @@ class FloatingPoint { // We cannot use std::numeric_limits::max() as it clashes with the max() // macro defined by . template <> -inline float FloatingPoint::Max() { return FLT_MAX; } +inline float FloatingPoint::Max() { + return FLT_MAX; +} template <> -inline double FloatingPoint::Max() { return DBL_MAX; } +inline double FloatingPoint::Max() { + return DBL_MAX; +} // Typedefs the instances of the FloatingPoint template class that we // care to use. @@ -463,7 +457,8 @@ class TestFactoryBase { TestFactoryBase() {} private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase); + TestFactoryBase(const TestFactoryBase&) = delete; + TestFactoryBase& operator=(const TestFactoryBase&) = delete; }; // This class provides implementation of TeastFactoryBase interface. @@ -656,7 +651,8 @@ inline const char* SkipComma(const char* str) { if (comma == nullptr) { return nullptr; } - while (IsSpace(*(++comma))) {} + while (IsSpace(*(++comma))) { + } return comma; } @@ -670,7 +666,7 @@ inline std::string GetPrefixUntilComma(const char* str) { // Splits a given string on a given delimiter, populating a given // vector with the fields. void SplitString(const ::std::string& str, char delimiter, - ::std::vector< ::std::string>* dest); + ::std::vector<::std::string>* dest); // The default argument to the template below for the case when the user does // not provide a name generator. @@ -783,13 +779,13 @@ class TypeParameterizedTestSuite { const std::vector& type_names = GenerateNames()) { RegisterTypeParameterizedTestSuiteInstantiation(case_name); - std::string test_name = StripTrailingSpaces( - GetPrefixUntilComma(test_names)); + std::string test_name = + StripTrailingSpaces(GetPrefixUntilComma(test_names)); if (!state->TestExists(test_name)) { fprintf(stderr, "Failed to get code location for test %s.%s at %s.", case_name, test_name.c_str(), - FormatFileLocation(code_location.file.c_str(), - code_location.line).c_str()); + FormatFileLocation(code_location.file.c_str(), code_location.line) + .c_str()); fflush(stderr); posix::Abort(); } @@ -833,8 +829,8 @@ class TypeParameterizedTestSuite { // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -GTEST_API_ std::string GetCurrentOsStackTraceExceptTop( - UnitTest* unit_test, int skip_count); +GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, + int skip_count); // Helpers for suppressing warnings on unreachable code or constant // condition. @@ -883,7 +879,8 @@ class GTEST_API_ Random { private: uint32_t state_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); + Random(const Random&) = delete; + Random& operator=(const Random&) = delete; }; // Turns const U&, U&, const U, and U all into U. @@ -956,7 +953,9 @@ IsContainer IsContainerTest(int /* dummy */) { typedef char IsNotContainer; template -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 @@ -1019,11 +1018,13 @@ bool ArrayEq(const T* lhs, size_t size, const U* rhs); // This generic version is used when k is 0. template -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 -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); } @@ -1033,8 +1034,7 @@ inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { template 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; } @@ -1044,8 +1044,7 @@ bool ArrayEq(const T* lhs, size_t size, const U* rhs) { template 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; } @@ -1059,11 +1058,13 @@ void CopyArray(const T* from, size_t size, U* to); // This generic version is used when k is 0. template -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 -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); } @@ -1116,8 +1117,7 @@ class NativeArray { } ~NativeArray() { - if (clone_ != &NativeArray::InitRef) - delete[] array_; + if (clone_ != &NativeArray::InitRef) delete[] array_; } // STL-style container methods. @@ -1125,8 +1125,7 @@ class NativeArray { const_iterator begin() const { return array_; } const_iterator end() const { return array_ + size_; } bool operator==(const NativeArray& rhs) const { - return size() == rhs.size() && - ArrayEq(begin(), size(), rhs.begin()); + return size() == rhs.size() && ArrayEq(begin(), size(), rhs.begin()); } private: @@ -1337,9 +1336,9 @@ struct tuple_size> #endif } // namespace std -#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ - ::testing::internal::AssertHelper(result_type, file, line, message) \ - = ::testing::Message() +#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ + ::testing::internal::AssertHelper(result_type, file, line, message) = \ + ::testing::Message() #define GTEST_MESSAGE_(message, result_type) \ GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) @@ -1460,103 +1459,112 @@ class NeverThrown { #endif // GTEST_HAS_EXCEPTIONS -#define GTEST_TEST_NO_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::TrueWithString gtest_msg{}) { \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \ - catch (...) { \ - gtest_msg.value = "it throws."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ - fail(("Expected: " #statement " doesn't throw an exception.\n" \ - " Actual: " + gtest_msg.value).c_str()) +#define GTEST_TEST_NO_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::TrueWithString gtest_msg{}) { \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \ + catch (...) { \ + gtest_msg.value = "it throws."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__) \ + : fail(("Expected: " #statement " doesn't throw an exception.\n" \ + " Actual: " + \ + gtest_msg.value) \ + .c_str()) -#define GTEST_TEST_ANY_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - bool gtest_caught_any = false; \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (...) { \ - gtest_caught_any = true; \ - } \ - if (!gtest_caught_any) { \ +#define GTEST_TEST_ANY_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + bool gtest_caught_any = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } catch (...) { \ + gtest_caught_any = true; \ + } \ + if (!gtest_caught_any) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ - fail("Expected: " #statement " throws an exception.\n" \ - " Actual: it doesn't.") - + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__) \ + : fail("Expected: " #statement \ + " throws an exception.\n" \ + " Actual: it doesn't.") // Implements Boolean test assertions such as EXPECT_TRUE. expression can be // either a boolean expression or an AssertionResult. text is a textual // representation of expression as it was passed into the EXPECT_TRUE. #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const ::testing::AssertionResult gtest_ar_ = \ - ::testing::AssertionResult(expression)) \ - ; \ - else \ - fail(::testing::internal::GetBoolAssertionFailureMessage(\ - gtest_ar_, text, #actual, #expected).c_str()) + 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()) { \ +#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ - fail("Expected: " #statement " doesn't generate new fatal " \ - "failures in the current thread.\n" \ - " Actual: it does.") + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \ + : fail("Expected: " #statement \ + " doesn't generate new fatal " \ + "failures in the current thread.\n" \ + " Actual: it does.") // Expands to the name of the class that implements the given test. #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ test_suite_name##_##test_name##_Test // Helper macro for defining tests. -#define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \ - static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \ - "test_suite_name must not be empty"); \ - static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \ - "test_name must not be empty"); \ - class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ - : public parent_class { \ - public: \ - GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \ - ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \ - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ - test_name)); \ - GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ - test_name)); \ - \ - private: \ - void TestBody() override; \ - static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ - }; \ - \ - ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \ - test_name)::test_info_ = \ - ::testing::internal::MakeAndRegisterTestInfo( \ - #test_suite_name, #test_name, nullptr, nullptr, \ - ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \ - ::testing::internal::SuiteApiResolver< \ - parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \ - ::testing::internal::SuiteApiResolver< \ - parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \ - new ::testing::internal::TestFactoryImpl); \ +#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); \ void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody() #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 ff25d995..e7af2f90 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -47,19 +47,18 @@ #include #include -#include "gtest/internal/gtest-internal.h" -#include "gtest/internal/gtest-port.h" #include "gtest/gtest-printers.h" #include "gtest/gtest-test-part.h" +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-port.h" namespace testing { // Input to a parameterized test name generator, describing a test parameter. // Consists of the parameter value and the integer parameter index. template 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; }; @@ -85,8 +84,10 @@ namespace internal { GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name, CodeLocation code_location); -template class ParamGeneratorInterface; -template class ParamGenerator; +template +class ParamGeneratorInterface; +template +class ParamGenerator; // Interface for iterating over elements provided by an implementation // of ParamGeneratorInterface. @@ -130,8 +131,7 @@ class ParamIterator { // ParamIterator assumes ownership of the impl_ pointer. ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} ParamIterator& operator=(const ParamIterator& other) { - if (this != &other) - impl_.reset(other.impl_->Clone()); + if (this != &other) impl_.reset(other.impl_->Clone()); return *this; } @@ -158,7 +158,7 @@ class ParamIterator { private: friend class ParamGenerator; explicit ParamIterator(ParamIteratorInterface* impl) : impl_(impl) {} - std::unique_ptr > impl_; + std::unique_ptr> impl_; }; // ParamGeneratorInterface is the binary interface to access generators @@ -180,7 +180,7 @@ class ParamGeneratorInterface { // This class implements copy initialization semantics and the contained // ParamGeneratorInterface instance is shared among all copies // of the original object. This is possible because that instance is immutable. -template +template class ParamGenerator { public: typedef ParamIterator iterator; @@ -197,7 +197,7 @@ class ParamGenerator { iterator end() const { return iterator(impl_->End()); } private: - std::shared_ptr > impl_; + std::shared_ptr> impl_; }; // Generates values from a range of two comparable values. Can be used to @@ -208,8 +208,10 @@ template class RangeGenerator : public ParamGeneratorInterface { public: RangeGenerator(T begin, T end, IncrementT step) - : begin_(begin), end_(end), - step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} + : begin_(begin), + end_(end), + step_(step), + end_index_(CalculateEndIndex(begin, end, step)) {} ~RangeGenerator() override {} ParamIteratorInterface* Begin() const override { @@ -252,7 +254,9 @@ class RangeGenerator : public ParamGeneratorInterface { private: Iterator(const Iterator& other) : ParamIteratorInterface(), - 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. @@ -264,12 +268,10 @@ class RangeGenerator : public ParamGeneratorInterface { 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(i + step)) - end_index++; + for (T i = begin; i < end; i = static_cast(i + step)) end_index++; return end_index; } @@ -284,7 +286,6 @@ class RangeGenerator : public ParamGeneratorInterface { 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 @@ -342,13 +343,13 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { << "The program attempted to compare iterators " << "from different generators." << std::endl; return iterator_ == - CheckedDowncastToActualType(&other)->iterator_; + CheckedDowncastToActualType(&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(), base_(other.base_), iterator_(other.iterator_) {} @@ -395,8 +396,8 @@ template 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(¶meter_); return new TestClass(); @@ -405,7 +406,8 @@ class ParameterizedTestFactory : public TestFactoryBase { private: const ParamType parameter_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); + ParameterizedTestFactory(const ParameterizedTestFactory&) = delete; + ParameterizedTestFactory& operator=(const ParameterizedTestFactory&) = delete; }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. @@ -441,7 +443,8 @@ class TestMetaFactory } private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); + TestMetaFactory(const TestMetaFactory&) = delete; + TestMetaFactory& operator=(const TestMetaFactory&) = delete; }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. @@ -472,7 +475,10 @@ class ParameterizedTestSuiteInfoBase { ParameterizedTestSuiteInfoBase() {} private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase); + ParameterizedTestSuiteInfoBase(const ParameterizedTestSuiteInfoBase&) = + delete; + ParameterizedTestSuiteInfoBase& operator=( + const ParameterizedTestSuiteInfoBase&) = delete; }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. @@ -548,8 +554,8 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { test_it != tests_.end(); ++test_it) { std::shared_ptr 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 generator((*gen_it->generator)()); ParamNameGeneratorFunc* name_func = gen_it->name_func; @@ -557,7 +563,7 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { int line = gen_it->line; std::string test_suite_name; - if ( !instantiation_name.empty() ) + if (!instantiation_name.empty()) test_suite_name = instantiation_name + "/"; test_suite_name += test_info->test_suite_base_name; @@ -570,17 +576,16 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { Message test_name_stream; - std::string param_name = name_func( - TestParamInfo(*param_it, i)); + std::string param_name = + name_func(TestParamInfo(*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); @@ -597,15 +602,15 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { SuiteApiResolver::GetTearDownCaseOrSuite(file, line), test_info->test_meta_factory->CreateTestFactory(*param_it)); } // for param_it - } // for gen_it - } // for test_it + } // for gen_it + } // for test_it if (!generated_instantiations) { // There are no generaotrs, or they all generate nothing ... InsertSyntheticTestCase(GetTestSuiteName(), code_location_, !tests_.empty()); } - } // RegisterTests + } // RegisterTests private: // LocalTestInfo structure keeps information about a single test registered @@ -621,42 +626,39 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { const std::string test_suite_base_name; const std::string test_base_name; - const std::unique_ptr > test_meta_factory; + const std::unique_ptr> test_meta_factory; const CodeLocation code_location; }; - using TestInfoContainer = ::std::vector >; + using TestInfoContainer = ::std::vector>; // Records data received from INSTANTIATE_TEST_SUITE_P macros: // 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) {} + 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; + std::string name; + GeneratorCreationFunc* generator; + ParamNameGeneratorFunc* name_func; + const char* file; + int line; }; typedef ::std::vector 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; @@ -667,7 +669,9 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { TestInfoContainer tests_; InstantiationContainer instantiations_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo); + ParameterizedTestSuiteInfo(const ParameterizedTestSuiteInfo&) = delete; + ParameterizedTestSuiteInfo& operator=(const ParameterizedTestSuiteInfo&) = + delete; }; // class ParameterizedTestSuiteInfo // Legacy API is deprecated but still available @@ -710,7 +714,7 @@ class ParameterizedTestSuiteRegistry { // type we are looking for, so we downcast it to that type // without further checks. typed_test_info = CheckedDowncastToActualType< - ParameterizedTestSuiteInfo >(test_suite_info); + ParameterizedTestSuiteInfo>(test_suite_info); } break; } @@ -742,7 +746,10 @@ class ParameterizedTestSuiteRegistry { TestSuiteInfoContainer test_suite_infos_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry); + ParameterizedTestSuiteRegistry(const ParameterizedTestSuiteRegistry&) = + delete; + ParameterizedTestSuiteRegistry& operator=( + const ParameterizedTestSuiteRegistry&) = delete; }; // Keep track of what type-parameterized test suite are defined and @@ -837,7 +844,8 @@ class CartesianProductGenerator : public ParamIteratorInterface { public: IteratorImpl(const ParamGeneratorInterface* base, - const std::tuple...>& generators, bool is_end) + const std::tuple...>& generators, + bool is_end) : base_(base), begin_(std::get(generators).begin()...), end_(std::get(generators).end()...), diff --git a/googletest/include/gtest/internal/gtest-port-arch.h b/googletest/include/gtest/internal/gtest-port-arch.h index 22bbad97..f025db76 100644 --- a/googletest/include/gtest/internal/gtest-port-arch.h +++ b/googletest/include/gtest/internal/gtest-port-arch.h @@ -37,72 +37,72 @@ // 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 -# 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 +#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#define GTEST_OS_WINDOWS_DESKTOP 1 +#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) +#define GTEST_OS_WINDOWS_PHONE 1 +#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) +#define GTEST_OS_WINDOWS_RT 1 +#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE) +#define GTEST_OS_WINDOWS_PHONE 1 +#define GTEST_OS_WINDOWS_TV_TITLE 1 +#else +// WINAPI_FAMILY defined but no known partition matched. +// Default to desktop. +#define GTEST_OS_WINDOWS_DESKTOP 1 +#endif +#else +#define GTEST_OS_WINDOWS_DESKTOP 1 +#endif // _WIN32_WCE #elif defined __OS2__ -# define GTEST_OS_OS2 1 +#define GTEST_OS_OS2 1 #elif defined __APPLE__ -# define GTEST_OS_MAC 1 -# include -# if TARGET_OS_IPHONE -# define GTEST_OS_IOS 1 -# endif +#define GTEST_OS_MAC 1 +#include +#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 +#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 diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 929b7090..7162e6e1 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -170,6 +170,7 @@ // GTEST_HAS_TYPED_TEST - typed tests // GTEST_HAS_TYPED_TEST_P - type-parameterized tests // GTEST_IS_THREADSAFE - Google Test is thread-safe. +// 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. @@ -192,8 +193,6 @@ // 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_COPY_AND_ASSIGN_ - disables copy ctor and operator=. -// GTEST_DISALLOW_MOVE_AND_ASSIGN_ - disables move ctor and operator=. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is // suppressed (constant conditional). @@ -217,10 +216,13 @@ // - synchronization primitives. // // Regular expressions: -// RE - a simple regular expression class using the POSIX -// Extended Regular Expression syntax on UNIX-like platforms -// 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. @@ -240,8 +242,6 @@ // 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: @@ -275,36 +275,42 @@ #include #ifndef _WIN32_WCE -# include -# include +#include +#include #endif // !_WIN32_WCE #if defined __APPLE__ -# include -# include +#include +#include #endif #include "gtest/internal/custom/gtest-port.h" #include "gtest/internal/gtest-port-arch.h" +#if GTEST_HAS_ABSL +#include "absl/flags/declare.h" +#include "absl/flags/flag.h" +#include "absl/flags/reflection.h" +#endif + #if !defined(GTEST_DEV_EMAIL_) -# define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" -# define GTEST_FLAG_PREFIX_ "gtest_" -# define GTEST_FLAG_PREFIX_DASH_ "gtest-" -# define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" -# define GTEST_NAME_ "Google Test" -# define GTEST_PROJECT_URL_ "https://github.com/google/googletest/" +#define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" +#define GTEST_FLAG_PREFIX_ "gtest_" +#define GTEST_FLAG_PREFIX_DASH_ "gtest-" +#define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" +#define GTEST_NAME_ "Google Test" +#define GTEST_PROJECT_URL_ "https://github.com/google/googletest/" #endif // !defined(GTEST_DEV_EMAIL_) #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_) -# define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" +#define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_) // Determines the version of gcc that is used to compile this. #ifdef __GNUC__ // 40302 means version 4.3.2. -# define GTEST_GCC_VER_ \ - (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) +#define GTEST_GCC_VER_ \ + (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif // __GNUC__ // Macros for disabling Microsoft Visual C++ warnings. @@ -313,41 +319,37 @@ // /* 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 -# include -# endif +#if !GTEST_OS_WINDOWS_MOBILE +#include +#include +#endif // In order to avoid having to include , use forward declaration #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two @@ -367,68 +369,55 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // This assumes that non-Windows OSes provide unistd.h. For OSes where this // is not the case, we need to include headers that provide the functions // mentioned above. -# include -# include +#include +#include #endif // GTEST_OS_WINDOWS #if GTEST_OS_LINUX_ANDROID // Used to define __ANDROID_API__ matching the target NDK API level. -# include // NOLINT +#include // NOLINT #endif // Defines this to true if and only if Google Test can use POSIX regular // expressions. #ifndef GTEST_HAS_POSIX_RE -# if GTEST_OS_LINUX_ANDROID +#if GTEST_OS_LINUX_ANDROID // On Android, is only available starting with Gingerbread. -# define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) -# else +#define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) +#else #define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA) -# endif +#endif #endif -#if GTEST_USES_PCRE -// The appropriate headers have already been included. - +// Select the regular expression implementation. +#if GTEST_HAS_ABSL +// When using Abseil, RE2 is required. +#include "absl/strings/string_view.h" +#include "re2/re2.h" +#define GTEST_USES_RE2 1 #elif GTEST_HAS_POSIX_RE - -// On some platforms, needs someone to define size_t, and -// won't compile otherwise. We can #include it here as we already -// included , which is guaranteed to define size_t through -// . -# include // NOLINT - -# define GTEST_USES_POSIX_RE 1 - -#elif GTEST_OS_WINDOWS - -// is not available on Windows. Use our own simple regex -// implementation instead. -# define GTEST_USES_SIMPLE_RE 1 - +#include // NOLINT +#define GTEST_USES_POSIX_RE 1 #else - -// may not be available on this platform. Use our own -// simple regex implementation instead. -# define GTEST_USES_SIMPLE_RE 1 - -#endif // GTEST_USES_PCRE +// Use our own simple regex implementation. +#define GTEST_USES_SIMPLE_RE 1 +#endif #ifndef GTEST_HAS_EXCEPTIONS // The user didn't tell us whether exceptions are enabled, so we need // to figure it out. -# if defined(_MSC_VER) && defined(_CPPUNWIND) +#if defined(_MSC_VER) && defined(_CPPUNWIND) // MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__BORLANDC__) +#define GTEST_HAS_EXCEPTIONS 1 +#elif defined(__BORLANDC__) // C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS // macro to enable exceptions, so we'll do the same. // Assumes that exceptions are enabled by default. -# ifndef _HAS_EXCEPTIONS -# define _HAS_EXCEPTIONS 1 -# endif // _HAS_EXCEPTIONS -# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS -# elif defined(__clang__) +#ifndef _HAS_EXCEPTIONS +#define _HAS_EXCEPTIONS 1 +#endif // _HAS_EXCEPTIONS +#define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS +#elif defined(__clang__) // clang defines __EXCEPTIONS if and only if exceptions are enabled before clang // 220714, but if and only if cleanups are enabled after that. In Obj-C++ files, // there can be cleanups for ObjC exceptions which also need cleanups, even if @@ -437,27 +426,27 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // cleanups prior to that. To reliably check for C++ exception availability with // clang, check for // __EXCEPTIONS && __has_feature(cxx_exceptions). -# define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) -# elif defined(__GNUC__) && __EXCEPTIONS +#define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) +#elif defined(__GNUC__) && __EXCEPTIONS // gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__SUNPRO_CC) +#define GTEST_HAS_EXCEPTIONS 1 +#elif defined(__SUNPRO_CC) // Sun Pro CC supports exceptions. However, there is no compile-time way of // detecting whether they are enabled or not. Therefore, we assume that // they are enabled unless the user tells us otherwise. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__IBMCPP__) && __EXCEPTIONS +#define GTEST_HAS_EXCEPTIONS 1 +#elif defined(__IBMCPP__) && __EXCEPTIONS // xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__HP_aCC) +#define GTEST_HAS_EXCEPTIONS 1 +#elif defined(__HP_aCC) // Exception handling is in effect by default in HP aCC compiler. It has to // be turned of by +noeh compiler option if desired. -# define GTEST_HAS_EXCEPTIONS 1 -# else +#define GTEST_HAS_EXCEPTIONS 1 +#else // For other compilers, we assume exceptions are disabled to be // conservative. -# define GTEST_HAS_EXCEPTIONS 0 -# endif // defined(_MSC_VER) || defined(__BORLANDC__) +#define GTEST_HAS_EXCEPTIONS 0 +#endif // defined(_MSC_VER) || defined(__BORLANDC__) #endif // GTEST_HAS_EXCEPTIONS #ifndef GTEST_HAS_STD_WSTRING @@ -477,63 +466,62 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // The user didn't tell us whether RTTI is enabled, so we need to // figure it out. -# ifdef _MSC_VER +#ifdef _MSC_VER #ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled. -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif +#define GTEST_HAS_RTTI 1 +#else +#define GTEST_HAS_RTTI 0 +#endif // Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is // enabled. -# elif defined(__GNUC__) +#elif defined(__GNUC__) -# ifdef __GXX_RTTI +#ifdef __GXX_RTTI // When building against STLport with the Android NDK and with // -frtti -fno-exceptions, the build fails at link time with undefined // references to __cxa_bad_typeid. Note sure if STL or toolchain bug, // so disable RTTI when detected. -# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ - !defined(__EXCEPTIONS) -# define GTEST_HAS_RTTI 0 -# else -# define GTEST_HAS_RTTI 1 -# endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS -# else -# define GTEST_HAS_RTTI 0 -# endif // __GXX_RTTI +#if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && !defined(__EXCEPTIONS) +#define GTEST_HAS_RTTI 0 +#else +#define GTEST_HAS_RTTI 1 +#endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS +#else +#define GTEST_HAS_RTTI 0 +#endif // __GXX_RTTI // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the // first version with C++ support. -# elif defined(__clang__) +#elif defined(__clang__) -# define GTEST_HAS_RTTI __has_feature(cxx_rtti) +#define GTEST_HAS_RTTI __has_feature(cxx_rtti) // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if // both the typeid and dynamic_cast features are present. -# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) +#elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) -# ifdef __RTTI_ALL__ -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif +#ifdef __RTTI_ALL__ +#define GTEST_HAS_RTTI 1 +#else +#define GTEST_HAS_RTTI 0 +#endif -# else +#else // For all other compilers, we assume RTTI is enabled. -# define GTEST_HAS_RTTI 1 +#define GTEST_HAS_RTTI 1 -# endif // _MSC_VER +#endif // _MSC_VER #endif // GTEST_HAS_RTTI // It's this header's responsibility to #include when RTTI // is enabled. #if GTEST_HAS_RTTI -# include +#include #endif // Determines whether Google Test can use the pthreads library. @@ -553,10 +541,10 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #if GTEST_HAS_PTHREAD // gtest-port.h guarantees to #include when GTEST_HAS_PTHREAD is // true. -# include // NOLINT +#include // NOLINT // For timespec and nanosleep, used below. -# include // NOLINT +#include // NOLINT #endif // Determines whether clone(2) is supported. @@ -566,24 +554,23 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_HAS_CLONE // The user didn't tell us, so we need to figure it out. -# if GTEST_OS_LINUX && !defined(__ia64__) -# if GTEST_OS_LINUX_ANDROID +#if GTEST_OS_LINUX && !defined(__ia64__) +#if GTEST_OS_LINUX_ANDROID // On Android, clone() became available at different API levels for each 32-bit // architecture. -# if defined(__LP64__) || \ - (defined(__arm__) && __ANDROID_API__ >= 9) || \ - (defined(__mips__) && __ANDROID_API__ >= 12) || \ - (defined(__i386__) && __ANDROID_API__ >= 17) -# define GTEST_HAS_CLONE 1 -# else -# define GTEST_HAS_CLONE 0 -# endif -# else -# define GTEST_HAS_CLONE 1 -# endif -# else -# define GTEST_HAS_CLONE 0 -# endif // GTEST_OS_LINUX && !defined(__ia64__) +#if defined(__LP64__) || (defined(__arm__) && __ANDROID_API__ >= 9) || \ + (defined(__mips__) && __ANDROID_API__ >= 12) || \ + (defined(__i386__) && __ANDROID_API__ >= 17) +#define GTEST_HAS_CLONE 1 +#else +#define GTEST_HAS_CLONE 0 +#endif +#else +#define GTEST_HAS_CLONE 1 +#endif +#else +#define GTEST_HAS_CLONE 0 +#endif // GTEST_OS_LINUX && !defined(__ia64__) #endif // GTEST_HAS_CLONE @@ -594,10 +581,10 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // platforms except known mobile ones. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA -# define GTEST_HAS_STREAM_REDIRECTION 0 -# else -# define GTEST_HAS_STREAM_REDIRECTION 1 -# endif // !GTEST_OS_WINDOWS_MOBILE +#define GTEST_HAS_STREAM_REDIRECTION 0 +#else +#define GTEST_HAS_STREAM_REDIRECTION 1 +#endif // !GTEST_OS_WINDOWS_MOBILE #endif // GTEST_HAS_STREAM_REDIRECTION // Determines whether to support death tests. @@ -609,7 +596,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \ GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU || \ GTEST_OS_GNU_HURD) -# define GTEST_HAS_DEATH_TEST 1 +#define GTEST_HAS_DEATH_TEST 1 #endif // Determines whether to support type-driven tests. @@ -618,8 +605,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Sun Pro CC, IBM Visual Age, and HP aCC support. #if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \ defined(__IBMCPP__) || defined(__HP_aCC) -# define GTEST_HAS_TYPED_TEST 1 -# define GTEST_HAS_TYPED_TEST_P 1 +#define GTEST_HAS_TYPED_TEST 1 +#define GTEST_HAS_TYPED_TEST_P 1 #endif // Determines whether the system compiler uses UTF-16 for encoding wide strings. @@ -630,7 +617,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \ GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD || \ GTEST_OS_GNU_HURD -# define GTEST_CAN_STREAM_RESULTS_ 1 +#define GTEST_CAN_STREAM_RESULTS_ 1 #endif // Defines some utility macros. @@ -644,9 +631,12 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // // The "switch (0) case 0:" idiom is used to suppress this. #ifdef __INTEL_COMPILER -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ +#define GTEST_AMBIGUOUS_ELSE_BLOCKER_ #else -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT +#define GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + switch (0) \ + case 0: \ + default: // NOLINT #endif // Use this annotation at the end of a struct/class definition to @@ -661,46 +651,32 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Also use it after a variable or parameter declaration to tell the // compiler the variable/parameter does not have to be used. #if defined(__GNUC__) && !defined(COMPILER_ICC) -# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) +#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused)) #elif defined(__clang__) -# if __has_attribute(unused) -# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) -# endif +#if __has_attribute(unused) +#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused)) +#endif #endif #ifndef GTEST_ATTRIBUTE_UNUSED_ -# define GTEST_ATTRIBUTE_UNUSED_ +#define GTEST_ATTRIBUTE_UNUSED_ #endif // Use this annotation before a function that takes a printf format string. #if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC) -# if defined(__MINGW_PRINTF_FORMAT) +#if defined(__MINGW_PRINTF_FORMAT) // MinGW has two different printf implementations. Ensure the format macro // matches the selected implementation. See // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/. -# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ - __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \ - first_to_check))) -# else -# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ - __attribute__((__format__(__printf__, string_index, first_to_check))) -# endif +#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ + __attribute__(( \ + __format__(__MINGW_PRINTF_FORMAT, string_index, first_to_check))) #else -# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) +#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ + __attribute__((__format__(__printf__, string_index, first_to_check))) +#endif +#else +#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) #endif - -// A macro to disallow copy constructor and operator= -// This should be used in the private: declarations for a class. -// NOLINT is for modernize-use-trailing-return-type in macro uses. -#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \ - type(type const&) = delete; \ - type& operator=(type const&) = delete /* NOLINT */ - -// A macro to disallow move constructor and operator= -// This should be used in the private: declarations for a class. -// NOLINT is for modernize-use-trailing-return-type in macro uses. -#define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \ - type(type&&) noexcept = delete; \ - type& operator=(type&&) noexcept = delete /* NOLINT */ // Tell the compiler to warn about unused return values for functions declared // with this macro. The macro should be used on function declarations @@ -708,9 +684,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; #if defined(__GNUC__) && !defined(COMPILER_ICC) -# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) +#define GTEST_MUST_USE_RESULT_ __attribute__((warn_unused_result)) #else -# define GTEST_MUST_USE_RESULT_ +#define GTEST_MUST_USE_RESULT_ #endif // __GNUC__ && !COMPILER_ICC // MS C++ compiler emits warning when a conditional expression is compile time @@ -721,10 +697,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // while (true) { // GTEST_INTENTIONAL_CONST_COND_POP_() // } -# define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) -# define GTEST_INTENTIONAL_CONST_COND_POP_() \ - GTEST_DISABLE_MSC_WARNINGS_POP_() +#define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) +#define GTEST_INTENTIONAL_CONST_COND_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_() // Determine whether the compiler supports Microsoft's Structured Exception // Handling. This is supported by several Windows compilers but generally @@ -732,13 +707,13 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_HAS_SEH // The user didn't tell us, so we need to figure it out. -# if defined(_MSC_VER) || defined(__BORLANDC__) +#if defined(_MSC_VER) || defined(__BORLANDC__) // These two compilers are known to support SEH. -# define GTEST_HAS_SEH 1 -# else +#define GTEST_HAS_SEH 1 +#else // Assume no SEH. -# define GTEST_HAS_SEH 0 -# endif +#define GTEST_HAS_SEH 0 +#endif #endif // GTEST_HAS_SEH @@ -754,8 +729,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #if GTEST_IS_THREADSAFE // Some platforms don't support including these threading related headers. #include // NOLINT -#include // NOLINT -#endif // GTEST_IS_THREADSAFE +#include // 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 @@ -763,30 +738,30 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_API_ #ifdef _MSC_VER -# if GTEST_LINKED_AS_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllimport) -# elif GTEST_CREATE_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllexport) -# endif +#if GTEST_LINKED_AS_SHARED_LIBRARY +#define GTEST_API_ __declspec(dllimport) +#elif GTEST_CREATE_SHARED_LIBRARY +#define GTEST_API_ __declspec(dllexport) +#endif #elif __GNUC__ >= 4 || defined(__clang__) -# define GTEST_API_ __attribute__((visibility ("default"))) +#define GTEST_API_ __attribute__((visibility("default"))) #endif // _MSC_VER #endif // GTEST_API_ #ifndef GTEST_API_ -# define GTEST_API_ +#define GTEST_API_ #endif // GTEST_API_ #ifndef GTEST_DEFAULT_DEATH_TEST_STYLE -# define GTEST_DEFAULT_DEATH_TEST_STYLE "fast" +#define GTEST_DEFAULT_DEATH_TEST_STYLE "fast" #endif // GTEST_DEFAULT_DEATH_TEST_STYLE #ifdef __GNUC__ // Ask the compiler to never inline a given function. -# define GTEST_NO_INLINE_ __attribute__((noinline)) +#define GTEST_NO_INLINE_ __attribute__((noinline)) #else -# define GTEST_NO_INLINE_ +#define GTEST_NO_INLINE_ #endif #if defined(__clang__) @@ -805,60 +780,58 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. #if !defined(GTEST_HAS_CXXABI_H_) -# if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER)) -# define GTEST_HAS_CXXABI_H_ 1 -# else -# define GTEST_HAS_CXXABI_H_ 0 -# endif +#if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER)) +#define GTEST_HAS_CXXABI_H_ 1 +#else +#define GTEST_HAS_CXXABI_H_ 0 +#endif #endif // A function level attribute to disable checking for use of uninitialized // memory when built with MemorySanitizer. #if defined(__clang__) -# if __has_feature(memory_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \ - __attribute__((no_sanitize_memory)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -# endif // __has_feature(memory_sanitizer) +#if __has_feature(memory_sanitizer) +#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ __attribute__((no_sanitize_memory)) #else -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +#endif // __has_feature(memory_sanitizer) +#else +#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ #endif // __clang__ // A function level attribute to disable AddressSanitizer instrumentation. #if defined(__clang__) -# if __has_feature(address_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ - __attribute__((no_sanitize_address)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -# endif // __has_feature(address_sanitizer) +#if __has_feature(address_sanitizer) +#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ + __attribute__((no_sanitize_address)) #else -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +#endif // __has_feature(address_sanitizer) +#else +#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ #endif // __clang__ // A function level attribute to disable HWAddressSanitizer instrumentation. #if defined(__clang__) -# if __has_feature(hwaddress_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \ - __attribute__((no_sanitize("hwaddress"))) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -# endif // __has_feature(hwaddress_sanitizer) +#if __has_feature(hwaddress_sanitizer) +#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \ + __attribute__((no_sanitize("hwaddress"))) #else -# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ +#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ +#endif // __has_feature(hwaddress_sanitizer) +#else +#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ #endif // __clang__ // A function level attribute to disable ThreadSanitizer instrumentation. #if defined(__clang__) -# if __has_feature(thread_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \ - __attribute__((no_sanitize_thread)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -# endif // __has_feature(thread_sanitizer) +#if __has_feature(thread_sanitizer) +#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ __attribute__((no_sanitize_thread)) #else -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +#endif // __has_feature(thread_sanitizer) +#else +#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ #endif // __clang__ namespace testing { @@ -880,25 +853,37 @@ namespace internal { // Secret object, which is what we want. class Secret; -// The GTEST_COMPILE_ASSERT_ is a legacy macro used to verify that a compile -// time expression is true (in new code, use static_assert instead). For -// example, you could use it to verify the size of a static array: -// -// GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES, -// names_incorrect_size); -// -// The second argument to the macro must be a valid C++ identifier. If the -// expression is false, compiler will issue an error containing this identifier. -#define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) - // A helper for suppressing warnings on constant condition. It just // returns 'condition'. GTEST_API_ bool IsTrue(bool condition); // Defines RE. -#if GTEST_USES_PCRE -// if used, PCRE is injected by custom/gtest-port.h +#if GTEST_USES_RE2 + +// This is almost `using RE = ::RE2`, except it is copy-constructible, and it +// needs to disambiguate the `std::string`, `absl::string_view`, and `const +// char*` constructors. +class GTEST_API_ RE { + public: + RE(absl::string_view regex) : regex_(regex) {} // NOLINT + RE(const char* regex) : RE(absl::string_view(regex)) {} // NOLINT + RE(const std::string& regex) : RE(absl::string_view(regex)) {} // NOLINT + RE(const RE& other) : RE(other.pattern()) {} + + const std::string& pattern() const { return regex_.pattern(); } + + static bool FullMatch(absl::string_view str, const RE& re) { + return RE2::FullMatch(str, re.regex_); + } + static bool PartialMatch(absl::string_view str, const RE& re) { + return RE2::PartialMatch(str, re.regex_); + } + + private: + RE2 regex_; +}; + #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE // A simple C++ wrapper for . It uses the POSIX Extended @@ -937,19 +922,19 @@ class GTEST_API_ RE { const char* pattern_; bool is_valid_; -# if GTEST_USES_POSIX_RE +#if GTEST_USES_POSIX_RE regex_t full_regex_; // For FullMatch(). regex_t partial_regex_; // For PartialMatch(). -# else // GTEST_USES_SIMPLE_RE +#else // GTEST_USES_SIMPLE_RE const char* full_pattern_; // For FullMatch(); -# endif +#endif }; -#endif // GTEST_USES_PCRE +#endif // ::testing::internal::RE implementation // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. @@ -967,12 +952,7 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. -enum GTestLogSeverity { - GTEST_INFO, - GTEST_WARNING, - GTEST_ERROR, - GTEST_FATAL -}; +enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL }; // Formats log entry severity, provides a stream object for streaming the // log message, and terminates the message with a newline when going out of @@ -989,14 +969,16 @@ class GTEST_API_ GTestLog { private: const GTestLogSeverity severity_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); + GTestLog(const GTestLog&) = delete; + GTestLog& operator=(const GTestLog&) = delete; }; #if !defined(GTEST_LOG_) -# define GTEST_LOG_(severity) \ - ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ - __FILE__, __LINE__).GetStream() +#define GTEST_LOG_(severity) \ + ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ + __FILE__, __LINE__) \ + .GetStream() inline void LogToStderr() {} inline void FlushInfoLog() { fflush(nullptr); } @@ -1018,12 +1000,12 @@ inline void FlushInfoLog() { fflush(nullptr); } // condition itself, plus additional message streamed into it, if any, // and then it aborts the program. It aborts the program irrespective of // whether it is built in the debug mode or not. -# define GTEST_CHECK_(condition) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::IsTrue(condition)) \ - ; \ - else \ - GTEST_LOG_(FATAL) << "Condition " #condition " failed. " +#define GTEST_CHECK_(condition) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::IsTrue(condition)) \ + ; \ + else \ + GTEST_LOG_(FATAL) << "Condition " #condition " failed. " #endif // !defined(GTEST_CHECK_) // An all-mode assert to verify that the given POSIX-style function @@ -1032,9 +1014,8 @@ inline void FlushInfoLog() { fflush(nullptr); } // in {} if you need to use it as the only statement in an 'if' // branch. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ - if (const int gtest_error = (posix_call)) \ - GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ - << gtest_error + if (const int gtest_error = (posix_call)) \ + GTEST_LOG_(FATAL) << #posix_call << "failed with error " << gtest_error // Transforms "T" into "const T&" according to standard reference collapsing // rules (this is only needed as a backport for C++98 compilers that do not @@ -1048,9 +1029,13 @@ inline void FlushInfoLog() { fflush(nullptr); } // Note that the non-const reference will not have "const" added. This is // standard, and necessary so that "T" can always bind to "const T&". template -struct ConstRef { typedef const T& type; }; +struct ConstRef { + typedef const T& type; +}; template -struct ConstRef { typedef T& type; }; +struct ConstRef { + typedef T& type; +}; // The argument T must depend on some template parameters. #define GTEST_REFERENCE_TO_CONST_(T) \ @@ -1076,8 +1061,10 @@ struct ConstRef { 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 -inline To ImplicitCast_(To x) { return x; } +template +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 @@ -1100,17 +1087,17 @@ inline To ImplicitCast_(To x) { return x; } // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., down_cast). The internal // namespace alone is not enough because the function can be found by ADL. -template // use like this: DownCast_(foo); -inline To DownCast_(From* f) { // so we only accept pointers +template // use like this: DownCast_(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_(to); + GTEST_INTENTIONAL_CONST_COND_POP_() + const To to = nullptr; + ::testing::internal::ImplicitCast_(to); } #if GTEST_HAS_RTTI @@ -1176,7 +1163,7 @@ void ClearInjectableArgvs(); // Defines synchronization primitives. #if GTEST_IS_THREADSAFE -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // Provides leak-safe Windows kernel handle ownership. // Used in death tests and in threading support. class GTEST_API_ AutoHandle { @@ -1203,15 +1190,16 @@ class GTEST_API_ AutoHandle { Handle handle_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); + AutoHandle(const AutoHandle&) = delete; + AutoHandle& operator=(const AutoHandle&) = delete; }; -# endif +#endif -# if GTEST_HAS_NOTIFICATION_ +#if GTEST_HAS_NOTIFICATION_ // Notification has already been imported into the namespace. // Nothing to do here. -# else +#else // 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. @@ -1245,12 +1233,12 @@ class GTEST_API_ Notification { std::condition_variable cv_; bool notified_; }; -# endif // GTEST_HAS_NOTIFICATION_ +#endif // GTEST_HAS_NOTIFICATION_ // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD // defined, but we don't want to use MinGW's pthreads implementation, which // has conformance problems with some versions of the POSIX standard. -# if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW +#if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW // As a C-function, ThreadFuncWithCLinkage cannot be templated itself. // Consequently, it cannot select a correct instantiation of ThreadWithParam @@ -1326,16 +1314,17 @@ class ThreadWithParam : public ThreadWithParamBase { // finished. pthread_t thread_; // The native thread object. - GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); + ThreadWithParam(const ThreadWithParam&) = delete; + ThreadWithParam& operator=(const ThreadWithParam&) = delete; }; -# endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || - // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ +#endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || + // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ -# if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ +#if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ // Mutex and ThreadLocal have already been imported into the namespace. // Nothing to do here. -# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +#elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Mutex implements mutex on Windows platforms. It is used in conjunction // with class MutexLock: @@ -1389,14 +1378,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 @@ -1405,15 +1395,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; @@ -1440,7 +1430,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 @@ -1469,7 +1460,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: @@ -1483,30 +1474,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. @@ -1543,7 +1530,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(); } @@ -1562,16 +1549,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( - ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer(); + ThreadLocalRegistry::GetValueOnCurrentThread(this)) + ->pointer(); } - virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const { + ThreadLocalValueHolderBase* NewValueForCurrentThread() const override { return default_factory_->MakeNewHolder(); } @@ -1582,7 +1570,8 @@ class ThreadLocal : public ThreadLocalBase { virtual ValueHolder* MakeNewHolder() const = 0; private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); + ValueHolderFactory(const ValueHolderFactory&) = delete; + ValueHolderFactory& operator=(const ValueHolderFactory&) = delete; }; class DefaultValueHolderFactory : public ValueHolderFactory { @@ -1591,7 +1580,9 @@ class ThreadLocal : public ThreadLocalBase { ValueHolder* MakeNewHolder() const override { return new ValueHolder(); } private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); + DefaultValueHolderFactory(const DefaultValueHolderFactory&) = delete; + DefaultValueHolderFactory& operator=(const DefaultValueHolderFactory&) = + delete; }; class InstanceValueHolderFactory : public ValueHolderFactory { @@ -1604,15 +1595,18 @@ class ThreadLocal : public ThreadLocalBase { private: const T value_; // The value for each thread. - GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); + InstanceValueHolderFactory(const InstanceValueHolderFactory&) = delete; + InstanceValueHolderFactory& operator=(const InstanceValueHolderFactory&) = + delete; }; std::unique_ptr 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 { @@ -1659,8 +1653,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, @@ -1679,12 +1673,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 @@ -1694,15 +1687,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; @@ -1759,7 +1752,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() { @@ -1791,7 +1785,8 @@ class GTEST_API_ ThreadLocal { virtual ValueHolder* MakeNewHolder() const = 0; private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); + ValueHolderFactory(const ValueHolderFactory&) = delete; + ValueHolderFactory& operator=(const ValueHolderFactory&) = delete; }; class DefaultValueHolderFactory : public ValueHolderFactory { @@ -1800,7 +1795,9 @@ class GTEST_API_ ThreadLocal { ValueHolder* MakeNewHolder() const override { return new ValueHolder(); } private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); + DefaultValueHolderFactory(const DefaultValueHolderFactory&) = delete; + DefaultValueHolderFactory& operator=(const DefaultValueHolderFactory&) = + delete; }; class InstanceValueHolderFactory : public ValueHolderFactory { @@ -1813,17 +1810,20 @@ class GTEST_API_ ThreadLocal { private: const T value_; // The value for each thread. - GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); + InstanceValueHolderFactory(const InstanceValueHolderFactory&) = delete; + InstanceValueHolderFactory& operator=(const InstanceValueHolderFactory&) = + delete; }; // A key pthreads uses for looking up per-thread values. const pthread_key_t key_; std::unique_ptr 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 @@ -1840,10 +1840,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 @@ -1866,6 +1866,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_; }; @@ -1877,11 +1878,11 @@ class GTEST_API_ ThreadLocal { GTEST_API_ size_t GetThreadCount(); #if GTEST_OS_WINDOWS -# define GTEST_PATH_SEP_ "\\" -# define GTEST_HAS_ALT_PATH_SEP_ 1 +#define GTEST_PATH_SEP_ "\\" +#define GTEST_HAS_ALT_PATH_SEP_ 1 #else -# define GTEST_PATH_SEP_ "/" -# define GTEST_HAS_ALT_PATH_SEP_ 0 +#define GTEST_PATH_SEP_ "/" +#define GTEST_HAS_ALT_PATH_SEP_ 0 #endif // GTEST_OS_WINDOWS // Utilities for char. @@ -1939,8 +1940,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; } @@ -1958,36 +1958,34 @@ namespace posix { typedef struct _stat StatStruct; -# ifdef __BORLANDC__ +#ifdef __BORLANDC__ inline int DoIsATTY(int fd) { return isatty(fd); } inline int StrCaseCmp(const char* s1, const char* s2) { return stricmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } -# else // !__BORLANDC__ -# if GTEST_OS_WINDOWS_MOBILE +#else // !__BORLANDC__ +#if GTEST_OS_WINDOWS_MOBILE inline int DoIsATTY(int /* fd */) { return 0; } -# else +#else inline int DoIsATTY(int fd) { return _isatty(fd); } -# endif // GTEST_OS_WINDOWS_MOBILE +#endif // GTEST_OS_WINDOWS_MOBILE inline int StrCaseCmp(const char* s1, const char* s2) { return _stricmp(s1, s2); } inline char* StrDup(const char* src) { return _strdup(src); } -# endif // __BORLANDC__ +#endif // __BORLANDC__ -# if GTEST_OS_WINDOWS_MOBILE +#if GTEST_OS_WINDOWS_MOBILE inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this // time and thus not defined there. -# else +#else inline int FileNo(FILE* file) { return _fileno(file); } inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline int RmDir(const char* dir) { return _rmdir(dir); } -inline bool IsDir(const StatStruct& st) { - return (_S_IFDIR & st.st_mode) != 0; -} -# endif // GTEST_OS_WINDOWS_MOBILE +inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; } +#endif // GTEST_OS_WINDOWS_MOBILE #elif GTEST_OS_ESP8266 typedef struct stat StatStruct; @@ -2051,12 +2049,12 @@ inline FILE* FOpen(const char* path, const char* mode) { std::wstring wide_path = converter.from_bytes(path); std::wstring wide_mode = converter.from_bytes(mode); return _wfopen(wide_path.c_str(), wide_mode.c_str()); -#else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW +#else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW return fopen(path, mode); #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW } #if !GTEST_OS_WINDOWS_MOBILE -inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { +inline 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); } @@ -2108,13 +2106,13 @@ GTEST_DISABLE_MSC_DEPRECATED_POP_() // snprintf is a variadic function. #if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE // MSVC 2005 and above support variadic macros. -# define GTEST_SNPRINTF_(buffer, size, format, ...) \ - _snprintf_s(buffer, size, size, format, __VA_ARGS__) +#define GTEST_SNPRINTF_(buffer, size, format, ...) \ + _snprintf_s(buffer, size, size, format, __VA_ARGS__) #elif defined(_MSC_VER) // Windows CE does not define _snprintf_s -# define GTEST_SNPRINTF_ _snprintf +#define GTEST_SNPRINTF_ _snprintf #else -# define GTEST_SNPRINTF_ snprintf +#define GTEST_SNPRINTF_ snprintf #endif // The biggest signed integer type the compiler supports. @@ -2174,55 +2172,84 @@ using TimeInMillis = int64_t; // Represents time in milliseconds. // Macro for referencing flags. #if !defined(GTEST_FLAG) -# define GTEST_FLAG(name) FLAGS_gtest_##name +#define GTEST_FLAG_NAME_(name) gtest_##name +#define GTEST_FLAG(name) FLAGS_gtest_##name #endif // !defined(GTEST_FLAG) -#if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) -# define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 -#endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) +// Pick a command line flags implementation. +#if GTEST_HAS_ABSL -#if !defined(GTEST_DECLARE_bool_) -# define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver +// Macros for defining flags. +#define GTEST_DEFINE_bool_(name, default_val, doc) \ + ABSL_FLAG(bool, GTEST_FLAG_NAME_(name), default_val, doc) +#define GTEST_DEFINE_int32_(name, default_val, doc) \ + ABSL_FLAG(int32_t, GTEST_FLAG_NAME_(name), default_val, doc) +#define GTEST_DEFINE_string_(name, default_val, doc) \ + ABSL_FLAG(std::string, GTEST_FLAG_NAME_(name), default_val, doc) // Macros for declaring flags. -#define GTEST_DECLARE_bool_(name) \ - 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_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(>EST_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) \ namespace testing { \ GTEST_API_ bool GTEST_FLAG(name) = (default_val); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + 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") + } \ + 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") + } \ + 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 -#if !defined(GTEST_FLAG_GET) #define GTEST_FLAG_GET(name) ::testing::GTEST_FLAG(name) #define GTEST_FLAG_SET(name, value) (void)(::testing::GTEST_FLAG(name) = value) -#endif // !defined(GTEST_FLAG_GET) +#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 @@ -2324,7 +2351,7 @@ inline ::std::nullopt_t Nullopt() { return ::std::nullopt; } #if GTEST_HAS_ABSL // Always use absl::string_view for Matcher<> specializations if googletest // is built with absl support. -# define GTEST_INTERNAL_HAS_STRING_VIEW 1 +#define GTEST_INTERNAL_HAS_STRING_VIEW 1 #include "absl/strings/string_view.h" namespace testing { namespace internal { @@ -2332,11 +2359,11 @@ using StringView = ::absl::string_view; } // namespace internal } // namespace testing #else -# ifdef __has_include -# if __has_include() && __cplusplus >= 201703L +#ifdef __has_include +#if __has_include() && __cplusplus >= 201703L // Otherwise for C++17 and higher use std::string_view for Matcher<> // specializations. -# define GTEST_INTERNAL_HAS_STRING_VIEW 1 +#define GTEST_INTERNAL_HAS_STRING_VIEW 1 #include namespace testing { namespace internal { @@ -2345,8 +2372,8 @@ using StringView = ::std::string_view; } // namespace testing // The case where absl is configured NOT to alias std::string_view is not // supported. -# endif // __has_include() && __cplusplus >= 201703L -# endif // __has_include +#endif // __has_include() && __cplusplus >= 201703L +#endif // __has_include #endif // GTEST_HAS_ABSL #if GTEST_HAS_ABSL diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h index 4cb8e07c..cca2e1f2 100644 --- a/googletest/include/gtest/internal/gtest-string.h +++ b/googletest/include/gtest/internal/gtest-string.h @@ -45,10 +45,11 @@ #ifdef __BORLANDC__ // string.h is not guaranteed to provide strcpy on C++ Builder. -# include +#include #endif #include + #include #include @@ -125,8 +126,7 @@ class GTEST_API_ String { // Unlike strcasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL C string, // including the empty string. - static bool CaseInsensitiveCStringEquals(const char* lhs, - const char* rhs); + static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs); // Compares two wide C strings, ignoring case. Returns true if and only if // they have the same content. @@ -145,8 +145,8 @@ class GTEST_API_ String { // Returns true if and only if the given string ends with the given suffix, // ignoring case. Any string is considered to end with an empty suffix. - static bool EndsWithCaseInsensitive( - const std::string& str, const std::string& suffix); + static bool EndsWithCaseInsensitive(const std::string& str, + const std::string& suffix); // Formats an int value as "%02d". static std::string FormatIntWidth2(int value); // "%02d" for width == 2 @@ -165,7 +165,7 @@ class GTEST_API_ String { private: String(); // Not meant to be instantiated. -}; // class String +}; // class String // Gets the content of the stringstream's buffer as an std::string. Each '\0' // character in the buffer is replaced with "\\0". diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index 665564a9..6bc02a7d 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -41,11 +41,11 @@ // #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 -# elif defined(__HP_aCC) -# include -# endif // GTEST_HASH_CXXABI_H_ +#if GTEST_HAS_CXXABI_H_ +#include +#elif defined(__HP_aCC) +#include +#endif // GTEST_HASH_CXXABI_H_ namespace testing { namespace internal { @@ -103,7 +103,9 @@ std::string GetTypeName() { // A unique type indicating an empty node struct None {}; -# define GTEST_TEMPLATE_ template class +#define GTEST_TEMPLATE_ \ + template \ + class // The template "selector" struct TemplateSel is used to // represent Tmpl, which must be a class template with one type @@ -121,8 +123,7 @@ struct TemplateSel { }; }; -# define GTEST_BIND_(TmplSel, T) \ - TmplSel::template Bind::type +#define GTEST_BIND_(TmplSel, T) TmplSel::template Bind::type template struct Templates { diff --git a/googletest/samples/prime_tables.h b/googletest/samples/prime_tables.h index 3a10352b..7c0286e1 100644 --- a/googletest/samples/prime_tables.h +++ b/googletest/samples/prime_tables.h @@ -27,8 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - // This provides interface PrimeTable that determines whether a number is a // prime and determines a next prime number. This interface is used // in Google Test samples demonstrating use of parameterized tests. @@ -57,7 +55,7 @@ class OnTheFlyPrimeTable : public PrimeTable { bool IsPrime(int n) const override { if (n <= 1) return false; - for (int i = 2; i*i <= n; i++) { + for (int i = 2; i * i <= n; i++) { // n is divisible by an integer other than 1 and itself. if ((n % i) == 0) return false; } @@ -104,13 +102,13 @@ class PreCalculatedPrimeTable : public PrimeTable { // Checks every candidate for prime number (we know that 2 is the only even // prime). - for (int i = 2; i*i <= max; i += i%2+1) { + for (int i = 2; i * i <= max; i += i % 2 + 1) { if (!is_prime_[i]) continue; // Marks all multiples of i (except i itself) as non-prime. // We are starting here from i-th multiplier, because all smaller // complex numbers were already marked. - for (int j = i*i; j <= max; j += i) { + for (int j = i * i; j <= max; j += i) { is_prime_[j] = false; } } diff --git a/googletest/samples/sample1.cc b/googletest/samples/sample1.cc index 1d427597..80b69f41 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/sample10_unittest.cc b/googletest/samples/sample10_unittest.cc index 36cdac22..95b4811b 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. @@ -104,14 +103,15 @@ TEST(ListenersTest, LeaksWater) { } } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { InitGoogleTest(&argc, argv); bool check_for_leaks = false; - if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0 ) + if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0) check_for_leaks = true; else - printf("%s\n", "Run this program with --check_for_leaks to enable " + printf("%s\n", + "Run this program with --check_for_leaks to enable " "custom leak checking in the tests."); // If we are given the --check_for_leaks command line flag, installs the diff --git a/googletest/samples/sample1_unittest.cc b/googletest/samples/sample1_unittest.cc index cb08b61a..60f2770c 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 #include "sample1.h" + +#include + #include "gtest/gtest.h" namespace { @@ -69,7 +70,6 @@ namespace { // // - // 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 d8e87239..be7c4c99 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 0f986895..15a1ce77 100644 --- a/googletest/samples/sample2.h +++ b/googletest/samples/sample2.h @@ -34,7 +34,6 @@ #include - // A simple string class. class MyString { private: diff --git a/googletest/samples/sample2_unittest.cc b/googletest/samples/sample2_unittest.cc index 41e31c17..cd734f94 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 659e0f0b..bc3ffb9c 100644 --- a/googletest/samples/sample3-inl.h +++ b/googletest/samples/sample3-inl.h @@ -34,7 +34,6 @@ #include - // 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* node = head_; QueueNode* next = node->next(); - for (; ;) { + for (;;) { delete node; node = next; if (node == nullptr) break; @@ -162,11 +161,11 @@ class Queue { private: QueueNode* head_; // The first node of the queue. QueueNode* last_; // The last node of the queue. - size_t size_; // The number of elements in the queue. + size_t size_; // The number of elements in the queue. // We disallow copying a queue. Queue(const Queue&); - const Queue& operator = (const Queue&); + const Queue& operator=(const Queue&); }; #endif // GOOGLETEST_SAMPLES_SAMPLE3_INL_H_ diff --git a/googletest/samples/sample3_unittest.cc b/googletest/samples/sample3_unittest.cc index b19416d5..71609c6a 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 * q) { + void MapTester(const Queue* q) { // Creates a new queue, where each element is twice as big as the // corresponding one in q. - const Queue * const new_q = q->Map(Double); + const Queue* 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 b0ee6093..489c89b0 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 - #include "sample4.h" +#include + // 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_unittest.cc b/googletest/samples/sample4_unittest.cc index d5144c0d..fb9973fe 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 0a21dd21..cc8c0f01 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 #include -#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 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 da317eed..cf576f0a 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 @@ -151,8 +149,7 @@ using testing::Types; // the PrimeTableTest fixture defined earlier: template -class PrimeTableTest2 : public PrimeTableTest { -}; +class PrimeTableTest2 : public PrimeTableTest {}; // 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 diff --git a/googletest/samples/sample7_unittest.cc b/googletest/samples/sample7_unittest.cc index e0efc29e..3ad22cab 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 PrimeTable* CreatePreCalculatedPrimeTable() { diff --git a/googletest/samples/sample8_unittest.cc b/googletest/samples/sample8_unittest.cc index 10488b0e..9717e286 100644 --- a/googletest/samples/sample8_unittest.cc +++ b/googletest/samples/sample8_unittest.cc @@ -27,14 +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. - // This sample shows how to test code relying on some global flag variables. // Combine() helps with generating all possible combinations of such flags, // and each test is given one combination as a parameter. // Use class definitions to test from this header. #include "prime_tables.h" - #include "gtest/gtest.h" namespace { @@ -79,10 +77,10 @@ class HybridPrimeTable : public PrimeTable { int max_precalculated_; }; -using ::testing::TestWithParam; using ::testing::Bool; -using ::testing::Values; using ::testing::Combine; +using ::testing::TestWithParam; +using ::testing::Values; // To test all code paths for HybridPrimeTable we must test it with numbers // both within and outside PreCalculatedPrimeTable's capacity and also with diff --git a/googletest/samples/sample9_unittest.cc b/googletest/samples/sample9_unittest.cc index 0245b531..d627ea7d 100644 --- a/googletest/samples/sample9_unittest.cc +++ b/googletest/samples/sample9_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 // an alternative console output and how to use the UnitTest reflection API // to enumerate test suites and tests and to inspect their results. @@ -38,10 +37,10 @@ using ::testing::EmptyTestEventListener; using ::testing::InitGoogleTest; using ::testing::Test; -using ::testing::TestSuite; using ::testing::TestEventListeners; using ::testing::TestInfo; using ::testing::TestPartResult; +using ::testing::TestSuite; using ::testing::UnitTest; namespace { // Provides alternative output mode which produces minimal amount of @@ -59,29 +58,23 @@ class TersePrinter : public EmptyTestEventListener { // Called before a test starts. void OnTestStart(const TestInfo& test_info) override { - fprintf(stdout, - "*** Test %s.%s starting.\n", - test_info.test_suite_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_suite_name(), + fprintf(stdout, "*** Test %s.%s ending.\n", test_info.test_suite_name(), test_info.name()); fflush(stdout); } @@ -101,14 +94,15 @@ TEST(CustomOutputTest, Fails) { } } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { InitGoogleTest(&argc, argv); bool terse_output = false; - if (argc > 1 && strcmp(argv[1], "--terse_output") == 0 ) + if (argc > 1 && strcmp(argv[1], "--terse_output") == 0) terse_output = true; else - printf("%s\n", "Run this program with --terse_output to change the way " + printf("%s\n", + "Run this program with --terse_output to change the way " "it prints its output."); UnitTest& unit_test = *UnitTest::GetInstance(); @@ -149,8 +143,7 @@ int main(int argc, char **argv) { } // Test that were meant to fail should not affect the test program outcome. - if (unexpectedly_failed_tests == 0) - ret_val = 0; + if (unexpectedly_failed_tests == 0) ret_val = 0; return ret_val; } diff --git a/googletest/src/gtest-all.cc b/googletest/src/gtest-all.cc index 29eba165..2a70ed88 100644 --- a/googletest/src/gtest-all.cc +++ b/googletest/src/gtest-all.cc @@ -38,7 +38,6 @@ #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" @@ -47,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 index 9f90e872..f1c0b10d 100644 --- a/googletest/src/gtest-assertion-result.cc +++ b/googletest/src/gtest-assertion-result.cc @@ -33,8 +33,8 @@ #include "gtest/gtest-assertion-result.h" -#include #include +#include #include "gtest/gtest-message.h" @@ -63,14 +63,10 @@ AssertionResult AssertionResult::operator!() const { } // Makes a successful assertion result. -AssertionResult AssertionSuccess() { - return AssertionResult(true); -} +AssertionResult AssertionSuccess() { return AssertionResult(true); } // Makes a failed assertion result. -AssertionResult AssertionFailure() { - return AssertionResult(false); -} +AssertionResult AssertionFailure() { return AssertionResult(false); } // Makes a failed assertion result with the given failure message. // Deprecated; use AssertionFailure() << message. diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 87d5e9b9..e6abc627 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -35,49 +35,49 @@ #include #include -#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 -# endif // GTEST_OS_MAC +#if GTEST_OS_MAC +#include +#endif // GTEST_OS_MAC -# include -# include -# include +#include +#include +#include -# if GTEST_OS_LINUX -# include -# endif // GTEST_OS_LINUX +#if GTEST_OS_LINUX +#include +#endif // GTEST_OS_LINUX -# include +#include -# if GTEST_OS_WINDOWS -# include -# else -# include -# include -# endif // GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS +#include +#else +#include +#include +#endif // GTEST_OS_WINDOWS -# if GTEST_OS_QNX -# include -# endif // GTEST_OS_QNX +#if GTEST_OS_QNX +#include +#endif // GTEST_OS_QNX -# if GTEST_OS_FUCHSIA -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# endif // GTEST_OS_FUCHSIA +#if GTEST_OS_FUCHSIA +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif // GTEST_OS_FUCHSIA #endif // GTEST_HAS_DEATH_TEST @@ -137,9 +137,9 @@ namespace internal { // Valid only for fast death tests. Indicates the code is running in the // child process of a fast style death test. -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA static bool g_in_fast_death_test_child = false; -# endif +#endif // Returns a Boolean value indicating whether the caller is currently // executing in the context of the death test child process. Tools such as @@ -147,13 +147,13 @@ static bool g_in_fast_death_test_child = false; // tests. IMPORTANT: This is an internal utility. Using it may break the // implementation of death tests. User code MUST NOT use it. bool InDeathTestChild() { -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA // On Windows and Fuchsia, death tests are thread-safe regardless of the value // of the death_test_style flag. return !GTEST_FLAG_GET(internal_run_death_test).empty(); -# else +#else if (GTEST_FLAG_GET(death_test_style) == "threadsafe") return !GTEST_FLAG_GET(internal_run_death_test).empty(); @@ -165,40 +165,38 @@ bool InDeathTestChild() { } // namespace internal // ExitedWithCode constructor. -ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { -} +ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {} // ExitedWithCode function-call operator. bool ExitedWithCode::operator()(int exit_status) const { -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA return exit_status == exit_code_; -# else +#else return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; -# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA } -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // KilledBySignal constructor. -KilledBySignal::KilledBySignal(int signum) : signum_(signum) { -} +KilledBySignal::KilledBySignal(int signum) : signum_(signum) {} // KilledBySignal function-call operator. bool KilledBySignal::operator()(int exit_status) const { -# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) +#if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) { bool result; if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { return result; } } -# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) +#endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; } -# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA namespace internal { @@ -209,23 +207,23 @@ namespace internal { static std::string ExitSummary(int exit_code) { Message m; -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA m << "Exited with exit status " << exit_code; -# else +#else if (WIFEXITED(exit_code)) { m << "Exited with exit status " << WEXITSTATUS(exit_code); } else if (WIFSIGNALED(exit_code)) { m << "Terminated by signal " << WTERMSIG(exit_code); } -# ifdef WCOREDUMP +#ifdef WCOREDUMP if (WCOREDUMP(exit_code)) { m << " (core dumped)"; } -# endif -# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#endif +#endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA return m.GetString(); } @@ -236,7 +234,7 @@ bool ExitedUnsuccessfully(int exit_status) { return !ExitedWithCode(0)(exit_status); } -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Generates a textual failure message when a death test finds more than // one thread running, or cannot determine the number of threads, prior // to executing the given statement. It is the responsibility of the @@ -257,7 +255,7 @@ static std::string DeathTestThreadWarning(size_t thread_count) { << " this is the last message you see before your test times out."; return msg.GetString(); } -# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Flag characters for reporting a death test that did not die. static const char kDeathTestLived = 'L'; @@ -307,14 +305,14 @@ static void DeathTestAbort(const std::string& message) { // A replacement for CHECK that calls DeathTestAbort if the assertion // fails. -# define GTEST_DEATH_TEST_CHECK_(expression) \ - do { \ - if (!::testing::internal::IsTrue(expression)) { \ - DeathTestAbort( \ - ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ - + ::testing::internal::StreamableToString(__LINE__) + ": " \ - + #expression); \ - } \ +#define GTEST_DEATH_TEST_CHECK_(expression) \ + do { \ + if (!::testing::internal::IsTrue(expression)) { \ + DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \ + ", line " + \ + ::testing::internal::StreamableToString(__LINE__) + \ + ": " + #expression); \ + } \ } while (::testing::internal::AlwaysFalse()) // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for @@ -324,23 +322,23 @@ static void DeathTestAbort(const std::string& message) { // evaluates the expression as long as it evaluates to -1 and sets // errno to EINTR. If the expression evaluates to -1 but errno is // something other than EINTR, DeathTestAbort is called. -# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ - do { \ - int gtest_retval; \ - do { \ - gtest_retval = (expression); \ - } while (gtest_retval == -1 && errno == EINTR); \ - if (gtest_retval == -1) { \ - DeathTestAbort( \ - ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ - + ::testing::internal::StreamableToString(__LINE__) + ": " \ - + #expression + " != -1"); \ - } \ +#define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ + do { \ + int gtest_retval; \ + do { \ + gtest_retval = (expression); \ + } while (gtest_retval == -1 && errno == EINTR); \ + if (gtest_retval == -1) { \ + DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \ + ", line " + \ + ::testing::internal::StreamableToString(__LINE__) + \ + ": " + #expression + " != -1"); \ + } \ } while (::testing::internal::AlwaysFalse()) // Returns the message describing the last system error in errno. std::string GetLastErrnoDescription() { - return errno == 0 ? "" : posix::StrError(errno); + return errno == 0 ? "" : posix::StrError(errno); } // This is called from a death test parent process to read a failure @@ -373,8 +371,9 @@ static void FailFromInternalError(int fd) { DeathTest::DeathTest() { TestInfo* const info = GetUnitTestImpl()->current_test_info(); if (info == nullptr) { - DeathTestAbort("Cannot run a death test outside of a TEST or " - "TEST_F construct"); + DeathTestAbort( + "Cannot run a death test outside of a TEST or " + "TEST_F construct"); } } @@ -503,9 +502,7 @@ void DeathTestImpl::ReadAndInterpretStatusByte() { set_read_fd(-1); } -std::string DeathTestImpl::GetErrorLogs() { - return GetCapturedStderr(); -} +std::string DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); } // Signals that the death test code which should have exited, didn't. // Should be called only in a death test child process. @@ -515,9 +512,9 @@ void DeathTestImpl::Abort(AbortReason reason) { // The parent process considers the death test to be a failure if // it finds any data in our pipe. So, here we write a single flag byte // to the pipe, then exit. - const char status_ch = - reason == TEST_DID_NOT_DIE ? kDeathTestLived : - reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; + const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived + : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew + : kDeathTestReturned; GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); // We are leaking the descriptor here because on some platforms (i.e., @@ -536,7 +533,7 @@ void DeathTestImpl::Abort(AbortReason reason) { // much easier. static ::std::string FormatDeathTestOutput(const ::std::string& output) { ::std::string ret; - for (size_t at = 0; ; ) { + for (size_t at = 0;;) { const size_t line_end = output.find('\n', at); ret += "[ DEATH ] "; if (line_end == ::std::string::npos) { @@ -571,8 +568,7 @@ static ::std::string FormatDeathTestOutput(const ::std::string& output) { // the first failing condition, in the order given above, is the one that is // reported. Also sets the last death test message string. bool DeathTestImpl::Passed(bool status_ok) { - if (!spawned()) - return false; + if (!spawned()) return false; const std::string error_message = GetErrorLogs(); @@ -583,15 +579,18 @@ bool DeathTestImpl::Passed(bool status_ok) { switch (outcome()) { case LIVED: buffer << " Result: failed to die.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); + << " Error msg:\n" + << FormatDeathTestOutput(error_message); break; case THREW: buffer << " Result: threw an exception.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); + << " Error msg:\n" + << FormatDeathTestOutput(error_message); break; case RETURNED: buffer << " Result: illegal return in test statement.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); + << " Error msg:\n" + << FormatDeathTestOutput(error_message); break; case DIED: if (status_ok) { @@ -608,7 +607,8 @@ bool DeathTestImpl::Passed(bool status_ok) { } else { buffer << " Result: died but not with expected exit code:\n" << " " << ExitSummary(status()) << "\n" - << "Actual msg:\n" << FormatDeathTestOutput(error_message); + << "Actual msg:\n" + << FormatDeathTestOutput(error_message); } break; case IN_PROGRESS: @@ -621,7 +621,7 @@ bool DeathTestImpl::Passed(bool status_ok) { return success; } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // WindowsDeathTest implements death tests on Windows. Due to the // specifics of starting new processes on Windows, death tests there are // always threadsafe, and Google Test considers the @@ -682,14 +682,12 @@ class WindowsDeathTest : public DeathTestImpl { // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int WindowsDeathTest::Wait() { - if (!spawned()) - return 0; + if (!spawned()) return 0; // Wait until the child either signals that it has acquired the write end // of the pipe or it dies. - const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; - switch (::WaitForMultipleObjects(2, - wait_handles, + const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()}; + switch (::WaitForMultipleObjects(2, wait_handles, FALSE, // Waits for any of the handles. INFINITE)) { case WAIT_OBJECT_0: @@ -710,9 +708,8 @@ int WindowsDeathTest::Wait() { // returns immediately if the child has already exited, regardless of // whether previous calls to WaitForMultipleObjects synchronized on this // handle or not. - GTEST_DEATH_TEST_CHECK_( - WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), - INFINITE)); + GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 == + ::WaitForSingleObject(child_handle_.Get(), INFINITE)); DWORD status_code; GTEST_DEATH_TEST_CHECK_( ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); @@ -745,12 +742,12 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE}; HANDLE read_handle, write_handle; - GTEST_DEATH_TEST_CHECK_( - ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, - 0) // Default buffer size. - != FALSE); - set_read_fd(::_open_osfhandle(reinterpret_cast(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(read_handle), O_RDONLY)); write_handle_.Reset(write_handle); event_handle_.Reset(::CreateEvent( &handles_are_inheritable, @@ -777,9 +774,8 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { 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(""); @@ -812,7 +808,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { return OVERSEE_TEST; } -# elif GTEST_OS_FUCHSIA +#elif GTEST_OS_FUCHSIA class FuchsiaDeathTest : public DeathTestImpl { public: @@ -858,18 +854,13 @@ class Arguments { template void AddArguments(const ::std::vector& arguments) { for (typename ::std::vector::const_iterator i = arguments.begin(); - i != arguments.end(); - ++i) { + i != arguments.end(); ++i) { args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); } } - char* const* Argv() { - return &args_[0]; - } + char* const* Argv() { return &args_[0]; } - int size() { - return static_cast(args_.size()) - 1; - } + int size() { return static_cast(args_.size()) - 1; } private: std::vector args_; @@ -883,8 +874,7 @@ int FuchsiaDeathTest::Wait() { const int kSocketKey = 1; const int kExceptionKey = 2; - if (!spawned()) - return 0; + if (!spawned()) return 0; // Create a port to wait for socket/task/exception events. zx_status_t status_zx; @@ -893,8 +883,8 @@ int FuchsiaDeathTest::Wait() { GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); // Register to wait for the child process to terminate. - status_zx = child_process_.wait_async( - port, kProcessKey, ZX_PROCESS_TERMINATED, 0); + status_zx = + child_process_.wait_async(port, kProcessKey, ZX_PROCESS_TERMINATED, 0); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); // Register to wait for the socket to be readable or closed. @@ -903,8 +893,8 @@ int FuchsiaDeathTest::Wait() { GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); // Register to wait for an exception. - status_zx = exception_channel_.wait_async( - port, kExceptionKey, ZX_CHANNEL_READABLE, 0); + status_zx = exception_channel_.wait_async(port, kExceptionKey, + ZX_CHANNEL_READABLE, 0); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); bool process_terminated = false; @@ -934,9 +924,9 @@ int FuchsiaDeathTest::Wait() { size_t old_length = captured_stderr_.length(); size_t bytes_read = 0; captured_stderr_.resize(old_length + kBufferSize); - status_zx = stderr_socket_.read( - 0, &captured_stderr_.front() + old_length, kBufferSize, - &bytes_read); + status_zx = + stderr_socket_.read(0, &captured_stderr_.front() + old_length, + kBufferSize, &bytes_read); captured_stderr_.resize(old_length + bytes_read); } while (status_zx == ZX_OK); if (status_zx == ZX_ERR_PEER_CLOSED) { @@ -992,11 +982,10 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + "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); + 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()); @@ -1019,8 +1008,7 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { // Create a socket pair will be used to receive the child process' stderr. zx::socket stderr_producer_socket; - status = - zx::socket::create(0, &stderr_producer_socket, &stderr_socket_); + status = zx::socket::create(0, &stderr_producer_socket, &stderr_socket_); GTEST_DEATH_TEST_CHECK_(status >= 0); int stderr_producer_fd = -1; status = @@ -1037,35 +1025,32 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { // Create a child job. zx_handle_t child_job = ZX_HANDLE_INVALID; - status = zx_job_create(zx_job_default(), 0, & child_job); + status = zx_job_create(zx_job_default(), 0, &child_job); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); zx_policy_basic_t policy; policy.condition = ZX_POL_NEW_ANY; policy.policy = ZX_POL_ACTION_ALLOW; - status = zx_job_set_policy( - child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1); + status = zx_job_set_policy(child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, + &policy, 1); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); // Create an exception channel attached to the |child_job|, to allow // us to suppress the system default exception handler from firing. - status = - zx_task_create_exception_channel( - child_job, 0, exception_channel_.reset_and_get_address()); + status = zx_task_create_exception_channel( + child_job, 0, exception_channel_.reset_and_get_address()); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); // Spawn the child process. - status = fdio_spawn_etc( - child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr, - 2, spawn_actions, child_process_.reset_and_get_address(), nullptr); + status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], + args.Argv(), nullptr, 2, spawn_actions, + child_process_.reset_and_get_address(), nullptr); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); set_spawned(true); return OVERSEE_TEST; } -std::string FuchsiaDeathTest::GetErrorLogs() { - return captured_stderr_; -} +std::string FuchsiaDeathTest::GetErrorLogs() { return captured_stderr_; } #else // We are neither on Windows, nor on Fuchsia. @@ -1096,8 +1081,7 @@ ForkingDeathTest::ForkingDeathTest(const char* a_statement, // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int ForkingDeathTest::Wait() { - if (!spawned()) - return 0; + if (!spawned()) return 0; ReadAndInterpretStatusByte(); @@ -1176,11 +1160,11 @@ class ExecDeathTest : public ForkingDeathTest { private: static ::std::vector GetArgvsForDeathTestChildProcess() { ::std::vector args = GetInjectableArgvs(); -# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) +#if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) ::std::vector 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. @@ -1207,14 +1191,11 @@ class Arguments { template void AddArguments(const ::std::vector& arguments) { for (typename ::std::vector::const_iterator i = arguments.begin(); - i != arguments.end(); - ++i) { + i != arguments.end(); ++i) { args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); } } - char* const* Argv() { - return &args_[0]; - } + char* const* Argv() { return &args_[0]; } private: std::vector args_; @@ -1227,9 +1208,9 @@ struct ExecDeathTestArgs { int close_fd; // File descriptor to close; the read end of a pipe }; -# if GTEST_OS_QNX +#if GTEST_OS_QNX extern "C" char** environ; -# else // GTEST_OS_QNX +#else // GTEST_OS_QNX // The main function for a threadsafe-style death test child process. // This function is called in a clone()-ed process and thus must avoid // any potentially unsafe operations like malloc or libc functions. @@ -1244,8 +1225,8 @@ static int ExecDeathTestChildMain(void* child_arg) { UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { - DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + - GetLastErrnoDescription()); + DeathTestAbort(std::string("chdir(\"") + original_dir + + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } @@ -1256,13 +1237,12 @@ static int ExecDeathTestChildMain(void* child_arg) { // one path separator. execv(args->argv[0], args->argv); DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " + - original_dir + " failed: " + - GetLastErrnoDescription()); + original_dir + " failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } -# endif // GTEST_OS_QNX +#endif // GTEST_OS_QNX -# if GTEST_HAS_CLONE +#if GTEST_HAS_CLONE // Two utility routines that together determine the direction the stack // grows. // This could be accomplished more elegantly by a single recursive @@ -1296,7 +1276,7 @@ static bool StackGrowsDown() { StackLowerThanAddress(&dummy, &result); return result; } -# endif // GTEST_HAS_CLONE +#endif // GTEST_HAS_CLONE // Spawns a child process with the same executable as the current process in // a thread-safe manner and instructs it to run the death test. The @@ -1306,10 +1286,10 @@ static bool StackGrowsDown() { // spawn(2) there instead. The function dies with an error message if // anything goes wrong. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { - ExecDeathTestArgs args = { argv, close_fd }; + ExecDeathTestArgs args = {argv, close_fd}; pid_t child_pid = -1; -# if GTEST_OS_QNX +#if GTEST_OS_QNX // Obtains the current directory and sets it to be closed in the child // process. const int cwd_fd = open(".", O_RDONLY); @@ -1322,16 +1302,16 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { - DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + - GetLastErrnoDescription()); + DeathTestAbort(std::string("chdir(\"") + original_dir + + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } int fd_flags; // Set close_fd to be closed after spawn. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); - GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, - fd_flags | FD_CLOEXEC)); + GTEST_DEATH_TEST_CHECK_SYSCALL_( + fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC)); struct inheritance inherit = {0}; // spawn is a system call. child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ); @@ -1339,8 +1319,8 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); -# else // GTEST_OS_QNX -# if GTEST_OS_LINUX +#else // GTEST_OS_QNX +#if GTEST_OS_LINUX // When a SIGPROF signal is received while fork() or clone() are executing, // the process may hang. To avoid this, we ignore SIGPROF here and re-enable // it after the call to fork()/clone() is complete. @@ -1349,11 +1329,11 @@ 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 +#if GTEST_HAS_CLONE const bool use_fork = GTEST_FLAG_GET(death_test_use_fork); if (!use_fork) { @@ -1373,7 +1353,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { const size_t kMaxStackAlignment = 64; void* const stack_top = static_cast(stack) + - (stack_grows_down ? stack_size - kMaxStackAlignment : 0); + (stack_grows_down ? stack_size - kMaxStackAlignment : 0); GTEST_DEATH_TEST_CHECK_( static_cast(stack_size) > kMaxStackAlignment && reinterpret_cast(stack_top) % kMaxStackAlignment == 0); @@ -1382,19 +1362,19 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); } -# else +#else const bool use_fork = true; -# endif // GTEST_HAS_CLONE +#endif // GTEST_HAS_CLONE if (use_fork && (child_pid = fork()) == 0) { - ExecDeathTestChildMain(&args); - _exit(0); + ExecDeathTestChildMain(&args); + _exit(0); } -# endif // GTEST_OS_QNX -# if GTEST_OS_LINUX +#endif // GTEST_OS_QNX +#if GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_SYSCALL_( sigaction(SIGPROF, &saved_sigprof_action, nullptr)); -# endif // GTEST_OS_LINUX +#endif // GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_(child_pid != -1); return child_pid; @@ -1450,7 +1430,7 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { return OVERSEE_TEST; } -# endif // !GTEST_OS_WINDOWS +#endif // !GTEST_OS_WINDOWS // Creates a concrete DeathTest-derived class that depends on the // --gtest_death_test_style flag, and sets the pointer pointed to @@ -1464,15 +1444,15 @@ bool DefaultDeathTestFactory::Create(const char* statement, UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); - const int death_test_index = impl->current_test_info() - ->increment_death_test_count(); + const int death_test_index = + impl->current_test_info()->increment_death_test_count(); if (flag != nullptr) { if (death_test_index > flag->index()) { DeathTest::set_last_death_test_message( - "Death test count (" + StreamableToString(death_test_index) - + ") somehow exceeded expected maximum (" - + StreamableToString(flag->index()) + ")"); + "Death test count (" + StreamableToString(death_test_index) + + ") somehow exceeded expected maximum (" + + StreamableToString(flag->index()) + ")"); return false; } @@ -1483,21 +1463,21 @@ bool DefaultDeathTestFactory::Create(const char* statement, } } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS if (GTEST_FLAG_GET(death_test_style) == "threadsafe" || GTEST_FLAG_GET(death_test_style) == "fast") { *test = new WindowsDeathTest(statement, std::move(matcher), file, line); } -# elif GTEST_OS_FUCHSIA +#elif GTEST_OS_FUCHSIA if (GTEST_FLAG_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_GET(death_test_style) == "threadsafe") { *test = new ExecDeathTest(statement, std::move(matcher), file, line); @@ -1505,7 +1485,7 @@ bool DefaultDeathTestFactory::Create(const char* statement, *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 \"" + @@ -1517,16 +1497,16 @@ bool DefaultDeathTestFactory::Create(const char* statement, return true; } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // Recreates the pipe and event handles from the provided parameters, // signals the event, and returns a file descriptor wrapped around the pipe // handle. This function is called in the child process only. static int GetStatusFileDescriptor(unsigned int parent_process_id, - size_t write_handle_as_size_t, - size_t event_handle_as_size_t) { + size_t write_handle_as_size_t, + size_t event_handle_as_size_t) { AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, - FALSE, // Non-inheritable. - parent_process_id)); + FALSE, // Non-inheritable. + parent_process_id)); if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { DeathTestAbort("Unable to open parent process " + StreamableToString(parent_process_id)); @@ -1534,8 +1514,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); - const HANDLE write_handle = - reinterpret_cast(write_handle_as_size_t); + const HANDLE write_handle = reinterpret_cast(write_handle_as_size_t); HANDLE dup_write_handle; // The newly initialized handle is accessible only in the parent @@ -1557,9 +1536,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, HANDLE dup_event_handle; if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, - ::GetCurrentProcess(), &dup_event_handle, - 0x0, - FALSE, + ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE, DUPLICATE_SAME_ACCESS)) { DeathTestAbort("Unable to duplicate the event handle " + StreamableToString(event_handle_as_size_t) + @@ -1581,7 +1558,7 @@ 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 @@ -1597,45 +1574,41 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields); int write_fd = -1; -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS unsigned int parent_process_id = 0; size_t write_handle_as_size_t = 0; size_t event_handle_as_size_t = 0; - if (fields.size() != 6 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index) - || !ParseNaturalNumber(fields[3], &parent_process_id) - || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) - || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { + if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) || + !ParseNaturalNumber(fields[2], &index) || + !ParseNaturalNumber(fields[3], &parent_process_id) || + !ParseNaturalNumber(fields[4], &write_handle_as_size_t) || + !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG_GET(internal_run_death_test)); } - write_fd = GetStatusFileDescriptor(parent_process_id, - write_handle_as_size_t, + write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t, event_handle_as_size_t); -# elif GTEST_OS_FUCHSIA +#elif GTEST_OS_FUCHSIA - if (fields.size() != 3 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index)) { + 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)) { + 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 0b562940..f6ee90cd 100644 --- a/googletest/src/gtest-filepath.cc +++ b/googletest/src/gtest-filepath.cc @@ -30,29 +30,31 @@ #include "gtest/internal/gtest-filepath.h" #include -#include "gtest/internal/gtest-port.h" + #include "gtest/gtest-message.h" +#include "gtest/internal/gtest-port.h" #if GTEST_OS_WINDOWS_MOBILE -# include +#include #elif GTEST_OS_WINDOWS -# include -# include +#include +#include #else -# include -# include // Some Linux distributions define PATH_MAX here. -#endif // GTEST_OS_WINDOWS_MOBILE +#include + +#include // Some Linux distributions define PATH_MAX here. +#endif // GTEST_OS_WINDOWS_MOBILE #include "gtest/internal/gtest-string.h" #if GTEST_OS_WINDOWS -# define GTEST_PATH_MAX_ _MAX_PATH +#define GTEST_PATH_MAX_ _MAX_PATH #elif defined(PATH_MAX) -# define GTEST_PATH_MAX_ PATH_MAX +#define GTEST_PATH_MAX_ PATH_MAX #elif defined(_XOPEN_PATH_MAX) -# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX +#define GTEST_PATH_MAX_ _XOPEN_PATH_MAX #else -# define GTEST_PATH_MAX_ _POSIX_PATH_MAX +#define GTEST_PATH_MAX_ _POSIX_PATH_MAX #endif // GTEST_OS_WINDOWS namespace testing { @@ -66,16 +68,16 @@ namespace internal { const char kPathSeparator = '\\'; const char kAlternatePathSeparator = '/'; const char kAlternatePathSeparatorString[] = "/"; -# if GTEST_OS_WINDOWS_MOBILE +#if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't have a current directory. You should not use // the current directory in tests on Windows CE, but this at least // provides a reasonable fallback. const char kCurrentDirectoryString[] = "\\"; // Windows CE doesn't define INVALID_FILE_ATTRIBUTES const DWORD kInvalidFileAttributes = 0xffffffff; -# else +#else const char kCurrentDirectoryString[] = ".\\"; -# endif // GTEST_OS_WINDOWS_MOBILE +#endif // GTEST_OS_WINDOWS_MOBILE #else const char kPathSeparator = '/'; const char kCurrentDirectoryString[] = "./"; @@ -99,17 +101,17 @@ FilePath FilePath::GetCurrentDir() { // something reasonable. return FilePath(kCurrentDirectoryString); #elif GTEST_OS_WINDOWS - char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + char cwd[GTEST_PATH_MAX_ + 1] = {'\0'}; return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd); #else - char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + char cwd[GTEST_PATH_MAX_ + 1] = {'\0'}; char* result = getcwd(cwd, sizeof(cwd)); -# if GTEST_OS_NACL +#if GTEST_OS_NACL // getcwd will likely fail in NaCl due to the sandbox, so return something // reasonable. The user may have provided a shim implementation for getcwd, // however, so fallback only when failure is detected. return FilePath(result == nullptr ? kCurrentDirectoryString : cwd); -# endif // GTEST_OS_NACL +#endif // GTEST_OS_NACL return FilePath(result == nullptr ? "" : cwd); #endif // GTEST_OS_WINDOWS_MOBILE } @@ -121,8 +123,8 @@ FilePath FilePath::GetCurrentDir() { FilePath FilePath::RemoveExtension(const char* extension) const { const std::string dot_extension = std::string(".") + extension; if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { - return FilePath(pathname_.substr( - 0, pathname_.length() - dot_extension.length())); + return FilePath( + pathname_.substr(0, pathname_.length() - dot_extension.length())); } return *this; } @@ -178,15 +180,14 @@ FilePath FilePath::RemoveFileName() const { // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. FilePath FilePath::MakeFileName(const FilePath& directory, - const FilePath& base_name, - int number, + const FilePath& base_name, int number, const char* extension) { std::string file; if (number == 0) { file = base_name.string() + "." + extension; } else { - file = base_name.string() + "_" + StreamableToString(number) - + "." + extension; + file = + base_name.string() + "_" + StreamableToString(number) + "." + extension; } return ConcatPaths(directory, FilePath(file)); } @@ -195,8 +196,7 @@ FilePath FilePath::MakeFileName(const FilePath& directory, // On Windows, uses \ as the separator rather than /. FilePath FilePath::ConcatPaths(const FilePath& directory, const FilePath& relative_path) { - if (directory.IsEmpty()) - return relative_path; + if (directory.IsEmpty()) return relative_path; const FilePath dir(directory.RemoveTrailingPathSeparator()); return FilePath(dir.string() + kPathSeparator + relative_path.string()); } @@ -207,7 +207,7 @@ bool FilePath::FileOrDirectoryExists() const { #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); const DWORD attributes = GetFileAttributes(unicode); - delete [] unicode; + delete[] unicode; return attributes != kInvalidFileAttributes; #else posix::StatStruct file_stat{}; @@ -222,8 +222,8 @@ bool FilePath::DirectoryExists() const { #if GTEST_OS_WINDOWS // Don't strip off trailing separator if path is a root directory on // Windows (like "C:\\"). - const FilePath& path(IsRootDirectory() ? *this : - RemoveTrailingPathSeparator()); + const FilePath& path(IsRootDirectory() ? *this + : RemoveTrailingPathSeparator()); #else const FilePath& path(*this); #endif @@ -231,15 +231,15 @@ bool FilePath::DirectoryExists() const { #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); const DWORD attributes = GetFileAttributes(unicode); - delete [] unicode; + delete[] unicode; if ((attributes != kInvalidFileAttributes) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) { result = true; } #else posix::StatStruct file_stat{}; - result = posix::Stat(path.c_str(), &file_stat) == 0 && - posix::IsDir(file_stat); + result = + posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat); #endif // GTEST_OS_WINDOWS_MOBILE return result; @@ -260,10 +260,9 @@ bool FilePath::IsAbsolutePath() const { const char* const name = pathname_.c_str(); #if GTEST_OS_WINDOWS return pathname_.length() >= 3 && - ((name[0] >= 'a' && name[0] <= 'z') || - (name[0] >= 'A' && name[0] <= 'Z')) && - name[1] == ':' && - IsPathSeparator(name[2]); + ((name[0] >= 'a' && name[0] <= 'z') || + (name[0] >= 'A' && name[0] <= 'Z')) && + name[1] == ':' && IsPathSeparator(name[2]); #else return IsPathSeparator(name[0]); #endif @@ -321,7 +320,7 @@ bool FilePath::CreateFolder() const { FilePath removed_sep(this->RemoveTrailingPathSeparator()); LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); int result = CreateDirectory(unicode, nullptr) ? 0 : -1; - delete [] unicode; + delete[] unicode; #elif GTEST_OS_WINDOWS int result = _mkdir(pathname_.c_str()); #elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA @@ -341,9 +340,8 @@ bool FilePath::CreateFolder() const { // name, otherwise return the name string unmodified. // On Windows platform, uses \ as the separator, other platforms use /. FilePath FilePath::RemoveTrailingPathSeparator() const { - return IsDirectory() - ? FilePath(pathname_.substr(0, pathname_.length() - 1)) - : *this; + return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1)) + : *this; } // Removes any redundant separators that might be in the pathname. diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 3f5551d1..0b9e929c 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -35,7 +35,7 @@ #define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_ #ifndef _WIN32_WCE -# include +#include #endif // !_WIN32_WCE #include #include // For strtoll/_strtoul64/malloc/free. @@ -50,16 +50,16 @@ #include "gtest/internal/gtest-port.h" #if GTEST_CAN_STREAM_RESULTS_ -# include // NOLINT -# include // NOLINT +#include // NOLINT +#include // NOLINT #endif #if GTEST_OS_WINDOWS -# include // NOLINT -#endif // GTEST_OS_WINDOWS +#include // 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 */) @@ -109,15 +109,16 @@ GTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value); // Returns a random seed in range [1, kMaxRandomSeed] based on the // given --gtest_random_seed flag value. inline int GetRandomSeedFromFlag(int32_t random_seed_flag) { - const unsigned int raw_seed = (random_seed_flag == 0) ? - static_cast(GetTimeInMillis()) : - static_cast(random_seed_flag); + const unsigned int raw_seed = + (random_seed_flag == 0) ? static_cast(GetTimeInMillis()) + : static_cast(random_seed_flag); // Normalizes the actual seed to range [1, kMaxRandomSeed] such that // it's easy to type. const int normalized_seed = static_cast((raw_seed - 1U) % - static_cast(kMaxRandomSeed)) + 1; + static_cast(kMaxRandomSeed)) + + 1; return normalized_seed; } @@ -261,8 +262,8 @@ GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val); // returns true if and only if the test should be run on this shard. The test id // is some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. -GTEST_API_ bool ShouldRunTestOnShard( - int total_shards, int shard_index, int test_id); +GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, + int test_id); // STL container utilities. @@ -274,8 +275,7 @@ inline int CountIf(const Container& c, Predicate predicate) { // Solaris has a non-standard signature. int count = 0; for (auto it = c.begin(); it != c.end(); ++it) { - if (predicate(*it)) - ++count; + if (predicate(*it)) ++count; } return count; } @@ -424,7 +424,9 @@ class OsStackTraceGetterInterface { static const char* const kElidedFramesMarker; private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); + OsStackTraceGetterInterface(const OsStackTraceGetterInterface&) = delete; + OsStackTraceGetterInterface& operator=(const OsStackTraceGetterInterface&) = + delete; }; // A working implementation of the OsStackTraceGetterInterface interface. @@ -446,7 +448,8 @@ class OsStackTraceGetter : public OsStackTraceGetterInterface { void* caller_frame_ = nullptr; #endif // GTEST_HAS_ABSL - GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); + OsStackTraceGetter(const OsStackTraceGetter&) = delete; + OsStackTraceGetter& operator=(const OsStackTraceGetter&) = delete; }; // Information about a Google Test trace point. @@ -459,7 +462,7 @@ struct TraceInfo { // This is the default global test part result reporter used in UnitTestImpl. // This class should only be used by UnitTestImpl. class DefaultGlobalTestPartResultReporter - : public TestPartResultReporterInterface { + : public TestPartResultReporterInterface { public: explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. Reports the test part @@ -469,7 +472,10 @@ class DefaultGlobalTestPartResultReporter private: UnitTestImpl* const unit_test_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); + DefaultGlobalTestPartResultReporter( + const DefaultGlobalTestPartResultReporter&) = delete; + DefaultGlobalTestPartResultReporter& operator=( + const DefaultGlobalTestPartResultReporter&) = delete; }; // This is the default per thread test part result reporter used in @@ -485,7 +491,10 @@ class DefaultPerThreadTestPartResultReporter private: UnitTestImpl* const unit_test_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); + DefaultPerThreadTestPartResultReporter( + const DefaultPerThreadTestPartResultReporter&) = delete; + DefaultPerThreadTestPartResultReporter& operator=( + const DefaultPerThreadTestPartResultReporter&) = delete; }; // The private implementation of the UnitTest class. We don't protect @@ -728,9 +737,7 @@ class GTEST_API_ UnitTestImpl { } // Clears the results of ad-hoc test assertions. - void ClearAdHocTestResult() { - ad_hoc_test_result_.Clear(); - } + void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); } // Adds a TestProperty to the current TestResult object when invoked in a // context of a test or a test suite, or to the global property set. If the @@ -738,10 +745,7 @@ class GTEST_API_ UnitTestImpl { // updated. void RecordProperty(const TestProperty& test_property); - enum ReactionToSharding { - HONOR_SHARDING_PROTOCOL, - IGNORE_SHARDING_PROTOCOL - }; + enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL }; // Matches the full name of each test against the user-specified // filter to decide whether the test should run, then records the @@ -947,7 +951,8 @@ class GTEST_API_ UnitTestImpl { // starts. bool catch_exceptions_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); + UnitTestImpl(const UnitTestImpl&) = delete; + UnitTestImpl& operator=(const UnitTestImpl&) = delete; }; // class UnitTestImpl // Convenience function for accessing the global UnitTest @@ -970,8 +975,9 @@ GTEST_API_ bool IsValidEscape(char ch); GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); GTEST_API_ bool ValidateRegex(const char* regex); GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); -GTEST_API_ bool MatchRepetitionAndRegexAtHead( - bool escaped, char ch, char repeat, const char* regex, const char* str); +GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch, + char repeat, const char* regex, + const char* str); GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); #endif // GTEST_USES_SIMPLE_RE @@ -1073,8 +1079,7 @@ class StreamingListener : public EmptyTestEventListener { } ~SocketWriter() override { - if (sockfd_ != -1) - CloseConnection(); + if (sockfd_ != -1) CloseConnection(); } // Sends a string to the socket. @@ -1084,9 +1089,8 @@ class StreamingListener : public EmptyTestEventListener { const auto len = static_cast(message.length()); if (write(sockfd_, message.c_str(), len) != static_cast(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_; } } @@ -1107,7 +1111,8 @@ class StreamingListener : public EmptyTestEventListener { const std::string host_name_; const std::string port_num_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); + SocketWriter(const SocketWriter&) = delete; + SocketWriter& operator=(const SocketWriter&) = delete; }; // class SocketWriter // Escapes '=', '&', '%', and '\n' characters in str as "%xx". @@ -1119,7 +1124,9 @@ class StreamingListener : public EmptyTestEventListener { } explicit StreamingListener(AbstractSocketWriter* socket_writer) - : socket_writer_(socket_writer) { Start(); } + : socket_writer_(socket_writer) { + Start(); + } void OnTestProgramStart(const UnitTest& /* unit_test */) override { SendLn("event=TestProgramStart"); @@ -1142,9 +1149,9 @@ 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 @@ -1167,8 +1174,7 @@ class StreamingListener : public EmptyTestEventListener { void OnTestEnd(const TestInfo& test_info) override { SendLn("event=TestEnd&passed=" + - FormatBool((test_info.result())->Passed()) + - "&elapsed_time=" + + FormatBool((test_info.result())->Passed()) + "&elapsed_time=" + StreamableToString((test_info.result())->elapsed_time()) + "ms"); } @@ -1192,7 +1198,8 @@ class StreamingListener : public EmptyTestEventListener { const std::unique_ptr socket_writer_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); + StreamingListener(const StreamingListener&) = delete; + StreamingListener& operator=(const StreamingListener&) = delete; }; // class StreamingListener #endif // GTEST_CAN_STREAM_RESULTS_ diff --git a/googletest/src/gtest-matchers.cc b/googletest/src/gtest-matchers.cc index 65104eba..7e3bcc0c 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 +#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 diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index d47550ae..73a1115a 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -27,61 +27,62 @@ // (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 #include #include #include + #include #include #include #if GTEST_OS_WINDOWS -# include -# include -# include -# include // Used in ThreadLocal. -# ifdef _MSC_VER -# include -# endif // _MSC_VER +#include +#include +#include + +#include // Used in ThreadLocal. +#ifdef _MSC_VER +#include +#endif // _MSC_VER #else -# include +#include #endif // GTEST_OS_WINDOWS #if GTEST_OS_MAC -# include -# include -# include +#include +#include +#include #endif // GTEST_OS_MAC #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ GTEST_OS_NETBSD || GTEST_OS_OPENBSD -# include -# if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD -# include -# endif +#include +#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD +#include +#endif #endif #if GTEST_OS_QNX -# include -# include -# include +#include +#include +#include #endif // GTEST_OS_QNX #if GTEST_OS_AIX -# include -# include +#include +#include #endif // GTEST_OS_AIX #if GTEST_OS_FUCHSIA -# include -# include +#include +#include #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" @@ -131,8 +132,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(thread_list), + vm_deallocate(task, reinterpret_cast(thread_list), sizeof(thread_t) * thread_count); return static_cast(thread_count); } else { @@ -141,7 +141,7 @@ size_t GetThreadCount() { } #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ - GTEST_OS_NETBSD + GTEST_OS_NETBSD #if GTEST_OS_NETBSD #undef KERN_PROC @@ -184,12 +184,12 @@ size_t GetThreadCount() { // we cannot detect it. size_t GetThreadCount() { int mib[] = { - CTL_KERN, - KERN_PROC, - KERN_PROC_PID | KERN_PROC_SHOW_THREADS, - getpid(), - sizeof(struct kinfo_proc), - 0, + CTL_KERN, + KERN_PROC, + KERN_PROC_PID | KERN_PROC_SHOW_THREADS, + getpid(), + sizeof(struct kinfo_proc), + 0, }; u_int miblen = sizeof(mib) / sizeof(mib[0]); @@ -210,8 +210,7 @@ size_t GetThreadCount() { // exclude empty members size_t nthreads = 0; for (size_t i = 0; i < size / static_cast(mib[4]); i++) { - if (info[i].p_tid != -1) - nthreads++; + if (info[i].p_tid != -1) nthreads++; } return nthreads; } @@ -254,13 +253,9 @@ size_t GetThreadCount() { size_t GetThreadCount() { int dummy_buffer; size_t avail; - zx_status_t status = zx_object_get_info( - zx_process_self(), - ZX_INFO_PROCESS_THREADS, - &dummy_buffer, - 0, - nullptr, - &avail); + zx_status_t status = + zx_object_get_info(zx_process_self(), ZX_INFO_PROCESS_THREADS, + &dummy_buffer, 0, nullptr, &avail); if (status == ZX_OK) { return avail; } else { @@ -280,23 +275,15 @@ size_t GetThreadCount() { #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS -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. @@ -308,7 +295,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."; } } @@ -370,8 +357,7 @@ 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); @@ -388,7 +374,8 @@ class MemoryIsNotDeallocated private: int old_crtdbg_flag_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated); + MemoryIsNotDeallocated(const MemoryIsNotDeallocated&) = delete; + MemoryIsNotDeallocated& operator=(const MemoryIsNotDeallocated&) = delete; }; #endif // _MSC_VER @@ -414,15 +401,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. @@ -467,9 +452,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_; // Does not own. Notification* thread_can_start_; @@ -487,20 +470,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) @@ -527,8 +508,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; @@ -556,9 +539,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); @@ -588,9 +570,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); @@ -616,9 +597,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. @@ -644,8 +624,7 @@ class ThreadLocalRegistryImpl { static DWORD WINAPI WatcherThreadFunc(LPVOID param) { const ThreadIdAndHandle* tah = reinterpret_cast(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; @@ -669,16 +648,17 @@ class ThreadLocalRegistryImpl { }; Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); // NOLINT -Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); // NOLINT +Mutex ThreadLocalRegistryImpl::thread_map_mutex_( + Mutex::kStaticMutex); // NOLINT ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( - const ThreadLocalBase* thread_local_instance) { + const ThreadLocalBase* thread_local_instance) { return ThreadLocalRegistryImpl::GetValueOnCurrentThread( thread_local_instance); } void ThreadLocalRegistry::OnThreadLocalDestroyed( - const ThreadLocalBase* thread_local_instance) { + const ThreadLocalBase* thread_local_instance) { ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); } @@ -766,7 +746,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. @@ -779,17 +759,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; } @@ -800,7 +791,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; @@ -842,12 +834,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; } @@ -865,12 +857,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(-1) - 1; + const size_t max_count = (repeat == '?') ? 1 : static_cast(-1) - 1; // We cannot call numeric_limits::max() as it conflicts with the // max() macro on Windows. @@ -883,8 +873,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; } @@ -898,25 +887,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); } } @@ -931,13 +918,11 @@ bool MatchRegexAtHead(const char* regex, const char* str) { bool MatchRegexAnywhere(const char* regex, const char* str) { if (regex == nullptr || str == nullptr) return false; - if (*regex == '^') - return MatchRegexAtHead(regex + 1, str); + if (*regex == '^') return MatchRegexAtHead(regex + 1, str); // A successful match can be anywhere in str. do { - if (MatchRegexAtHead(regex, str)) - return true; + if (MatchRegexAtHead(regex, str)) return true; } while (*str++ != '\0'); return false; } @@ -1018,8 +1003,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) @@ -1030,12 +1015,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. @@ -1058,27 +1044,26 @@ class CapturedStream { public: // The ctor redirects the stream to a temporary file. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { -# if GTEST_OS_WINDOWS - char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT - char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT +#if GTEST_OS_WINDOWS + char temp_dir_path[MAX_PATH + 1] = {'\0'}; // NOLINT + char temp_file_path[MAX_PATH + 1] = {'\0'}; // NOLINT ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); - const UINT success = ::GetTempFileNameA(temp_dir_path, - "gtest_redir", + const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, // Generate unique file name. temp_file_path); GTEST_CHECK_(success != 0) << "Unable to create a temporary file in " << temp_dir_path; const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); - GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " - << temp_file_path; + GTEST_CHECK_(captured_fd != -1) + << "Unable to open temporary file " << temp_file_path; filename_ = temp_file_path; -# else +#else // There's no guarantee that a test has write access to the current // directory, so we create the temporary file in a temporary directory. std::string name_template; -# if GTEST_OS_LINUX_ANDROID +#if GTEST_OS_LINUX_ANDROID // Note: Android applications are expected to call the framework's // Context.getExternalStorageDirectory() method through JNI to get // the location of the world-writable SD Card directory. However, @@ -1091,7 +1076,7 @@ class CapturedStream { // '/sdcard' and other variants cannot be relied on, as they are not // guaranteed to be mounted, or may have a delay in mounting. name_template = "/data/local/tmp/"; -# elif GTEST_OS_IOS +#elif GTEST_OS_IOS char user_temp_dir[PATH_MAX + 1]; // Documented alternative to NSTemporaryDirectory() (for obtaining creating @@ -1112,9 +1097,9 @@ class CapturedStream { name_template = user_temp_dir; if (name_template.back() != GTEST_PATH_SEP_[0]) name_template.push_back(GTEST_PATH_SEP_[0]); -# else +#else name_template = "/tmp/"; -# endif +#endif name_template.append("gtest_captured_stream.XXXXXX"); // mkstemp() modifies the string bytes in place, and does not go beyond the @@ -1130,15 +1115,13 @@ class CapturedStream { << " for test; does the test have access to the /tmp directory?"; } filename_ = std::move(name_template); -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS fflush(nullptr); dup2(captured_fd, fd_); close(captured_fd); } - ~CapturedStream() { - remove(filename_.c_str()); - } + ~CapturedStream() { remove(filename_.c_str()); } std::string GetCapturedString() { if (uncaptured_fd_ != -1) { @@ -1165,7 +1148,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_() @@ -1215,10 +1199,6 @@ std::string GetCapturedStderr() { #endif // GTEST_HAS_STREAM_REDIRECTION - - - - size_t GetFileSize(FILE* file) { fseek(file, 0, SEEK_END); return static_cast(ftell(file)); @@ -1236,7 +1216,8 @@ std::string ReadEntireFile(FILE* file) { // Keeps reading the file until we cannot read further or the // pre-determined file size is reached. do { - bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); + bytes_last_read = + fread(buffer + bytes_read, 1, file_size - bytes_read, file); bytes_read += bytes_last_read; } while (bytes_last_read > 0 && bytes_read < file_size); @@ -1324,7 +1305,7 @@ bool ParseInt32(const Message& src_text, const char* str, int32_t* value) { // LONG_MAX or LONG_MIN when the input overflows.) result != long_value // The parsed value overflows as an int32_t. - ) { + ) { Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" @@ -1368,8 +1349,8 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) { } int32_t result = default_value; - if (!ParseInt32(Message() << "Environment variable " << env_var, - string_value, &result)) { + if (!ParseInt32(Message() << "Environment variable " << env_var, string_value, + &result)) { printf("The default value %s is used.\n", (Message() << default_value).GetString().c_str()); fflush(stdout); @@ -1388,7 +1369,7 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) { // not check that the flag is 'output' // In essence this checks an env variable called XML_OUTPUT_FILE // and if it is set we prepend "xml:" to its value, if it not set we return "" -std::string OutputFlagAlsoCheckEnvVar(){ +std::string OutputFlagAlsoCheckEnvVar() { std::string default_value_for_output_flag = ""; const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE"); if (nullptr != xml_output_file_env) { diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc index 0c80ab7c..f3976d23 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 @@ -101,7 +100,7 @@ void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); *os << " ... "; // Rounds up to 2-byte boundary. - const size_t resume_pos = (count - kChunkSize + 1)/2*2; + const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2; PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); } *os << ">"; @@ -136,11 +135,7 @@ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, // - as is if it's a printable ASCII (e.g. 'a', '2', ' '), // - as a hexadecimal escape sequence (e.g. '\x7F'), or // - as a special escape sequence (e.g. '\r', '\n'). -enum CharFormat { - kAsIs, - kHexEscape, - kSpecialEscape -}; +enum CharFormat { kAsIs, kHexEscape, kSpecialEscape }; // Returns true if c is a printable ASCII character. We test the // value of c directly instead of calling isprint(), which is buggy on @@ -213,35 +208,21 @@ static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) { } } -static const char* GetCharWidthPrefix(char) { - return ""; -} +static const char* GetCharWidthPrefix(char) { return ""; } -static const char* GetCharWidthPrefix(signed char) { - return ""; -} +static const char* GetCharWidthPrefix(signed char) { return ""; } -static const char* GetCharWidthPrefix(unsigned char) { - return ""; -} +static const char* GetCharWidthPrefix(unsigned char) { return ""; } #ifdef __cpp_char8_t -static const char* GetCharWidthPrefix(char8_t) { - return "u8"; -} +static const char* GetCharWidthPrefix(char8_t) { return "u8"; } #endif -static const char* GetCharWidthPrefix(char16_t) { - return "u"; -} +static const char* GetCharWidthPrefix(char16_t) { return "u"; } -static const char* GetCharWidthPrefix(char32_t) { - return "U"; -} +static const char* GetCharWidthPrefix(char32_t) { return "U"; } -static const char* GetCharWidthPrefix(wchar_t) { - return "L"; -} +static const char* GetCharWidthPrefix(wchar_t) { return "L"; } // Prints a char c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. @@ -276,8 +257,7 @@ void PrintCharAndCodeTo(Char c, ostream* os) { // To aid user debugging, we also print c's code in decimal, unless // it's 0 (in which case c was printed as '\\0', making the code // obvious). - if (c == 0) - return; + if (c == 0) return; *os << " (" << static_cast(c); // For more convenience, we print c's code again in hexadecimal, @@ -354,12 +334,10 @@ void PrintTo(__int128_t v, ::std::ostream* os) { // The array starts at begin, the length is len, it may include '\0' characters // and may not be NUL-terminated. template -GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -static CharFormat PrintCharsAsStringTo( - const CharType* begin, size_t len, ostream* os) { +GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ + GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ + GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static CharFormat + PrintCharsAsStringTo(const CharType* begin, size_t len, ostream* os) { const char* const quote_prefix = GetCharWidthPrefix(*begin); *os << quote_prefix << "\""; bool is_previous_hex = false; @@ -385,12 +363,11 @@ static CharFormat PrintCharsAsStringTo( // Prints a (const) char/wchar_t array of 'len' elements, starting at address // 'begin'. CharType must be either char or wchar_t. template -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'. @@ -481,28 +458,28 @@ void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); } namespace { bool ContainsUnprintableControlCodes(const char* str, size_t length) { - const unsigned char *s = reinterpret_cast(str); + const unsigned char* s = reinterpret_cast(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(str); + const unsigned char* s = reinterpret_cast(str); for (size_t i = 0; i < length;) { unsigned char lead = s[i++]; @@ -515,15 +492,13 @@ bool IsValidUTF8(const char* str, size_t length) { } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) { ++i; // 2-byte character } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length && - IsUTF8TrailByte(s[i]) && - IsUTF8TrailByte(s[i + 1]) && + IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) && // check for non-shortest form and surrogate (lead != 0xe0 || s[i] >= 0xa0) && (lead != 0xed || s[i] < 0xa0)) { i += 2; // 3-byte character } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length && - IsUTF8TrailByte(s[i]) && - IsUTF8TrailByte(s[i + 1]) && + IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) && IsUTF8TrailByte(s[i + 2]) && // check for non-shortest form (lead != 0xf0 || s[i] >= 0x90) && diff --git a/googletest/src/gtest-test-part.cc b/googletest/src/gtest-test-part.cc index a938683c..eb7c8d1c 100644 --- a/googletest/src/gtest-test-part.cc +++ b/googletest/src/gtest-test-part.cc @@ -51,13 +51,11 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { return os << internal::FormatFileLocation(result.file_name(), result.line_number()) << " " - << (result.type() == TestPartResult::kSuccess - ? "Success" - : result.type() == TestPartResult::kSkip - ? "Skipped" - : result.type() == TestPartResult::kFatalFailure - ? "Fatal failure" - : "Non-fatal failure") + << (result.type() == TestPartResult::kSuccess ? "Success" + : result.type() == TestPartResult::kSkip ? "Skipped" + : result.type() == TestPartResult::kFatalFailure + ? "Fatal failure" + : "Non-fatal failure") << ":\n" << result.message() << std::endl; } @@ -86,8 +84,8 @@ namespace internal { HasNewFatalFailureHelper::HasNewFatalFailureHelper() : has_new_fatal_failure_(false), - original_reporter_(GetUnitTestImpl()-> - GetTestPartResultReporterForCurrentThread()) { + original_reporter_( + GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) { GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); } @@ -98,8 +96,7 @@ HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { void HasNewFatalFailureHelper::ReportTestPartResult( const TestPartResult& result) { - if (result.fatally_failed()) - has_new_fatal_failure_ = true; + if (result.fatally_failed()) has_new_fatal_failure_ = true; original_reporter_->ReportTestPartResult(result); } diff --git a/googletest/src/gtest-typed-test.cc b/googletest/src/gtest-typed-test.cc index c02c3df6..a2828b83 100644 --- a/googletest/src/gtest-typed-test.cc +++ b/googletest/src/gtest-typed-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-typed-test.h" #include "gtest/gtest.h" @@ -38,8 +37,7 @@ namespace internal { // Skips to the first non-space char in str. Returns an empty string if str // contains only whitespace characters. static const char* SkipSpaces(const char* str) { - while (IsSpace(*str)) - str++; + while (IsSpace(*str)) str++; return str; } @@ -85,8 +83,7 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames( } for (RegisteredTestIter it = registered_tests_.begin(); - it != registered_tests_.end(); - ++it) { + it != registered_tests_.end(); ++it) { if (tests.count(it->first) == 0) { errors << "You forgot to list test " << it->first << ".\n"; } diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index de774eb6..509a3de9 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -44,6 +44,7 @@ #include // NOLINT #include #include +#include #include #include #include @@ -60,69 +61,70 @@ #if GTEST_OS_LINUX -# include // NOLINT -# include // NOLINT -# include // NOLINT +#include // NOLINT +#include // NOLINT +#include // NOLINT // Declares vsnprintf(). This header is not available on Windows. -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include +#include // NOLINT +#include // NOLINT +#include // NOLINT +#include // NOLINT + +#include #elif GTEST_OS_ZOS -# include // NOLINT +#include // NOLINT // On z/OS we additionally need strings.h for strcasecmp. -# include // NOLINT +#include // NOLINT #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. -# include // NOLINT -# undef min +#include // NOLINT +#undef min #elif GTEST_OS_WINDOWS // We are on Windows proper. -# include // NOLINT -# undef min +#include // NOLINT +#undef min #ifdef _MSC_VER -# include // NOLINT +#include // NOLINT #endif -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT +#include // NOLINT +#include // NOLINT +#include // NOLINT +#include // NOLINT -# if GTEST_OS_WINDOWS_MINGW -# include // NOLINT -# endif // GTEST_OS_WINDOWS_MINGW +#if GTEST_OS_WINDOWS_MINGW +#include // NOLINT +#endif // GTEST_OS_WINDOWS_MINGW #else // cpplint thinks that the header is already included, so we want to // silence it. -# include // NOLINT -# include // NOLINT +#include // NOLINT +#include // NOLINT #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS -# include +#include #endif #if GTEST_CAN_STREAM_RESULTS_ -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT +#include // NOLINT +#include // NOLINT +#include // NOLINT +#include // NOLINT #endif #include "src/gtest-internal-inl.h" #if GTEST_OS_WINDOWS -# define vsnprintf _vsnprintf +#define vsnprintf _vsnprintf #endif // GTEST_OS_WINDOWS #if GTEST_OS_MAC @@ -135,7 +137,10 @@ #include "absl/debugging/failure_signal_handler.h" #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" +#include "absl/flags/parse.h" +#include "absl/flags/usage.h" #include "absl/strings/str_cat.h" +#include "absl/strings/str_replace.h" #endif // GTEST_HAS_ABSL namespace testing { @@ -271,8 +276,7 @@ GTEST_DEFINE_bool_( "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 @@ -374,10 +378,9 @@ namespace internal { uint32_t Random::Generate(uint32_t range) { // These constants are the same as are used in glibc's rand(3). // Use wider types than necessary to prevent unsigned overflow diagnostics. - state_ = static_cast(1103515245ULL*state_ + 12345U) % kMaxRange; + state_ = static_cast(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 << ")."; @@ -422,26 +425,20 @@ 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 { @@ -478,7 +475,6 @@ class FailureTest : public Test { const bool as_error_; }; - } // namespace std::set* GetIgnoredParameterizedTestSuites() { @@ -522,7 +518,8 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location, "To suppress this error for this test suite, insert the following line " "(in a non-header) in the namespace it is defined in:" "\n\n" - "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");"; + "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + + name + ");"; std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">"; RegisterTest( // @@ -542,19 +539,18 @@ void RegisterTypeParameterizedTestSuite(const char* test_suite_name, } void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { - GetUnitTestImpl() - ->type_parameterized_test_registry() - .RegisterInstantiation(case_name); + GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation( + case_name); } void TypeParameterizedTestSuiteRegistry::RegisterTestSuite( const char* test_suite_name, CodeLocation code_location) { suites_.emplace(std::string(test_suite_name), - TypeParameterizedTestSuiteInfo(code_location)); + TypeParameterizedTestSuiteInfo(code_location)); } void TypeParameterizedTestSuiteRegistry::RegisterInstantiation( - const char* test_suite_name) { + const char* test_suite_name) { auto it = suites_.find(std::string(test_suite_name)); if (it != suites_.end()) { it->second.instantiated = true; @@ -648,16 +644,15 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { 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()) @@ -665,8 +660,7 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { internal::FilePath(UnitTest::GetInstance()->original_working_dir()), internal::FilePath(colon + 1)); - if (!output_name.IsDirectory()) - return output_name.string(); + if (!output_name.IsDirectory()) return output_name.string(); internal::FilePath result(internal::FilePath::GenerateUniqueFileName( output_name, internal::GetCurrentExecutableName(), @@ -877,8 +871,7 @@ int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { // results. Intercepts only failures from the current thread. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( TestPartResultArray* result) - : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), - result_(result) { + : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) { Init(); } @@ -887,8 +880,7 @@ ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( // results. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( InterceptMode intercept_mode, TestPartResultArray* result) - : intercept_mode_(intercept_mode), - result_(result) { + : intercept_mode_(intercept_mode), result_(result) { Init(); } @@ -932,9 +924,7 @@ namespace internal { // from user test code. GetTestTypeId() is guaranteed to always // return the same value, as it always calls GetTypeId<>() from the // gtest.cc, which is within the Google Test framework. -TypeId GetTestTypeId() { - return GetTypeId(); -} +TypeId GetTestTypeId() { return GetTypeId(); } // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). @@ -949,9 +939,9 @@ static AssertionResult HasOneFailure(const char* /* results_expr */, const TestPartResultArray& results, TestPartResult::Type type, const std::string& substr) { - const std::string expected(type == TestPartResult::kFatalFailure ? - "1 fatal failure" : - "1 non-fatal failure"); + const std::string expected(type == TestPartResult::kFatalFailure + ? "1 fatal failure" + : "1 non-fatal failure"); Message msg; if (results.size() != 1) { msg << "Expected: " << expected << "\n" @@ -970,10 +960,10 @@ static AssertionResult HasOneFailure(const char* /* results_expr */, } if (strstr(r.message(), substr.c_str()) == nullptr) { - return AssertionFailure() << "Expected: " << expected << " containing \"" - << substr << "\"\n" - << " Actual:\n" - << r; + return AssertionFailure() + << "Expected: " << expected << " containing \"" << substr << "\"\n" + << " Actual:\n" + << r; } return AssertionSuccess(); @@ -996,7 +986,8 @@ SingleFailureChecker::~SingleFailureChecker() { } DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( - UnitTestImpl* unit_test) : unit_test_(unit_test) {} + UnitTestImpl* unit_test) + : unit_test_(unit_test) {} void DefaultGlobalTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { @@ -1005,7 +996,8 @@ void DefaultGlobalTestPartResultReporter::ReportTestPartResult( } DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( - UnitTestImpl* unit_test) : unit_test_(unit_test) {} + UnitTestImpl* unit_test) + : unit_test_(unit_test) {} void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { @@ -1159,8 +1151,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) { const int unicode_length = MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0); WCHAR* unicode = new WCHAR[unicode_length + 1]; - MultiByteToWideChar(CP_ACP, 0, ansi, length, - unicode, unicode_length); + MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length); unicode[unicode_length] = 0; return unicode; } @@ -1169,7 +1160,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) { // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the ANSI string, or NULL if the // input is NULL. -const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { +const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { if (!utf16_str) return nullptr; const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr, 0, nullptr, nullptr); @@ -1188,7 +1179,7 @@ const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { // Unlike strcmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. -bool String::CStringEquals(const char * lhs, const char * rhs) { +bool String::CStringEquals(const char* lhs, const char* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; @@ -1202,11 +1193,10 @@ bool String::CStringEquals(const char * lhs, const char * rhs) { // encoding, and streams the result to the given Message object. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, Message* msg) { - for (size_t i = 0; i != length; ) { // NOLINT + for (size_t i = 0; i != length;) { // NOLINT if (wstr[i] != L'\0') { *msg << WideStringToUtf8(wstr + i, static_cast(length - i)); - while (i != length && wstr[i] != L'\0') - i++; + while (i != length && wstr[i] != L'\0') i++; } else { *msg << '\0'; i++; @@ -1248,17 +1238,17 @@ Message::Message() : ss_(new ::std::stringstream) { // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. -Message& Message::operator <<(const wchar_t* wide_c_str) { +Message& Message::operator<<(const wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } -Message& Message::operator <<(wchar_t* wide_c_str) { +Message& Message::operator<<(wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. -Message& Message::operator <<(const ::std::wstring& wstr) { +Message& Message::operator<<(const ::std::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } @@ -1561,8 +1551,7 @@ std::vector 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; @@ -1579,10 +1568,8 @@ AssertionResult EqFailure(const char* lhs_expression, } if (!lhs_value.empty() && !rhs_value.empty()) { - const std::vector lhs_lines = - SplitEscapedString(lhs_value); - const std::vector rhs_lines = - SplitEscapedString(rhs_value); + const std::vector lhs_lines = SplitEscapedString(lhs_value); + const std::vector 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); @@ -1594,27 +1581,21 @@ AssertionResult EqFailure(const char* lhs_expression, // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. std::string GetBoolAssertionFailureMessage( - const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value) { + const AssertionResult& assertion_result, const char* expression_text, + const char* actual_predicate_value, const char* expected_predicate_value) { const char* actual_message = assertion_result.message(); Message msg; msg << "Value of: " << expression_text << "\n Actual: " << actual_predicate_value; - if (actual_message[0] != '\0') - msg << " (" << actual_message << ")"; + if (actual_message[0] != '\0') msg << " (" << actual_message << ")"; msg << "\nExpected: " << expected_predicate_value; return msg.GetString(); } // Helper function for implementing ASSERT_NEAR. -AssertionResult DoubleNearPredFormat(const char* expr1, - const char* expr2, - const char* abs_error_expr, - double val1, - double val2, - double abs_error) { +AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, + const char* abs_error_expr, double val1, + double val2, double abs_error) { const double diff = fabs(val1 - val2); if (diff <= abs_error) return AssertionSuccess(); @@ -1644,20 +1625,17 @@ AssertionResult DoubleNearPredFormat(const char* expr1, "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead."; } return AssertionFailure() - << "The difference between " << expr1 << " and " << expr2 - << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" - << expr1 << " evaluates to " << val1 << ",\n" - << expr2 << " evaluates to " << val2 << ", and\n" - << abs_error_expr << " evaluates to " << abs_error << "."; + << "The difference between " << expr1 << " and " << expr2 << " is " + << diff << ", which exceeds " << abs_error_expr << ", where\n" + << expr1 << " evaluates to " << val1 << ",\n" + << expr2 << " evaluates to " << val2 << ", and\n" + << abs_error_expr << " evaluates to " << abs_error << "."; } - // Helper template for implementing FloatLE() and DoubleLE(). template -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(); @@ -1682,24 +1660,24 @@ AssertionResult FloatingPointLE(const char* expr1, << val2; return AssertionFailure() - << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" - << " Actual: " << StringStreamToString(&val1_ss) << " vs " - << StringStreamToString(&val2_ss); + << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" + << " Actual: " << StringStreamToString(&val1_ss) << " vs " + << StringStreamToString(&val2_ss); } } // namespace internal // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. -AssertionResult FloatLE(const char* expr1, const char* expr2, - float val1, float val2) { +AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, + float val2) { return internal::FloatingPointLE(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(expr1, expr2, val1, val2); } @@ -1707,62 +1685,51 @@ namespace internal { // The helper function for {ASSERT|EXPECT}_STREQ. AssertionResult CmpHelperSTREQ(const char* lhs_expression, - const char* rhs_expression, - const char* lhs, + const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - false); + return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), + PrintToString(rhs), false); } // The helper function for {ASSERT|EXPECT}_STRCASEEQ. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, - const char* rhs_expression, - const char* lhs, + const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - true); + return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), + PrintToString(rhs), true); } // The helper function for {ASSERT|EXPECT}_STRNE. AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const char* s1, + const char* s2_expression, const char* s1, const char* s2) { if (!String::CStringEquals(s1, s2)) { return AssertionSuccess(); } else { - return AssertionFailure() << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: \"" - << s1 << "\" vs \"" << s2 << "\""; + return AssertionFailure() + << "Expected: (" << s1_expression << ") != (" << s2_expression + << "), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } // The helper function for {ASSERT|EXPECT}_STRCASENE. AssertionResult CmpHelperSTRCASENE(const char* s1_expression, - const char* s2_expression, - const char* s1, + const char* s2_expression, const char* s1, const char* s2) { if (!String::CaseInsensitiveCStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() - << "Expected: (" << s1_expression << ") != (" - << s2_expression << ") (ignoring case), actual: \"" - << s1 << "\" vs \"" << s2 << "\""; + << "Expected: (" << s1_expression << ") != (" << s2_expression + << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } @@ -1790,8 +1757,7 @@ bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { // StringType here can be either ::std::string or ::std::wstring. template -bool IsSubstringPred(const StringType& needle, - const StringType& haystack) { +bool IsSubstringPred(const StringType& needle, const StringType& haystack) { return haystack.find(needle) != StringType::npos; } @@ -1800,21 +1766,22 @@ bool IsSubstringPred(const StringType& needle, // StringType here can be const char*, const wchar_t*, ::std::string, // or ::std::wstring. template -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 @@ -1823,52 +1790,52 @@ AssertionResult IsSubstringImpl( // substring of haystack (NULL is considered a substring of itself // only), and return an appropriate error message when they fail. -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, const char* needle, + const char* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, const wchar_t* needle, + const wchar_t* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, + const ::std::string& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::string& needle, + const ::std::string& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #if GTEST_HAS_STD_WSTRING -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, + const ::std::wstring& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::wstring& needle, + const ::std::wstring& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #endif // GTEST_HAS_STD_WSTRING @@ -1880,43 +1847,42 @@ namespace internal { namespace { // Helper function for IsHRESULT{SuccessFailure} predicates -AssertionResult HRESULTFailureHelper(const char* expr, - const char* expected, +AssertionResult HRESULTFailureHelper(const char* expr, const char* expected, long hr) { // NOLINT -# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE // Windows CE doesn't support FormatMessage. const char error_text[] = ""; -# else +#else // Looks up the human-readable system message for the HRESULT code // and since we're not passing any params to FormatMessage, we don't // want inserts expanded. - const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS; + const DWORD kFlags = + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; const DWORD kBufSize = 4096; // Gets the system's human readable message string for this HRESULT. - char error_text[kBufSize] = { '\0' }; + char error_text[kBufSize] = {'\0'}; DWORD message_length = ::FormatMessageA(kFlags, - 0, // no source, we're asking system + 0, // no source, we're asking system static_cast(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 @@ -1950,16 +1916,18 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // The maximum code-point a one-byte UTF-8 sequence can represent. -constexpr uint32_t kMaxCodePoint1 = (static_cast(1) << 7) - 1; +constexpr uint32_t kMaxCodePoint1 = (static_cast(1) << 7) - 1; // The maximum code-point a two-byte UTF-8 sequence can represent. constexpr uint32_t kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1; // The maximum code-point a three-byte UTF-8 sequence can represent. -constexpr uint32_t kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1; +constexpr uint32_t kMaxCodePoint3 = + (static_cast(1) << (4 + 2 * 6)) - 1; // The maximum code-point a four-byte UTF-8 sequence can represent. -constexpr uint32_t kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1; +constexpr uint32_t kMaxCodePoint4 = + (static_cast(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 @@ -1984,7 +1952,7 @@ std::string CodePointToUtf8(uint32_t code_point) { char str[5]; // Big enough for the largest valid code point. if (code_point <= kMaxCodePoint1) { str[1] = '\0'; - str[0] = static_cast(code_point); // 0xxxxxxx + str[0] = static_cast(code_point); // 0xxxxxxx } else if (code_point <= kMaxCodePoint2) { str[2] = '\0'; str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx @@ -2012,8 +1980,8 @@ std::string CodePointToUtf8(uint32_t code_point) { // and thus should be combined into a single Unicode code point // using CreateCodePointFromUtf16SurrogatePair. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { - return sizeof(wchar_t) == 2 && - (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; + return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 && + (second & 0xFC00) == 0xDC00; } // Creates a Unicode code point from UTF16 surrogate pair. @@ -2044,8 +2012,7 @@ inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. std::string WideStringToUtf8(const wchar_t* str, int num_chars) { - if (num_chars == -1) - num_chars = static_cast(wcslen(str)); + if (num_chars == -1) num_chars = static_cast(wcslen(str)); ::std::stringstream stream; for (int i = 0; i < num_chars; ++i) { @@ -2054,8 +2021,8 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { if (str[i] == L'\0') { break; } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { - unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], - str[i + 1]); + unicode_code_point = + CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]); i++; } else { unicode_code_point = static_cast(str[i]); @@ -2068,7 +2035,7 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { // Converts a wide C string to an std::string using the UTF-8 encoding. // NULL will be converted to "(null)". -std::string String::ShowWideCString(const wchar_t * wide_c_str) { +std::string String::ShowWideCString(const wchar_t* wide_c_str) { if (wide_c_str == nullptr) return "(null)"; return internal::WideStringToUtf8(wide_c_str, -1); @@ -2080,7 +2047,7 @@ std::string String::ShowWideCString(const wchar_t * wide_c_str) { // Unlike wcscmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. -bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { +bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; @@ -2090,33 +2057,27 @@ bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { // Helper function for *_STREQ on wide strings. AssertionResult CmpHelperSTREQ(const char* lhs_expression, - const char* rhs_expression, - const wchar_t* lhs, + const char* rhs_expression, const wchar_t* lhs, const wchar_t* rhs) { if (String::WideCStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - false); + return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), + PrintToString(rhs), false); } // Helper function for *_STRNE on wide strings. AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, + const char* s2_expression, const wchar_t* s1, const wchar_t* s2) { if (!String::WideCStringEquals(s1, s2)) { return AssertionSuccess(); } - return AssertionFailure() << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: " - << PrintToString(s1) - << " vs " << PrintToString(s2); + return AssertionFailure() + << "Expected: (" << s1_expression << ") != (" << s2_expression + << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2); } // Compares two C strings, ignoring case. Returns true if and only if they have @@ -2125,7 +2086,7 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, // Unlike strcasecmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. -bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { +bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; return posix::StrCaseCmp(lhs, rhs) == 0; @@ -2167,8 +2128,8 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, // Returns true if and only if str ends with the given suffix, ignoring case. // Any string is considered to end with an empty suffix. -bool String::EndsWithCaseInsensitive( - const std::string& str, const std::string& suffix) { +bool String::EndsWithCaseInsensitive(const std::string& str, + const std::string& suffix) { const size_t str_len = str.length(); const size_t suffix_len = suffix.length(); return (str_len >= suffix_len) && @@ -2251,15 +2212,13 @@ TestResult::TestResult() : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {} // D'tor. -TestResult::~TestResult() { -} +TestResult::~TestResult() {} // Returns the i-th test part result among all the results. i can // range from 0 to total_part_count() - 1. If i is not in that range, // aborts the program. const TestPartResult& TestResult::GetTestPartResult(int i) const { - if (i < 0 || i >= total_part_count()) - internal::posix::Abort(); + if (i < 0 || i >= total_part_count()) internal::posix::Abort(); return test_part_results_.at(static_cast(i)); } @@ -2267,15 +2226,12 @@ const TestPartResult& TestResult::GetTestPartResult(int i) const { // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& TestResult::GetTestProperty(int i) const { - if (i < 0 || i >= test_property_count()) - internal::posix::Abort(); + if (i < 0 || i >= test_property_count()) internal::posix::Abort(); return test_properties_.at(static_cast(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) { @@ -2304,15 +2260,8 @@ void TestResult::RecordProperty(const std::string& xml_element, // The list of reserved attributes used in the 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 element of XML // output. @@ -2322,8 +2271,8 @@ static const char* const kReservedTestSuiteAttributes[] = { // The list of reserved attributes used in the 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") @@ -2385,7 +2334,7 @@ static bool ValidateTestPropertyName( const std::string& property_name, const std::vector& 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_ << ")"; @@ -2423,8 +2372,7 @@ bool TestResult::Skipped() const { // Returns true if and only if the test failed. bool TestResult::Failed() const { for (int i = 0; i < total_part_count(); ++i) { - if (GetTestPartResult(i).failed()) - return true; + if (GetTestPartResult(i).failed()) return true; } return false; } @@ -2465,27 +2413,22 @@ int TestResult::test_property_count() const { // Creates a Test object. // The c'tor saves the states of all flags. -Test::Test() - : gtest_flag_saver_(new GTEST_FLAG_SAVER_) { -} +Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {} // The d'tor restores the states of all flags. The actual work is // done by the d'tor of the gtest_flag_saver_ field, and thus not // visible here. -Test::~Test() { -} +Test::~Test() {} // Sets up the test fixture. // // A sub-class may override this. -void Test::SetUp() { -} +void Test::SetUp() {} // Tears down the test fixture. // // A sub-class may override this. -void Test::TearDown() { -} +void Test::TearDown() {} // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const std::string& key, const std::string& value) { @@ -2590,8 +2533,8 @@ bool Test::HasSameFixtureClass() { static std::string* FormatSehExceptionMessage(DWORD exception_code, const char* location) { Message message; - message << "SEH exception with code 0x" << std::setbase(16) << - exception_code << std::setbase(10) << " thrown in " << location << "."; + message << "SEH exception with code 0x" << std::setbase(16) << exception_code + << std::setbase(10) << " thrown in " << location << "."; return new std::string(message.GetString()); } @@ -2634,8 +2577,8 @@ GoogleTestFailureException::GoogleTestFailureException( // exceptions in the same function. Therefore, we provide a separate // wrapper function for handling SEH exceptions.) template -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)(); @@ -2644,8 +2587,8 @@ Result HandleSehExceptionsInMethodIfSupported( // We create the exception message on the heap because VC++ prohibits // creation of objects with destructors on stack in functions using __try // (see error C2712). - std::string* exception_message = FormatSehExceptionMessage( - GetExceptionCode(), location); + std::string* exception_message = + FormatSehExceptionMessage(GetExceptionCode(), location); internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, *exception_message); delete exception_message; @@ -2661,8 +2604,8 @@ Result HandleSehExceptionsInMethodIfSupported( // exceptions, if they are supported; returns the 0-value for type // Result in case of an SEH exception. template -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 @@ -2728,16 +2671,16 @@ void Test::Run() { // GTEST_SKIP(). if (!HasFatalFailure() && !IsSkipped()) { impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &Test::TestBody, "the test body"); + internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody, + "the test body"); } // However, we want to clean up as much as possible. Hence we will // always call TearDown(), even if SetUp() or the test body has // failed. impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &Test::TearDown, "TearDown()"); + internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown, + "TearDown()"); } // Returns true if and only if the current test has a fatal failure. @@ -2747,8 +2690,9 @@ bool Test::HasFatalFailure() { // Returns true if and only if the current test has a non-fatal failure. bool Test::HasNonfatalFailure() { - return internal::GetUnitTestImpl()->current_test_result()-> - HasNonfatalFailure(); + return internal::GetUnitTestImpl() + ->current_test_result() + ->HasNonfatalFailure(); } // Returns true if and only if the current test was skipped. @@ -2848,11 +2792,10 @@ class TestNameIs { // Constructor. // // TestNameIs has NO default constructor. - explicit TestNameIs(const char* name) - : name_(name) {} + explicit TestNameIs(const char* name) : name_(name) {} // Returns true if and only if the test name of test_info matches name_. - bool operator()(const TestInfo * test_info) const { + bool operator()(const TestInfo* test_info) const { return test_info && test_info->name() == name_; } @@ -2882,7 +2825,7 @@ void UnitTestImpl::RegisterParameterizedTests() { void TestInfo::Run() { TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); if (!should_run_) { - if (is_disabled_) repeater->OnTestDisabled(*this); + if (is_disabled_ && matches_filter_) repeater->OnTestDisabled(*this); return; } @@ -3145,11 +3088,10 @@ void TestSuite::UnshuffleTests() { // // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(5, "book", "books") returns "5 books". -static std::string FormatCountableNoun(int count, - const char * singular_form, - const char * plural_form) { +static std::string FormatCountableNoun(int count, const char* singular_form, + const char* plural_form) { return internal::StreamableToString(count) + " " + - (count == 1 ? singular_form : plural_form); + (count == 1 ? singular_form : plural_form); } // Formats the count of tests. @@ -3166,7 +3108,7 @@ static std::string FormatTestSuiteCount(int test_suite_count) { // representation. Both kNonFatalFailure and kFatalFailure are translated // to "Failure", as the user usually doesn't care about the difference // between the two when viewing the test result. -static const char * TestPartResultTypeToString(TestPartResult::Type type) { +static const char* TestPartResultTypeToString(TestPartResult::Type type) { switch (type) { case TestPartResult::kSkip: return "Skipped\n"; @@ -3193,17 +3135,18 @@ enum class GTestColor { kDefault, kRed, kGreen, kYellow }; // Prints a TestPartResult to an std::string. static std::string PrintTestPartResultToString( const TestPartResult& test_part_result) { - return (Message() - << internal::FormatFileLocation(test_part_result.file_name(), - test_part_result.line_number()) - << " " << TestPartResultTypeToString(test_part_result.type()) - << test_part_result.message()).GetString(); + return (Message() << internal::FormatFileLocation( + test_part_result.file_name(), + test_part_result.line_number()) + << " " + << TestPartResultTypeToString(test_part_result.type()) + << test_part_result.message()) + .GetString(); } // Prints a TestPartResult. static void PrintTestPartResult(const TestPartResult& test_part_result) { - const std::string& result = - PrintTestPartResultToString(test_part_result); + const std::string& result = PrintTestPartResultToString(test_part_result); printf("%s\n", result.c_str()); fflush(stdout); // If the test program runs in Visual Studio or a debugger, the @@ -3220,8 +3163,8 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) { } // class PrettyUnitTestResultPrinter -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ - !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \ + !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW // Returns the character attribute for the given color. static WORD GetColorAttribute(GTestColor color) { @@ -3232,7 +3175,8 @@ static WORD GetColorAttribute(GTestColor color) { return FOREGROUND_GREEN; case GTestColor::kYellow: return FOREGROUND_RED | FOREGROUND_GREEN; - default: return 0; + default: + return 0; } } @@ -3318,9 +3262,9 @@ bool ShouldUseColor(bool stdout_is_tty) { } return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || - String::CaseInsensitiveCStringEquals(gtest_color, "true") || - String::CaseInsensitiveCStringEquals(gtest_color, "t") || - String::CStringEquals(gtest_color, "1"); + String::CaseInsensitiveCStringEquals(gtest_color, "true") || + String::CaseInsensitiveCStringEquals(gtest_color, "t") || + String::CStringEquals(gtest_color, "1"); // We take "yes", "true", "t", and "1" as meaning "yes". If the // value is neither one of these nor "auto", we treat it as "no" to // be conservative. @@ -3332,7 +3276,7 @@ bool ShouldUseColor(bool stdout_is_tty) { // that would be colored when printed, as can be done on Linux. GTEST_ATTRIBUTE_PRINTF_(2, 3) -static void ColoredPrintf(GTestColor color, const char *fmt, ...) { +static void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_list args; va_start(args, fmt); @@ -3351,8 +3295,8 @@ static void ColoredPrintf(GTestColor color, const char *fmt, ...) { return; } -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ - !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \ + !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); // Gets the current text color. @@ -3444,7 +3388,7 @@ class PrettyUnitTestResultPrinter : public TestEventListener { static void PrintSkippedTests(const UnitTest& unit_test); }; - // Fired before each iteration of tests starts. +// Fired before each iteration of tests starts. void PrettyUnitTestResultPrinter::OnTestIterationStart( const UnitTest& unit_test, int iteration) { if (GTEST_FLAG_GET(repeat) != 1) @@ -3560,12 +3504,12 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); } PrintTestName(test_info.test_suite_name(), test_info.name()); - if (test_info.result()->Failed()) - PrintFullTestCommentIfPresent(test_info); + if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info); if (GTEST_FLAG_GET(print_time)) { - printf(" (%s ms)\n", internal::StreamableToString( - test_info.result()->elapsed_time()).c_str()); + printf(" (%s ms)\n", + internal::StreamableToString(test_info.result()->elapsed_time()) + .c_str()); } else { printf("\n"); } @@ -3833,7 +3777,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 @@ -3871,18 +3815,19 @@ class TestEventRepeater : public TestEventListener { // The list of listeners that receive events. std::vector listeners_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); + TestEventRepeater(const TestEventRepeater&) = delete; + TestEventRepeater& operator=(const TestEventRepeater&) = delete; }; TestEventRepeater::~TestEventRepeater() { ForEach(listeners_, Delete); } -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(i)); @@ -3895,14 +3840,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) \ @@ -4049,7 +3994,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. @@ -4089,8 +4035,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) { @@ -4197,12 +4143,12 @@ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { return ""; // YYYY-MM-DDThh:mm:ss.sss return StreamableToString(time_struct.tm_year + 1900) + "-" + - String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + - String::FormatIntWidth2(time_struct.tm_mday) + "T" + - String::FormatIntWidth2(time_struct.tm_hour) + ":" + - String::FormatIntWidth2(time_struct.tm_min) + ":" + - String::FormatIntWidth2(time_struct.tm_sec) + "." + - String::FormatIntWidthN(static_cast(ms % 1000), 3); + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + + String::FormatIntWidth2(time_struct.tm_mday) + "T" + + String::FormatIntWidth2(time_struct.tm_hour) + ":" + + String::FormatIntWidth2(time_struct.tm_min) + ":" + + String::FormatIntWidth2(time_struct.tm_sec) + "." + + String::FormatIntWidthN(static_cast(ms % 1000), 3); } // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. @@ -4213,8 +4159,8 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, for (;;) { const char* const next_segment = strstr(segment, "]]>"); if (next_segment != nullptr) { - stream->write( - segment, static_cast(next_segment - segment)); + stream->write(segment, + static_cast(next_segment - segment)); *stream << "]]>]]>"); } else { @@ -4226,15 +4172,13 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, } void XmlUnitTestResultPrinter::OutputXmlAttribute( - std::ostream* stream, - const std::string& element_name, - const std::string& name, - const std::string& value) { + std::ostream* stream, const std::string& element_name, + const std::string& name, const std::string& value) { const std::vector& 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 << ">."; @@ -4300,10 +4244,11 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, OutputXmlAttribute(stream, kTestsuite, "type_param", test_info.type_param()); } + + OutputXmlAttribute(stream, kTestsuite, "file", test_info.file()); + OutputXmlAttribute(stream, kTestsuite, "line", + StreamableToString(test_info.line())); if (GTEST_FLAG_GET(list_tests)) { - OutputXmlAttribute(stream, kTestsuite, "file", test_info.file()); - OutputXmlAttribute(stream, kTestsuite, "line", - StreamableToString(test_info.line())); *stream << " />\n"; return; } @@ -4338,8 +4283,7 @@ void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream, internal::FormatCompilerIndependentFileLocation(part.file_name(), part.line_number()); const std::string summary = location + "\n" + part.summary(); - *stream << " "; const std::string detail = location + "\n" + part.message(); OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); @@ -4480,7 +4424,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(); } @@ -4526,16 +4470,12 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener { //// streams the attribute as JSON. static void OutputJsonKey(std::ostream* stream, const std::string& element_name, - const std::string& name, - const std::string& value, - const std::string& indent, - bool comma = true); + const std::string& name, const std::string& value, + const std::string& indent, bool comma = true); static void OutputJsonKey(std::ostream* stream, const std::string& element_name, - const std::string& name, - int value, - const std::string& indent, - bool comma = true); + const std::string& name, int value, + const std::string& indent, bool comma = true); // Streams a test suite JSON stanza containing the given test result. // @@ -4568,7 +4508,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. @@ -4580,7 +4522,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); @@ -4646,55 +4588,48 @@ static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) { return ""; // YYYY-MM-DDThh:mm:ss return StreamableToString(time_struct.tm_year + 1900) + "-" + - String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + - String::FormatIntWidth2(time_struct.tm_mday) + "T" + - String::FormatIntWidth2(time_struct.tm_hour) + ":" + - String::FormatIntWidth2(time_struct.tm_min) + ":" + - String::FormatIntWidth2(time_struct.tm_sec) + "Z"; + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + + String::FormatIntWidth2(time_struct.tm_mday) + "T" + + String::FormatIntWidth2(time_struct.tm_hour) + ":" + + String::FormatIntWidth2(time_struct.tm_min) + ":" + + String::FormatIntWidth2(time_struct.tm_sec) + "Z"; } static inline std::string Indent(size_t width) { return std::string(width, ' '); } -void JsonUnitTestResultPrinter::OutputJsonKey( - std::ostream* stream, - const std::string& element_name, - const std::string& name, - const std::string& value, - const std::string& indent, - bool comma) { +void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream, + const std::string& element_name, + const std::string& name, + const std::string& value, + const std::string& indent, + bool comma) { const std::vector& 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& 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. @@ -4758,11 +4693,14 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(), kIndent); } + + OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent); + OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false); if (GTEST_FLAG_GET(list_tests)) { - OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent); - OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false); *stream << "\n" << Indent(8) << "}"; return; + } else { + *stream << ",\n"; } OutputJsonKey(stream, kTestsuite, "status", @@ -4794,7 +4732,9 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, if (part.failed()) { *stream << ",\n"; if (++failures == 1) { - *stream << kIndent << "\"" << "failures" << "\": [\n"; + *stream << kIndent << "\"" + << "failures" + << "\": [\n"; } const std::string location = internal::FormatCompilerIndependentFileLocation(part.file_name(), @@ -4807,8 +4747,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, } } - if (failures > 0) - *stream << "\n" << kIndent << "]"; + if (failures > 0) *stream << "\n" << kIndent << "]"; *stream << "\n" << Indent(8) << "}"; } @@ -4904,7 +4843,9 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result()); } - *stream << "\n" << kIndent << "]\n" << "}\n"; + *stream << "\n" + << kIndent << "]\n" + << "}\n"; } void JsonUnitTestResultPrinter::PrintJsonTestList( @@ -4939,7 +4880,8 @@ std::string JsonUnitTestResultPrinter::TestPropertiesAsJson( Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); - attributes << ",\n" << indent << "\"" << property.key() << "\": " + attributes << ",\n" + << indent << "\"" << property.key() << "\": " << "\"" << EscapeJson(property.value()) << "\""; } return attributes.GetString(); @@ -4979,14 +4921,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); @@ -4995,8 +4937,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) { @@ -5065,7 +5007,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) return result; -#else // !GTEST_HAS_ABSL +#else // !GTEST_HAS_ABSL static_cast(max_depth); static_cast(skip_count); return ""; @@ -5089,8 +5031,8 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { class ScopedPrematureExitFile { public: explicit ScopedPrematureExitFile(const char* premature_exit_filepath) - : premature_exit_filepath_(premature_exit_filepath ? - premature_exit_filepath : "") { + : premature_exit_filepath_( + premature_exit_filepath ? premature_exit_filepath : "") { // If a path to the premature-exit file is specified... if (!premature_exit_filepath_.empty()) { // create the file with a single "0" character in it. I/O @@ -5118,7 +5060,8 @@ class ScopedPrematureExitFile { private: const std::string premature_exit_filepath_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile); + ScopedPrematureExitFile(const ScopedPrematureExitFile&) = delete; + ScopedPrematureExitFile& operator=(const ScopedPrematureExitFile&) = delete; }; } // namespace internal @@ -5292,7 +5235,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. @@ -5335,9 +5278,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 @@ -5362,12 +5303,11 @@ Environment* UnitTest::AddEnvironment(Environment* env) { // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // this to report their results. The user code should use the // assertion macros instead of calling this directly. -void UnitTest::AddTestPartResult( - TestPartResult::Type result_type, - const char* file_name, - int line_number, - const std::string& message, - const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { +void UnitTest::AddTestPartResult(TestPartResult::Type result_type, + const char* file_name, int line_number, + const std::string& message, + const std::string& os_stack_trace) + GTEST_LOCK_EXCLUDED_(mutex_) { Message msg; msg << message; @@ -5377,8 +5317,9 @@ void UnitTest::AddTestPartResult( for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) { const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; - msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) - << " " << trace.message; + msg << "\n" + << internal::FormatFileLocation(trace.file, trace.line) << " " + << trace.message; } } @@ -5388,8 +5329,8 @@ void UnitTest::AddTestPartResult( const TestPartResult result = TestPartResult( result_type, file_name, line_number, msg.GetString().c_str()); - impl_->GetTestPartResultReporterForCurrentThread()-> - ReportTestPartResult(result); + impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult( + result); if (result_type != TestPartResult::kSuccess && result_type != TestPartResult::kSkip) { @@ -5482,20 +5423,20 @@ int UnitTest::Run() { // process. In either case the user does not want to see pop-up dialogs // about crashes - they are expected. if (impl()->catch_exceptions() || in_death_test_child_process) { -# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // SetErrorMode doesn't exist on CE. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); -# endif // !GTEST_OS_WINDOWS_MOBILE +#endif // !GTEST_OS_WINDOWS_MOBILE -# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE +#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE // Death test children can be terminated with _abort(). On Windows, // _abort() can show a dialog with a warning message. This forces the // abort message to go to stderr instead. _set_error_mode(_OUT_TO_STDERR); -# endif +#endif -# if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE +#if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE // In the debug version, Visual Studio pops up a separate dialog // offering a choice to debug the aborted program. We need to suppress // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement @@ -5515,14 +5456,15 @@ int UnitTest::Run() { _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); } -# endif +#endif } #endif // GTEST_OS_WINDOWS return internal::HandleExceptionsInMethodIfSupported( - impl(), - &internal::UnitTestImpl::RunAllTests, - "auxiliary test code (environments or event listeners)") ? 0 : 1; + impl(), &internal::UnitTestImpl::RunAllTests, + "auxiliary test code (environments or event listeners)") + ? 0 + : 1; } // Returns the working directory when the first TEST() or TEST_F() was @@ -5567,14 +5509,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. @@ -5585,8 +5523,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(); } @@ -5687,8 +5624,8 @@ void UnitTestImpl::ConfigureStreamingOutput() { 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."; @@ -5833,8 +5770,7 @@ bool UnitTestImpl::RunAllTests() { const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized(); // Do not run any test if the --help flag was specified. - if (g_help_flag) - return true; + if (g_help_flag) return true; // Repeats the call to the post-flag parsing initialization in case the // user didn't call InitGoogleTest. @@ -5852,11 +5788,11 @@ bool UnitTestImpl::RunAllTests() { #if GTEST_HAS_DEATH_TEST in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != nullptr); -# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) +#if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) if (in_subprocess_for_death_test) { GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); } -# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) +#endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) #endif // GTEST_HAS_DEATH_TEST const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, @@ -5864,9 +5800,9 @@ 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_GET(list_tests)) { @@ -6049,8 +5985,7 @@ void WriteToShardStatusFileIfNeeded() { // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. -bool ShouldShard(const char* total_shards_env, - const char* shard_index_env, +bool ShouldShard(const char* total_shards_env, const char* shard_index_env, bool in_subprocess_for_death_test) { if (in_subprocess_for_death_test) { return false; @@ -6062,27 +5997,27 @@ bool ShouldShard(const char* total_shards_env, if (total_shards == -1 && shard_index == -1) { return false; } else if (total_shards == -1 && shard_index != -1) { - const Message msg = Message() - << "Invalid environment variables: you have " - << kTestShardIndex << " = " << shard_index - << ", but have left " << kTestTotalShards << " unset.\n"; + const Message msg = Message() << "Invalid environment variables: you have " + << kTestShardIndex << " = " << shard_index + << ", but have left " << kTestTotalShards + << " unset.\n"; ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (total_shards != -1 && shard_index == -1) { const Message msg = Message() - << "Invalid environment variables: you have " - << kTestTotalShards << " = " << total_shards - << ", but have left " << kTestShardIndex << " unset.\n"; + << "Invalid environment variables: you have " + << kTestTotalShards << " = " << total_shards + << ", but have left " << kTestShardIndex << " unset.\n"; ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (shard_index < 0 || shard_index >= total_shards) { - const Message msg = Message() - << "Invalid environment variables: we require 0 <= " - << kTestShardIndex << " < " << kTestTotalShards - << ", but you have " << kTestShardIndex << "=" << shard_index - << ", " << kTestTotalShards << "=" << total_shards << ".\n"; + const Message msg = + Message() << "Invalid environment variables: we require 0 <= " + << kTestShardIndex << " < " << kTestTotalShards + << ", but you have " << kTestShardIndex << "=" << shard_index + << ", " << kTestTotalShards << "=" << total_shards << ".\n"; ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); @@ -6124,10 +6059,12 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md // . Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { - const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? - Int32FromEnvOrDie(kTestTotalShards, -1) : -1; - const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? - Int32FromEnvOrDie(kTestShardIndex, -1) : -1; + const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL + ? Int32FromEnvOrDie(kTestTotalShards, -1) + : -1; + const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL + ? Int32FromEnvOrDie(kTestShardIndex, -1) + : -1; const PositiveAndNegativeUnitTestFilter gtest_flag_filter( GTEST_FLAG_GET(filter)); @@ -6337,7 +6274,7 @@ GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) { // suppress unreachable code warnings. namespace { class ClassUniqueToAlwaysTrue {}; -} +} // namespace bool IsTrue(bool condition) { return condition; } @@ -6345,8 +6282,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; } @@ -6458,8 +6394,7 @@ static bool ParseFlag(const char* str, const char* flag_name, 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) || @@ -6563,18 +6498,18 @@ static const char kColorEncodedHelpMessage[] = " Generate a JSON or XML report in the given directory or with the " "given\n" " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n" -# if GTEST_CAN_STREAM_RESULTS_ +#if GTEST_CAN_STREAM_RESULTS_ " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" " Stream test results to the given server.\n" -# endif // GTEST_CAN_STREAM_RESULTS_ +#endif // GTEST_CAN_STREAM_RESULTS_ "\n" "Assertion Behavior:\n" -# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS +#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" " Set the default death test style.\n" -# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS +#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" " Turn assertion failures into debugger break-points.\n" @@ -6651,10 +6586,8 @@ static void LoadFlagsFromFile(const std::string& path) { std::vector 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_ @@ -6680,9 +6613,7 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { LoadFlagsFromFile(flagfile_value); remove_flag = true; #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ - } else if (arg_string == "--help" || arg_string == "-h" || - arg_string == "-?" || arg_string == "/?" || - HasGoogleTestFlagPrefix(arg)) { + } else if (arg_string == "--help" || HasGoogleTestFlagPrefix(arg)) { // Both help flag and unrecognized Google Test flags (excluding // internal ones) trigger help display. g_help_flag = true; @@ -6717,7 +6648,27 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { // Parses the command line for Google Test flags, without initializing // other parts of Google Test. void ParseGoogleTestFlagsOnly(int* argc, char** argv) { +#if GTEST_HAS_ABSL + if (*argc > 0) { + // absl::ParseCommandLine() requires *argc > 0. + auto positional_args = absl::flags_internal::ParseCommandLineImpl( + *argc, argv, absl::flags_internal::ArgvListAction::kRemoveParsedArgs, + absl::flags_internal::UsageFlagsAction::kHandleUsage, + absl::flags_internal::OnUndefinedFlag::kReportUndefined); + // Any command-line positional arguments not part of any command-line flag + // (or arguments to a flag) are copied back out to argv, with the program + // invocation name at position 0, and argc is resized. This includes + // positional arguments after the flag-terminating delimiter '--'. + // See https://abseil.io/docs/cpp/guides/flags. + std::copy(positional_args.begin(), positional_args.end(), argv); + if (static_cast(positional_args.size()) < *argc) { + argv[positional_args.size()] = nullptr; + *argc = static_cast(positional_args.size()); + } + } +#else ParseGoogleTestFlagsOnlyImpl(argc, argv); +#endif // Fix the value of *_NSGetArgc() on macOS, but if and only if // *_NSGetArgv() == argv @@ -6752,6 +6703,12 @@ void InitGoogleTestImpl(int* argc, CharType** argv) { #if GTEST_HAS_ABSL absl::InitializeSymbolizer(g_argvs[0].c_str()); + + // When using the Abseil Flags library, set the program usage message to the + // help message, but remove the color-encoding from the message first. + absl::SetProgramUsageMessage(absl::StrReplaceAll( + kColorEncodedHelpMessage, + {{"@D", ""}, {"@R", ""}, {"@G", ""}, {"@Y", ""}, {"@@", "@"}})); #endif // GTEST_HAS_ABSL ParseGoogleTestFlagsOnly(argc, argv); @@ -6772,7 +6729,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_) } @@ -6782,7 +6739,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_) } @@ -6798,42 +6755,42 @@ void InitGoogleTest() { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv); -#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) +#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(&argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } +#if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) +// Return value of first environment variable that is set and contains +// a non-empty string. If there are none, return the "fallback" string. +// Since we like the temporary directory to have a directory separator suffix, +// add it if not provided in the environment variable value. +static std::string GetTempDirFromEnv( + std::initializer_list environment_variables, + const char* fallback, char separator) { + for (const char* variable_name : environment_variables) { + const char* value = internal::posix::GetEnv(variable_name); + if (value != nullptr && value[0] != '\0') { + if (value[strlen(value) - 1] != separator) { + return std::string(value).append(1, separator); + } + return value; + } + } + return fallback; +} +#endif + std::string TempDir() { #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) return GTEST_CUSTOM_TEMPDIR_FUNCTION_(); -#elif GTEST_OS_WINDOWS_MOBILE - return "\\temp\\"; -#elif GTEST_OS_WINDOWS - const char* temp_dir = internal::posix::GetEnv("TEMP"); - if (temp_dir == nullptr || temp_dir[0] == '\0') { - return "\\temp\\"; - } else if (temp_dir[strlen(temp_dir) - 1] == '\\') { - return temp_dir; - } else { - return std::string(temp_dir) + "\\"; - } +#elif GTEST_OS_WINDOWS || GTEST_OS_WINDOWS_MOBILE + return GetTempDirFromEnv({"TEST_TMPDIR", "TEMP"}, "\\temp\\", '\\'); #elif GTEST_OS_LINUX_ANDROID - const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR"); - if (temp_dir == nullptr || temp_dir[0] == '\0') { - return "/data/local/tmp/"; - } else { - return temp_dir; - } -#elif GTEST_OS_LINUX - const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR"); - if (temp_dir == nullptr || temp_dir[0] == '\0') { - return "/tmp/"; - } else { - return temp_dir; - } + return GetTempDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/data/local/tmp/", '/'); #else - return "/tmp/"; -#endif // GTEST_OS_WINDOWS_MOBILE + return GetTempDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/tmp/", '/'); +#endif } // Class ScopedTrace @@ -6850,8 +6807,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 46b27c3d..44976375 100644 --- a/googletest/src/gtest_main.cc +++ b/googletest/src/gtest_main.cc @@ -28,15 +28,14 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include + #include "gtest/gtest.h" #if GTEST_OS_ESP8266 || GTEST_OS_ESP32 #if GTEST_OS_ESP8266 extern "C" { #endif -void setup() { - testing::InitGoogleTest(); -} +void setup() { testing::InitGoogleTest(); } void loop() { RUN_ALL_TESTS(); } diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 8fd595c7..7754c130 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -174,6 +174,10 @@ py_test( name = "gtest_help_test", size = "small", srcs = ["gtest_help_test.py"], + args = select({ + "//:has_absl": ["--has_absl_flags"], + "//conditions:default": [], + }), data = [":gtest_help_test_"], deps = [":gtest_test_utils"], ) diff --git a/googletest/test/googletest-break-on-failure-unittest_.cc b/googletest/test/googletest-break-on-failure-unittest_.cc index f84957a2..324294f3 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 @@ -41,34 +40,32 @@ #include "gtest/gtest.h" #if GTEST_OS_WINDOWS -# include -# include +#include +#include #endif namespace { // A test that's expected to fail. -TEST(Foo, Bar) { - EXPECT_EQ(2, 3); -} +TEST(Foo, Bar) { EXPECT_EQ(2, 3); } #if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE // On Windows Mobile global exception handlers are not supported. -LONG WINAPI ExitWithExceptionCode( - struct _EXCEPTION_POINTERS* exception_pointers) { +LONG WINAPI +ExitWithExceptionCode(struct _EXCEPTION_POINTERS* exception_pointers) { exit(exception_pointers->ExceptionRecord->ExceptionCode); } #endif } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { #if GTEST_OS_WINDOWS // Suppresses display of the Windows error dialog upon encountering // a general protection fault (segment violation). SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); -# if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE +#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE // The default unhandled exception filter does not always exit // with the exception code as exit code - for example it exits with @@ -78,7 +75,7 @@ int main(int argc, char **argv) { // exceptions. SetUnhandledExceptionFilter(ExitWithExceptionCode); -# endif +#endif #endif // GTEST_OS_WINDOWS testing::InitGoogleTest(&argc, argv); diff --git a/googletest/test/googletest-catch-exceptions-test_.cc b/googletest/test/googletest-catch-exceptions-test_.cc index 8c127d40..3c8f4f4b 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 // NOLINT +#include // NOLINT #include // For exit(). #include "gtest/gtest.h" #if GTEST_HAS_SEH -# include +#include #endif #if GTEST_HAS_EXCEPTIONS -# include // For set_terminate(). -# include +#include // For set_terminate(). +#include #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_.cc b/googletest/test/googletest-color-test_.cc index 220a3a00..55657b72 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 62a84b47..4737ff9b 100644 --- a/googletest/test/googletest-death-test-test.cc +++ b/googletest/test/googletest-death-test-test.cc @@ -31,7 +31,6 @@ // Tests for death tests. #include "gtest/gtest-death-test.h" - #include "gtest/gtest.h" #include "gtest/internal/gtest-filepath.h" @@ -40,25 +39,25 @@ using testing::internal::AlwaysTrue; #if GTEST_HAS_DEATH_TEST -# if GTEST_OS_WINDOWS -# include // For O_BINARY -# include // For chdir(). -# include -# else -# include -# include // For waitpid. -# endif // GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS +#include // For chdir(). +#include // For O_BINARY +#include +#else +#include // For waitpid. +#include +#endif // GTEST_OS_WINDOWS -# include -# include -# include +#include +#include +#include -# if GTEST_OS_LINUX -# include -# endif // GTEST_OS_LINUX +#if GTEST_OS_LINUX +#include +#endif // GTEST_OS_LINUX -# include "gtest/gtest-spi.h" -# include "src/gtest-internal-inl.h" +#include "gtest/gtest-spi.h" +#include "src/gtest-internal-inl.h" namespace posix = ::testing::internal::posix; @@ -90,6 +89,7 @@ class ReplaceDeathTestFactory { unit_test_impl_->death_test_factory_.release(); unit_test_impl_->death_test_factory_.reset(old_factory_); } + private: // Prevents copying ReplaceDeathTestFactory objects. ReplaceDeathTestFactory(const ReplaceDeathTestFactory&); @@ -116,8 +116,7 @@ void DieWithMessage(const ::std::string& message) { // Some compilers can recognize that _exit() never returns and issue the // 'unreachable code' warning for code following this function, unless // fooled by a fake condition. - if (AlwaysTrue()) - _exit(1); + if (AlwaysTrue()) _exit(1); } void DieInside(const ::std::string& function) { @@ -137,8 +136,7 @@ class TestForDeathTest : public testing::Test { // A method of the test fixture that may die. void MemberFunction() { - if (should_die_) - DieInside("MemberFunction"); + if (should_die_) DieInside("MemberFunction"); } // True if and only if MemberFunction() should die. @@ -153,8 +151,7 @@ class MayDie { // A member function that may die. void MemberFunction() const { - if (should_die_) - DieInside("MayDie::MemberFunction"); + if (should_die_) DieInside("MayDie::MemberFunction"); } private: @@ -173,8 +170,7 @@ int NonVoidFunction() { // A unary function that may die. void DieIf(bool should_die) { - if (should_die) - DieInside("DieIf"); + if (should_die) DieInside("DieIf"); } // A binary function that may die. @@ -195,16 +191,16 @@ void DeathTestSubroutine() { int DieInDebugElse12(int* sideeffect) { if (sideeffect) *sideeffect = 12; -# ifndef NDEBUG +#ifndef NDEBUG DieInside("DieInDebugElse12"); -# endif // NDEBUG +#endif // NDEBUG return 12; } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // Death in dbg due to Windows CRT assertion failure, not opt. int DieInCRTDebugElse12(int* sideeffect) { @@ -224,7 +220,7 @@ int DieInCRTDebugElse12(int* sideeffect) { #endif // GTEST_OS_WINDOWS -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA // Tests the ExitedWithCode predicate. TEST(ExitStatusPredicateTest, ExitedWithCode) { @@ -237,7 +233,7 @@ TEST(ExitStatusPredicateTest, ExitedWithCode) { EXPECT_FALSE(testing::ExitedWithCode(1)(0)); } -# else +#else // Returns the exit status of a process that calls _exit(2) with a // given exit code. This is a helper function for the @@ -270,14 +266,14 @@ static int KilledExitStatus(int signum) { // Tests the ExitedWithCode predicate. TEST(ExitStatusPredicateTest, ExitedWithCode) { - const int status0 = NormalExitStatus(0); - const int status1 = NormalExitStatus(1); + const int status0 = NormalExitStatus(0); + const int status1 = NormalExitStatus(1); const int status42 = NormalExitStatus(42); const testing::ExitedWithCode pred0(0); const testing::ExitedWithCode pred1(1); const testing::ExitedWithCode pred42(42); - EXPECT_PRED1(pred0, status0); - EXPECT_PRED1(pred1, status1); + EXPECT_PRED1(pred0, status0); + EXPECT_PRED1(pred1, status1); EXPECT_PRED1(pred42, status42); EXPECT_FALSE(pred0(status1)); EXPECT_FALSE(pred42(status0)); @@ -296,7 +292,7 @@ TEST(ExitStatusPredicateTest, KilledBySignal) { EXPECT_FALSE(pred_kill(status_segv)); } -# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA // The following code intentionally tests a suboptimal syntax. #ifdef __GNUC__ @@ -320,8 +316,7 @@ TEST_F(TestForDeathTest, SingleStatement) { // doesn't expand into an "if" statement without an "else" ; - if (AlwaysFalse()) - ASSERT_DEATH(return, "") << "did not die"; + if (AlwaysFalse()) ASSERT_DEATH(return, "") << "did not die"; if (AlwaysFalse()) ; @@ -332,7 +327,7 @@ TEST_F(TestForDeathTest, SingleStatement) { #pragma GCC diagnostic pop #endif -# if GTEST_USES_PCRE +#if GTEST_USES_PCRE void DieWithEmbeddedNul() { fprintf(stderr, "Hello%cmy null world.\n", '\0'); @@ -347,7 +342,7 @@ TEST_F(TestForDeathTest, EmbeddedNulInMessage) { ASSERT_DEATH(DieWithEmbeddedNul(), "my null world"); } -# endif // GTEST_USES_PCRE +#endif // GTEST_USES_PCRE // Tests that death test macros expand to code which interacts well with switch // statements. @@ -357,12 +352,12 @@ TEST_F(TestForDeathTest, SwitchStatement) { GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) switch (0) - default: - ASSERT_DEATH(_exit(1), "") << "exit in default switch handler"; + default: + ASSERT_DEATH(_exit(1), "") << "exit in default switch handler"; switch (0) - case 0: - EXPECT_DEATH(_exit(1), "") << "exit in switch case"; + case 0: + EXPECT_DEATH(_exit(1), "") << "exit in switch case"; GTEST_DISABLE_MSC_WARNINGS_POP_() } @@ -396,8 +391,9 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) { ASSERT_DEATH(_exit(1), ""); } -# if GTEST_OS_LINUX -void SigprofAction(int, siginfo_t*, void*) { /* no op */ } +#if GTEST_OS_LINUX +void SigprofAction(int, siginfo_t*, void*) { /* no op */ +} // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms). void SetSigprofActionAndTimer() { @@ -448,7 +444,7 @@ TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) { 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: @@ -487,13 +483,11 @@ TEST_F(TestForDeathTest, MixedStyles) { 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 (!GTEST_FLAG_GET(death_test_use_fork)) { @@ -505,7 +499,7 @@ TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { } } -# endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD +#endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD // Tests that a method of another class can be used in a death test. TEST_F(TestForDeathTest, MethodOfAnotherClass) { @@ -527,7 +521,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { const testing::internal::RE regex(regex_c_str); EXPECT_DEATH(GlobalFunction(), regex); -# if !GTEST_USES_PCRE +#if !GTEST_USES_PCRE const ::std::string regex_std_str(regex_c_str); EXPECT_DEATH(GlobalFunction(), regex_std_str); @@ -536,7 +530,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { // lifetime extension of the pointer is not sufficient. EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str()); -# endif // !GTEST_USES_PCRE +#endif // !GTEST_USES_PCRE } // Tests that a non-void function can be used in a death test. @@ -551,9 +545,7 @@ TEST_F(TestForDeathTest, FunctionWithParameter) { } // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture. -TEST_F(TestForDeathTest, OutsideFixture) { - DeathTestSubroutine(); -} +TEST_F(TestForDeathTest, OutsideFixture) { DeathTestSubroutine(); } // Tests that death tests can be done inside a loop. TEST_F(TestForDeathTest, InsideLoop) { @@ -564,25 +556,28 @@ TEST_F(TestForDeathTest, InsideLoop) { // Tests that a compound statement can be used in a death test. TEST_F(TestForDeathTest, CompoundStatement) { - EXPECT_DEATH({ // NOLINT - const int x = 2; - const int y = x + 1; - DieIfLessThan(x, y); - }, - "DieIfLessThan"); + EXPECT_DEATH( + { // NOLINT + const int x = 2; + const int y = x + 1; + DieIfLessThan(x, y); + }, + "DieIfLessThan"); } // Tests that code that doesn't die causes a death test to fail. TEST_F(TestForDeathTest, DoesNotDie) { - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), - "failed to die"); + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), "failed to die"); } // Tests that a death test fails when the error message isn't expected. TEST_F(TestForDeathTest, ErrorMessageMismatch) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message."; - }, "died but not with expected error"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_DEATH(DieIf(true), "DieIfLessThan") + << "End of death test message."; + }, + "died but not with expected error"); } // On exit, *aborted will be true if and only if the EXPECT_DEATH() @@ -596,19 +591,20 @@ void ExpectDeathTestHelper(bool* aborted) { // Tests that EXPECT_DEATH doesn't abort the test on failure. TEST_F(TestForDeathTest, EXPECT_DEATH) { bool aborted = true; - EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), - "failed to die"); + EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), "failed to die"); EXPECT_FALSE(aborted); } // Tests that ASSERT_DEATH does abort the test on failure. TEST_F(TestForDeathTest, ASSERT_DEATH) { static bool aborted; - EXPECT_FATAL_FAILURE({ // NOLINT - aborted = true; - ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. - aborted = false; - }, "failed to die"); + EXPECT_FATAL_FAILURE( + { // NOLINT + aborted = true; + ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. + aborted = false; + }, + "failed to die"); EXPECT_TRUE(aborted); } @@ -653,20 +649,20 @@ TEST_F(TestForDeathTest, TestExpectDebugDeath) { EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex) << "Must accept a streamed message"; -# ifdef NDEBUG +#ifdef NDEBUG // Checks that the assignment occurs in opt mode (sideeffect). EXPECT_EQ(12, sideeffect); -# else +#else // Checks that the assignment does not occur in dbg mode (no sideeffect). EXPECT_EQ(0, sideeffect); -# endif +#endif } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode // In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable @@ -682,7 +678,7 @@ TEST_F(TestForDeathTest, CRTDebugDeath) { } #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: @@ -697,20 +693,20 @@ TEST_F(TestForDeathTest, TestAssertDebugDeath) { ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12") << "Must accept a streamed message"; -# ifdef NDEBUG +#ifdef NDEBUG // Checks that the assignment occurs in opt mode (sideeffect). EXPECT_EQ(12, sideeffect); -# else +#else // Checks that the assignment does not occur in dbg mode (no sideeffect). EXPECT_EQ(0, sideeffect); -# endif +#endif } -# ifndef NDEBUG +#ifndef NDEBUG void ExpectDebugDeathHelper(bool* aborted) { *aborted = true; @@ -718,10 +714,11 @@ void ExpectDebugDeathHelper(bool* aborted) { *aborted = false; } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { - printf("This test should be considered failing if it shows " - "any pop-up dialogs.\n"); + printf( + "This test should be considered failing if it shows " + "any pop-up dialogs.\n"); fflush(stdout); EXPECT_DEATH( @@ -731,7 +728,7 @@ TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { }, ""); } -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort // the function. @@ -822,42 +819,44 @@ TEST_F(TestForDeathTest, AssertDebugDeathAborts10) { EXPECT_TRUE(aborted); } -# endif // _NDEBUG +#endif // _NDEBUG // Tests the *_EXIT family of macros, using a variety of predicates. static void TestExitMacros() { - EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); + EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), ""); -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // Of all signals effects on the process exit code, only those of SIGABRT // are documented on Windows. // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c. EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar"; -# elif !GTEST_OS_FUCHSIA +#elif !GTEST_OS_FUCHSIA // Fuchsia has no unix signals. EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo"; ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar"; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "") - << "This failure is expected, too."; - }, "This failure is expected, too."); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "") + << "This failure is expected, too."; + }, + "This failure is expected, too."); -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "") - << "This failure is expected."; - }, "This failure is expected."); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "") + << "This failure is expected."; + }, + "This failure is expected."); } -TEST_F(TestForDeathTest, ExitMacros) { - TestExitMacros(); -} +TEST_F(TestForDeathTest, ExitMacros) { TestExitMacros(); } TEST_F(TestForDeathTest, ExitMacrosUsingFork) { GTEST_FLAG_SET(death_test_use_fork, true); @@ -866,39 +865,40 @@ TEST_F(TestForDeathTest, ExitMacrosUsingFork) { TEST_F(TestForDeathTest, InvalidStyle) { GTEST_FLAG_SET(death_test_style, "rococo"); - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_DEATH(_exit(0), "") << "This failure is expected."; - }, "This failure is expected."); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_DEATH(_exit(0), "") << "This failure is expected."; + }, + "This failure is expected."); } TEST_F(TestForDeathTest, DeathTestFailedOutput) { 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) { 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"); + 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) { 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" @@ -931,8 +931,8 @@ class MockDeathTestFactory : public DeathTestFactory { int line, DeathTest** test) override; // Sets the parameters for subsequent calls to Create. - void SetParameters(bool create, DeathTest::TestRole role, - int status, bool passed); + void SetParameters(bool create, DeathTest::TestRole role, int status, + bool passed); // Accessors. int AssumeRoleCalls() const { return assume_role_calls_; } @@ -974,17 +974,15 @@ class MockDeathTestFactory : public DeathTestFactory { bool test_deleted_; }; - // A DeathTest implementation useful in testing. It returns values set // at its creation from its various inherited DeathTest methods, and // reports calls to those methods to its parent MockDeathTestFactory // object. class MockDeathTest : public DeathTest { public: - MockDeathTest(MockDeathTestFactory *parent, - TestRole role, int status, bool passed) : - parent_(parent), role_(role), status_(status), passed_(passed) { - } + MockDeathTest(MockDeathTestFactory* parent, TestRole role, int status, + bool passed) + : parent_(parent), role_(role), status_(status), passed_(passed) {} ~MockDeathTest() override { parent_->test_deleted_ = true; } TestRole AssumeRole() override { ++parent_->assume_role_calls_; @@ -1009,7 +1007,6 @@ class MockDeathTest : public DeathTest { const bool passed_; }; - // MockDeathTestFactory constructor. MockDeathTestFactory::MockDeathTestFactory() : create_(true), @@ -1019,13 +1016,10 @@ MockDeathTestFactory::MockDeathTestFactory() assume_role_calls_(0), wait_calls_(0), passed_args_(), - abort_args_() { -} - + abort_args_() {} // Sets the parameters for subsequent calls to Create. -void MockDeathTestFactory::SetParameters(bool create, - DeathTest::TestRole role, +void MockDeathTestFactory::SetParameters(bool create, DeathTest::TestRole role, int status, bool passed) { create_ = create; role_ = role; @@ -1038,7 +1032,6 @@ void MockDeathTestFactory::SetParameters(bool create, abort_args_.clear(); } - // Sets test to NULL (if create_ is false) or to the address of a new // MockDeathTest object with parameters taken from the last call // to SetParameters (if create_ is true). Always returns true. @@ -1078,10 +1071,12 @@ class MacroLogicDeathTest : public testing::Test { // test cannot be run directly from a test routine that uses a // MockDeathTest, or the remainder of the routine will not be executed. static void RunReturningDeathTest(bool* flag) { - ASSERT_DEATH({ // NOLINT - *flag = true; - return; - }, ""); + ASSERT_DEATH( + { // NOLINT + *flag = true; + return; + }, + ""); } }; @@ -1166,8 +1161,7 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) { // _exit(2) is called in that case by ForkingDeathTest, but not by // our MockDeathTest. ASSERT_EQ(2U, factory_->AbortCalls()); - EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, - factory_->AbortArgument(0)); + EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0)); EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, factory_->AbortArgument(1)); EXPECT_TRUE(factory_->TestDeleted()); @@ -1183,12 +1177,16 @@ TEST(SuccessRegistrationDeathTest, NoSuccessPart) { TEST(StreamingAssertionsDeathTest, DeathTest) { EXPECT_DEATH(_exit(1), "") << "unexpected failure"; ASSERT_DEATH(_exit(1), "") << "unexpected failure"; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_DEATH(_exit(0), "") << "expected failure"; - }, "expected failure"); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_DEATH(_exit(0), "") << "expected failure"; - }, "expected failure"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_DEATH(_exit(0), "") << "expected failure"; + }, + "expected failure"); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_DEATH(_exit(0), "") << "expected failure"; + }, + "expected failure"); } // Tests that GetLastErrnoDescription returns an empty string when the @@ -1200,7 +1198,7 @@ TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) { EXPECT_STREQ("", GetLastErrnoDescription().c_str()); } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS TEST(AutoHandleTest, AutoHandleWorks) { HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); ASSERT_NE(INVALID_HANDLE_VALUE, handle); @@ -1225,15 +1223,15 @@ TEST(AutoHandleTest, AutoHandleWorks) { testing::internal::AutoHandle auto_handle2; EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get()); } -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS typedef unsigned __int64 BiggestParsable; typedef signed __int64 BiggestSignedParsable; -# else +#else typedef unsigned long long BiggestParsable; typedef signed long long BiggestSignedParsable; -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS // We cannot use std::numeric_limits::max() as it clashes with the // max() macro defined by . @@ -1324,11 +1322,11 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { EXPECT_EQ(123, char_result); } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS TEST(EnvironmentTest, HandleFitsIntoSizeT) { ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); } -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger // failures when death tests are available on the system. @@ -1346,21 +1344,25 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) { TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) { 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) { 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) { @@ -1488,8 +1490,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) { // doesn't expand into an "if" statement without an "else" ; // NOLINT - if (AlwaysFalse()) - ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die"; + if (AlwaysFalse()) ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die"; if (AlwaysFalse()) ; // NOLINT @@ -1508,21 +1509,18 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) { GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) switch (0) - default: - ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") - << "exit in default switch handler"; + default: + ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in default switch handler"; switch (0) - case 0: - EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case"; + case 0: + EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case"; GTEST_DISABLE_MSC_WARNINGS_POP_() } // Tests that a test case whose name ends with "DeathTest" works fine // on Windows. -TEST(NotADeathTest, Test) { - SUCCEED(); -} +TEST(NotADeathTest, Test) { SUCCEED(); } } // namespace diff --git a/googletest/test/googletest-death-test_ex_test.cc b/googletest/test/googletest-death-test_ex_test.cc index bbacc8ae..f2515e37 100644 --- a/googletest/test/googletest-death-test_ex_test.cc +++ b/googletest/test/googletest-death-test_ex_test.cc @@ -35,15 +35,15 @@ #if GTEST_HAS_DEATH_TEST -# if GTEST_HAS_SEH -# include // For RaiseException(). -# endif +#if GTEST_HAS_SEH +#include // For RaiseException(). +#endif -# include "gtest/gtest-spi.h" +#include "gtest/gtest-spi.h" -# if GTEST_HAS_EXCEPTIONS +#if GTEST_HAS_EXCEPTIONS -# include // For std::exception. +#include // For std::exception. // Tests that death tests report thrown exceptions as failures and that the // exceptions do not escape death test macros. @@ -67,12 +67,11 @@ 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. @@ -81,7 +80,7 @@ TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) { << "with catch_exceptions " << (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled"); } -# endif +#endif #endif // GTEST_HAS_DEATH_TEST diff --git a/googletest/test/googletest-env-var-test_.cc b/googletest/test/googletest-env-var-test_.cc index 0ff01522..36533750 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,8 +42,7 @@ 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) { diff --git a/googletest/test/googletest-failfast-unittest_.cc b/googletest/test/googletest-failfast-unittest_.cc index 0b2c951b..3bd05a8e 100644 --- a/googletest/test/googletest-failfast-unittest_.cc +++ b/googletest/test/googletest-failfast-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 @@ -160,7 +159,7 @@ TEST(HasSkipTest, Test4) { FAIL() << "Expected failure."; } } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); ::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener()); return RUN_ALL_TESTS(); diff --git a/googletest/test/googletest-filepath-test.cc b/googletest/test/googletest-filepath-test.cc index aafad36f..fe53f848 100644 --- a/googletest/test/googletest-filepath-test.cc +++ b/googletest/test/googletest-filepath-test.cc @@ -35,15 +35,15 @@ // This file is #included from gtest-internal.h. // Do not #include this file anywhere else! -#include "gtest/internal/gtest-filepath.h" #include "gtest/gtest.h" +#include "gtest/internal/gtest-filepath.h" #include "src/gtest-internal-inl.h" #if GTEST_OS_WINDOWS_MOBILE -# include // NOLINT +#include // NOLINT #elif GTEST_OS_WINDOWS -# include // NOLINT -#endif // GTEST_OS_WINDOWS_MOBILE +#include // NOLINT +#endif // GTEST_OS_WINDOWS_MOBILE namespace testing { namespace internal { @@ -55,16 +55,16 @@ namespace { int remove(const char* path) { LPCWSTR wpath = String::AnsiToUtf16(path); int ret = DeleteFile(wpath) ? 0 : -1; - delete [] wpath; + delete[] wpath; return ret; } // Windows CE doesn't have the _rmdir C function. int _rmdir(const char* path) { FilePath filepath(path); - LPCWSTR wpath = String::AnsiToUtf16( - filepath.RemoveTrailingPathSeparator().c_str()); + LPCWSTR wpath = + String::AnsiToUtf16(filepath.RemoveTrailingPathSeparator().c_str()); int ret = RemoveDirectory(wpath) ? 0 : -1; - delete [] wpath; + delete[] wpath; return ret; } @@ -78,18 +78,18 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) { const FilePath cwd = FilePath::GetCurrentDir(); posix::ChDir(original_dir.c_str()); -# if GTEST_OS_WINDOWS || GTEST_OS_OS2 +#if GTEST_OS_WINDOWS || GTEST_OS_OS2 // Skips the ":". const char* const cwd_without_drive = strchr(cwd.c_str(), ':'); ASSERT_TRUE(cwd_without_drive != NULL); EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1); -# else +#else EXPECT_EQ(GTEST_PATH_SEP_, cwd.string()); -# endif +#endif } #endif // GTEST_OS_WINDOWS_MOBILE @@ -112,33 +112,34 @@ TEST(RemoveDirectoryNameTest, WhenEmptyName) { // RemoveDirectoryName "afile" -> "afile" TEST(RemoveDirectoryNameTest, ButNoDirectory) { - EXPECT_EQ("afile", - FilePath("afile").RemoveDirectoryName().string()); + EXPECT_EQ("afile", FilePath("afile").RemoveDirectoryName().string()); } // RemoveDirectoryName "/afile" -> "afile" TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) { EXPECT_EQ("afile", - FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); + FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); } // RemoveDirectoryName "adir/" -> "" TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) { EXPECT_EQ("", - FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string()); + FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string()); } // RemoveDirectoryName "adir/afile" -> "afile" TEST(RemoveDirectoryNameTest, ShouldGiveFileName) { - EXPECT_EQ("afile", + EXPECT_EQ( + "afile", FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); } // RemoveDirectoryName "adir/subdir/afile" -> "afile" TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) { EXPECT_EQ("afile", - FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") - .RemoveDirectoryName().string()); + FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") + .RemoveDirectoryName() + .string()); } #if GTEST_HAS_ALT_PATH_SEP_ @@ -182,7 +183,7 @@ TEST(RemoveFileNameTest, EmptyName) { // RemoveFileName "adir/" -> "adir/" TEST(RemoveFileNameTest, ButNoFile) { EXPECT_EQ("adir" GTEST_PATH_SEP_, - FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string()); + FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string()); } // RemoveFileName "adir/afile" -> "adir/" @@ -194,14 +195,15 @@ TEST(RemoveFileNameTest, GivesDirName) { // RemoveFileName "adir/subdir/afile" -> "adir/subdir/" TEST(RemoveFileNameTest, GivesDirAndSubDirName) { EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_, - FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") - .RemoveFileName().string()); + FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") + .RemoveFileName() + .string()); } // RemoveFileName "/afile" -> "/" TEST(RemoveFileNameTest, GivesRootDir) { EXPECT_EQ(GTEST_PATH_SEP_, - FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string()); + FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string()); } #if GTEST_HAS_ALT_PATH_SEP_ @@ -235,44 +237,43 @@ TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) { #endif TEST(MakeFileNameTest, GenerateWhenNumberIsZero) { - FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), - 0, "xml"); + FilePath actual = + FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 0, "xml"); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); } TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) { - FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), - 12, "xml"); + FilePath actual = + FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 12, "xml"); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); } TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) { FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), - FilePath("bar"), 0, "xml"); + FilePath("bar"), 0, "xml"); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); } TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) { FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), - FilePath("bar"), 12, "xml"); + FilePath("bar"), 12, "xml"); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); } TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) { - FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), - 0, "xml"); + FilePath actual = + FilePath::MakeFileName(FilePath(""), FilePath("bar"), 0, "xml"); EXPECT_EQ("bar.xml", actual.string()); } TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) { - FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), - 14, "xml"); + FilePath actual = + FilePath::MakeFileName(FilePath(""), FilePath("bar"), 14, "xml"); EXPECT_EQ("bar_14.xml", actual.string()); } TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) { - FilePath actual = FilePath::ConcatPaths(FilePath("foo"), - FilePath("bar.xml")); + FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath("bar.xml")); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); } @@ -283,8 +284,7 @@ TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) { } TEST(ConcatPathsTest, Path1BeingEmpty) { - FilePath actual = FilePath::ConcatPaths(FilePath(""), - FilePath("bar.xml")); + FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath("bar.xml")); EXPECT_EQ("bar.xml", actual.string()); } @@ -294,8 +294,7 @@ TEST(ConcatPathsTest, Path2BeingEmpty) { } TEST(ConcatPathsTest, BothPathBeingEmpty) { - FilePath actual = FilePath::ConcatPaths(FilePath(""), - FilePath("")); + FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath("")); EXPECT_EQ("", actual.string()); } @@ -307,16 +306,16 @@ TEST(ConcatPathsTest, Path1ContainsPathSep) { } TEST(ConcatPathsTest, Path2ContainsPathSep) { - FilePath actual = FilePath::ConcatPaths( - FilePath("foo" GTEST_PATH_SEP_), - FilePath("bar" GTEST_PATH_SEP_ "bar.xml")); + FilePath actual = + FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_), + FilePath("bar" GTEST_PATH_SEP_ "bar.xml")); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml", actual.string()); } TEST(ConcatPathsTest, Path2EndsWithPathSep) { - FilePath actual = FilePath::ConcatPaths(FilePath("foo"), - FilePath("bar" GTEST_PATH_SEP_)); + FilePath actual = + FilePath::ConcatPaths(FilePath("foo"), FilePath("bar" GTEST_PATH_SEP_)); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string()); } @@ -332,7 +331,8 @@ TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) { // RemoveTrailingPathSeparator "foo/" -> "foo" TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { - EXPECT_EQ("foo", + EXPECT_EQ( + "foo", FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string()); #if GTEST_HAS_ALT_PATH_SEP_ EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string()); @@ -343,18 +343,19 @@ TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) { EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_) - .RemoveTrailingPathSeparator().string()); + .RemoveTrailingPathSeparator() + .string()); } // RemoveTrailingPathSeparator "foo/bar" -> "foo/bar" TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) { - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", - FilePath("foo" GTEST_PATH_SEP_ "bar") - .RemoveTrailingPathSeparator().string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ "bar") + .RemoveTrailingPathSeparator() + .string()); } TEST(DirectoryTest, RootDirectoryExists) { -#if GTEST_OS_WINDOWS // We are on Windows. +#if GTEST_OS_WINDOWS // We are on Windows. char current_drive[_MAX_PATH]; // NOLINT current_drive[0] = static_cast(_getdrive() + 'A' - 1); current_drive[1] = ':'; @@ -393,12 +394,12 @@ TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) { TEST(DirectoryTest, CurrentDirectoryExists) { #if GTEST_OS_WINDOWS // We are on Windows. -# ifndef _WIN32_CE // Windows CE doesn't have a current directory. +#ifndef _WIN32_CE // Windows CE doesn't have a current directory. EXPECT_TRUE(FilePath(".").DirectoryExists()); EXPECT_TRUE(FilePath(".\\").DirectoryExists()); -# endif // _WIN32_CE +#endif // _WIN32_CE #else EXPECT_TRUE(FilePath(".").DirectoryExists()); EXPECT_TRUE(FilePath("./").DirectoryExists()); @@ -406,34 +407,35 @@ TEST(DirectoryTest, CurrentDirectoryExists) { } // "foo/bar" == foo//bar" == "foo///bar" -TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) { +TEST(NormalizeTest, MultipleConsecutiveSeparatorsInMidstring) { EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ "bar").string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", - FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ - GTEST_PATH_SEP_ "bar").string()); + EXPECT_EQ( + "foo" GTEST_PATH_SEP_ "bar", + FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar") + .string()); } // "/bar" == //bar" == "///bar" -TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) { +TEST(NormalizeTest, MultipleConsecutiveSeparatorsAtStringStart) { + EXPECT_EQ(GTEST_PATH_SEP_ "bar", FilePath(GTEST_PATH_SEP_ "bar").string()); EXPECT_EQ(GTEST_PATH_SEP_ "bar", - FilePath(GTEST_PATH_SEP_ "bar").string()); - EXPECT_EQ(GTEST_PATH_SEP_ "bar", - FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); - EXPECT_EQ(GTEST_PATH_SEP_ "bar", - FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); + FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); + EXPECT_EQ( + GTEST_PATH_SEP_ "bar", + FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); } // "foo/" == foo//" == "foo///" -TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { +TEST(NormalizeTest, MultipleConsecutiveSeparatorsAtStringEnd) { + EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo" GTEST_PATH_SEP_).string()); EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo" GTEST_PATH_SEP_).string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); + FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); + EXPECT_EQ( + "foo" GTEST_PATH_SEP_, + FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); } #if GTEST_HAS_ALT_PATH_SEP_ @@ -442,12 +444,10 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { // regardless of their combination (e.g. "foo\" =="foo/\" == // "foo\\/"). TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) { - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo/").string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo/").string()); EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo" GTEST_PATH_SEP_ "/").string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo//" GTEST_PATH_SEP_).string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo//" GTEST_PATH_SEP_).string()); } #endif @@ -478,15 +478,15 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) { class DirectoryCreationTest : public Test { protected: void SetUp() override { - testdata_path_.Set(FilePath( - TempDir() + GetCurrentExecutableName().string() + - "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_)); + testdata_path_.Set( + FilePath(TempDir() + GetCurrentExecutableName().string() + + "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_)); testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator()); - unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), - 0, "txt")); - unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), - 1, "txt")); + unique_file0_.Set( + FilePath::MakeFileName(testdata_path_, FilePath("unique"), 0, "txt")); + unique_file1_.Set( + FilePath::MakeFileName(testdata_path_, FilePath("unique"), 1, "txt")); remove(testdata_file_.c_str()); remove(unique_file0_.c_str()); @@ -512,8 +512,8 @@ class DirectoryCreationTest : public Test { // a directory named 'test' from a file named 'test'. Example names: FilePath testdata_path_; // "/tmp/directory_creation/test/" FilePath testdata_file_; // "/tmp/directory_creation/test" - FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt" - FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt" + FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt" + FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt" }; TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) { @@ -530,8 +530,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) { } TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { - FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_, - FilePath("unique"), "txt")); + FilePath file_path(FilePath::GenerateUniqueFileName( + testdata_path_, FilePath("unique"), "txt")); EXPECT_EQ(unique_file0_.string(), file_path.string()); EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there @@ -540,8 +540,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { CreateTextFile(file_path.c_str()); EXPECT_TRUE(file_path.FileOrDirectoryExists()); - FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_, - FilePath("unique"), "txt")); + FilePath file_path2(FilePath::GenerateUniqueFileName( + testdata_path_, FilePath("unique"), "txt")); EXPECT_EQ(unique_file1_.string(), file_path2.string()); EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there CreateTextFile(file_path2.c_str()); @@ -614,14 +614,16 @@ TEST(FilePathTest, IsAbsolutePath) { EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath()); EXPECT_FALSE(FilePath("").IsAbsolutePath()); #if GTEST_OS_WINDOWS - EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not" - GTEST_PATH_SEP_ "relative").IsAbsolutePath()); + EXPECT_TRUE( + FilePath("c:\\" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative") + .IsAbsolutePath()); EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath()); - EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not" - GTEST_PATH_SEP_ "relative").IsAbsolutePath()); + EXPECT_TRUE( + FilePath("c:/" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative") + .IsAbsolutePath()); #else EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative") - .IsAbsolutePath()); + .IsAbsolutePath()); #endif // GTEST_OS_WINDOWS } diff --git a/googletest/test/googletest-filter-unittest.py b/googletest/test/googletest-filter-unittest.py index bd1d5a5d..2c4a1b18 100755 --- a/googletest/test/googletest-filter-unittest.py +++ b/googletest/test/googletest-filter-unittest.py @@ -113,6 +113,9 @@ TEST_CASE_REGEX = re.compile(r'^\[\-+\] \d+ tests? from (\w+(/\w+)?)') # Regex for parsing test names from Google Test's output. TEST_REGEX = re.compile(r'^\[\s*RUN\s*\].*\.(\w+(/\w+)?)') +# Regex for parsing disabled banner from Google Test's output +DISABLED_BANNER_REGEX = re.compile(r'^\[\s*DISABLED\s*\] (.*)') + # The command line flag to tell Google Test to output the list of tests it # will run. LIST_TESTS_FLAG = '--gtest_list_tests' @@ -206,6 +209,17 @@ def RunAndExtractTestList(args = None): return (tests_run, p.exit_code) +def RunAndExtractDisabledBannerList(args=None): + """Runs the test program and returns tests that printed a disabled banner.""" + p = gtest_test_utils.Subprocess([COMMAND] + (args or []), env=environ) + banners_printed = [] + for line in p.output.split('\n'): + match = DISABLED_BANNER_REGEX.match(line) + if match is not None: + banners_printed.append(match.group(1)) + return banners_printed + + def InvokeWithModifiedEnv(extra_env, function, *args, **kwargs): """Runs the given function and arguments in a modified environment.""" try: @@ -613,6 +627,23 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): self.assert_(os.path.exists(shard_status_file)) os.remove(shard_status_file) + def testDisabledBanner(self): + """Tests that the disabled banner prints only tests that match filter.""" + make_filter = lambda s: ['--%s=%s' % (FILTER_FLAG, s)] + + banners = RunAndExtractDisabledBannerList(make_filter('*')) + self.AssertSetEqual(banners, [ + 'BarTest.DISABLED_TestFour', 'BarTest.DISABLED_TestFive', + 'BazTest.DISABLED_TestC' + ]) + + banners = RunAndExtractDisabledBannerList(make_filter('Bar*')) + self.AssertSetEqual( + banners, ['BarTest.DISABLED_TestFour', 'BarTest.DISABLED_TestFive']) + + banners = RunAndExtractDisabledBannerList(make_filter('*-Bar*')) + self.AssertSetEqual(banners, ['BazTest.DISABLED_TestC']) + if SUPPORTS_DEATH_TESTS: def testShardingWorksWithDeathTests(self): """Tests integration with death tests and sharding.""" diff --git a/googletest/test/googletest-filter-unittest_.cc b/googletest/test/googletest-filter-unittest_.cc index d30ec9c7..bc7aa594 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 { -}; +class ParamTest : public testing::TestWithParam {}; -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-json-outfiles-test.py b/googletest/test/googletest-json-outfiles-test.py index db9716c2..179283b8 100644 --- a/googletest/test/googletest-json-outfiles-test.py +++ b/googletest/test/googletest-json-outfiles-test.py @@ -71,6 +71,8 @@ EXPECTED_1 = { u'*', u'testsuite': [{ u'name': u'TestSomeProperties', + u'file': u'gtest_xml_outfile1_test_.cc', + u'line': 41, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -115,6 +117,8 @@ EXPECTED_2 = { u'*', u'testsuite': [{ u'name': u'TestSomeProperties', + u'file': u'gtest_xml_outfile2_test_.cc', + u'line': 41, u'status': u'RUN', u'result': u'COMPLETED', u'timestamp': u'*', diff --git a/googletest/test/googletest-json-output-unittest.py b/googletest/test/googletest-json-output-unittest.py index cb31965e..e0fbe465 100644 --- a/googletest/test/googletest-json-output-unittest.py +++ b/googletest/test/googletest-json-output-unittest.py @@ -90,6 +90,8 @@ EXPECTED_NON_EMPTY = { u'*', u'testsuite': [{ u'name': u'Succeeds', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 51, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -114,6 +116,10 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'Fails', + u'file': + u'gtest_xml_output_unittest_.cc', + u'line': + 59, u'status': u'RUN', u'result': @@ -148,6 +154,8 @@ EXPECTED_NON_EMPTY = { u'*', u'testsuite': [{ u'name': u'DISABLED_test_not_run', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 66, u'status': u'NOTRUN', u'result': u'SUPPRESSED', u'time': u'*', @@ -171,6 +179,8 @@ EXPECTED_NON_EMPTY = { u'*', u'testsuite': [{ u'name': u'Skipped', + u'file': 'gtest_xml_output_unittest_.cc', + u'line': 73, u'status': u'RUN', u'result': u'SKIPPED', u'time': u'*', @@ -178,6 +188,8 @@ EXPECTED_NON_EMPTY = { u'classname': u'SkippedTest' }, { u'name': u'SkippedWithMessage', + u'file': 'gtest_xml_output_unittest_.cc', + u'line': 77, u'status': u'RUN', u'result': u'SKIPPED', u'time': u'*', @@ -186,6 +198,10 @@ EXPECTED_NON_EMPTY = { }, { u'name': u'SkippedAfterFailure', + u'file': + 'gtest_xml_output_unittest_.cc', + u'line': + 81, u'status': u'RUN', u'result': @@ -220,6 +236,8 @@ EXPECTED_NON_EMPTY = { u'*', u'testsuite': [{ u'name': u'Succeeds', + u'file': 'gtest_xml_output_unittest_.cc', + u'line': 86, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -228,6 +246,10 @@ EXPECTED_NON_EMPTY = { }, { u'name': u'Fails', + u'file': + u'gtest_xml_output_unittest_.cc', + u'line': + 91, u'status': u'RUN', u'result': @@ -251,6 +273,8 @@ EXPECTED_NON_EMPTY = { }] }, { u'name': u'DISABLED_test', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 96, u'status': u'NOTRUN', u'result': u'SUPPRESSED', u'time': u'*', @@ -275,6 +299,10 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'OutputsCData', + u'file': + u'gtest_xml_output_unittest_.cc', + u'line': + 100, u'status': u'RUN', u'result': @@ -311,6 +339,10 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'InvalidCharactersInMessage', + u'file': + u'gtest_xml_output_unittest_.cc', + u'line': + 107, u'status': u'RUN', u'result': @@ -349,6 +381,8 @@ EXPECTED_NON_EMPTY = { u'aye', u'testsuite': [{ u'name': u'OneProperty', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 119, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -357,6 +391,8 @@ EXPECTED_NON_EMPTY = { u'key_1': u'1' }, { u'name': u'IntValuedProperty', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 123, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -365,6 +401,8 @@ EXPECTED_NON_EMPTY = { u'key_int': u'1' }, { u'name': u'ThreeProperties', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 127, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -375,6 +413,8 @@ EXPECTED_NON_EMPTY = { u'key_3': u'3' }, { u'name': u'TwoValuesForOneKeyUsesLastValue', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 133, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -399,6 +439,8 @@ EXPECTED_NON_EMPTY = { u'*', u'testsuite': [{ u'name': u'RecordProperty', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 138, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -407,6 +449,8 @@ EXPECTED_NON_EMPTY = { u'key': u'1' }, { u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 151, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -415,6 +459,8 @@ EXPECTED_NON_EMPTY = { u'key_for_utility_int': u'1' }, { u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 155, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -440,6 +486,8 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'HasTypeParamAttribute', u'type_param': u'int', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 171, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -464,6 +512,8 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'HasTypeParamAttribute', u'type_param': u'long', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 171, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -488,6 +538,8 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'HasTypeParamAttribute', u'type_param': u'int', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 178, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -512,6 +564,8 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'HasTypeParamAttribute', u'type_param': u'long', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 178, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -536,6 +590,8 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'HasValueParamAttribute/0', u'value_param': u'33', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 162, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -544,6 +600,8 @@ EXPECTED_NON_EMPTY = { }, { u'name': u'HasValueParamAttribute/1', u'value_param': u'42', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 162, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -552,6 +610,8 @@ EXPECTED_NON_EMPTY = { }, { u'name': u'AnotherTestThatHasValueParamAttribute/0', u'value_param': u'33', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 163, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -560,6 +620,8 @@ EXPECTED_NON_EMPTY = { }, { u'name': u'AnotherTestThatHasValueParamAttribute/1', u'value_param': u'42', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 163, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -603,6 +665,8 @@ EXPECTED_FILTERED = { u'*', u'testsuite': [{ u'name': u'Succeeds', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 51, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', diff --git a/googletest/test/googletest-list-tests-unittest_.cc b/googletest/test/googletest-list-tests-unittest_.cc index 493c6f00..5577e896 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 @@ -40,38 +39,27 @@ #include "gtest/gtest.h" // Several different test cases and tests that will be listed. -TEST(Foo, Bar1) { -} +TEST(Foo, Bar1) {} -TEST(Foo, Bar2) { -} +TEST(Foo, Bar2) {} -TEST(Foo, DISABLED_Bar3) { -} +TEST(Foo, DISABLED_Bar3) {} -TEST(Abc, Xyz) { -} +TEST(Abc, Xyz) {} -TEST(Abc, Def) { -} +TEST(Abc, Def) {} -TEST(FooBar, Baz) { -} +TEST(FooBar, Baz) {} -class FooTest : public testing::Test { -}; +class FooTest : public testing::Test {}; -TEST_F(FooTest, Test1) { -} +TEST_F(FooTest, Test1) {} -TEST_F(FooTest, DISABLED_Test2) { -} +TEST_F(FooTest, DISABLED_Test2) {} -TEST_F(FooTest, Test3) { -} +TEST_F(FooTest, Test3) {} -TEST(FooDeathTest, Test1) { -} +TEST(FooDeathTest, Test1) {} // A group of value-parameterized tests. @@ -86,70 +74,66 @@ class MyType { }; // Teaches Google Test how to print a MyType. -void PrintTo(const MyType& x, std::ostream* os) { - *os << x.value(); -} +void PrintTo(const MyType& x, std::ostream* os) { *os << x.value(); } -class ValueParamTest : public testing::TestWithParam { -}; +class ValueParamTest : public testing::TestWithParam {}; -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 -class TypedTest : public testing::Test { -}; +class TypedTest : public testing::Test {}; template -class MyArray { -}; +class MyArray {}; -typedef testing::Types > MyTypes; +typedef testing::Types< + VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT + int*, MyArray > + 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 -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 e7f9b13f..89d01b37 100644 --- a/googletest/test/googletest-listener-test.cc +++ b/googletest/test/googletest-listener-test.cc @@ -41,10 +41,10 @@ using ::testing::AddGlobalTestEnvironment; using ::testing::Environment; using ::testing::InitGoogleTest; using ::testing::Test; -using ::testing::TestSuite; using ::testing::TestEventListener; using ::testing::TestInfo; using ::testing::TestPartResult; +using ::testing::TestSuite; using ::testing::UnitTest; // Used by tests to register their events. @@ -65,8 +65,8 @@ class EventRecordingListener : public TestEventListener { void OnTestIterationStart(const UnitTest& /*unit_test*/, int iteration) override { Message message; - message << GetFullMethodName("OnTestIterationStart") - << "(" << iteration << ")"; + message << GetFullMethodName("OnTestIterationStart") << "(" << iteration + << ")"; g_events->push_back(message.GetString()); } @@ -112,8 +112,8 @@ class EventRecordingListener : public TestEventListener { void OnTestIterationEnd(const UnitTest& /*unit_test*/, int iteration) override { Message message; - message << GetFullMethodName("OnTestIterationEnd") - << "(" << iteration << ")"; + message << GetFullMethodName("OnTestIterationEnd") << "(" << iteration + << ")"; g_events->push_back(message.GetString()); } @@ -122,9 +122,7 @@ class EventRecordingListener : public TestEventListener { } private: - std::string GetFullMethodName(const char* name) { - return name_ + "." + name; - } + std::string GetFullMethodName(const char* name) { return name_ + "." + name; } std::string name_; }; @@ -252,22 +250,21 @@ void VerifyResults(const std::vector& 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(i), data[i].c_str()); + printf(" Actual event #%lu: %s\n", static_cast(i), + data[i].c_str()); } } -int main(int argc, char **argv) { +int main(int argc, char** argv) { std::vector events; g_events = &events; InitGoogleTest(&argc, argv); @@ -506,14 +503,12 @@ int main(int argc, char **argv) { "1st.OnTestProgramEnd"}; #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - VerifyResults(events, - expected_events, - sizeof(expected_events)/sizeof(expected_events[0])); + VerifyResults(events, expected_events, + sizeof(expected_events) / sizeof(expected_events[0])); // We need to check manually for ad hoc test failures that happen after // RUN_ALL_TESTS finishes. - if (UnitTest::GetInstance()->Failed()) - ret_val = 1; + if (UnitTest::GetInstance()->Failed()) ret_val = 1; return ret_val; } diff --git a/googletest/test/googletest-message-test.cc b/googletest/test/googletest-message-test.cc index 962d5191..252a8619 100644 --- a/googletest/test/googletest-message-test.cc +++ b/googletest/test/googletest-message-test.cc @@ -31,7 +31,6 @@ // Tests for the Message class. #include "gtest/gtest-message.h" - #include "gtest/gtest.h" namespace { @@ -69,8 +68,9 @@ TEST(MessageTest, StreamsFloat) { // Tests streaming a double. TEST(MessageTest, StreamsDouble) { - const std::string s = (Message() << 1260570880.4555497 << " " - << 1260572265.1954534).GetString(); + const std::string s = + (Message() << 1260570880.4555497 << " " << 1260572265.1954534) + .GetString(); // Both numbers should be printed with enough precision. EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str()); EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str()); @@ -108,8 +108,7 @@ TEST(MessageTest, StreamsString) { // Tests that we can output strings containing embedded NULs. TEST(MessageTest, StreamsStringWithEmbeddedNUL) { - const char char_array_with_nul[] = - "Here's a NUL\0 and some more string"; + const char char_array_with_nul[] = "Here's a NUL\0 and some more string"; const ::std::string string_with_nul(char_array_with_nul, sizeof(char_array_with_nul) - 1); EXPECT_EQ("Here's a NUL\\0 and some more string", @@ -129,10 +128,11 @@ TEST(MessageTest, StreamsInt) { // Tests that basic IO manipulators (endl, ends, and flush) can be // streamed to Message. TEST(MessageTest, StreamsBasicIoManip) { - EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.", - (Message() << "Line 1." << std::endl - << "A NUL char " << std::ends << std::flush - << " in line 2.").GetString()); + EXPECT_EQ( + "Line 1.\nA NUL char \\0 in line 2.", + (Message() << "Line 1." << std::endl + << "A NUL char " << std::ends << std::flush << " in line 2.") + .GetString()); } // Tests Message::GetString() diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc index cd386ff2..1265c225 100644 --- a/googletest/test/googletest-options-test.cc +++ b/googletest/test/googletest-options-test.cc @@ -39,9 +39,9 @@ #include "gtest/gtest.h" #if GTEST_OS_WINDOWS_MOBILE -# include +#include #elif GTEST_OS_WINDOWS -# include +#include #elif GTEST_OS_OS2 // For strcasecmp on OS/2 #include @@ -85,9 +85,9 @@ TEST(XmlOutputTest, GetOutputFileSingleFile) { TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) { GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_); const std::string expected_output_file = - GetAbsolutePathOf( - FilePath(std::string("path") + GTEST_PATH_SEP_ + - GetCurrentExecutableName().string() + ".xml")).string(); + GetAbsolutePathOf(FilePath(std::string("path") + GTEST_PATH_SEP_ + + GetCurrentExecutableName().string() + ".xml")) + .string(); const std::string& output_file = UnitTestOptions::GetAbsolutePathToOutputFile(); #if GTEST_OS_WINDOWS @@ -115,13 +115,10 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { const bool success = exe_str == "app"; #else const bool success = - exe_str == "googletest-options-test" || - exe_str == "gtest_all_test" || - exe_str == "lt-gtest_all_test" || - exe_str == "gtest_dll_test"; + exe_str == "googletest-options-test" || exe_str == "gtest_all_test" || + exe_str == "lt-gtest_all_test" || exe_str == "gtest_dll_test"; #endif // GTEST_OS_WINDOWS - if (!success) - FAIL() << "GetCurrentExecutableName() returns " << exe_str; + if (!success) FAIL() << "GetCurrentExecutableName() returns " << exe_str; } #if !GTEST_OS_FUCHSIA @@ -145,23 +142,26 @@ class XmlOutputChangeDirTest : public Test { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) { GTEST_FLAG_SET(output, ""); - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("test_detail.xml")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); + EXPECT_EQ( + FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml")) + .string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); } TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) { GTEST_FLAG_SET(output, "xml"); - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("test_detail.xml")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); + EXPECT_EQ( + FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml")) + .string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); } TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) { GTEST_FLAG_SET(output, "xml:filename.abc"); - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("filename.abc")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); + EXPECT_EQ( + FilePath::ConcatPaths(original_working_dir_, FilePath("filename.abc")) + .string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); } TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { @@ -170,7 +170,8 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { 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 diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index b0ad52ca..c2f96d98 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -33,12 +33,12 @@ // desired messages. Therefore, most tests in this file are MEANT TO // FAIL. +#include + #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "src/gtest-internal-inl.h" -#include - #if _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */) #endif // _MSC_VER @@ -56,9 +56,7 @@ namespace posix = ::testing::internal::posix; // Tests catching fatal failures. // A subroutine used by the following test. -void TestEq1(int x) { - ASSERT_EQ(1, x); -} +void TestEq1(int x) { ASSERT_EQ(1, x); } // This function calls a test subroutine, catches the fatal failure it // generates, and then returns early. @@ -76,24 +74,19 @@ void TryTestSubroutine() { FAIL() << "This should never be reached."; } -TEST(PassingTest, PassingTest1) { -} +TEST(PassingTest, PassingTest1) {} -TEST(PassingTest, PassingTest2) { -} +TEST(PassingTest, PassingTest2) {} // Tests that parameters of failing parameterized tests are printed in the // failing test summary. class FailingParamTest : public testing::TestWithParam {}; -TEST_P(FailingParamTest, Fails) { - EXPECT_EQ(1, GetParam()); -} +TEST_P(FailingParamTest, Fails) { EXPECT_EQ(1, GetParam()); } // This generates a test which will fail. Google Test is expected to print // its parameter when it outputs the list of all failed tests. -INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, - FailingParamTest, +INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, FailingParamTest, testing::Values(2)); // Tests that an empty value for the test suite basename yields just @@ -146,18 +139,16 @@ TEST(FatalFailureTest, FatalFailureInNestedSubroutine) { // Tests HasFatalFailure() after a failed EXPECT check. TEST(FatalFailureTest, NonfatalFailureInSubroutine) { printf("(expecting a failure on false)\n"); - EXPECT_TRUE(false); // Generates a nonfatal failure + EXPECT_TRUE(false); // Generates a nonfatal failure ASSERT_FALSE(HasFatalFailure()); // This should succeed. } // Tests interleaving user logging and Google Test assertions. TEST(LoggingTest, InterleavingLoggingAndAssertions) { - static const int a[4] = { - 3, 9, 2, 6 - }; + static const int a[4] = {3, 9, 2, 6}; printf("(expecting 2 failures on (3) >= (a[i]))\n"); - for (int i = 0; i < static_cast(sizeof(a)/sizeof(*a)); i++) { + for (int i = 0; i < static_cast(sizeof(a) / sizeof(*a)); i++) { printf("i == %d\n", i); EXPECT_GE(3, a[i]); } @@ -297,16 +288,14 @@ struct CheckPoints { static void ThreadWithScopedTrace(CheckPoints* check_points) { { SCOPED_TRACE("Trace B"); - ADD_FAILURE() - << "Expected failure #1 (in thread B, only trace B alive)."; + ADD_FAILURE() << "Expected failure #1 (in thread B, only trace B alive)."; check_points->n1.Notify(); check_points->n2.WaitForNotification(); ADD_FAILURE() << "Expected failure #3 (in thread B, trace A & B both alive)."; } // Trace B dies here. - ADD_FAILURE() - << "Expected failure #4 (in thread B, only trace A alive)."; + ADD_FAILURE() << "Expected failure #4 (in thread B, only trace A alive)."; check_points->n3.Notify(); } @@ -325,11 +314,9 @@ TEST(SCOPED_TRACETest, WorksConcurrently) { check_points.n2.Notify(); check_points.n3.WaitForNotification(); - ADD_FAILURE() - << "Expected failure #5 (in thread A, only trace A alive)."; + ADD_FAILURE() << "Expected failure #5 (in thread A, only trace A alive)."; } // Trace A dies here. - ADD_FAILURE() - << "Expected failure #6 (in thread A, no trace alive)."; + ADD_FAILURE() << "Expected failure #6 (in thread A, no trace alive)."; thread.Join(); } #endif // GTEST_IS_THREADSAFE @@ -412,9 +399,7 @@ class FatalFailureInFixtureConstructorTest : public testing::Test { } private: - void Init() { - FAIL() << "Expected failure #1, in the test fixture c'tor."; - } + void Init() { FAIL() << "Expected failure #1, in the test fixture c'tor."; } }; TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) { @@ -436,9 +421,7 @@ class NonFatalFailureInSetUpTest : public testing::Test { void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; } private: - void Deinit() { - FAIL() << "Expected failure #4, in the test fixture d'tor."; - } + void Deinit() { FAIL() << "Expected failure #4, in the test fixture d'tor."; } }; TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) { @@ -458,9 +441,7 @@ class FatalFailureInSetUpTest : public testing::Test { void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; } private: - void Deinit() { - FAIL() << "Expected failure #3, in the test fixture d'tor."; - } + void Deinit() { FAIL() << "Expected failure #3, in the test fixture d'tor."; } }; TEST_F(FatalFailureInSetUpTest, FailureInSetUp) { @@ -488,14 +469,12 @@ TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) { namespace foo { -class MixedUpTestSuiteTest : public testing::Test { -}; +class MixedUpTestSuiteTest : public testing::Test {}; TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {} TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {} -class MixedUpTestSuiteWithSameTestNameTest : public testing::Test { -}; +class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {}; TEST_F(MixedUpTestSuiteWithSameTestNameTest, TheSecondTestWithThisNameShouldFail) {} @@ -504,16 +483,14 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest, namespace bar { -class MixedUpTestSuiteTest : public testing::Test { -}; +class MixedUpTestSuiteTest : public testing::Test {}; // The following two tests are expected to fail. We rely on the // golden file to check that Google Test generates the right error message. TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {} TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {} -class MixedUpTestSuiteWithSameTestNameTest : public testing::Test { -}; +class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {}; // Expected to fail. We rely on the golden file to check that Google Test // generates the right error message. @@ -527,8 +504,7 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest, // test case checks the scenario where TEST_F appears before TEST, and // the second one checks where TEST appears before TEST_F. -class TEST_F_before_TEST_in_same_test_case : public testing::Test { -}; +class TEST_F_before_TEST_in_same_test_case : public testing::Test {}; TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {} @@ -536,15 +512,13 @@ TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {} // generates the right error message. TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {} -class TEST_before_TEST_F_in_same_test_case : public testing::Test { -}; +class TEST_before_TEST_F_in_same_test_case : public testing::Test {}; TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {} // Expected to fail. We rely on the golden file to check that Google Test // generates the right error message. -TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) { -} +TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {} // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE(). int global_integer = 0; @@ -552,9 +526,9 @@ int global_integer = 0; // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables. TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) { global_integer = 0; - EXPECT_NONFATAL_FAILURE({ - EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; - }, "Expected non-fatal failure."); + EXPECT_NONFATAL_FAILURE( + { EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; }, + "Expected non-fatal failure."); } // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables @@ -563,53 +537,48 @@ TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) { int m = 0; static int n; n = 1; - EXPECT_NONFATAL_FAILURE({ - EXPECT_EQ(m, n) << "Expected non-fatal failure."; - }, "Expected non-fatal failure."); + EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(m, n) << "Expected non-fatal failure."; }, + "Expected non-fatal failure."); } // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly // one non-fatal failure and no fatal failure. TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) { - EXPECT_NONFATAL_FAILURE({ - ADD_FAILURE() << "Expected non-fatal failure."; - }, "Expected non-fatal failure."); + EXPECT_NONFATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, + "Expected non-fatal failure."); } // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no // non-fatal failure. TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) { printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - }, ""); + EXPECT_NONFATAL_FAILURE({}, ""); } // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two // non-fatal failures. TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) { printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - ADD_FAILURE() << "Expected non-fatal failure 1."; - ADD_FAILURE() << "Expected non-fatal failure 2."; - }, ""); + EXPECT_NONFATAL_FAILURE( + { + ADD_FAILURE() << "Expected non-fatal failure 1."; + ADD_FAILURE() << "Expected non-fatal failure 2."; + }, + ""); } // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal // failure. TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) { printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - FAIL() << "Expected fatal failure."; - }, ""); + EXPECT_NONFATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, ""); } // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being // tested returns. TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - return; - }, ""); + EXPECT_NONFATAL_FAILURE({ return; }, ""); } #if GTEST_HAS_EXCEPTIONS @@ -619,10 +588,8 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { printf("(expecting a failure)\n"); try { - EXPECT_NONFATAL_FAILURE({ - throw 0; - }, ""); - } catch(int) { // NOLINT + EXPECT_NONFATAL_FAILURE({ throw 0; }, ""); + } catch (int) { // NOLINT } } @@ -631,9 +598,9 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { // Tests that EXPECT_FATAL_FAILURE() can reference global variables. TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { global_integer = 0; - EXPECT_FATAL_FAILURE({ - ASSERT_EQ(1, global_integer) << "Expected fatal failure."; - }, "Expected fatal failure."); + EXPECT_FATAL_FAILURE( + { ASSERT_EQ(1, global_integer) << "Expected fatal failure."; }, + "Expected fatal failure."); } // Tests that EXPECT_FATAL_FAILURE() can reference local static @@ -641,58 +608,51 @@ TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) { static int n; n = 1; - EXPECT_FATAL_FAILURE({ - ASSERT_EQ(0, n) << "Expected fatal failure."; - }, "Expected fatal failure."); + EXPECT_FATAL_FAILURE({ ASSERT_EQ(0, n) << "Expected fatal failure."; }, + "Expected fatal failure."); } // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly // one fatal failure and no non-fatal failure. TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) { - EXPECT_FATAL_FAILURE({ - FAIL() << "Expected fatal failure."; - }, "Expected fatal failure."); + EXPECT_FATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, + "Expected fatal failure."); } // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal // failure. TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) { printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - }, ""); + EXPECT_FATAL_FAILURE({}, ""); } // A helper for generating a fatal failure. -void FatalFailure() { - FAIL() << "Expected fatal failure."; -} +void FatalFailure() { FAIL() << "Expected fatal failure."; } // Tests that EXPECT_FATAL_FAILURE() fails when there are two // fatal failures. TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) { printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - FatalFailure(); - FatalFailure(); - }, ""); + EXPECT_FATAL_FAILURE( + { + FatalFailure(); + FatalFailure(); + }, + ""); } // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal // failure. TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) { printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - ADD_FAILURE() << "Expected non-fatal failure."; - }, ""); + EXPECT_FATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, ""); } // Tests that EXPECT_FATAL_FAILURE() fails when the statement being // tested returns. TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - return; - }, ""); + EXPECT_FATAL_FAILURE({ return; }, ""); } #if GTEST_HAS_EXCEPTIONS @@ -702,10 +662,8 @@ TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) { printf("(expecting a failure)\n"); try { - EXPECT_FATAL_FAILURE({ - throw 0; - }, ""); - } catch(int) { // NOLINT + EXPECT_FATAL_FAILURE({ throw 0; }, ""); + } catch (int) { // NOLINT } } @@ -717,21 +675,14 @@ std::string ParamNameFunc(const testing::TestParamInfo& info) { return info.param; } -class ParamTest : public testing::TestWithParam { -}; +class ParamTest : public testing::TestWithParam {}; -TEST_P(ParamTest, Success) { - EXPECT_EQ("a", GetParam()); -} +TEST_P(ParamTest, Success) { EXPECT_EQ("a", GetParam()); } -TEST_P(ParamTest, Failure) { - EXPECT_EQ("b", GetParam()) << "Expected failure"; -} +TEST_P(ParamTest, Failure) { EXPECT_EQ("b", GetParam()) << "Expected failure"; } -INSTANTIATE_TEST_SUITE_P(PrintingStrings, - ParamTest, - testing::Values(std::string("a")), - ParamNameFunc); +INSTANTIATE_TEST_SUITE_P(PrintingStrings, ParamTest, + testing::Values(std::string("a")), ParamNameFunc); // The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P. using NoTests = ParamTest; @@ -739,20 +690,17 @@ INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello")); // fails under kErrorOnUninstantiatedParameterizedTest=true class DetectNotInstantiatedTest : public testing::TestWithParam {}; -TEST_P(DetectNotInstantiatedTest, Used) { } +TEST_P(DetectNotInstantiatedTest, Used) {} // This would make the test failure from the above go away. // INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1)); template -class TypedTest : public testing::Test { -}; +class TypedTest : public testing::Test {}; TYPED_TEST_SUITE(TypedTest, testing::Types); -TYPED_TEST(TypedTest, Success) { - EXPECT_EQ(0, TypeParam()); -} +TYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); } TYPED_TEST(TypedTest, Failure) { EXPECT_EQ(1, TypeParam()) << "Expected failure"; @@ -781,14 +729,11 @@ TYPED_TEST(TypedTestWithNames, Success) {} TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); } template -class TypedTestP : public testing::Test { -}; +class TypedTestP : public testing::Test {}; TYPED_TEST_SUITE_P(TypedTestP); -TYPED_TEST_P(TypedTestP, Success) { - EXPECT_EQ(0U, TypeParam()); -} +TYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); } TYPED_TEST_P(TypedTestP, Failure) { EXPECT_EQ(1U, TypeParam()) << "Expected failure"; @@ -813,7 +758,7 @@ class TypedTestPNames { }; INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes, - TypedTestPNames); + TypedTestPNames); template class DetectNotInstantiatedTypesTest : public testing::Test {}; @@ -835,34 +780,28 @@ REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used); // We rely on the golden file to verify that tests whose test case // name ends with DeathTest are run first. -TEST(ADeathTest, ShouldRunFirst) { -} +TEST(ADeathTest, ShouldRunFirst) {} // We rely on the golden file to verify that typed tests whose test // case name ends with DeathTest are run first. template -class ATypedDeathTest : public testing::Test { -}; +class ATypedDeathTest : public testing::Test {}; typedef testing::Types NumericTypes; TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes); -TYPED_TEST(ATypedDeathTest, ShouldRunFirst) { -} - +TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {} // We rely on the golden file to verify that type-parameterized tests // whose test case name ends with DeathTest are run first. template -class ATypeParamDeathTest : public testing::Test { -}; +class ATypeParamDeathTest : public testing::Test {}; TYPED_TEST_SUITE_P(ATypeParamDeathTest); -TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) { -} +TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {} REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst); @@ -874,10 +813,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes); // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}. class ExpectFailureTest : public testing::Test { public: // Must be public and not protected due to a bug in g++ 3.4.2. - enum FailureMode { - FATAL_FAILURE, - NONFATAL_FAILURE - }; + enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE }; static void AddFailure(FailureMode failure) { if (failure == FATAL_FAILURE) { FAIL() << "Expected fatal failure."; @@ -893,11 +829,13 @@ TEST_F(ExpectFailureTest, ExpectFatalFailure) { EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure."); // Expected fatal failure, but got a non-fatal failure. printf("(expecting 1 failure)\n"); - EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal " + EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), + "Expected non-fatal " "failure."); // Wrong message. printf("(expecting 1 failure)\n"); - EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure " + EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), + "Some other fatal failure " "expected."); } @@ -910,7 +848,8 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailure) { EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure."); // Wrong message. printf("(expecting 1 failure)\n"); - EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal " + EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), + "Some other non-fatal " "failure."); } @@ -975,7 +914,8 @@ TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) { TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) { // Expected non-fatal failure, but succeeds. printf("(expecting 1 failure)\n"); - EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal " + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), + "Expected non-fatal " "failure."); // Expected non-fatal failure, but got a fatal failure. printf("(expecting 1 failure)\n"); @@ -1064,16 +1004,14 @@ class TestSuiteThatFailsToSetUp : public testing::Test { public: static void SetUpTestSuite() { EXPECT_TRUE(false); } }; -TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { - std::abort(); -} +TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); } // The main function. // // The idea is to use Google Test to run all the tests we have defined (some // of them are intended to fail), and then compare the test results // with the "golden" file. -int main(int argc, char **argv) { +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. @@ -1081,7 +1019,7 @@ int main(int argc, char **argv) { // 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 = @@ -1092,17 +1030,16 @@ int main(int argc, char **argv) { if (GTEST_FLAG_GET(internal_run_death_test) != "") { // Skip the usual output capturing if we're running as the child // process of an threadsafe-style death test. -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS posix::FReopen("nul:", "w", stdout); -# else +#else posix::FReopen("/dev/null", "w", stdout); -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS return RUN_ALL_TESTS(); } #endif // GTEST_HAS_DEATH_TEST - if (internal_skip_environment_and_ad_hoc_tests) - return RUN_ALL_TESTS(); + if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS(); // Registers two global test environments. // The golden file verifies that they are set up in the order they @@ -1110,7 +1047,7 @@ int main(int argc, char **argv) { testing::AddGlobalTestEnvironment(new FooEnvironment); testing::AddGlobalTestEnvironment(new BarEnvironment); #if _MSC_VER -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127 -#endif // _MSC_VER + GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127 +#endif // _MSC_VER return RunAllTests(); } diff --git a/googletest/test/googletest-param-test-invalid-name1-test_.cc b/googletest/test/googletest-param-test-invalid-name1-test_.cc index 955d6999..004733a1 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 {}; -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_.cc b/googletest/test/googletest-param-test-invalid-name2-test_.cc index 76371df5..d0c44da5 100644 --- a/googletest/test/googletest-param-test-invalid-name2-test_.cc +++ b/googletest/test/googletest-param-test-invalid-name2-test_.cc @@ -27,22 +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. - #include "gtest/gtest.h" namespace { class DummyTest : public ::testing::TestWithParam {}; std::string StringParamTestSuffix( - const testing::TestParamInfo& info) { + const testing::TestParamInfo &info) { return std::string(info.param); } -TEST_P(DummyTest, Dummy) { -} +TEST_P(DummyTest, Dummy) {} -INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, - DummyTest, +INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, DummyTest, ::testing::Values("a", "b", "a", "c"), StringParamTestSuffix); } // namespace @@ -51,5 +48,3 @@ int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } - - diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc index 023aa46d..848ef975 100644 --- a/googletest/test/googletest-param-test-test.cc +++ b/googletest/test/googletest-param-test-test.cc @@ -32,21 +32,21 @@ // generators objects produce correct parameter sequences and that // Google Test runtime instantiates correct tests from those sequences. +#include "test/googletest-param-test-test.h" + +#include +#include +#include +#include +#include +#include +#include + #include "gtest/gtest.h" +#include "src/gtest-internal-inl.h" // for UnitTestOptions -# include -# include -# include -# include -# include -# include -# include - -# include "src/gtest-internal-inl.h" // for UnitTestOptions -# include "test/googletest-param-test-test.h" - -using ::std::vector; using ::std::sort; +using ::std::vector; using ::testing::AddGlobalTestEnvironment; using ::testing::Bool; @@ -85,15 +85,14 @@ void VerifyGenerator(const ParamGenerator& generator, // We cannot use EXPECT_EQ() here as the values may be tuples, // which don't support <<. EXPECT_TRUE(expected_values[i] == *it) - << "where i is " << i - << ", expected_values[i] is " << PrintValue(expected_values[i]) - << ", *it is " << PrintValue(*it) + << "where i is " << i << ", expected_values[i] is " + << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it) << ", and 'it' is an iterator created with the copy constructor.\n"; ++it; } EXPECT_TRUE(it == generator.end()) - << "At the presumed end of sequence when accessing via an iterator " - << "created with the copy constructor.\n"; + << "At the presumed end of sequence when accessing via an iterator " + << "created with the copy constructor.\n"; // Test the iterator assignment. The following lines verify that // the sequence accessed via an iterator initialized via the @@ -105,15 +104,14 @@ void VerifyGenerator(const ParamGenerator& 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 @@ -216,8 +214,7 @@ class DogAdder { DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {} DogAdder operator=(const DogAdder& other) { - if (this != &other) - value_ = other.value_; + if (this != &other) value_ = other.value_; return *this; } DogAdder operator+(const DogAdder& other) const { @@ -225,9 +222,7 @@ class DogAdder { msg << value_.c_str() << other.value_.c_str(); return DogAdder(msg.GetString().c_str()); } - bool operator<(const DogAdder& other) const { - return value_ < other.value_; - } + bool operator<(const DogAdder& other) const { return value_ < other.value_; } const std::string& value() const { return value_; } private: @@ -372,19 +367,17 @@ TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) { } TEST(ValuesTest, ValuesWorksForMaxLengthList) { - const ParamGenerator 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 gen = + Values(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, + 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, + 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, + 420, 430, 440, 450, 460, 470, 480, 490, 500); const int expected_values[] = { - 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, - 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, - 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, - 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, - 410, 420, 430, 440, 450, 460, 470, 480, 490, 500}; + 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, + 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, + 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, + 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500}; VerifyGenerator(gen, expected_values); } @@ -530,7 +523,6 @@ TEST(CombineTest, NonDefaultConstructAssign) { EXPECT_TRUE(it == gen.end()); } - // Tests that an generator produces correct sequence after being // assigned from another generator. TEST(ParamGeneratorTest, AssignmentWorks) { @@ -573,7 +565,7 @@ class TestGenerationEnvironment : public ::testing::Environment { Message msg; msg << "TestsExpandedAndRun/" << i; if (UnitTestOptions::FilterMatchesTest( - "TestExpansionModule/MultipleTestGenerationTest", + "TestExpansionModule/MultipleTestGenerationTest", msg.GetString().c_str())) { perform_check = true; } @@ -595,15 +587,20 @@ class TestGenerationEnvironment : public ::testing::Environment { } private: - TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0), - tear_down_count_(0), test_body_count_(0) {} + TestGenerationEnvironment() + : fixture_constructor_count_(0), + set_up_count_(0), + tear_down_count_(0), + test_body_count_(0) {} int fixture_constructor_count_; int set_up_count_; int tear_down_count_; int test_body_count_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationEnvironment); + TestGenerationEnvironment(const TestGenerationEnvironment&) = delete; + TestGenerationEnvironment& operator=(const TestGenerationEnvironment&) = + delete; }; const int test_generation_params[] = {36, 42, 72}; @@ -612,7 +609,7 @@ class TestGenerationTest : public TestWithParam { public: enum { PARAMETER_COUNT = - sizeof(test_generation_params)/sizeof(test_generation_params[0]) + sizeof(test_generation_params) / sizeof(test_generation_params[0]) }; typedef TestGenerationEnvironment Environment; @@ -636,9 +633,9 @@ class TestGenerationTest : public TestWithParam { for (int i = 0; i < PARAMETER_COUNT; ++i) { Message test_name; test_name << "TestsExpandedAndRun/" << i; - if ( !UnitTestOptions::FilterMatchesTest( - "TestExpansionModule/MultipleTestGenerationTest", - test_name.GetString())) { + if (!UnitTestOptions::FilterMatchesTest( + "TestExpansionModule/MultipleTestGenerationTest", + test_name.GetString())) { all_tests_in_test_case_selected = false; } } @@ -668,7 +665,8 @@ class TestGenerationTest : public TestWithParam { static vector collected_parameters_; private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationTest); + TestGenerationTest(const TestGenerationTest&) = delete; + TestGenerationTest& operator=(const TestGenerationTest&) = delete; }; vector TestGenerationTest::collected_parameters_; @@ -729,8 +727,7 @@ TEST_P(ExternalInstantiationTest, IsMultipleOf33) { // Tests that a parameterized test case can be instantiated with multiple // generators. class MultipleInstantiationTest : public TestWithParam {}; -TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) { -} +TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {} INSTANTIATE_TEST_SUITE_P(Sequence1, MultipleInstantiationTest, Values(1, 2)); INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5)); @@ -780,7 +777,7 @@ class NamingTest : public TestWithParam {}; TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_suite_name()); @@ -801,7 +798,7 @@ class MacroNamingTest : public TestWithParam {}; TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_suite_name()); EXPECT_STREQ("FooSomeTestName/0", test_info->name()); @@ -815,7 +812,7 @@ class MacroNamingTestNonParametrized : public ::testing::Test {}; TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized), PREFIX_WITH_FOO(SomeTestName)) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_suite_name()); EXPECT_STREQ("FooSomeTestName", test_info->name()); @@ -839,9 +836,8 @@ TEST(MacroNameing, LookupNames) { EXPECT_NE( // know_suite_names.find("FortyTwo/MacroNamingTest"), know_suite_names.end()); - EXPECT_NE( - know_suite_names.find("MacroNamingTestNonParametrized"), - know_suite_names.end()); + EXPECT_NE(know_suite_names.find("MacroNamingTestNonParametrized"), + know_suite_names.end()); // Check that the expected form of the test name actually exists. EXPECT_NE( // know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"), @@ -924,7 +920,7 @@ class CustomIntegerNamingTest : public TestWithParam {}; TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); Message test_name_stream; test_name_stream << "TestsReportCorrectNames/" << GetParam(); EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); @@ -949,7 +945,7 @@ class CustomStructNamingTest : public TestWithParam {}; TEST_P(CustomStructNamingTest, TestsReportCorrectNames) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); Message test_name_stream; test_name_stream << "TestsReportCorrectNames/" << GetParam(); EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); @@ -979,7 +975,7 @@ class StatefulNamingTest : public ::testing::TestWithParam { TEST_P(StatefulNamingTest, TestsReportCorrectNames) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); sum_ += GetParam(); Message test_name_stream; test_name_stream << "TestsReportCorrectNames/" << sum_; @@ -1007,7 +1003,7 @@ class CommentTest : public TestWithParam {}; TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); } @@ -1021,7 +1017,8 @@ INSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest, // perform simple tests on both. class NonParameterizedBaseTest : public ::testing::Test { public: - NonParameterizedBaseTest() : n_(17) { } + NonParameterizedBaseTest() : n_(17) {} + protected: int n_; }; @@ -1029,16 +1026,14 @@ class NonParameterizedBaseTest : public ::testing::Test { class ParameterizedDerivedTest : public NonParameterizedBaseTest, public ::testing::WithParamInterface { protected: - ParameterizedDerivedTest() : count_(0) { } + ParameterizedDerivedTest() : count_(0) {} int count_; static int global_count_; }; int ParameterizedDerivedTest::global_count_ = 0; -TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { - EXPECT_EQ(17, n_); -} +TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { EXPECT_EQ(17, n_); } TEST_P(ParameterizedDerivedTest, SeesSequence) { EXPECT_EQ(17, n_); @@ -1046,11 +1041,10 @@ TEST_P(ParameterizedDerivedTest, SeesSequence) { EXPECT_EQ(GetParam(), global_count_++); } -class ParameterizedDeathTest : public ::testing::TestWithParam { }; +class ParameterizedDeathTest : public ::testing::TestWithParam {}; TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) { - EXPECT_DEATH_IF_SUPPORTED(GetParam(), - ".* value-parameterized test .*"); + EXPECT_DEATH_IF_SUPPORTED(GetParam(), ".* value-parameterized test .*"); } INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest, @@ -1084,11 +1078,11 @@ class NotInstantiatedTest : public testing::TestWithParam {}; // ... we mark is as allowed. GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest); -TEST_P(NotInstantiatedTest, Used) { } +TEST_P(NotInstantiatedTest, Used) {} using OtherName = NotInstantiatedTest; GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName); -TEST_P(OtherName, Used) { } +TEST_P(OtherName, Used) {} // Used but not instantiated, this would fail. but... template @@ -1097,11 +1091,11 @@ TYPED_TEST_SUITE_P(NotInstantiatedTypeTest); // ... we mark is as allowed. GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest); -TYPED_TEST_P(NotInstantiatedTypeTest, Used) { } +TYPED_TEST_P(NotInstantiatedTypeTest, Used) {} REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used); } // namespace works_here -int main(int argc, char **argv) { +int main(int argc, char** argv) { // Used in TestGenerationTest test suite. AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance()); // Used in GeneratorEvaluationTest test suite. Tests that the updated value diff --git a/googletest/test/googletest-param-test-test.h b/googletest/test/googletest-param-test-test.h index 89193753..6d77e104 100644 --- a/googletest/test/googletest-param-test-test.h +++ b/googletest/test/googletest-param-test-test.h @@ -39,13 +39,11 @@ // Test fixture for testing definition and instantiation of a test // in separate translation units. -class ExternalInstantiationTest : public ::testing::TestWithParam { -}; +class ExternalInstantiationTest : public ::testing::TestWithParam {}; // Test fixture for testing instantiation of a test in multiple // translation units. class InstantiationInMultipleTranslationUnitsTest - : public ::testing::TestWithParam { -}; + : public ::testing::TestWithParam {}; #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 2a29fb1d..71727a67 100644 --- a/googletest/test/googletest-param-test2-test.cc +++ b/googletest/test/googletest-param-test2-test.cc @@ -46,8 +46,7 @@ ParamGenerator 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 b14e1f76..c20dfa4c 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -33,18 +33,18 @@ #include "gtest/internal/gtest-port.h" #if GTEST_OS_MAC -# include +#include #endif // GTEST_OS_MAC #include // NOLINT #include #include -#include // NOLINT +#include // NOLINT #include // For std::pair and std::make_pair. #include -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" #include "src/gtest-internal-inl.h" using std::make_pair; @@ -238,8 +238,8 @@ TEST(GtestCheckSyntaxTest, WorksWithSwitch) { } switch (0) - case 0: - GTEST_CHECK_(true) << "Check failed in switch case"; + case 0: + GTEST_CHECK_(true) << "Check failed in switch case"; } // Verifies behavior of FormatFileLocation. @@ -281,7 +281,7 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { } #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \ - GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ + GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD void* ThreadFunc(void* data) { internal::Mutex* mutex = static_cast(data); @@ -357,13 +357,13 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { const bool a_false_condition = false; const char regex[] = #ifdef _MSC_VER - "googletest-port-test\\.cc\\(\\d+\\):" + "googletest-port-test\\.cc\\(\\d+\\):" #elif GTEST_USES_POSIX_RE - "googletest-port-test\\.cc:[0-9]+" + "googletest-port-test\\.cc:[0-9]+" #else - "googletest-port-test\\.cc:\\d+" + "googletest-port-test\\.cc:\\d+" #endif // _MSC_VER - ".*a_false_condition.*Extra info.*"; + ".*a_false_condition.*Extra info.*"; EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info", regex); @@ -372,10 +372,12 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { #if GTEST_HAS_DEATH_TEST TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { - EXPECT_EXIT({ - GTEST_CHECK_(true) << "Extra info"; - ::std::cerr << "Success\n"; - exit(0); }, + EXPECT_EXIT( + { + GTEST_CHECK_(true) << "Extra info"; + ::std::cerr << "Success\n"; + exit(0); + }, ::testing::ExitedWithCode(0), "Success"); } @@ -385,17 +387,13 @@ TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { // the platform. The test will produce compiler errors in case of failure. // For simplicity, we only cover the most important platforms here. TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { -#if !GTEST_USES_PCRE -# if GTEST_HAS_POSIX_RE - +#if GTEST_HAS_ABSL + EXPECT_TRUE(GTEST_USES_RE2); +#elif GTEST_HAS_POSIX_RE EXPECT_TRUE(GTEST_USES_POSIX_RE); - -# else - +#else EXPECT_TRUE(GTEST_USES_SIMPLE_RE); - -# endif -#endif // !GTEST_USES_PCRE +#endif } #if GTEST_USES_POSIX_RE @@ -423,9 +421,9 @@ TYPED_TEST(RETest, ImplicitConstructorWorks) { // Tests that RE's constructors reject invalid regular expressions. TYPED_TEST(RETest, RejectsInvalidRegex) { - EXPECT_NONFATAL_FAILURE({ - const RE invalid(TypeParam("?")); - }, "\"?\" is not a valid POSIX Extended regular expression."); + EXPECT_NONFATAL_FAILURE( + { const RE invalid(TypeParam("?")); }, + "\"?\" is not a valid POSIX Extended regular expression."); } // Tests RE::FullMatch(). @@ -819,8 +817,7 @@ TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) { EXPECT_TRUE(MatchRegexAtHead("a?b", "ab")); } -TEST(MatchRegexAtHeadTest, - WorksWhenRegexStartsWithRepetionOfEscapeSequence) { +TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) { EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc")); EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b")); @@ -876,17 +873,14 @@ TEST(RETest, ImplicitConstructorWorks) { // Tests that RE's constructors reject invalid regular expressions. TEST(RETest, RejectsInvalidRegex) { - EXPECT_NONFATAL_FAILURE({ - const RE normal(NULL); - }, "NULL is not a valid simple regular expression"); + EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); }, + "NULL is not a valid simple regular expression"); - EXPECT_NONFATAL_FAILURE({ - const RE normal(".*(\\w+"); - }, "'(' is unsupported"); + EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); }, + "'(' is unsupported"); - EXPECT_NONFATAL_FAILURE({ - const RE invalid("^?"); - }, "'?' can only follow a repeatable token"); + EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); }, + "'?' can only follow a repeatable token"); } // Tests RE::FullMatch(). @@ -1028,12 +1022,13 @@ TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) { TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) { // AssertHeld() is flaky only in the presence of multiple threads accessing // the lock. In this case, the test is robust. - EXPECT_DEATH_IF_SUPPORTED({ - Mutex m; - { MutexLock lock(&m); } - m.AssertHeld(); - }, - "thread .*hold"); + EXPECT_DEATH_IF_SUPPORTED( + { + Mutex m; + { MutexLock lock(&m); } + m.AssertHeld(); + }, + "thread .*hold"); } TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { @@ -1044,8 +1039,8 @@ 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_); @@ -1076,7 +1071,7 @@ class AtomicCounterWithMutex { 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; @@ -1086,12 +1081,11 @@ class AtomicCounterWithMutex { private: volatile int value_; Mutex* const mutex_; // Protects value_. - Random random_; + Random random_; }; void CountingThreadFunc(pair 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. @@ -1107,14 +1101,12 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) { // Creates and runs kThreadCount threads that increment locked_counter // kCycleCount times each. for (int i = 0; i < kThreadCount; ++i) { - counting_threads[i].reset(new ThreadType(&CountingThreadFunc, - make_pair(&locked_counter, - kCycleCount), - &threads_can_start)); + counting_threads[i].reset(new ThreadType( + &CountingThreadFunc, make_pair(&locked_counter, kCycleCount), + &threads_can_start)); } threads_can_start.Notify(); - for (int i = 0; i < kThreadCount; ++i) - counting_threads[i]->Join(); + for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join(); // If the mutex lets more than one thread to increment the counter at a // time, they are likely to encounter a race condition and have some @@ -1124,7 +1116,7 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) { } template -void RunFromThread(void (func)(T), T param) { +void RunFromThread(void(func)(T), T param) { ThreadWithParam thread(func, param, nullptr); thread.Join(); } @@ -1190,7 +1182,8 @@ class DestructorCall { #endif static std::vector* const list_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall); + DestructorCall(const DestructorCall&) = delete; + DestructorCall& operator=(const DestructorCall&) = delete; }; std::vector* const DestructorCall::list_ = diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index 0058917a..acfecf97 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-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 Test - The Google C++ Testing and Mocking Framework // // This file tests the universal value printer. @@ -56,30 +55,20 @@ // Some user-defined types for testing the universal value printer. // An anonymous enum type. -enum AnonymousEnum { - kAE1 = -1, - kAE2 = 1 -}; +enum AnonymousEnum { kAE1 = -1, kAE2 = 1 }; // An enum without a user-defined printer. -enum EnumWithoutPrinter { - kEWP1 = -2, - kEWP2 = 42 -}; +enum EnumWithoutPrinter { kEWP1 = -2, kEWP2 = 42 }; // An enum with a << operator. -enum EnumWithStreaming { - kEWS1 = 10 -}; +enum EnumWithStreaming { kEWS1 = 10 }; std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) { return os << (e == kEWS1 ? "kEWS1" : "invalid"); } // An enum with a PrintTo() function. -enum EnumWithPrintTo { - kEWPT1 = 1 -}; +enum EnumWithPrintTo { kEWPT1 = 1 }; void PrintTo(EnumWithPrintTo e, std::ostream* os) { *os << (e == kEWPT1 ? "kEWPT1" : "invalid"); @@ -108,6 +97,7 @@ template class UnprintableTemplateInGlobal { public: UnprintableTemplateInGlobal() : value_() {} + private: T value_; }; @@ -133,6 +123,7 @@ class UnprintableInFoo { public: UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); } double z() const { return z_; } + private: char xy_[8]; double z_; @@ -149,8 +140,7 @@ void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) { } // A type with a user-defined << for printing its pointer. -struct PointerPrintable { -}; +struct PointerPrintable {}; ::std::ostream& operator<<(::std::ostream& os, const PointerPrintable* /* x */) { @@ -164,6 +154,7 @@ class PrintableViaPrintToTemplate { explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {} const T& value() const { return value_; } + private: T value_; }; @@ -180,6 +171,7 @@ class StreamableTemplateInFoo { StreamableTemplateInFoo() : value_() {} const T& value() const { return value_; } + private: T value_; }; @@ -255,7 +247,6 @@ class UniversalPrinter> { }; } // namespace internal - namespace gtest_printers_test { using ::std::deque; @@ -350,29 +341,21 @@ TEST(PrintCharTest, PlainChar) { // signed char. TEST(PrintCharTest, SignedChar) { EXPECT_EQ("'\\0'", Print(static_cast('\0'))); - EXPECT_EQ("'\\xCE' (-50)", - Print(static_cast(-50))); + EXPECT_EQ("'\\xCE' (-50)", Print(static_cast(-50))); } // unsigned char. TEST(PrintCharTest, UnsignedChar) { EXPECT_EQ("'\\0'", Print(static_cast('\0'))); - EXPECT_EQ("'b' (98, 0x62)", - Print(static_cast('b'))); + EXPECT_EQ("'b' (98, 0x62)", Print(static_cast('b'))); } -TEST(PrintCharTest, Char16) { - EXPECT_EQ("U+0041", Print(u'A')); -} +TEST(PrintCharTest, Char16) { EXPECT_EQ("U+0041", Print(u'A')); } -TEST(PrintCharTest, Char32) { - EXPECT_EQ("U+0041", Print(U'A')); -} +TEST(PrintCharTest, Char32) { EXPECT_EQ("U+0041", Print(U'A')); } #ifdef __cpp_char8_t -TEST(PrintCharTest, Char8) { - EXPECT_EQ("U+0041", Print(u8'A')); -} +TEST(PrintCharTest, Char8) { EXPECT_EQ("U+0041", Print(u8'A')); } #endif // Tests printing other simple, built-in types. @@ -414,8 +397,8 @@ TEST(PrintTypeSizeTest, Wchar_t) { TEST(PrintBuiltInTypeTest, Integer) { EXPECT_EQ("'\\xFF' (255)", Print(static_cast(255))); // uint8 EXPECT_EQ("'\\x80' (-128)", Print(static_cast(-128))); // int8 - EXPECT_EQ("65535", Print(std::numeric_limits::max())); // uint16 - EXPECT_EQ("-32768", Print(std::numeric_limits::min())); // int16 + EXPECT_EQ("65535", Print(std::numeric_limits::max())); // uint16 + EXPECT_EQ("-32768", Print(std::numeric_limits::min())); // int16 EXPECT_EQ("4294967295", Print(std::numeric_limits::max())); // uint32 EXPECT_EQ("-2147483648", @@ -446,7 +429,7 @@ TEST(PrintBuiltInTypeTest, Size_t) { #if !GTEST_OS_WINDOWS // Windows has no ssize_t type. EXPECT_EQ("-2", Print(static_cast(-2))); // ssize_t. -#endif // !GTEST_OS_WINDOWS +#endif // !GTEST_OS_WINDOWS } // gcc/clang __{u,}int128_t values. @@ -516,8 +499,9 @@ TEST(PrintCStringTest, Null) { // Tests that C strings are escaped properly. TEST(PrintCStringTest, EscapesProperly) { const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f" - "\\n\\r\\t\\v\\x7F\\xFF a\"", + EXPECT_EQ(PrintPointer(p) + + " pointing to \"'\\\"?\\\\\\a\\b\\f" + "\\n\\r\\t\\v\\x7F\\xFF a\"", Print(p)); } @@ -636,10 +620,12 @@ TEST(PrintWideCStringTest, Null) { // Tests that wide C strings are escaped properly. TEST(PrintWideCStringTest, EscapesProperly) { - const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r', - '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'}; - EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f" - "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"", + const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', + '\f', '\n', '\r', '\t', '\v', 0xD3, + 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'}; + EXPECT_EQ(PrintPointer(s) + + " pointing to L\"'\\\"?\\\\\\a\\b\\f" + "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"", Print(static_cast(s))); } #endif // native wchar_t @@ -721,10 +707,9 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) { // standard disallows casting between pointers to functions and // pointers to objects, and some compilers (e.g. GCC 3.4) enforce // this limitation. - EXPECT_EQ( - PrintPointer(reinterpret_cast( - reinterpret_cast(&MyFunction))), - Print(&MyFunction)); + EXPECT_EQ(PrintPointer(reinterpret_cast( + reinterpret_cast(&MyFunction))), + Print(&MyFunction)); int (*p)(bool) = NULL; // NOLINT EXPECT_EQ("NULL", Print(p)); } @@ -733,14 +718,13 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) { // another. template 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 @@ -761,8 +745,7 @@ TEST(PrintPointerTest, MemberVariablePointer) { EXPECT_TRUE(HasPrefix(Print(&Foo::value), Print(sizeof(&Foo::value)) + "-byte object ")); int Foo::*p = NULL; // NOLINT - EXPECT_TRUE(HasPrefix(Print(p), - Print(sizeof(p)) + "-byte object ")); + EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object ")); } // Tests printing member function pointers. Although they are called @@ -776,8 +759,7 @@ TEST(PrintPointerTest, MemberFunctionPointer) { HasPrefix(Print(&Foo::MyVirtualMethod), Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object ")); int (Foo::*p)(char) = NULL; // NOLINT - EXPECT_TRUE(HasPrefix(Print(p), - Print(sizeof(p)) + "-byte object ")); + EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object ")); } // Tests printing C arrays. @@ -791,29 +773,26 @@ std::string PrintArrayHelper(T (&a)[N]) { // One-dimensional array. TEST(PrintArrayTest, OneDimensionalArray) { - int a[5] = { 1, 2, 3, 4, 5 }; + int a[5] = {1, 2, 3, 4, 5}; EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a)); } // Two-dimensional array. TEST(PrintArrayTest, TwoDimensionalArray) { - int a[2][5] = { - { 1, 2, 3, 4, 5 }, - { 6, 7, 8, 9, 0 } - }; + int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}}; EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a)); } // Array of const elements. TEST(PrintArrayTest, ConstArray) { - const bool a[1] = { false }; + const bool a[1] = {false}; EXPECT_EQ("{ false }", PrintArrayHelper(a)); } // char array without terminating NUL. TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) { // Array a contains '\0' in the middle and doesn't end with '\0'. - char a[] = { 'H', '\0', 'i' }; + char a[] = {'H', '\0', 'i'}; EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a)); } @@ -834,9 +813,7 @@ TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) { // char8_t array with terminating NUL. TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) { const char8_t a[] = u8"\0世界"; - EXPECT_EQ( - "u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", - PrintArrayHelper(a)); + EXPECT_EQ("u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", PrintArrayHelper(a)); } #endif @@ -889,7 +866,7 @@ TEST(PrintArrayTest, ObjectArray) { // Array with many elements. TEST(PrintArrayTest, BigArray) { - int a[100] = { 1, 2, 3 }; + int a[100] = {1, 2, 3}; EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }", PrintArrayHelper(a)); } @@ -909,11 +886,14 @@ TEST(PrintStringTest, StringAmbiguousHex) { // '\x6', '\x6B', or '\x6BA'. // a hex escaping sequence following by a decimal digit - EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3"))); + EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" + "3"))); // a hex escaping sequence following by a hex digit (lower-case) - EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas"))); + EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" + "bananas"))); // a hex escaping sequence following by a hex digit (upper-case) - EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA"))); + EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" + "BANANA"))); // a hex escaping sequence following by a non-xdigit EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!"))); } @@ -923,19 +903,21 @@ TEST(PrintStringTest, StringAmbiguousHex) { // ::std::wstring. TEST(PrintWideStringTest, StringInStdNamespace) { const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; - const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t)); - EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" - "\\xD3\\x576\\x8D3\\xC74D a\\0\"", - Print(str)); + const ::std::wstring str(s, sizeof(s) / sizeof(wchar_t)); + EXPECT_EQ( + "L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" + "\\xD3\\x576\\x8D3\\xC74D a\\0\"", + Print(str)); } TEST(PrintWideStringTest, StringAmbiguousHex) { // same for wide strings. - EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3"))); - EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", - Print(::std::wstring(L"mm\x6" L"bananas"))); - EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", - Print(::std::wstring(L"NOM\x6" L"BANANA"))); + EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" + L"3"))); + EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", Print(::std::wstring(L"mm\x6" + L"bananas"))); + EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", Print(::std::wstring(L"NOM\x6" + L"BANANA"))); EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!"))); } #endif // GTEST_HAS_STD_WSTRING @@ -1049,7 +1031,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) { EXPECT_EQ("{ 1, 3 }", Print(non_empty)); } - TEST(PrintStlContainerTest, OneElementHashMap) { ::std::unordered_map map1; map1[1] = 'a'; @@ -1065,11 +1046,9 @@ TEST(PrintStlContainerTest, HashMultiMap) { const std::string result = Print(map1); EXPECT_TRUE(result == "{ (5, true), (5, false) }" || result == "{ (5, false), (5, true) }") - << " where Print(map1) returns \"" << result << "\"."; + << " where Print(map1) returns \"" << result << "\"."; } - - TEST(PrintStlContainerTest, HashSet) { ::std::unordered_set set1; set1.insert(1); @@ -1078,7 +1057,7 @@ TEST(PrintStlContainerTest, HashSet) { TEST(PrintStlContainerTest, HashMultiSet) { const int kSize = 5; - int a[kSize] = { 1, 1, 2, 5, 1 }; + int a[kSize] = {1, 1, 2, 5, 1}; ::std::unordered_multiset set1(a, a + kSize); // Elements of hash_multiset can be printed in any order. @@ -1094,8 +1073,8 @@ TEST(PrintStlContainerTest, HashMultiSet) { ASSERT_NE(isdigit(static_cast(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; } } @@ -1105,7 +1084,6 @@ TEST(PrintStlContainerTest, HashMultiSet) { EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); } - TEST(PrintStlContainerTest, List) { const std::string a[] = {"hello", "world"}; const list strings(a, a + 2); @@ -1135,20 +1113,19 @@ TEST(PrintStlContainerTest, MultiMap) { } TEST(PrintStlContainerTest, Set) { - const unsigned int a[] = { 3, 0, 5 }; + const unsigned int a[] = {3, 0, 5}; set 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 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 ints(a, a + 3); EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); } @@ -1166,32 +1143,34 @@ TEST(PrintStlContainerTest, Vector) { } TEST(PrintStlContainerTest, LongSequence) { - const int a[100] = { 1, 2, 3 }; + const int a[100] = {1, 2, 3}; const vector 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 l1(a1, a1 + 2); const list l2(a2, a2 + 3); - vector > v; + vector> 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 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 b(a, 2, RelationToSourceReference()); EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b)); } @@ -1243,20 +1222,18 @@ TEST(PrintStdTupleTest, VariousSizes) { t10(false, 'a', static_cast(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, char> nested( - ::std::make_tuple(5, true), 'a'); + ::std::tuple<::std::tuple, 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; @@ -1280,8 +1257,7 @@ TEST(PrintReferenceWrapper, Unprintable) { // Unprintable types in the global namespace. TEST(PrintUnprintableTypeTest, InGlobalNamespace) { - EXPECT_EQ("1-byte object <00>", - Print(UnprintableTemplateInGlobal())); + EXPECT_EQ("1-byte object <00>", Print(UnprintableTemplateInGlobal())); } // Unprintable types in a user namespace. @@ -1298,14 +1274,15 @@ struct Big { }; TEST(PrintUnpritableTypeTest, BigObject) { - EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>", - Print(Big())); + EXPECT_EQ( + "257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>", + Print(Big())); } // Tests printing user-defined streamable types. @@ -1348,8 +1325,7 @@ TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) { // Tests printing user-defined types that have a PrintTo() function. TEST(PrintPrintableTypeTest, InUserNamespace) { - EXPECT_EQ("PrintableViaPrintTo: 0", - Print(::foo::PrintableViaPrintTo())); + EXPECT_EQ("PrintableViaPrintTo: 0", Print(::foo::PrintableViaPrintTo())); } // Tests printing a pointer to a user-defined type that has a << @@ -1371,16 +1347,14 @@ TEST(PrintReferenceTest, PrintsAddressAndValue) { int n = 5; EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n)); - int a[2][3] = { - { 0, 1, 2 }, - { 3, 4, 5 } - }; + int a[2][3] = {{0, 1, 2}, {3, 4, 5}}; EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }", PrintByRef(a)); const ::foo::UnprintableInFoo x; - EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object " - "", + EXPECT_EQ("@" + PrintPointer(&x) + + " 16-byte object " + "", PrintByRef(x)); } @@ -1396,33 +1370,29 @@ TEST(PrintReferenceTest, HandlesFunctionPointer) { // this limitation. const std::string fp_string = PrintPointer(reinterpret_cast( reinterpret_cast(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(&p)) + " " + - Print(sizeof(p)) + "-byte object ")); + EXPECT_TRUE(HasPrefix(PrintByRef(p), + "@" + PrintPointer(reinterpret_cast(&p)) + + " " + Print(sizeof(p)) + "-byte object ")); char (Foo::*p2)(int n) = &Foo::MyVirtualMethod; - EXPECT_TRUE(HasPrefix( - PrintByRef(p2), - "@" + PrintPointer(reinterpret_cast(&p2)) + " " + - Print(sizeof(p2)) + "-byte object ")); + EXPECT_TRUE(HasPrefix(PrintByRef(p2), + "@" + PrintPointer(reinterpret_cast(&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 @@ -1431,8 +1401,7 @@ TEST(PrintReferenceTest, HandlesMemberVariablePointer) { // scalar TEST(FormatForComparisonFailureMessageTest, WorksForScalar) { - EXPECT_STREQ("123", - FormatForComparisonFailureMessage(123, 124).c_str()); + EXPECT_STREQ("123", FormatForComparisonFailureMessage(123, 124).c_str()); } // non-char pointer @@ -1446,9 +1415,8 @@ TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) { TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) { // In expression 'array == x', 'array' is compared by pointer. // Therefore we want to print an array operand as a pointer. - int n[] = { 1, 2, 3 }; - EXPECT_EQ(PrintPointer(n), - FormatForComparisonFailureMessage(n, n).c_str()); + int n[] = {1, 2, 3}; + EXPECT_EQ(PrintPointer(n), FormatForComparisonFailureMessage(n, n).c_str()); } // Tests formatting a char pointer when it's compared with another pointer. @@ -1464,8 +1432,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) { // const char* const char* s = "hello"; - EXPECT_EQ(PrintPointer(s), - FormatForComparisonFailureMessage(s, s).c_str()); + EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str()); // char* char ch = 'a'; @@ -1482,8 +1449,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) { // const wchar_t* const wchar_t* s = L"hello"; - EXPECT_EQ(PrintPointer(s), - FormatForComparisonFailureMessage(s, s).c_str()); + EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str()); // wchar_t* wchar_t ch = L'a'; @@ -1580,13 +1546,11 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) { // Useful for testing PrintToString(). We cannot use EXPECT_EQ() // there as its implementation uses PrintToString(). The caller must // ensure that 'value' has no side effect. -#define EXPECT_PRINT_TO_STRING_(value, expected_string) \ - EXPECT_TRUE(PrintToString(value) == (expected_string)) \ +#define EXPECT_PRINT_TO_STRING_(value, expected_string) \ + EXPECT_TRUE(PrintToString(value) == (expected_string)) \ << " where " #value " prints as " << (PrintToString(value)) -TEST(PrintToStringTest, WorksForScalar) { - EXPECT_PRINT_TO_STRING_(123, "123"); -} +TEST(PrintToStringTest, WorksForScalar) { EXPECT_PRINT_TO_STRING_(123, "123"); } TEST(PrintToStringTest, WorksForPointerToConstChar) { const char* p = "hello"; @@ -1611,7 +1575,7 @@ TEST(PrintToStringTest, EscapesForPointerToNonConstChar) { } TEST(PrintToStringTest, WorksForArray) { - int n[3] = { 1, 2, 3 }; + int n[3] = {1, 2, 3}; EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }"); } @@ -1628,8 +1592,8 @@ TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) { EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\""); } - TEST(PrintToStringTest, ContainsNonLatin) { - // Sanity test with valid UTF-8. Prints both in hex and as text. +TEST(PrintToStringTest, ContainsNonLatin) { + // Test with valid UTF-8. Prints both in hex and as text. std::string non_ascii_str = ::std::string("오전 4:30"); EXPECT_PRINT_TO_STRING_(non_ascii_str, "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n" @@ -1645,57 +1609,58 @@ TEST(IsValidUTF8Test, IllFormedUTF8) { // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is // expected to fail, thus output does not contain "As Text:". - static const char *const kTestdata[][2] = { - // 2-byte lead byte followed by a single-byte character. - {"\xC3\x74", "\"\\xC3t\""}, - // Valid 2-byte character followed by an orphan trail byte. - {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""}, - // Lead byte without trail byte. - {"abc\xC3", "\"abc\\xC3\""}, - // 3-byte lead byte, single-byte character, orphan trail byte. - {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""}, - // Truncated 3-byte character. - {"\xE2\x80", "\"\\xE2\\x80\""}, - // Truncated 3-byte character followed by valid 2-byte char. - {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""}, - // Truncated 3-byte character followed by a single-byte character. - {"\xE2\x80\x7A", "\"\\xE2\\x80z\""}, - // 3-byte lead byte followed by valid 3-byte character. - {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""}, - // 4-byte lead byte followed by valid 3-byte character. - {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""}, - // Truncated 4-byte character. - {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""}, - // Invalid UTF-8 byte sequences embedded in other chars. - {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""}, - {"abc\xC3\x84\xE2\x80\xC3\x84xyz", - "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""}, - // Non-shortest UTF-8 byte sequences are also ill-formed. - // The classics: xC0, xC1 lead byte. - {"\xC0\x80", "\"\\xC0\\x80\""}, - {"\xC1\x81", "\"\\xC1\\x81\""}, - // Non-shortest sequences. - {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""}, - {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""}, - // Last valid code point before surrogate range, should be printed as text, - // too. - {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"퟿\""}, - // Start of surrogate lead. Surrogates are not printed as text. - {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""}, - // Last non-private surrogate lead. - {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""}, - // First private-use surrogate lead. - {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""}, - // Last private-use surrogate lead. - {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""}, - // Mid-point of surrogate trail. - {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""}, - // First valid code point after surrogate range, should be printed as text, - // too. - {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""} - }; + 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) { + for (int i = 0; i < int(sizeof(kTestdata) / sizeof(kTestdata[0])); ++i) { EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]); } } @@ -1844,15 +1809,15 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) { } TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::make_tuple(1)); + Strings result = + UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1)); ASSERT_EQ(1u, result.size()); EXPECT_EQ("1", result[0]); } TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::make_tuple(1, 'a')); + Strings result = + UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1, 'a')); ASSERT_EQ(2u, result.size()); EXPECT_EQ("1", result[0]); EXPECT_EQ("'a' (97, 0x61)", result[1]); diff --git a/googletest/test/googletest-setuptestsuite-test_.cc b/googletest/test/googletest-setuptestsuite-test_.cc index a4bc4ef4..d20899f5 100644 --- a/googletest/test/googletest-setuptestsuite-test_.cc +++ b/googletest/test/googletest-setuptestsuite-test_.cc @@ -27,23 +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. - #include "gtest/gtest.h" class SetupFailTest : public ::testing::Test { protected: - static void SetUpTestSuite() { - ASSERT_EQ("", "SET_UP_FAIL"); - } + static void SetUpTestSuite() { ASSERT_EQ("", "SET_UP_FAIL"); } }; TEST_F(SetupFailTest, NoopPassingTest) {} class TearDownFailTest : public ::testing::Test { protected: - static void TearDownTestSuite() { - ASSERT_EQ("", "TEAR_DOWN_FAIL"); - } + static void TearDownTestSuite() { ASSERT_EQ("", "TEAR_DOWN_FAIL"); } }; TEST_F(TearDownFailTest, NoopPassingTest) {} diff --git a/googletest/test/googletest-shuffle-test_.cc b/googletest/test/googletest-shuffle-test_.cc index 4505663a..a14e22f9 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" @@ -88,7 +87,7 @@ class TestNamePrinter : public EmptyTestEventListener { } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { InitGoogleTest(&argc, argv); // Replaces the default printer with TestNamePrinter, which prints diff --git a/googletest/test/googletest-test-part-test.cc b/googletest/test/googletest-test-part-test.cc index 44cf7ca0..076e5be2 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(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_.cc b/googletest/test/googletest-throw-on-failure-test_.cc index 83bb914c..3b81a5a1 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 // for fflush, fprintf, NULL, etc. +#include // for exit -#include // for fflush, fprintf, NULL, etc. -#include // for exit -#include // for set_terminate +#include // 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_.cc b/googletest/test/googletest-uninitialized-test_.cc index b4434d51..88b61fce 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 e83ca2e1..f2eae120 100644 --- a/googletest/test/gtest-typed-test2_test.cc +++ b/googletest/test/gtest-typed-test2_test.cc @@ -27,11 +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. - #include -#include "test/gtest-typed-test_test.h" #include "gtest/gtest.h" +#include "test/gtest-typed-test_test.h" // Tests that the same type-parameterized test case can be // instantiated in different translation units linked together. diff --git a/googletest/test/gtest-typed-test_test.cc b/googletest/test/gtest-typed-test_test.cc index 5fc678cb..af23f86d 100644 --- a/googletest/test/gtest-typed-test_test.cc +++ b/googletest/test/gtest-typed-test_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 "test/gtest-typed-test_test.h" #include @@ -50,9 +49,7 @@ class CommonTest : public Test { // For some technical reason, SetUpTestSuite() and TearDownTestSuite() // must be public. public: - static void SetUpTestSuite() { - shared_ = new T(5); - } + static void SetUpTestSuite() { shared_ = new T(5); } static void TearDownTestSuite() { delete shared_; @@ -130,8 +127,7 @@ TYPED_TEST(CommonTest, ValuesAreStillCorrect) { // translation unit. template -class TypedTest1 : public Test { -}; +class TypedTest1 : public Test {}; // Verifies that the second argument of TYPED_TEST_SUITE can be a // single type. @@ -139,8 +135,7 @@ TYPED_TEST_SUITE(TypedTest1, int); TYPED_TEST(TypedTest1, A) {} template -class TypedTest2 : public Test { -}; +class TypedTest2 : public Test {}; // Verifies that the second argument of TYPED_TEST_SUITE can be a // Types<...> type list. @@ -155,15 +150,12 @@ TYPED_TEST(TypedTest2, A) {} namespace library1 { template -class NumericTest : public Test { -}; +class NumericTest : public Test {}; typedef Types NumericTypes; TYPED_TEST_SUITE(NumericTest, NumericTypes); -TYPED_TEST(NumericTest, DefaultIsZero) { - EXPECT_EQ(0, TypeParam()); -} +TYPED_TEST(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); } } // namespace library1 @@ -265,8 +257,7 @@ TEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) { // and SetUp()/TearDown() work correctly in type-parameterized tests. template -class DerivedTest : public CommonTest { -}; +class DerivedTest : public CommonTest {}; TYPED_TEST_SUITE_P(DerivedTest); @@ -290,8 +281,8 @@ TYPED_TEST_P(DerivedTest, ValuesAreStillCorrect) { EXPECT_EQ(2, this->value_); } -REGISTER_TYPED_TEST_SUITE_P(DerivedTest, - ValuesAreCorrect, ValuesAreStillCorrect); +REGISTER_TYPED_TEST_SUITE_P(DerivedTest, ValuesAreCorrect, + ValuesAreStillCorrect); typedef Types MyTwoTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, DerivedTest, MyTwoTypes); @@ -334,14 +325,13 @@ class TypeParametrizedTestNames { }; INSTANTIATE_TYPED_TEST_SUITE_P(CustomName, TypeParametrizedTestWithNames, - TwoTypes, TypeParametrizedTestNames); + TwoTypes, TypeParametrizedTestNames); // Tests that multiple TYPED_TEST_SUITE_P's can be defined in the same // translation unit. template -class TypedTestP1 : public Test { -}; +class TypedTestP1 : public Test {}; TYPED_TEST_SUITE_P(TypedTestP1); @@ -359,8 +349,7 @@ using IntBeforeRegisterTypedTestSuiteP = int; REGISTER_TYPED_TEST_SUITE_P(TypedTestP1, A, B); template -class TypedTestP2 : public Test { -}; +class TypedTestP2 : public Test {}; TYPED_TEST_SUITE_P(TypedTestP2); @@ -396,21 +385,17 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, ContainerTest, MyContainers); namespace library2 { template -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 NumericTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, NumericTest, NumericTypes); @@ -418,20 +403,20 @@ static const char* GetTestName() { return testing::UnitTest::GetInstance()->current_test_info()->name(); } // Test the stripping of space from test names -template class TrimmedTest : public Test { }; +template +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 struct MyPair {}; +REGISTER_TYPED_TEST_SUITE_P(TrimmedTest, Test1, Test2, Test3, Test4, + Test5); // NOLINT +template +struct MyPair {}; // Be sure to try a type with a comma in its name just in case it matters. typedef Types > TrimTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, TrimmedTest, TrimTypes); } // namespace library2 - diff --git a/googletest/test/gtest-typed-test_test.h b/googletest/test/gtest-typed-test_test.h index 8ce559c9..f3ef0a59 100644 --- a/googletest/test/gtest-typed-test_test.h +++ b/googletest/test/gtest-typed-test_test.h @@ -40,21 +40,18 @@ using testing::Test; // and gtest-typed-test2_test.cc. template -class ContainerTest : public Test { -}; +class ContainerTest : public Test {}; TYPED_TEST_SUITE_P(ContainerTest); -TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) { - TypeParam container; -} +TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) { TypeParam container; } TYPED_TEST_P(ContainerTest, InitialSizeIsZero) { TypeParam container; EXPECT_EQ(0U, container.size()); } -REGISTER_TYPED_TEST_SUITE_P(ContainerTest, - CanBeDefaultConstructed, InitialSizeIsZero); +REGISTER_TYPED_TEST_SUITE_P(ContainerTest, CanBeDefaultConstructed, + InitialSizeIsZero); #endif // GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_ diff --git a/googletest/test/gtest-unittest-api_test.cc b/googletest/test/gtest-unittest-api_test.cc index 8ef50583..2a13fa32 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 // For strcmp. + #include +#include "gtest/gtest.h" + using ::testing::InitGoogleTest; namespace testing { @@ -56,13 +57,12 @@ class UnitTestHelper { static TestSuite const** GetSortedTestSuites() { UnitTest& unit_test = *UnitTest::GetInstance(); auto const** const test_suites = new const TestSuite*[static_cast( - unit_test.total_test_suite_count())]; + unit_test.total_test_suite_count())]; for (int i = 0; i < unit_test.total_test_suite_count(); ++i) test_suites[i] = unit_test.GetTestSuite(i); - std::sort(test_suites, - test_suites + unit_test.total_test_suite_count(), + std::sort(test_suites, test_suites + unit_test.total_test_suite_count(), LessByName()); return test_suites; } @@ -73,8 +73,7 @@ class UnitTestHelper { UnitTest& unit_test = *UnitTest::GetInstance(); for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { const TestSuite* test_suite = unit_test.GetTestSuite(i); - if (0 == strcmp(test_suite->name(), name)) - return test_suite; + if (0 == strcmp(test_suite->name(), name)) return test_suite; } return nullptr; } @@ -84,7 +83,7 @@ class UnitTestHelper { // array. static TestInfo const** GetSortedTests(const TestSuite* test_suite) { TestInfo const** const tests = new const TestInfo*[static_cast( - test_suite->total_test_count())]; + test_suite->total_test_count())]; for (int i = 0; i < test_suite->total_test_count(); ++i) tests[i] = test_suite->GetTestInfo(i); @@ -95,7 +94,8 @@ class UnitTestHelper { } }; -template class TestSuiteWithCommentTest : public Test {}; +template +class TestSuiteWithCommentTest : public Test {}; TYPED_TEST_SUITE(TestSuiteWithCommentTest, Types); TYPED_TEST(TestSuiteWithCommentTest, Dummy) {} @@ -319,7 +319,7 @@ class FinalSuccessChecker : public Environment { } // namespace internal } // namespace testing -int main(int argc, char **argv) { +int main(int argc, char** argv) { InitGoogleTest(&argc, argv); AddGlobalTestEnvironment(new testing::internal::FinalSuccessChecker()); diff --git a/googletest/test/gtest_assert_by_exception_test.cc b/googletest/test/gtest_assert_by_exception_test.cc index ada4cb30..f507eac4 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 #include +#include #include + #include +#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_environment_test.cc b/googletest/test/gtest_environment_test.cc index c7facf5a..122eaf3c 100644 --- a/googletest/test/gtest_environment_test.cc +++ b/googletest/test/gtest_environment_test.cc @@ -30,16 +30,15 @@ // // Tests using global test environments. -#include #include +#include + #include "gtest/gtest.h" #include "src/gtest-internal-inl.h" 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 { @@ -79,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_; } @@ -100,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) { @@ -126,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 diff --git a/googletest/test/gtest_help_test.py b/googletest/test/gtest_help_test.py index 6d2dde00..642ab865 100755 --- a/googletest/test/gtest_help_test.py +++ b/googletest/test/gtest_help_test.py @@ -39,6 +39,7 @@ SYNOPSIS import os import re +import sys from googletest.test import gtest_test_utils @@ -52,16 +53,15 @@ PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_') FLAG_PREFIX = '--gtest_' DEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style' STREAM_RESULT_TO_FLAG = FLAG_PREFIX + 'stream_result_to' -UNKNOWN_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing' +UNKNOWN_GTEST_PREFIXED_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing' LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' -INCORRECT_FLAG_VARIANTS = [re.sub('^--', '-', LIST_TESTS_FLAG), - re.sub('^--', '/', LIST_TESTS_FLAG), - re.sub('_', '-', LIST_TESTS_FLAG)] INTERNAL_FLAG_FOR_TESTING = FLAG_PREFIX + 'internal_flag_for_testing' SUPPORTS_DEATH_TESTS = "DeathTest" in gtest_test_utils.Subprocess( [PROGRAM_PATH, LIST_TESTS_FLAG]).output +HAS_ABSL_FLAGS = '--has_absl_flags' in sys.argv + # The help message must match this regex. HELP_REGEX = re.compile( FLAG_PREFIX + r'list_tests.*' + @@ -111,18 +111,37 @@ class GTestHelpTest(gtest_test_utils.TestCase): """ exit_code, output = RunWithFlag(flag) - self.assertEquals(0, exit_code) - self.assert_(HELP_REGEX.search(output), output) + if HAS_ABSL_FLAGS: + # The Abseil flags library prints the ProgramUsageMessage() with + # --help and returns 1. + self.assertEqual(1, exit_code) + else: + self.assertEqual(0, exit_code) + + self.assertTrue(HELP_REGEX.search(output), output) if IS_LINUX or IS_GNUHURD or IS_GNUKFREEBSD or IS_OPENBSD: - self.assert_(STREAM_RESULT_TO_FLAG in output, output) + 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. @@ -135,27 +154,21 @@ class GTestHelpTest(gtest_test_utils.TestCase): """ exit_code, output = RunWithFlag(flag) - self.assert_(exit_code != 0) - self.assert_(not HELP_REGEX.search(output), output) + self.assertNotEqual(exit_code, 0) + self.assertFalse(HELP_REGEX.search(output), output) def testPrintsHelpWithFullFlag(self): self.TestHelpFlag('--help') - def testPrintsHelpWithShortFlag(self): - self.TestHelpFlag('-h') - - def testPrintsHelpWithQuestionFlag(self): - self.TestHelpFlag('-?') - - def testPrintsHelpWithWindowsStyleQuestionFlag(self): - self.TestHelpFlag('/?') - def testPrintsHelpWithUnrecognizedGoogleTestFlag(self): - self.TestHelpFlag(UNKNOWN_FLAG) - - def testPrintsHelpWithIncorrectFlagStyle(self): - for incorrect_flag in INCORRECT_FLAG_VARIANTS: - self.TestHelpFlag(incorrect_flag) + # The behavior is slightly different when Abseil flags is + # used. Abseil flags rejects all unknown flags, while the builtin + # GTest flags implementation interprets an unknown flag with a + # '--gtest_' prefix as a request for help. + if HAS_ABSL_FLAGS: + self.TestUnknownFlagWithAbseil(UNKNOWN_GTEST_PREFIXED_FLAG) + else: + self.TestHelpFlag(UNKNOWN_GTEST_PREFIXED_FLAG) def testRunsTestsWithoutHelpFlag(self): """Verifies that when no help flag is specified, the tests are run @@ -171,4 +184,6 @@ class GTestHelpTest(gtest_test_utils.TestCase): if __name__ == '__main__': + if '--has_absl_flags' in sys.argv: + sys.argv.remove('--has_absl_flags') gtest_test_utils.Main() diff --git a/googletest/test/gtest_help_test_.cc b/googletest/test/gtest_help_test_.cc index 750ae6ce..da289f05 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. diff --git a/googletest/test/gtest_json_test_utils.py b/googletest/test/gtest_json_test_utils.py index 62bbfc28..f62896c9 100644 --- a/googletest/test/gtest_json_test_utils.py +++ b/googletest/test/gtest_json_test_utils.py @@ -50,6 +50,8 @@ def normalize(obj): elif key == 'failure': value = re.sub(r'^.*[/\\](.*:)\d+\n', '\\1*\n', value) return re.sub(r'Stack trace:\n(.|\n)*', 'Stack trace:\n*', value) + elif key == 'file': + return re.sub(r'^.*[/\\](.*)', '\\1', value) else: return normalize(value) if isinstance(obj, dict): diff --git a/googletest/test/gtest_main_unittest.cc b/googletest/test/gtest_main_unittest.cc index eddedeab..29cd5510 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 5eeb1473..3d436653 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 07/21/2021 by command -// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! - // Regression test for gtest_pred_impl.h // // This file is generated by a script and quite long. If you intend to @@ -49,8 +46,8 @@ #include -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" // A user-defined data type. struct Bool { @@ -80,12 +77,8 @@ bool PredFunction1(T1 v1) { // The following two functions are needed because a compiler doesn't have // a context yet to know which template function must be instantiated. -bool PredFunction1Int(int v1) { - return v1 > 0; -} -bool PredFunction1Bool(Bool v1) { - return v1 > 0; -} +bool PredFunction1Int(int v1) { return v1 > 0; } +bool PredFunction1Bool(Bool v1) { return v1 > 0; } // A unary predicate functor. struct PredFunctor1 { @@ -97,22 +90,17 @@ struct PredFunctor1 { // A unary predicate-formatter function. template -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 - testing::AssertionResult operator()(const char* e1, - const T1& v1) const { + testing::AssertionResult operator()(const char* e1, const T1& v1) const { return PredFormatFunction1(e1, v1); } }; @@ -130,9 +118,8 @@ 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_) { @@ -164,104 +151,100 @@ typedef Predicate1Test ASSERT_PRED1Test; // Tests a successful EXPECT_PRED1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED1(PredFunction1Int, - ++n1_); + EXPECT_PRED1(PredFunction1Int, ++n1_); finished_ = true; } // Tests a successful EXPECT_PRED1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED1(PredFunction1Bool, - Bool(++n1_)); + EXPECT_PRED1(PredFunction1Bool, Bool(++n1_)); finished_ = true; } // Tests a successful EXPECT_PRED1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED1(PredFunctor1(), - ++n1_); + EXPECT_PRED1(PredFunctor1(), ++n1_); finished_ = true; } // Tests a successful EXPECT_PRED1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED1(PredFunctor1(), - Bool(++n1_)); + EXPECT_PRED1(PredFunctor1(), Bool(++n1_)); finished_ = true; } // Tests a failed EXPECT_PRED1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED1(PredFunction1Int, - n1_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED1(PredFunction1Int, n1_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED1(PredFunction1Bool, - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED1(PredFunction1Bool, Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED1(PredFunctor1(), - n1_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED1(PredFunctor1(), n1_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED1(PredFunctor1(), - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED1(PredFunctor1(), Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED1(PredFunction1Int, - ++n1_); + ASSERT_PRED1(PredFunction1Int, ++n1_); finished_ = true; } // Tests a successful ASSERT_PRED1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED1(PredFunction1Bool, - Bool(++n1_)); + ASSERT_PRED1(PredFunction1Bool, Bool(++n1_)); finished_ = true; } // Tests a successful ASSERT_PRED1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED1(PredFunctor1(), - ++n1_); + ASSERT_PRED1(PredFunctor1(), ++n1_); finished_ = true; } // Tests a successful ASSERT_PRED1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED1(PredFunctor1(), - Bool(++n1_)); + ASSERT_PRED1(PredFunctor1(), Bool(++n1_)); finished_ = true; } @@ -269,147 +252,147 @@ TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED1(PredFunction1Int, - n1_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED1(PredFunction1Int, n1_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED1(PredFunction1Bool, - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED1(PredFunction1Bool, Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED1(PredFunctor1(), - n1_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED1(PredFunctor1(), n1_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED1(PredFunctor1(), - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED1(PredFunctor1(), Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a successful EXPECT_PRED_FORMAT1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT1(PredFormatFunction1, - ++n1_); + EXPECT_PRED_FORMAT1(PredFormatFunction1, ++n1_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED_FORMAT1(PredFormatFunction1, - Bool(++n1_)); + EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_)); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT1(PredFormatFunctor1(), - ++n1_); + EXPECT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED_FORMAT1(PredFormatFunctor1(), - Bool(++n1_)); + EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_)); finished_ = true; } // Tests a failed EXPECT_PRED_FORMAT1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT1(PredFormatFunction1, - n1_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT1(PredFormatFunction1, n1_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT1(PredFormatFunction1, - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT1(PredFormatFunctor1(), - n1_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT1(PredFormatFunctor1(), n1_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT1(PredFormatFunctor1(), - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED_FORMAT1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT1(PredFormatFunction1, - ++n1_); + ASSERT_PRED_FORMAT1(PredFormatFunction1, ++n1_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED_FORMAT1(PredFormatFunction1, - Bool(++n1_)); + ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_)); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT1(PredFormatFunctor1(), - ++n1_); + ASSERT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED_FORMAT1(PredFormatFunctor1(), - Bool(++n1_)); + ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_)); finished_ = true; } @@ -417,44 +400,48 @@ TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT1(PredFormatFunction1, - n1_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT1(PredFormatFunction1, n1_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT1(PredFormatFunction1, - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT1(PredFormatFunctor1(), - n1_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT1(PredFormatFunctor1(), n1_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT1(PredFormatFunctor1(), - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++)); + finished_ = true; + }, + ""); } // Sample functions/functors for testing binary predicate assertions. @@ -466,44 +453,33 @@ bool PredFunction2(T1 v1, T2 v2) { // The following two functions are needed because a compiler doesn't have // a context yet to know which template function must be instantiated. -bool PredFunction2Int(int v1, int v2) { - return v1 + v2 > 0; -} -bool PredFunction2Bool(Bool v1, Bool v2) { - return v1 + v2 > 0; -} +bool PredFunction2Int(int v1, int v2) { return v1 + v2 > 0; } +bool PredFunction2Bool(Bool v1, Bool v2) { return v1 + v2 > 0; } // A binary predicate functor. struct PredFunctor2 { template - 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 -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 - testing::AssertionResult operator()(const char* e1, - const char* e2, - const T1& v1, - const T2& v2) const { + testing::AssertionResult operator()(const char* e1, const char* e2, + const T1& v1, const T2& v2) const { return PredFormatFunction2(e1, e2, v1, v2); } }; @@ -521,12 +497,10 @@ 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_) { @@ -560,116 +534,100 @@ typedef Predicate2Test ASSERT_PRED2Test; // Tests a successful EXPECT_PRED2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED2(PredFunction2Int, - ++n1_, - ++n2_); + EXPECT_PRED2(PredFunction2Int, ++n1_, ++n2_); finished_ = true; } // Tests a successful EXPECT_PRED2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED2(PredFunction2Bool, - Bool(++n1_), - Bool(++n2_)); + EXPECT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a successful EXPECT_PRED2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED2(PredFunctor2(), - ++n1_, - ++n2_); + EXPECT_PRED2(PredFunctor2(), ++n1_, ++n2_); finished_ = true; } // Tests a successful EXPECT_PRED2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED2(PredFunctor2(), - Bool(++n1_), - Bool(++n2_)); + EXPECT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a failed EXPECT_PRED2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED2(PredFunction2Int, - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED2(PredFunction2Int, n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED2(PredFunction2Bool, - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED2(PredFunctor2(), - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED2(PredFunctor2(), n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED2(PredFunctor2(), - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED2(PredFunction2Int, - ++n1_, - ++n2_); + ASSERT_PRED2(PredFunction2Int, ++n1_, ++n2_); finished_ = true; } // Tests a successful ASSERT_PRED2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED2(PredFunction2Bool, - Bool(++n1_), - Bool(++n2_)); + ASSERT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a successful ASSERT_PRED2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED2(PredFunctor2(), - ++n1_, - ++n2_); + ASSERT_PRED2(PredFunctor2(), ++n1_, ++n2_); finished_ = true; } // Tests a successful ASSERT_PRED2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED2(PredFunctor2(), - Bool(++n1_), - Bool(++n2_)); + ASSERT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } @@ -677,163 +635,147 @@ TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED2(PredFunction2Int, - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED2(PredFunction2Int, n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED2(PredFunction2Bool, - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED2(PredFunctor2(), - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED2(PredFunctor2(), n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED2(PredFunctor2(), - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a successful EXPECT_PRED_FORMAT2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT2(PredFormatFunction2, - ++n1_, - ++n2_); + EXPECT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED_FORMAT2(PredFormatFunction2, - Bool(++n1_), - Bool(++n2_)); + EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT2(PredFormatFunctor2(), - ++n1_, - ++n2_); + EXPECT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED_FORMAT2(PredFormatFunctor2(), - Bool(++n1_), - Bool(++n2_)); + EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a failed EXPECT_PRED_FORMAT2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(PredFormatFunction2, - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(PredFormatFunction2, - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(PredFormatFunctor2(), - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(PredFormatFunctor2(), - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED_FORMAT2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT2(PredFormatFunction2, - ++n1_, - ++n2_); + ASSERT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED_FORMAT2(PredFormatFunction2, - Bool(++n1_), - Bool(++n2_)); + ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT2(PredFormatFunctor2(), - ++n1_, - ++n2_); + ASSERT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED_FORMAT2(PredFormatFunctor2(), - Bool(++n1_), - Bool(++n2_)); + ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } @@ -841,48 +783,48 @@ TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT2(PredFormatFunction2, - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT2(PredFormatFunction2, - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT2(PredFormatFunctor2(), - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT2(PredFormatFunctor2(), - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Sample functions/functors for testing ternary predicate assertions. @@ -894,49 +836,36 @@ bool PredFunction3(T1 v1, T2 v2, T3 v3) { // The following two functions are needed because a compiler doesn't have // a context yet to know which template function must be instantiated. -bool PredFunction3Int(int v1, int v2, int v3) { - return v1 + v2 + v3 > 0; -} -bool PredFunction3Bool(Bool v1, Bool v2, Bool v3) { - return v1 + v2 + v3 > 0; -} +bool PredFunction3Int(int v1, int v2, int v3) { return v1 + v2 + v3 > 0; } +bool PredFunction3Bool(Bool v1, Bool v2, Bool v3) { return v1 + v2 + v3 > 0; } // A ternary predicate functor. struct PredFunctor3 { template - 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 -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 - testing::AssertionResult operator()(const char* e1, - const char* e2, - const char* e3, - const T1& v1, - const T2& v2, - const T3& v3) const { + testing::AssertionResult operator()(const char* e1, const char* e2, + const char* e3, const T1& v1, + const T2& v2, const T3& v3) const { return PredFormatFunction3(e1, e2, e3, v1, v2, v3); } }; @@ -954,15 +883,12 @@ 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_) { @@ -998,128 +924,100 @@ typedef Predicate3Test ASSERT_PRED3Test; // Tests a successful EXPECT_PRED3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED3(PredFunction3Int, - ++n1_, - ++n2_, - ++n3_); + EXPECT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful EXPECT_PRED3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED3(PredFunction3Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_)); + EXPECT_PRED3(PredFunction3Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } // Tests a successful EXPECT_PRED3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED3(PredFunctor3(), - ++n1_, - ++n2_, - ++n3_); + EXPECT_PRED3(PredFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful EXPECT_PRED3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED3(PredFunctor3(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_)); + EXPECT_PRED3(PredFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } // Tests a failed EXPECT_PRED3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED3(PredFunction3Int, - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED3(PredFunction3Int, n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED3(PredFunction3Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED3(PredFunction3Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED3(PredFunctor3(), - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED3(PredFunctor3(), n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED3(PredFunctor3(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED3(PredFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED3(PredFunction3Int, - ++n1_, - ++n2_, - ++n3_); + ASSERT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful ASSERT_PRED3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED3Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED3(PredFunction3Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_)); + ASSERT_PRED3(PredFunction3Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } // Tests a successful ASSERT_PRED3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED3(PredFunctor3(), - ++n1_, - ++n2_, - ++n3_); + ASSERT_PRED3(PredFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful ASSERT_PRED3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED3(PredFunctor3(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_)); + ASSERT_PRED3(PredFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } @@ -1127,70 +1025,61 @@ TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED3(PredFunction3Int, - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED3(PredFunction3Int, n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED3Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED3(PredFunction3Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED3(PredFunction3Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED3(PredFunctor3(), - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED3(PredFunctor3(), n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED3(PredFunctor3(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED3(PredFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a successful EXPECT_PRED_FORMAT3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT3(PredFormatFunction3, - ++n1_, - ++n2_, - ++n3_); + EXPECT_PRED_FORMAT3(PredFormatFunction3, ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED_FORMAT3(PredFormatFunction3, - Bool(++n1_), - Bool(++n2_), + EXPECT_PRED_FORMAT3(PredFormatFunction3, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } @@ -1198,19 +1087,14 @@ TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) { // Tests a successful EXPECT_PRED_FORMAT3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT3(PredFormatFunctor3(), - ++n1_, - ++n2_, - ++n3_); + EXPECT_PRED_FORMAT3(PredFormatFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED_FORMAT3(PredFormatFunctor3(), - Bool(++n1_), - Bool(++n2_), + EXPECT_PRED_FORMAT3(PredFormatFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } @@ -1218,67 +1102,60 @@ TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) { // Tests a failed EXPECT_PRED_FORMAT3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT3(PredFormatFunction3, - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT3(PredFormatFunction3, n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT3(PredFormatFunction3, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT3(PredFormatFunction3, Bool(n1_++), Bool(n2_++), + Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT3(PredFormatFunctor3(), - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT3(PredFormatFunctor3(), n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT3(PredFormatFunctor3(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT3(PredFormatFunctor3(), Bool(n1_++), Bool(n2_++), + Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED_FORMAT3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT3(PredFormatFunction3, - ++n1_, - ++n2_, - ++n3_); + ASSERT_PRED_FORMAT3(PredFormatFunction3, ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED_FORMAT3(PredFormatFunction3, - Bool(++n1_), - Bool(++n2_), + ASSERT_PRED_FORMAT3(PredFormatFunction3, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } @@ -1286,19 +1163,14 @@ TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) { // Tests a successful ASSERT_PRED_FORMAT3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT3(PredFormatFunctor3(), - ++n1_, - ++n2_, - ++n3_); + ASSERT_PRED_FORMAT3(PredFormatFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED_FORMAT3(PredFormatFunctor3(), - Bool(++n1_), - Bool(++n2_), + ASSERT_PRED_FORMAT3(PredFormatFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } @@ -1307,52 +1179,50 @@ TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT3(PredFormatFunction3, - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT3(PredFormatFunction3, n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT3(PredFormatFunction3, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT3(PredFormatFunction3, Bool(n1_++), Bool(n2_++), + Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT3(PredFormatFunctor3(), - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT3(PredFormatFunctor3(), n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT3(PredFormatFunctor3(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT3(PredFormatFunctor3(), Bool(n1_++), Bool(n2_++), + Bool(n3_++)); + finished_ = true; + }, + ""); } // Sample functions/functors for testing 4-ary predicate assertions. @@ -1374,43 +1244,31 @@ bool PredFunction4Bool(Bool v1, Bool v2, Bool v3, Bool v4) { // A 4-ary predicate functor. struct PredFunctor4 { template - 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 -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 - testing::AssertionResult operator()(const char* e1, - const char* e2, - const char* e3, - const char* e4, - const T1& v1, - const T2& v2, - const T3& v3, + testing::AssertionResult operator()(const char* e1, const char* e2, + const char* e3, const char* e4, + const T1& v1, const T2& v2, const T3& v3, const T4& v4) const { return PredFormatFunction4(e1, e2, e3, e4, v1, v2, v3, v4); } @@ -1429,18 +1287,14 @@ 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_) { @@ -1478,21 +1332,14 @@ typedef Predicate4Test ASSERT_PRED4Test; // Tests a successful EXPECT_PRED4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED4(PredFunction4Int, - ++n1_, - ++n2_, - ++n3_, - ++n4_); + EXPECT_PRED4(PredFunction4Int, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful EXPECT_PRED4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED4(PredFunction4Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), + EXPECT_PRED4(PredFunction4Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } @@ -1500,21 +1347,14 @@ TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeSuccess) { // Tests a successful EXPECT_PRED4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED4(PredFunctor4(), - ++n1_, - ++n2_, - ++n3_, - ++n4_); + EXPECT_PRED4(PredFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful EXPECT_PRED4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED4(PredFunctor4(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), + EXPECT_PRED4(PredFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } @@ -1522,73 +1362,60 @@ TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeSuccess) { // Tests a failed EXPECT_PRED4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED4(PredFunction4Int, - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED4(PredFunction4Int, n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED4(PredFunction4Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED4(PredFunction4Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED4(PredFunctor4(), - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED4(PredFunctor4(), n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED4(PredFunctor4(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED4(PredFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED4(PredFunction4Int, - ++n1_, - ++n2_, - ++n3_, - ++n4_); + ASSERT_PRED4(PredFunction4Int, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful ASSERT_PRED4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED4(PredFunction4Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), + ASSERT_PRED4(PredFunction4Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } @@ -1596,21 +1423,14 @@ TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeSuccess) { // Tests a successful ASSERT_PRED4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED4(PredFunctor4(), - ++n1_, - ++n2_, - ++n3_, - ++n4_); + ASSERT_PRED4(PredFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful ASSERT_PRED4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED4(PredFunctor4(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), + ASSERT_PRED4(PredFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } @@ -1619,195 +1439,155 @@ TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED4(PredFunction4Int, - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED4(PredFunction4Int, n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED4(PredFunction4Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED4(PredFunction4Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED4(PredFunctor4(), - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED4(PredFunctor4(), n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED4(PredFunctor4(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED4(PredFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a successful EXPECT_PRED_FORMAT4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT4(PredFormatFunction4, - ++n1_, - ++n2_, - ++n3_, - ++n4_); + EXPECT_PRED_FORMAT4(PredFormatFunction4, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED_FORMAT4(PredFormatFunction4, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_)); + EXPECT_PRED_FORMAT4(PredFormatFunction4, Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_)); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT4(PredFormatFunctor4(), - ++n1_, - ++n2_, - ++n3_, - ++n4_); + EXPECT_PRED_FORMAT4(PredFormatFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED_FORMAT4(PredFormatFunctor4(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_)); + EXPECT_PRED_FORMAT4(PredFormatFunctor4(), Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_)); finished_ = true; } // Tests a failed EXPECT_PRED_FORMAT4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT4(PredFormatFunction4, - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT4(PredFormatFunction4, n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT4(PredFormatFunction4, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT4(PredFormatFunction4, Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT4(PredFormatFunctor4(), - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT4(PredFormatFunctor4(), n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT4(PredFormatFunctor4(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT4(PredFormatFunctor4(), Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED_FORMAT4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT4(PredFormatFunction4, - ++n1_, - ++n2_, - ++n3_, - ++n4_); + ASSERT_PRED_FORMAT4(PredFormatFunction4, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED_FORMAT4(PredFormatFunction4, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_)); + ASSERT_PRED_FORMAT4(PredFormatFunction4, Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_)); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT4(PredFormatFunctor4(), - ++n1_, - ++n2_, - ++n3_, - ++n4_); + ASSERT_PRED_FORMAT4(PredFormatFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED_FORMAT4(PredFormatFunctor4(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_)); + ASSERT_PRED_FORMAT4(PredFormatFunctor4(), Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_)); finished_ = true; } @@ -1815,56 +1595,50 @@ TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT4(PredFormatFunction4, - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT4(PredFormatFunction4, n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT4(PredFormatFunction4, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT4(PredFormatFunction4, Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT4(PredFormatFunctor4(), - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT4(PredFormatFunctor4(), n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT4(PredFormatFunctor4(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT4(PredFormatFunctor4(), Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++)); + finished_ = true; + }, + ""); } // Sample functions/functors for testing 5-ary predicate assertions. @@ -1886,10 +1660,7 @@ bool PredFunction5Bool(Bool v1, Bool v2, Bool v3, Bool v4, Bool v5) { // A 5-ary predicate functor. struct PredFunctor5 { template - bool operator()(const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4, + bool operator()(const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) { return v1 + v2 + v3 + v4 + v5 > 0; } @@ -1897,37 +1668,26 @@ struct PredFunctor5 { // A 5-ary predicate-formatter function. template -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 - testing::AssertionResult operator()(const char* e1, - const char* e2, - const char* e3, - const char* e4, - const char* e5, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4, + testing::AssertionResult operator()(const char* e1, const char* e2, + const char* e3, const char* e4, + const char* e5, const T1& v1, + const T2& v2, const T3& v3, const T4& v4, const T5& v5) const { return PredFormatFunction5(e1, e2, e3, e4, e5, v1, v2, v3, v4, v5); } @@ -1946,21 +1706,16 @@ 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_) { @@ -2000,152 +1755,106 @@ typedef Predicate5Test ASSERT_PRED5Test; // Tests a successful EXPECT_PRED5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED5(PredFunction5Int, - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + EXPECT_PRED5(PredFunction5Int, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful EXPECT_PRED5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED5Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED5(PredFunction5Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + EXPECT_PRED5(PredFunction5Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), + Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a successful EXPECT_PRED5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED5(PredFunctor5(), - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + EXPECT_PRED5(PredFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful EXPECT_PRED5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED5Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED5(PredFunctor5(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + EXPECT_PRED5(PredFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_), + Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a failed EXPECT_PRED5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED5(PredFunction5Int, - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED5(PredFunction5Int, n1_++, n2_++, n3_++, n4_++, n5_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED5Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED5(PredFunction5Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED5(PredFunction5Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED5(PredFunctor5(), - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED5(PredFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED5Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED5(PredFunctor5(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED5(PredFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED5(PredFunction5Int, - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + ASSERT_PRED5(PredFunction5Int, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful ASSERT_PRED5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED5Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED5(PredFunction5Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + ASSERT_PRED5(PredFunction5Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), + Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a successful ASSERT_PRED5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED5(PredFunctor5(), - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + ASSERT_PRED5(PredFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful ASSERT_PRED5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED5(PredFunctor5(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + ASSERT_PRED5(PredFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_), + Bool(++n4_), Bool(++n5_)); finished_ = true; } @@ -2153,211 +1862,157 @@ TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED5(PredFunction5Int, - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED5(PredFunction5Int, n1_++, n2_++, n3_++, n4_++, n5_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED5Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED5(PredFunction5Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED5(PredFunction5Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED5(PredFunctor5(), - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED5(PredFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED5(PredFunctor5(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED5(PredFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a successful EXPECT_PRED_FORMAT5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT5(PredFormatFunction5, - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + EXPECT_PRED_FORMAT5(PredFormatFunction5, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED_FORMAT5(PredFormatFunction5, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + EXPECT_PRED_FORMAT5(PredFormatFunction5, Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT5(PredFormatFunctor5(), - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + EXPECT_PRED_FORMAT5(PredFormatFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED_FORMAT5(PredFormatFunctor5(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + EXPECT_PRED_FORMAT5(PredFormatFunctor5(), Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a failed EXPECT_PRED_FORMAT5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT5(PredFormatFunction5, - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT5(PredFormatFunction5, n1_++, n2_++, n3_++, n4_++, + n5_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT5(PredFormatFunction5, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT5(PredFormatFunction5, Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT5(PredFormatFunctor5(), - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT5(PredFormatFunctor5(), n1_++, n2_++, n3_++, n4_++, + n5_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT5(PredFormatFunctor5(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT5(PredFormatFunctor5(), Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED_FORMAT5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT5(PredFormatFunction5, - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + ASSERT_PRED_FORMAT5(PredFormatFunction5, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED_FORMAT5(PredFormatFunction5, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + ASSERT_PRED_FORMAT5(PredFormatFunction5, Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT5(PredFormatFunctor5(), - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + ASSERT_PRED_FORMAT5(PredFormatFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED_FORMAT5(PredFormatFunctor5(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + ASSERT_PRED_FORMAT5(PredFormatFunctor5(), Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } @@ -2365,58 +2020,50 @@ TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT5(PredFormatFunction5, - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT5(PredFormatFunction5, n1_++, n2_++, n3_++, n4_++, + n5_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT5(PredFormatFunction5, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT5(PredFormatFunction5, Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT5(PredFormatFunctor5(), - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT5(PredFormatFunctor5(), n1_++, n2_++, n3_++, n4_++, + n5_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT5(PredFormatFunctor5(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT5(PredFormatFunctor5(), Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } diff --git a/googletest/test/gtest_premature_exit_test.cc b/googletest/test/gtest_premature_exit_test.cc index 1d1187ef..1a0c5ea4 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 6b10048f..73fb8dc9 100644 --- a/googletest/test/gtest_repeat_test.cc +++ b/googletest/test/gtest_repeat_test.cc @@ -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. - // Tests the --gtest_repeat=number flag. #include + #include + #include "gtest/gtest.h" #include "src/gtest-internal-inl.h" @@ -39,20 +40,19 @@ 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. @@ -79,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. @@ -108,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. diff --git a/googletest/test/gtest_skip_in_environment_setup_test.cc b/googletest/test/gtest_skip_in_environment_setup_test.cc index 93723106..5f21c27d 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 + #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 4a23004c..e1b8d655 100644 --- a/googletest/test/gtest_skip_test.cc +++ b/googletest/test/gtest_skip_test.cc @@ -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 1d94ac6b..e8e22a83 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 84348191..24b173ff 100644 --- a/googletest/test/gtest_stress_test.cc +++ b/googletest/test/gtest_stress_test.cc @@ -27,14 +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. - // Tests that SCOPED_TRACE() and various Google Test assertions can be // used in a large number of threads concurrently. -#include "gtest/gtest.h" - #include +#include "gtest/gtest.h" #include "src/gtest-internal-inl.h" #if GTEST_IS_THREADSAFE @@ -66,8 +64,7 @@ std::string IdToString(int id) { } void ExpectKeyAndValueWereRecordedForId( - const std::vector& properties, - int id, const char* suffix) { + const std::vector& properties, int id, const char* suffix) { TestPropertyKeyIs matches_key(IdToKey(id, suffix).c_str()); const std::vector::const_iterator property = std::find_if(properties.begin(), properties.end(), matches_key); @@ -121,15 +118,13 @@ TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) { std::unique_ptr > threads[kThreadCount]; Notification threads_can_start; for (int i = 0; i != kThreadCount; i++) - threads[i].reset(new ThreadWithParam(&ManyAsserts, - i, - &threads_can_start)); + threads[i].reset( + new ThreadWithParam(&ManyAsserts, i, &threads_can_start)); threads_can_start.Notify(); // Blocks until all the threads are done. - for (int i = 0; i != kThreadCount; i++) - threads[i]->Join(); + for (int i = 0; i != kThreadCount; i++) threads[i]->Join(); } // Ensures that kThreadCount*kThreadCount failures have been reported. @@ -149,7 +144,7 @@ TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) { ExpectKeyAndValueWereRecordedForId(properties, i, "string"); ExpectKeyAndValueWereRecordedForId(properties, i, "int"); } - CheckTestFailureCount(kThreadCount*kThreadCount); + CheckTestFailureCount(kThreadCount * kThreadCount); } void FailingThread(bool is_fatal) { @@ -196,8 +191,8 @@ TEST(FatalFailureTest, ExpectFatalFailureIgnoresFailuresInOtherThreads) { TEST(FatalFailureOnAllThreadsTest, ExpectFatalFailureOnAllThreads) { // This statement should succeed, because failures in all threads are // considered. - EXPECT_FATAL_FAILURE_ON_ALL_THREADS( - GenerateFatalFailureInAnotherThread(true), "expected"); + EXPECT_FATAL_FAILURE_ON_ALL_THREADS(GenerateFatalFailureInAnotherThread(true), + "expected"); CheckTestFailureCount(0); // We need to add a failure, because main() checks that there are failures. // But when only this test is run, we shouldn't have any failures. @@ -226,7 +221,7 @@ TEST(NonFatalFailureOnAllThreadsTest, ExpectNonFatalFailureOnAllThreads) { } // namespace } // namespace testing -int main(int argc, char **argv) { +int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); const int result = RUN_ALL_TESTS(); // Expected to fail. @@ -238,8 +233,7 @@ int main(int argc, char **argv) { #else TEST(StressTest, - DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) { -} + DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) {} int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); diff --git a/googletest/test/gtest_test_macro_stack_footprint_test.cc b/googletest/test/gtest_test_macro_stack_footprint_test.cc index a48db050..45f368b3 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_testbridge_test_.cc b/googletest/test/gtest_testbridge_test_.cc index 24617b20..c2c000dc 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 aeead13f..25d7c797 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 #include +#include #include + #include +#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 @@ -55,14 +55,14 @@ void TestFailureThrowsRuntimeError() { // 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 32bd297e..d75b96b0 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -137,8 +137,8 @@ TEST_F(StreamingListenerTest, OnTestEnd) { TEST_F(StreamingListenerTest, OnTestPartResultWithFatalFailure) { *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( @@ -293,11 +293,9 @@ using testing::internal::GetCapturedStdout; using testing::internal::ThreadWithParam; #endif -class TestingVector : public std::vector { -}; +class TestingVector : public std::vector {}; -::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] << " "; @@ -441,8 +439,7 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test { saved_tz_ = nullptr; GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */) - if (getenv("TZ")) - saved_tz_ = strdup(getenv("TZ")); + if (getenv("TZ")) saved_tz_ = strdup(getenv("TZ")); GTEST_DISABLE_MSC_DEPRECATED_POP_() // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We @@ -497,9 +494,8 @@ TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) { } TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) { - EXPECT_EQ( - "2011-10-31T18:52:42.234", - FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234)); + EXPECT_EQ("2011-10-31T18:52:42.234", + FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) { @@ -516,10 +512,10 @@ TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0)); } -# ifdef __BORLANDC__ +#ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" -# pragma option push -w-ccc -w-rch -# endif +#pragma option push -w-ccc -w-rch +#endif // Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal // when the RHS is a pointer type. @@ -593,10 +589,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(). @@ -624,20 +620,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(0x576))); + EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast(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(0x8D3))); + EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast(0x8D3))); // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 - EXPECT_EQ("\xEC\x9D\x8D", - CodePointToUtf8(static_cast(0xC74D))); + EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast(0xC74D))); } #if !GTEST_WIDE_STRING_USES_UTF16_ @@ -689,7 +682,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()); } @@ -698,12 +691,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()); } @@ -738,11 +731,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()); } @@ -750,13 +743,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_ @@ -764,21 +757,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_ @@ -787,9 +783,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, " @@ -918,7 +913,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(kVectorSize) || found_in_vector[e]) { @@ -945,8 +940,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); } @@ -971,7 +966,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_); @@ -993,7 +988,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_); @@ -1018,7 +1013,7 @@ TEST_F(VectorShuffleTest, ShufflesEntireVector) { } TEST_F(VectorShuffleTest, ShufflesStartOfVector) { - const int kRangeSize = kVectorSize/2; + const int kRangeSize = kVectorSize / 2; ShuffleRange(&random_, 0, kRangeSize, &vector_); @@ -1040,11 +1035,11 @@ TEST_F(VectorShuffleTest, ShufflesEndOfVector) { TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) { const int kRangeSize = static_cast(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(kVectorSize)); } @@ -1109,13 +1104,12 @@ TEST(StringTest, CaseInsensitiveWideCStringEquals) { // Tests String::ShowWideCString(). TEST(StringTest, ShowWideCString) { - EXPECT_STREQ("(null)", - String::ShowWideCString(NULL).c_str()); + EXPECT_STREQ("(null)", String::ShowWideCString(NULL).c_str()); EXPECT_STREQ("", String::ShowWideCString(L"").c_str()); EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str()); } -# if GTEST_OS_WINDOWS_MOBILE +#if GTEST_OS_WINDOWS_MOBILE TEST(StringTest, AnsiAndUtf16Null) { EXPECT_EQ(NULL, String::AnsiToUtf16(NULL)); EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL)); @@ -1124,21 +1118,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 @@ -1160,9 +1154,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."; @@ -1170,10 +1162,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(); @@ -1213,7 +1202,7 @@ TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) { #if GTEST_IS_THREADSAFE class ScopedFakeTestPartResultReporterWithThreadsTest - : public ScopedFakeTestPartResultReporterTest { + : public ScopedFakeTestPartResultReporterTest { protected: static void AddFailureInOtherThread(FailureMode failure) { ThreadWithParam thread(&AddFailure, failure, nullptr); @@ -1266,7 +1255,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 @@ -1294,7 +1283,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) { @@ -1313,16 +1302,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}. @@ -1330,8 +1323,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) { @@ -1350,15 +1342,19 @@ TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) { // statement that contains a macro which expands to code containing an // unprotected comma. TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { - EXPECT_NONFATAL_FAILURE({ - GTEST_USE_UNPROTECTED_COMMA_; - AddNonfatalFailure(); - }, ""); + EXPECT_NONFATAL_FAILURE( + { + GTEST_USE_UNPROTECTED_COMMA_; + AddNonfatalFailure(); + }, + ""); - EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({ - GTEST_USE_UNPROTECTED_COMMA_; - AddNonfatalFailure(); - }, ""); + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS( + { + GTEST_USE_UNPROTECTED_COMMA_; + AddNonfatalFailure(); + }, + ""); } #if GTEST_IS_THREADSAFE @@ -1402,21 +1398,18 @@ class TestResultTest : public Test { typedef std::vector 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!"); @@ -1429,10 +1422,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( - &TestResultAccessor::test_part_results(*r1)); - TPRVector* results2 = const_cast( - &TestResultAccessor::test_part_results(*r2)); + TPRVector* results1 = + const_cast(&TestResultAccessor::test_part_results(*r1)); + TPRVector* results2 = + const_cast(&TestResultAccessor::test_part_results(*r2)); // r0 is an empty TestResult. @@ -1683,15 +1676,11 @@ GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr; // tests are designed to work regardless of their order. // Modifies the Google Test flags in the test body. -TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { - VerifyAndModifyFlags(); -} +TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); } // Verifies that the Google Test flags in the body of the previous test were // restored to their original values. -TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { - VerifyAndModifyFlags(); -} +TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); } // Sets an environment variable with the given name to the given // value. If the value argument is "", unsets the environment @@ -1708,12 +1697,12 @@ static void SetEnv(const char* name, const char* value) { // Because putenv stores a pointer to the string buffer, we can't delete the // previous string (if present) until after it's replaced. - std::string *prev_env = NULL; + std::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*'. @@ -1745,7 +1734,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. @@ -1771,7 +1760,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 @@ -1855,8 +1844,7 @@ TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) { TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx"); EXPECT_DEATH_IF_SUPPORTED( - Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), - ".*"); + Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); } // Tests that Int32FromEnvOrDie() aborts with an error message @@ -1864,8 +1852,7 @@ TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234"); EXPECT_DEATH_IF_SUPPORTED( - Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), - ".*"); + Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); } // Tests that ShouldRunTestOnShard() selects all tests @@ -1972,7 +1959,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; } } } @@ -1984,7 +1972,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); } @@ -2016,8 +2004,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( @@ -2046,8 +2034,8 @@ void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( // Tests that property recording functions in UnitTest outside of tests // 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( @@ -2086,8 +2074,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. @@ -2128,16 +2115,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"); } @@ -2185,9 +2169,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 { @@ -2234,41 +2216,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(); @@ -2276,14 +2254,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. @@ -2293,11 +2269,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. @@ -2305,15 +2282,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 @@ -2325,14 +2304,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. @@ -2344,19 +2324,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. @@ -2364,13 +2348,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 @@ -2388,9 +2376,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."; @@ -2399,19 +2386,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."; @@ -2422,7 +2413,7 @@ TEST(PredTest, SingleEvaluationOnFailure) { TEST(PredTest, ExpectPredEvalFailure) { std::set set_a = {2, 1, 3, 4, 5}; std::set set_b = {0, 4, 8}; - const auto compare_sets = [] (std::set, std::set) { return false; }; + const auto compare_sets = [](std::set, std::set) { 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 " @@ -2432,9 +2423,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 bool IsNegative(T x) { @@ -2450,7 +2439,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 } @@ -2463,31 +2452,27 @@ TEST(PredicateAssertionTest, AcceptsTemplateFunction) { ASSERT_PRED2((GreaterThan), 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 AssertionResult IsNegativeFormat(const char* /* expr */, T x) { - return x < 0 ? AssertionSuccess() : - AssertionFailure(Message() << "Failure"); + return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } template 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* @@ -2504,20 +2489,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. @@ -2540,8 +2523,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. @@ -2550,8 +2532,7 @@ TEST(StringAssertionTest, ASSERT_STRCASEEQ) { ASSERT_STRCASEEQ(static_cast(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. @@ -2563,8 +2544,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. @@ -2582,17 +2562,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. @@ -2605,22 +2585,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"; @@ -2654,12 +2631,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 @@ -2680,13 +2658,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 @@ -2710,13 +2689,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 @@ -2729,13 +2708,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 @@ -2782,20 +2762,20 @@ class FloatingPointTest : public Test { const Bits zero_bits = Floating(0).bits(); // Makes some numbers close to 0.0. - values_.close_to_positive_zero = Floating::ReinterpretBits( - zero_bits + max_ulps/2); - values_.close_to_negative_zero = -Floating::ReinterpretBits( - zero_bits + max_ulps - max_ulps/2); - values_.further_from_negative_zero = -Floating::ReinterpretBits( - zero_bits + max_ulps + 1 - max_ulps/2); + values_.close_to_positive_zero = + Floating::ReinterpretBits(zero_bits + max_ulps / 2); + values_.close_to_negative_zero = + -Floating::ReinterpretBits(zero_bits + max_ulps - max_ulps / 2); + values_.further_from_negative_zero = + -Floating::ReinterpretBits(zero_bits + max_ulps + 1 - max_ulps / 2); // The bits that represent 1.0. const Bits one_bits = Floating(1).bits(); // Makes some numbers close to 1.0. values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps); - values_.further_from_one = Floating::ReinterpretBits( - one_bits + max_ulps + 1); + values_.further_from_one = + Floating::ReinterpretBits(one_bits + max_ulps + 1); // +infinity. values_.infinity = Floating::Infinity(); @@ -2804,23 +2784,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(1) << (Floating::kFractionBitCount - 1)) | 1); - values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask - | (static_cast(1) << (Floating::kFractionBitCount - 1)) | 200); + values_.nan1 = Floating::ReinterpretBits( + Floating::kExponentBitMask | + (static_cast(1) << (Floating::kFractionBitCount - 1)) | 1); + values_.nan2 = Floating::ReinterpretBits( + Floating::kExponentBitMask | + (static_cast(1) << (Floating::kFractionBitCount - 1)) | 200); } - void TestSize() { - EXPECT_EQ(sizeof(RawType), sizeof(Bits)); - } + void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); } static TestValues values_; }; @@ -2833,17 +2813,13 @@ typename FloatingPointTest::TestValues typedef FloatingPointTest 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. @@ -2864,10 +2840,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. @@ -2879,8 +2856,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. @@ -2909,15 +2885,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. @@ -2971,36 +2943,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 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. @@ -3021,10 +2997,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. @@ -3036,8 +3014,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. @@ -3061,12 +3038,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. @@ -3127,22 +3102,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. @@ -3154,9 +3136,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. @@ -3196,8 +3176,7 @@ TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) { // Tests that disabled typed tests aren't run. template -class TypedTest : public Test { -}; +class TypedTest : public Test {}; typedef testing::Types NumericTypes; TYPED_TEST_SUITE(TypedTest, NumericTypes); @@ -3207,8 +3186,7 @@ TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) { } template -class DISABLED_TypedTest : public Test { -}; +class DISABLED_TypedTest : public Test {}; TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes); @@ -3219,8 +3197,7 @@ TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) { // Tests that disabled type-parameterized tests aren't run. template -class TypedTestP : public Test { -}; +class TypedTestP : public Test {}; TYPED_TEST_SUITE_P(TypedTestP); @@ -3234,8 +3211,7 @@ REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun); INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes); template -class DISABLED_TypedTestP : public Test { -}; +class DISABLED_TypedTestP : public Test {}; TYPED_TEST_SUITE_P(DISABLED_TypedTestP); @@ -3255,15 +3231,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() { @@ -3306,8 +3278,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_); } @@ -3367,34 +3338,39 @@ TEST_F(SingleEvaluationTest, OtherCases) { #endif // GTEST_HAS_RTTI -void ThrowAnInteger() { - throw 1; -} -void ThrowRuntimeError(const char* what) { - throw std::runtime_error(what); -} +void ThrowAnInteger() { throw 1; } +void ThrowRuntimeError(const char* what) { throw std::runtime_error(what); } // Tests that assertion arguments are evaluated exactly once. TEST_F(SingleEvaluationTest, ExceptionTests) { // successful EXPECT_THROW - EXPECT_THROW({ // NOLINT - a_++; - ThrowAnInteger(); - }, int); + EXPECT_THROW( + { // NOLINT + a_++; + ThrowAnInteger(); + }, + int); EXPECT_EQ(1, a_); // failed EXPECT_THROW, throws different - EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT - a_++; - ThrowAnInteger(); - }, bool), "throws a different type"); + EXPECT_NONFATAL_FAILURE(EXPECT_THROW( + { // NOLINT + a_++; + ThrowAnInteger(); + }, + bool), + "throws a different type"); EXPECT_EQ(2, a_); // failed EXPECT_THROW, throws runtime error - EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT - a_++; - ThrowRuntimeError("A description"); - }, bool), "throws " ERROR_DESC " with description \"A description\""); + EXPECT_NONFATAL_FAILURE(EXPECT_THROW( + { // NOLINT + a_++; + ThrowRuntimeError("A description"); + }, + bool), + "throws " ERROR_DESC + " with description \"A description\""); EXPECT_EQ(3, a_); // failed EXPECT_THROW, throws nothing @@ -3407,9 +3383,10 @@ TEST_F(SingleEvaluationTest, ExceptionTests) { // failed EXPECT_NO_THROW EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT - a_++; - ThrowAnInteger(); - }), "it throws"); + a_++; + ThrowAnInteger(); + }), + "it throws"); EXPECT_EQ(6, a_); // successful EXPECT_ANY_THROW @@ -3430,12 +3407,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()); @@ -3454,12 +3427,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) { @@ -3582,8 +3553,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 <" @@ -3596,8 +3568,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" @@ -3607,8 +3578,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" @@ -3617,8 +3587,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" @@ -3635,9 +3604,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" @@ -3672,24 +3640,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. @@ -3737,7 +3702,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 @@ -3748,18 +3713,19 @@ TEST(ExpectTest, ASSERT_EQ_Double) { ASSERT_EQ(5.6, 5.6); // A failure. - EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), - "5.1"); + EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), "5.1"); } // Tests ASSERT_EQ. TEST(AssertionTest, ASSERT_EQ) { ASSERT_EQ(5, 2 + 3); + // clang-format off EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3), "Expected equality of these values:\n" " 5\n" " 2*3\n" " Which is: 6"); + // clang-format on } // Tests ASSERT_EQ(NULL, pointer). @@ -3784,8 +3750,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. @@ -3800,30 +3765,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 @@ -3834,7 +3795,7 @@ void ThrowNothing() {} TEST(AssertionTest, ASSERT_THROW) { ASSERT_THROW(ThrowAnInteger(), int); -# ifndef __BORLANDC__ +#ifndef __BORLANDC__ // ICE's in C++Builder 2007 and 2009. EXPECT_FATAL_FAILURE( @@ -3845,9 +3806,10 @@ TEST(AssertionTest, ASSERT_THROW) { ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error), "Expected: ThrowRuntimeError(\"A description\") " "throws an exception of type std::logic_error.\n " - "Actual: it throws " ERROR_DESC " " + "Actual: it throws " ERROR_DESC + " " "with description \"A description\"."); -# endif +#endif EXPECT_FATAL_FAILURE( ASSERT_THROW(ThrowNothing(), bool), @@ -3864,17 +3826,17 @@ TEST(AssertionTest, ASSERT_NO_THROW) { EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")), "Expected: ThrowRuntimeError(\"A description\") " "doesn't throw an exception.\n " - "Actual: it throws " ERROR_DESC " " + "Actual: it throws " ERROR_DESC + " " "with description \"A description\"."); } // Tests ASSERT_ANY_THROW. TEST(AssertionTest, ASSERT_ANY_THROW) { ASSERT_ANY_THROW(ThrowAnInteger()); - EXPECT_FATAL_FAILURE( - ASSERT_ANY_THROW(ThrowNothing()), - "Expected: ThrowNothing() throws an exception.\n" - " Actual: it doesn't."); + EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()), + "Expected: ThrowNothing() throws an exception.\n" + " Actual: it doesn't."); } #endif // GTEST_HAS_EXCEPTIONS @@ -3888,14 +3850,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. @@ -3907,6 +3866,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. @@ -3919,10 +3879,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() { @@ -3941,8 +3898,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"); @@ -3953,18 +3911,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); @@ -3980,7 +3936,7 @@ TEST(AssertionTest, NamedEnum) { enum { kCaseA = -1, -# if GTEST_OS_LINUX +#if GTEST_OS_LINUX // We want to test the case where the size of the anonymous enum is // larger than sizeof(int), to make sure our implementation of the @@ -3993,21 +3949,21 @@ enum { // assertions. kCaseB = testing::internal::kMaxBiggestInt, -# else +#else kCaseB = INT_MAX, -# endif // GTEST_OS_LINUX +#endif // GTEST_OS_LINUX kCaseC = 42 }; TEST(AssertionTest, AnonymousEnum) { -# if GTEST_OS_LINUX +#if GTEST_OS_LINUX EXPECT_EQ(static_cast(kCaseA), static_cast(kCaseB)); -# endif // GTEST_OS_LINUX +#endif // GTEST_OS_LINUX EXPECT_EQ(kCaseA, kCaseA); EXPECT_NE(kCaseA, kCaseB); @@ -4015,10 +3971,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); @@ -4027,34 +3981,25 @@ TEST(AssertionTest, AnonymousEnum) { ASSERT_GT(kCaseB, kCaseA); ASSERT_GE(kCaseA, kCaseA); -# ifndef __BORLANDC__ +#ifndef __BORLANDC__ // ICE's in C++Builder. - EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), - " kCaseB\n Which is: "); - EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), - "\n Which is: 42"); -# endif + EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), " kCaseB\n Which is: "); + EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: 42"); +#endif - EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), - "\n Which is: -1"); + EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: -1"); } #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC) #if GTEST_OS_WINDOWS -static HRESULT UnexpectedHRESULTFailure() { - return E_UNEXPECTED; -} +static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; } -static HRESULT OkHRESULTSuccess() { - return S_OK; -} +static HRESULT OkHRESULTSuccess() { return S_OK; } -static HRESULT FalseHRESULTSuccess() { - return S_FALSE; -} +static HRESULT FalseHRESULTSuccess() { return S_FALSE; } // HRESULT assertion tests test both zero and non-zero // success codes as well as failure message for each. @@ -4065,8 +4010,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) { @@ -4074,35 +4019,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. @@ -4112,25 +4057,23 @@ TEST(HRESULTAssertionTest, Streaming) { EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; - EXPECT_NONFATAL_FAILURE( - EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", - "expected failure"); + EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) + << "expected failure", + "expected failure"); -# ifndef __BORLANDC__ +#ifndef __BORLANDC__ // ICE's in C++Builder 2007 and 2009. - EXPECT_FATAL_FAILURE( - ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", - "expected failure"); -# endif + EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) + << "expected failure", + "expected failure"); +#endif - EXPECT_NONFATAL_FAILURE( - EXPECT_HRESULT_FAILED(S_OK) << "expected failure", - "expected failure"); + EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(S_OK) << "expected failure", + "expected failure"); - EXPECT_FATAL_FAILURE( - ASSERT_HRESULT_FAILED(S_OK) << "expected failure", - "expected failure"); + EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(S_OK) << "expected failure", + "expected failure"); } #endif // GTEST_OS_WINDOWS @@ -4153,8 +4096,7 @@ TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) { else ; // NOLINT - if (AlwaysFalse()) - ASSERT_LT(1, 3); + if (AlwaysFalse()) ASSERT_LT(1, 3); if (AlwaysFalse()) ; // NOLINT @@ -4192,24 +4134,21 @@ TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) { #pragma GCC diagnostic ignored "-Wpragmas" #endif TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) { - if (AlwaysFalse()) - EXPECT_THROW(ThrowNothing(), bool); + if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool); if (AlwaysTrue()) EXPECT_THROW(ThrowAnInteger(), int); else ; // NOLINT - if (AlwaysFalse()) - EXPECT_NO_THROW(ThrowAnInteger()); + if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger()); if (AlwaysTrue()) EXPECT_NO_THROW(ThrowNothing()); else ; // NOLINT - if (AlwaysFalse()) - EXPECT_ANY_THROW(ThrowNothing()); + if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing()); if (AlwaysTrue()) EXPECT_ANY_THROW(ThrowAnInteger()); @@ -4265,8 +4204,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. @@ -4277,22 +4216,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 @@ -4390,22 +4327,19 @@ TEST(AssertionWithMessageTest, ASSERT_FLOATING) { // Tests using ASSERT_FALSE with a streamed message. TEST(AssertionWithMessageTest, ASSERT_FALSE) { ASSERT_FALSE(false) << "This shouldn't fail."; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1 - << " evaluates to " << true; - }, "Expected failure"); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1 + << " evaluates to " << true; + }, + "Expected failure"); } // Tests using FAIL with a streamed message. -TEST(AssertionWithMessageTest, FAIL) { - EXPECT_FATAL_FAILURE(FAIL() << 0, - "0"); -} +TEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0, "0"); } // Tests using SUCCEED with a streamed message. -TEST(AssertionWithMessageTest, SUCCEED) { - SUCCEED() << "Success == " << 1; -} +TEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() << "Success == " << 1; } // Tests using ASSERT_TRUE with a streamed message. TEST(AssertionWithMessageTest, ASSERT_TRUE) { @@ -4422,13 +4356,16 @@ TEST(AssertionWithMessageTest, ASSERT_TRUE) { #if GTEST_OS_WINDOWS // Tests using wide strings in assertion messages. TEST(AssertionWithMessageTest, WideStringMessage) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_TRUE(false) << L"This failure is expected.\x8119"; - }, "This failure is expected."); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_EQ(1, 2) << "This failure is " - << L"expected too.\x8120"; - }, "This failure is expected too."); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_TRUE(false) << L"This failure is expected.\x8119"; + }, + "This failure is expected."); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_EQ(1, 2) << "This failure is " << L"expected too.\x8120"; + }, + "This failure is expected too."); } #endif // GTEST_OS_WINDOWS @@ -4444,8 +4381,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. @@ -4474,8 +4410,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. @@ -4494,19 +4429,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 @@ -4517,8 +4453,7 @@ TEST(ExpectTest, EXPECT_EQ_Double) { EXPECT_EQ(5.6, 5.6); // A failure. - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), - "5.1"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), "5.1"); } // Tests EXPECT_EQ(NULL, pointer). @@ -4543,8 +4478,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. @@ -4554,19 +4488,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(pv1); - EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), - "p1"); + EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), "p1"); } // Tests EXPECT_LE. @@ -4575,8 +4506,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. @@ -4584,8 +4514,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. @@ -4594,8 +4523,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. @@ -4603,8 +4531,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 @@ -4615,12 +4542,13 @@ TEST(ExpectTest, EXPECT_THROW) { EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool), "Expected: ThrowAnInteger() throws an exception of " "type bool.\n Actual: it throws a different type."); - EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"), - std::logic_error), - "Expected: ThrowRuntimeError(\"A description\") " - "throws an exception of type std::logic_error.\n " - "Actual: it throws " ERROR_DESC " " - "with description \"A description\"."); + EXPECT_NONFATAL_FAILURE( + EXPECT_THROW(ThrowRuntimeError("A description"), std::logic_error), + "Expected: ThrowRuntimeError(\"A description\") " + "throws an exception of type std::logic_error.\n " + "Actual: it throws " ERROR_DESC + " " + "with description \"A description\"."); EXPECT_NONFATAL_FAILURE( EXPECT_THROW(ThrowNothing(), bool), "Expected: ThrowNothing() throws an exception of type bool.\n" @@ -4636,17 +4564,17 @@ TEST(ExpectTest, EXPECT_NO_THROW) { EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")), "Expected: ThrowRuntimeError(\"A description\") " "doesn't throw an exception.\n " - "Actual: it throws " ERROR_DESC " " + "Actual: it throws " ERROR_DESC + " " "with description \"A description\"."); } // Tests EXPECT_ANY_THROW. TEST(ExpectTest, EXPECT_ANY_THROW) { EXPECT_ANY_THROW(ThrowAnInteger()); - EXPECT_NONFATAL_FAILURE( - EXPECT_ANY_THROW(ThrowNothing()), - "Expected: ThrowNothing() throws an exception.\n" - " Actual: it doesn't."); + EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()), + "Expected: ThrowNothing() throws an exception.\n" + " Actual: it doesn't."); } #endif // GTEST_HAS_EXCEPTIONS @@ -4658,7 +4586,6 @@ TEST(ExpectTest, ExpectPrecedence) { " true && false\n Which is: false"); } - // Tests the StreamableToString() function. // Tests using StreamableToString() on a scalar. @@ -4696,8 +4623,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. @@ -4705,25 +4631,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. // @@ -4737,10 +4662,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. @@ -4754,8 +4681,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); } @@ -4776,8 +4702,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."); } @@ -4810,37 +4735,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(0), - static_cast(0)); - EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast(0), - static_cast(1234)), - "1234"); + EXPECT_EQ(static_cast(0), static_cast(0)); + EXPECT_FATAL_FAILURE( + ASSERT_EQ(static_cast(0), static_cast(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. @@ -4856,8 +4778,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(0x8120), wchar), " wchar\n Which is: L'"); @@ -4876,13 +4797,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("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. @@ -4903,28 +4822,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(L"foo"), ::std::wstring(L"bar")); - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_EQ(const_cast(L"foo"), ::std::wstring(L"bar")); + }, + ""); } #endif // GTEST_HAS_STD_WSTRING @@ -4942,10 +4864,8 @@ TEST(EqAssertionTest, CharPointer) { char* const p2 = reinterpret_cast(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(0x1234), reinterpret_cast(0xABC0)), "ABC0"); @@ -4964,16 +4884,13 @@ TEST(EqAssertionTest, WideCharPointer) { wchar_t* const p2 = reinterpret_cast(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(pv3); const wchar_t* p4 = reinterpret_cast(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. @@ -4995,15 +4912,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_; } @@ -5065,9 +4978,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 { @@ -5077,9 +4988,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. @@ -5214,15 +5123,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() << ")"; } @@ -5239,7 +5147,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) { @@ -5264,14 +5172,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 @@ -5289,7 +5195,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, @@ -5320,21 +5226,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"; @@ -5343,11 +5246,9 @@ TEST(MessageTest, WideStrings) { // Streams a non-NULL of type wchar_t*. wstr = const_cast(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 { @@ -5361,14 +5262,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(); } }; @@ -5392,26 +5291,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 { -}; +class CodeLocationForTESTP : public TestWithParam {}; TEST_P(CodeLocationForTESTP, Verify) { VERIFY_CODE_LOCATION; @@ -5420,8 +5318,7 @@ TEST_P(CodeLocationForTESTP, Verify) { INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0)); template -class CodeLocationForTYPEDTEST : public Test { -}; +class CodeLocationForTYPEDTEST : public Test {}; TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int); @@ -5430,8 +5327,7 @@ TYPED_TEST(CodeLocationForTYPEDTEST, Verify) { } template -class CodeLocationForTYPEDTESTP : public Test { -}; +class CodeLocationForTYPEDTESTP : public Test {}; TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP); @@ -5444,6 +5340,7 @@ REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify); INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int); #undef VERIFY_CODE_LOCATION +// clang-format on // Tests setting up and tearing down a test case. // Legacy API is deprecated but still available @@ -5503,9 +5400,7 @@ const char* SetUpTestCaseTest::shared_resource_ = nullptr; TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); } // Another test that uses the shared resource. -TEST_F(SetUpTestCaseTest, Test2) { - EXPECT_STREQ("123", shared_resource_); -} +TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Tests SetupTestSuite/TearDown TestSuite @@ -5818,22 +5713,22 @@ class ParseFlagsTest : public Test { // verifies that the flag values are expected and that the // recognized flags are removed from the command line. template - 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(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); @@ -5846,16 +5741,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; } @@ -5863,10 +5758,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. @@ -5896,15 +5791,6 @@ TEST_F(ParseFlagsTest, FailFast) { GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false); } -// Tests parsing a bad --gtest_filter flag. -TEST_F(ParseFlagsTest, FilterBad) { - const char* argv[] = {"foo.exe", "--gtest_filter", nullptr}; - - const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr}; - - GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true); -} - // Tests parsing an empty --gtest_filter flag. TEST_F(ParseFlagsTest, FilterEmpty) { const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr}; @@ -6057,15 +5943,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}; @@ -6091,8 +5968,8 @@ TEST_F(ParseFlagsTest, OutputXmlDirectory) { const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_(argv, argv2, - Flags::Output("xml:directory/path/"), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"), + false); } // Tests having a --gtest_brief flag @@ -6273,8 +6150,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. @@ -6305,23 +6182,69 @@ TEST_F(ParseFlagsTest, ThrowOnFailureTrue) { GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } -# if GTEST_OS_WINDOWS +// Tests parsing a bad --gtest_filter flag. +TEST_F(ParseFlagsTest, FilterBad) { + const char* argv[] = {"foo.exe", "--gtest_filter", nullptr}; + + const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr}; + +#if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST + // Invalid flag arguments are a fatal error when using the Abseil Flags. + EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true), + testing::ExitedWithCode(1), + "ERROR: Missing the value for the flag 'gtest_filter'"); +#elif !GTEST_HAS_ABSL + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true); +#else + static_cast(argv); + static_cast(argv2); +#endif +} + +// Tests parsing --gtest_output (invalid). +TEST_F(ParseFlagsTest, OutputEmpty) { + const char* argv[] = {"foo.exe", "--gtest_output", nullptr}; + + const char* argv2[] = {"foo.exe", "--gtest_output", nullptr}; + +#if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST + // Invalid flag arguments are a fatal error when using the Abseil Flags. + EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true), + testing::ExitedWithCode(1), + "ERROR: Missing the value for the flag 'gtest_output'"); +#elif !GTEST_HAS_ABSL + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true); +#else + static_cast(argv); + static_cast(argv2); +#endif +} + +#if GTEST_HAS_ABSL +TEST_F(ParseFlagsTest, AbseilPositionalFlags) { + const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", "--", + "--other_flag", nullptr}; + + // When using Abseil flags, it should be possible to pass flags not recognized + // using "--" to delimit positional arguments. These flags should be returned + // though argv. + const char* argv2[] = {"foo.exe", "--other_flag", nullptr}; + + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); +} +#endif + +#if GTEST_OS_WINDOWS // Tests parsing wide strings. TEST_F(ParseFlagsTest, WideStrings) { - const wchar_t* argv[] = { - L"foo.exe", - L"--gtest_filter=Foo*", - L"--gtest_list_tests=1", - L"--gtest_break_on_failure", - L"--non_gtest_flag", - NULL - }; + const wchar_t* argv[] = {L"foo.exe", + L"--gtest_filter=Foo*", + L"--gtest_list_tests=1", + L"--gtest_break_on_failure", + L"--non_gtest_flag", + NULL}; - const wchar_t* argv2[] = { - L"foo.exe", - L"--non_gtest_flag", - NULL - }; + const wchar_t* argv2[] = {L"foo.exe", L"--non_gtest_flag", NULL}; Flags expected_flags; expected_flags.break_on_failure = true; @@ -6330,7 +6253,7 @@ TEST_F(ParseFlagsTest, WideStrings) { GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); } -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS #if GTEST_USE_OWN_FLAGFILE_FLAG_ class FlagfileTest : public ParseFlagsTest { @@ -6378,8 +6301,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(); @@ -6392,10 +6315,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(); @@ -6419,8 +6342,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."; } @@ -6428,8 +6350,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."; } @@ -6438,8 +6359,7 @@ class CurrentTestInfoTest : public Test { // Tests that current_test_info() returns TestInfo for currently running // test by checking the expected test name against the actual one. TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) { - const TestInfo* test_info = - UnitTest::GetInstance()->current_test_info(); + const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(nullptr != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name()) @@ -6453,8 +6373,7 @@ TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) { // use this test to see that the TestInfo object actually changed from // the previous invocation. TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) { - const TestInfo* test_info = - UnitTest::GetInstance()->current_test_info(); + const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(nullptr != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name()) @@ -6465,7 +6384,6 @@ TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) { } // namespace testing - // These two lines test that we can define tests in a namespace that // has the name "testing" and is nested in another namespace. namespace my_namespace { @@ -6514,13 +6432,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) { @@ -6543,7 +6460,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) { @@ -6614,28 +6531,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 @@ -6645,12 +6566,12 @@ TEST(StreamingAssertionsTest, AnyThrow) { TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) { 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. } @@ -6670,12 +6591,12 @@ TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) { TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) { 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. } @@ -6695,7 +6616,7 @@ TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) { TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { 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. } @@ -6718,49 +6639,49 @@ TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { // On non-Windows platforms, we rely on TERM to determine if the // terminal supports colors. - SetEnv("TERM", "dumb"); // TERM doesn't support colors. + SetEnv("TERM", "dumb"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "emacs"); // TERM doesn't support colors. + SetEnv("TERM", "emacs"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "vt100"); // TERM doesn't support colors. + SetEnv("TERM", "vt100"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors. + SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "xterm"); // TERM supports colors. + SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "xterm-color"); // TERM supports colors. + SetEnv("TERM", "xterm-color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "xterm-256color"); // TERM supports colors. + SetEnv("TERM", "xterm-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "screen"); // TERM supports colors. + SetEnv("TERM", "screen"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "screen-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "tmux"); // TERM supports colors. + SetEnv("TERM", "tmux"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "tmux-256color"); // TERM supports colors. + SetEnv("TERM", "tmux-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "rxvt-unicode"); // TERM supports colors. + SetEnv("TERM", "rxvt-unicode"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors. + EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. + + SetEnv("TERM", "linux"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "linux"); // TERM supports colors. - EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - - SetEnv("TERM", "cygwin"); // TERM supports colors. + SetEnv("TERM", "cygwin"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. #endif // GTEST_OS_WINDOWS } @@ -6880,12 +6801,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: @@ -6942,8 +6861,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); @@ -6986,7 +6905,8 @@ class SequenceTestingListener : public EmptyTestEventListener { std::vector* vector_; const char* const id_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener); + SequenceTestingListener(const SequenceTestingListener&) = delete; + SequenceTestingListener& operator=(const SequenceTestingListener&) = delete; }; TEST(EventListenerTest, AppendKeepsOrder) { @@ -6996,32 +6916,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()); @@ -7041,8 +6961,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); @@ -7060,17 +6980,20 @@ TEST(EventListenerTest, SuppressEventForwarding) { ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); TestEventListenersAccessor::SuppressEventForwarding(&listeners); ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } // Tests that events generated by Google Test are not forwarded in // death test subprocesses. TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) { - EXPECT_DEATH_IF_SUPPORTED({ - GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled( - *GetUnitTestImpl()->listeners())) << "expected failure";}, + EXPECT_DEATH_IF_SUPPORTED( + { + GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled( + *GetUnitTestImpl()->listeners())) + << "expected failure"; + }, "expected failure"); } @@ -7087,8 +7010,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); @@ -7101,8 +7024,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); } @@ -7124,8 +7047,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. @@ -7146,8 +7069,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); @@ -7160,8 +7083,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); } @@ -7183,8 +7106,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. @@ -7192,7 +7115,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 @@ -7272,28 +7195,26 @@ struct IncompleteType; // Tests that HasDebugStringAndShortDebugString::value is a compile-time // constant. TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) { - GTEST_COMPILE_ASSERT_( - HasDebugStringAndShortDebugString::value, - const_true); - GTEST_COMPILE_ASSERT_( + static_assert(HasDebugStringAndShortDebugString::value, + "const_true"); + static_assert( HasDebugStringAndShortDebugString::value, - const_true); - GTEST_COMPILE_ASSERT_(HasDebugStringAndShortDebugString< - const InheritsDebugStringMethods>::value, - const_true); - GTEST_COMPILE_ASSERT_( + "const_true"); + static_assert(HasDebugStringAndShortDebugString< + const InheritsDebugStringMethods>::value, + "const_true"); + static_assert( !HasDebugStringAndShortDebugString::value, - const_false); - GTEST_COMPILE_ASSERT_( + "const_false"); + static_assert( !HasDebugStringAndShortDebugString::value, - const_false); - GTEST_COMPILE_ASSERT_( + "const_false"); + static_assert( !HasDebugStringAndShortDebugString::value, - const_false); - GTEST_COMPILE_ASSERT_( - !HasDebugStringAndShortDebugString::value, const_false); - GTEST_COMPILE_ASSERT_(!HasDebugStringAndShortDebugString::value, - const_false); + "const_false"); + static_assert(!HasDebugStringAndShortDebugString::value, + "const_false"); + static_assert(!HasDebugStringAndShortDebugString::value, "const_false"); } // Tests that HasDebugStringAndShortDebugString::value is true when T has @@ -7344,7 +7265,6 @@ TEST(GTestReferenceToConstTest, Works) { TestGTestReferenceToConst(); } - // Tests IsContainerTest. class NonContainer {}; @@ -7356,10 +7276,9 @@ TEST(IsContainerTestTest, WorksForNonContainer) { } TEST(IsContainerTestTest, WorksForContainer) { + EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest>(0))); EXPECT_EQ(sizeof(IsContainer), - sizeof(IsContainerTest >(0))); - EXPECT_EQ(sizeof(IsContainer), - sizeof(IsContainerTest >(0))); + sizeof(IsContainerTest>(0))); } struct ConstOnlyContainerWithPointerIterator { @@ -7408,8 +7327,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)); @@ -7419,9 +7338,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)); @@ -7439,11 +7358,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)); } @@ -7469,7 +7388,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); @@ -7484,7 +7403,7 @@ TEST(CopyArrayTest, WorksForTwoDimensionalArrays) { // Tests NativeArray. TEST(NativeArrayTest, ConstructorFromArrayWorks) { - const int a[3] = { 0, 1, 2 }; + const int a[3] = {0, 1, 2}; NativeArray na(a, 3, RelationToSourceReference()); EXPECT_EQ(3U, na.size()); EXPECT_EQ(a, na.begin()); @@ -7514,7 +7433,7 @@ TEST(NativeArrayTest, TypeMembersAreCorrect) { } TEST(NativeArrayTest, MethodsWork) { - const int a[3] = { 0, 1, 2 }; + const int a[3] = {0, 1, 2}; NativeArray na(a, 3, RelationToSourceCopy()); ASSERT_EQ(3U, na.size()); EXPECT_EQ(3, na.end() - na.begin()); @@ -7533,14 +7452,14 @@ TEST(NativeArrayTest, MethodsWork) { NativeArray 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(b1, 3, RelationToSourceReference())); EXPECT_FALSE(na == NativeArray(b2, 4, RelationToSourceCopy())); } TEST(NativeArrayTest, WorksForTwoDimensionalArray) { - const char a[2][3] = { "hi", "lo" }; + const char a[2][3] = {"hi", "lo"}; NativeArray na(a, 2, RelationToSourceReference()); ASSERT_EQ(2U, na.size()); EXPECT_EQ(a, na.begin()); diff --git a/googletest/test/gtest_xml_outfiles_test.py b/googletest/test/gtest_xml_outfiles_test.py index 916bdf4d..c129e64b 100755 --- a/googletest/test/gtest_xml_outfiles_test.py +++ b/googletest/test/gtest_xml_outfiles_test.py @@ -43,7 +43,7 @@ GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_" EXPECTED_XML_1 = """ - + @@ -57,7 +57,7 @@ EXPECTED_XML_1 = """ EXPECTED_XML_2 = """ - + diff --git a/googletest/test/gtest_xml_output_unittest.py b/googletest/test/gtest_xml_output_unittest.py index f0b0c3b9..e1b7f1fc 100755 --- a/googletest/test/gtest_xml_output_unittest.py +++ b/googletest/test/gtest_xml_output_unittest.py @@ -67,10 +67,10 @@ else: EXPECTED_NON_EMPTY_XML = """ - + - + - - + + - + - + ]]>%(stack)s]]> - + - + - + - + - + - + - + - + - + - + - + - + - - - - + + + + - + - + - + - + """ % { 'stack': STACK_TRACE_TEMPLATE @@ -195,24 +195,24 @@ EXPECTED_FILTERED_TEST_XML = """ timestamp="*" name="AllTests" ad_hoc_property="42"> - + """ EXPECTED_SHARDED_TEST_XML = """ - + - + - + """ diff --git a/googletest/test/gtest_xml_output_unittest_.cc b/googletest/test/gtest_xml_output_unittest_.cc index c0036aae..4bdb0c7e 100644 --- a/googletest/test/gtest_xml_output_unittest_.cc +++ b/googletest/test/gtest_xml_output_unittest_.cc @@ -35,18 +35,18 @@ // // This program will be invoked from a Python unit test. Don't run it // directly. +// clang-format off #include "gtest/gtest.h" using ::testing::InitGoogleTest; +using ::testing::Test; using ::testing::TestEventListeners; using ::testing::TestWithParam; using ::testing::UnitTest; -using ::testing::Test; using ::testing::Values; -class SuccessfulTest : public Test { -}; +class SuccessfulTest : public Test {}; TEST_F(SuccessfulTest, Succeeds) { SUCCEED() << "This is a success."; @@ -191,3 +191,5 @@ int main(int argc, char** argv) { testing::Test::RecordProperty("ad_hoc_property", "42"); return RUN_ALL_TESTS(); } + +// clang-format on diff --git a/googletest/test/gtest_xml_test_utils.py b/googletest/test/gtest_xml_test_utils.py index 50c6e7dc..c6fb9f44 100755 --- a/googletest/test/gtest_xml_test_utils.py +++ b/googletest/test/gtest_xml_test_utils.py @@ -170,6 +170,10 @@ class GTestXMLTestCase(gtest_test_utils.TestCase): * The stack traces are removed. """ + if element.tagName == 'testcase': + source_file = element.getAttributeNode('file') + if source_file: + source_file.value = re.sub(r'^.*[/\\](.*)', '\\1', source_file.value) if element.tagName in ('testsuites', 'testsuite', 'testcase'): timestamp = element.getAttributeNode('timestamp') timestamp.value = re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d\d\d$', diff --git a/googletest/test/production.h b/googletest/test/production.h index 41a54722..4dec8d46 100644 --- a/googletest/test/production.h +++ b/googletest/test/production.h @@ -46,6 +46,7 @@ class PrivateCode { PrivateCode(); int x() const { return x_; } + private: void set_x(int an_x) { x_ = an_x; } int x_;