Merge branch 'google:main' into main

This commit is contained in:
Alessio 2025-11-16 18:36:32 +01:00 committed by GitHub
commit ffb6156362
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
33 changed files with 192 additions and 148 deletions

View File

@ -30,6 +30,8 @@
# #
# Bazel Build for Google C++ Testing Framework(Google Test) # Bazel Build for Google C++ Testing Framework(Google Test)
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
package(default_visibility = ["//visibility:public"]) package(default_visibility = ["//visibility:public"])
licenses(["notice"]) licenses(["notice"])

View File

@ -52,6 +52,11 @@ bazel_dep(
version = "2024-07-02.bcr.1", version = "2024-07-02.bcr.1",
) )
bazel_dep(
name = "rules_cc",
version = "0.2.8"
)
bazel_dep( bazel_dep(
name = "rules_python", name = "rules_python",
version = "1.3.0", version = "1.3.0",

View File

@ -45,12 +45,6 @@ http_archive(
load("@rules_python//python:repositories.bzl", "py_repositories") load("@rules_python//python:repositories.bzl", "py_repositories")
py_repositories() py_repositories()
http_archive(
name = "bazel_skylib",
sha256 = "cd55a062e763b9349921f0f5db8c3933288dc8ba4f76dd9416aac68acee3cb94",
urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz"],
)
http_archive( http_archive(
name = "platforms", name = "platforms",
urls = [ urls = [
@ -59,3 +53,9 @@ http_archive(
], ],
sha256 = "29742e87275809b5e598dc2f04d86960cc7a55b3067d97221c9abbc9926bff0f", sha256 = "29742e87275809b5e598dc2f04d86960cc7a55b3067d97221c9abbc9926bff0f",
) )
load("@bazel_features//:deps.bzl", "bazel_features_deps")
bazel_features_deps()
load("@rules_cc//cc:extensions.bzl", "compatibility_proxy_repo")
compatibility_proxy_repo()

View File

@ -66,8 +66,8 @@ fi
# Use Bazel Vendor mode to reduce reliance on external dependencies. # Use Bazel Vendor mode to reduce reliance on external dependencies.
if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f "${KOKORO_GFILE_DIR}/distdir/googletest_vendor.tar.gz" ]]; then if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f "${KOKORO_GFILE_DIR}/distdir/googletest_vendor.tar.gz" ]]; then
tar -xf "${KOKORO_GFILE_DIR}/distdir/googletest_vendor.tar.gz" -C "${TMP}/" tar -xf "${KOKORO_GFILE_DIR}/distdir/googletest_vendor.tar.gz" -C "${HOME}/"
BAZEL_EXTRA_ARGS="--vendor_dir=\"${TMP}/googletest_vendor\" ${BAZEL_EXTRA_ARGS:-}" BAZEL_EXTRA_ARGS="--vendor_dir=${HOME}/googletest_vendor ${BAZEL_EXTRA_ARGS:-}"
fi fi
cd ${GTEST_ROOT} cd ${GTEST_ROOT}

View File

@ -130,7 +130,7 @@ TEST(BarTest, DoesThis) {
## Setting Default Actions {#OnCall} ## Setting Default Actions {#OnCall}
gMock has a **built-in default action** for any function that returns `void`, gMock has a **built-in default action** for any function that returns `void`,
`bool`, a numeric value, or a pointer. In C++11, it will additionally returns `bool`, a numeric value, or a pointer. In C++11, it additionally returns
the default-constructed value, if one exists for the given type. the default-constructed value, if one exists for the given type.
To customize the default action for functions with return type `T`, use To customize the default action for functions with return type `T`, use

View File

@ -900,15 +900,16 @@ using ::testing::Not;
Matchers are function objects, and parametrized matchers can be composed just Matchers are function objects, and parametrized matchers can be composed just
like any other function. However because their types can be long and rarely like any other function. However because their types can be long and rarely
provide meaningful information, it can be easier to express them with C++14 provide meaningful information, it can be easier to express them with template
generic lambdas to avoid specifying types. For example, parameters and `auto`. For example,
```cpp ```cpp
using ::testing::Contains; using ::testing::Contains;
using ::testing::Property; using ::testing::Property;
inline constexpr auto HasFoo = [](const auto& f) { template <typename SubMatcher>
return Property("foo", &MyClass::foo, Contains(f)); inline constexpr auto HasFoo(const SubMatcher& sub_matcher) {
return Property("foo", &MyClass::foo, Contains(sub_matcher));
}; };
... ...
EXPECT_THAT(x, HasFoo("blah")); EXPECT_THAT(x, HasFoo("blah"));

View File

@ -49,6 +49,7 @@ Matcher | Description
| `NotNull()` | `argument` is a non-null pointer (raw or smart). | | `NotNull()` | `argument` is a non-null pointer (raw or smart). |
| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)| | `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)|
| `VariantWith<T>(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. | | `VariantWith<T>(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. |
| `AnyWith<T>(m)` | `argument` is `any<>` that holds a value of type T with a value matching `m`. |
| `Ref(variable)` | `argument` is a reference to `variable`. | | `Ref(variable)` | `argument` is a reference to `variable`. |
| `TypedEq<type>(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. | | `TypedEq<type>(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. |

View File

@ -1796,11 +1796,24 @@ struct SetArrayArgumentAction {
}; };
template <size_t k> template <size_t k>
struct DeleteArgAction { class DeleteArgAction {
public:
template <typename... Args> template <typename... Args>
void operator()(const Args&... args) const { void operator()(const Args&... args) const {
delete std::get<k>(std::tie(args...)); DoDelete(std::get<k>(std::tie(args...)));
} }
private:
template <typename T>
static void DoDelete(T* ptr) {
delete ptr;
}
template <typename T>
[[deprecated(
"DeleteArg<N> used for a non-pointer argument, it was likely migrated "
"to a smart pointer type. This action should be removed.")]]
static void DoDelete(T&) {}
}; };
template <typename Ptr> template <typename Ptr>
@ -1868,7 +1881,7 @@ typedef internal::IgnoredValue Unused;
// Deprecated single-argument DoAll. // Deprecated single-argument DoAll.
template <typename Action> template <typename Action>
GMOCK_DEPRECATE_AND_INLINE() GTEST_INTERNAL_DEPRECATE_AND_INLINE("Avoid using DoAll() for single actions")
typename std::decay<Action>::type DoAll(Action&& action) { typename std::decay<Action>::type DoAll(Action&& action) {
return std::forward<Action>(action); return std::forward<Action>(action);
} }
@ -2038,11 +2051,11 @@ PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(
// Various overloads for Invoke(). // Various overloads for Invoke().
// Legacy function. // Legacy function.
// Actions can now be implicitly constructed from callables. No need to create
// wrapper objects.
// This function exists for backwards compatibility. // This function exists for backwards compatibility.
template <typename FunctionImpl> template <typename FunctionImpl>
GMOCK_DEPRECATE_AND_INLINE() GTEST_INTERNAL_DEPRECATE_AND_INLINE(
"Actions can now be implicitly constructed from callables. No need to "
"create wrapper objects using Invoke().")
typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) { typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
return std::forward<FunctionImpl>(function_impl); return std::forward<FunctionImpl>(function_impl);
} }

View File

@ -1329,17 +1329,23 @@ class AllOfMatcherImpl : public MatcherInterface<const T&> {
// However, if matcher doesn't provide one, this method uses matcher's // However, if matcher doesn't provide one, this method uses matcher's
// description. // description.
std::string all_match_result; std::string all_match_result;
bool success = true;
for (const Matcher<T>& matcher : matchers_) { for (const Matcher<T>& matcher : matchers_) {
StringMatchResultListener slistener; StringMatchResultListener slistener;
// Return explanation for first failed matcher. // Return explanation for first failed matcher.
if (!matcher.MatchAndExplain(x, &slistener)) { if (!matcher.MatchAndExplain(x, &slistener)) {
const std::string explanation = slistener.str(); const std::string explanation = slistener.str();
if (!success) {
// Already had a failure.
*listener << ", and ";
}
if (!explanation.empty()) { if (!explanation.empty()) {
*listener << explanation; *listener << explanation;
} else { } else {
*listener << "which doesn't match (" << Describe(matcher) << ")"; *listener << "which doesn't match (" << Describe(matcher) << ")";
} }
return false; success = false;
continue;
} }
// Keep track of explanations in case all matchers succeed. // Keep track of explanations in case all matchers succeed.
std::string explanation = slistener.str(); std::string explanation = slistener.str();
@ -1356,8 +1362,10 @@ class AllOfMatcherImpl : public MatcherInterface<const T&> {
} }
} }
*listener << all_match_result; if (success) {
return true; *listener << all_match_result;
}
return success;
} }
private: private:

View File

@ -1292,10 +1292,10 @@ class MockSpec {
: function_mocker_(function_mocker), matchers_(matchers) {} : function_mocker_(function_mocker), matchers_(matchers) {}
// Adds a new default action spec to the function mocker and returns // Adds a new default action spec to the function mocker and returns
// the newly created spec. // the newly created spec. .WillByDefault() must be called on the returned
internal::OnCallSpec<F>& InternalDefaultActionSetAt(const char* file, // object.
int line, const char* obj, [[nodiscard]] internal::OnCallSpec<F>& InternalDefaultActionSetAt(
const char* call) { const char* file, int line, const char* obj, const char* call) {
LogWithLocation(internal::kInfo, file, line, LogWithLocation(internal::kInfo, file, line,
std::string("ON_CALL(") + obj + ", " + call + ") invoked"); std::string("ON_CALL(") + obj + ", " + call + ") invoked");
return function_mocker_->AddNewOnCallSpec(file, line, matchers_); return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
@ -1467,7 +1467,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
// function have been satisfied. If not, it will report Google Test // function have been satisfied. If not, it will report Google Test
// non-fatal failures for the violations. // non-fatal failures for the violations.
~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
MutexLock l(&g_gmock_mutex); MutexLock l(g_gmock_mutex);
VerifyAndClearExpectationsLocked(); VerifyAndClearExpectationsLocked();
Mock::UnregisterLocked(this); Mock::UnregisterLocked(this);
ClearDefaultActionsLocked(); ClearDefaultActionsLocked();
@ -1530,7 +1530,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
UntypedOnCallSpecs specs_to_delete; UntypedOnCallSpecs specs_to_delete;
untyped_on_call_specs_.swap(specs_to_delete); untyped_on_call_specs_.swap(specs_to_delete);
g_gmock_mutex.Unlock(); 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) { it != specs_to_delete.end(); ++it) {
delete static_cast<const OnCallSpec<F>*>(*it); delete static_cast<const OnCallSpec<F>*>(*it);
@ -1538,7 +1538,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
// Lock the mutex again, since the caller expects it to be locked when we // Lock the mutex again, since the caller expects it to be locked when we
// return. // return.
g_gmock_mutex.Lock(); g_gmock_mutex.lock();
} }
// Returns the result of invoking this mock function with the given // Returns the result of invoking this mock function with the given
@ -1646,7 +1646,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
const ArgumentTuple& args = const ArgumentTuple& args =
*static_cast<const ArgumentTuple*>(untyped_args); *static_cast<const ArgumentTuple*>(untyped_args);
MutexLock l(&g_gmock_mutex); MutexLock l(g_gmock_mutex);
TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args); TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
if (exp == nullptr) { // A match wasn't found. if (exp == nullptr) { // A match wasn't found.
this->FormatUnexpectedCallMessageLocked(args, what, why); this->FormatUnexpectedCallMessageLocked(args, what, why);

View File

@ -298,7 +298,7 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
// //
class WithoutMatchers { class WithoutMatchers {
private: private:
WithoutMatchers() {} WithoutMatchers() = default;
friend GTEST_API_ WithoutMatchers GetWithoutMatchers(); friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
}; };

View File

@ -57,19 +57,10 @@
#include "gmock/internal/custom/gmock-port.h" #include "gmock/internal/custom/gmock-port.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if defined(GTEST_HAS_ABSL) #if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
#include "absl/base/macros.h"
#define GMOCK_DEPRECATE_AND_INLINE() ABSL_DEPRECATE_AND_INLINE()
#if !defined(GTEST_NO_ABSL_FLAGS)
#include "absl/flags/declare.h" #include "absl/flags/declare.h"
#include "absl/flags/flag.h" #include "absl/flags/flag.h"
#endif // !defined(GTEST_NO_ABSL_FLAGS) #endif
#else // defined(GTEST_HAS_ABSL)
#define GMOCK_DEPRECATE_AND_INLINE()
#endif // defined(GTEST_HAS_ABSL)
// For MS Visual C++, check the compiler version. At least VS 2015 is // For MS Visual C++, check the compiler version. At least VS 2015 is
// required to compile Google Mock. // required to compile Google Mock.

View File

@ -156,7 +156,7 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
if (!LogIsVisible(severity)) return; if (!LogIsVisible(severity)) return;
// Ensures that logs from different threads don't interleave. // Ensures that logs from different threads don't interleave.
MutexLock l(&g_log_mutex); MutexLock l(g_log_mutex);
if (severity == kWarning) { if (severity == kWarning) {
// Prints a GMOCK WARNING marker to make the warnings easily searchable. // Prints a GMOCK WARNING marker to make the warnings easily searchable.

View File

@ -212,7 +212,7 @@ void ExpectationBase::CheckActionCountIfNotDone() const
GTEST_LOCK_EXCLUDED_(mutex_) { GTEST_LOCK_EXCLUDED_(mutex_) {
bool should_check = false; bool should_check = false;
{ {
MutexLock l(&mutex_); MutexLock l(mutex_);
if (!action_count_checked_) { if (!action_count_checked_) {
action_count_checked_ = true; action_count_checked_ = true;
should_check = true; should_check = true;
@ -318,7 +318,7 @@ UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default;
void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
{ {
MutexLock l(&g_gmock_mutex); MutexLock l(g_gmock_mutex);
mock_obj_ = mock_obj; mock_obj_ = mock_obj;
} }
Mock::Register(mock_obj, this); Mock::Register(mock_obj, this);
@ -332,7 +332,7 @@ void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
// We protect name_ under g_gmock_mutex in case this mock function // We protect name_ under g_gmock_mutex in case this mock function
// is called from two threads concurrently. // is called from two threads concurrently.
MutexLock l(&g_gmock_mutex); MutexLock l(g_gmock_mutex);
mock_obj_ = mock_obj; mock_obj_ = mock_obj;
name_ = name; name_ = name;
} }
@ -345,7 +345,7 @@ const void* UntypedFunctionMockerBase::MockObject() const
{ {
// We protect mock_obj_ under g_gmock_mutex in case this mock // We protect mock_obj_ under g_gmock_mutex in case this mock
// function is called from two threads concurrently. // function is called from two threads concurrently.
MutexLock l(&g_gmock_mutex); MutexLock l(g_gmock_mutex);
Assert(mock_obj_ != nullptr, __FILE__, __LINE__, Assert(mock_obj_ != nullptr, __FILE__, __LINE__,
"MockObject() must not be called before RegisterOwner() or " "MockObject() must not be called before RegisterOwner() or "
"SetOwnerAndName() has been called."); "SetOwnerAndName() has been called.");
@ -362,7 +362,7 @@ const char* UntypedFunctionMockerBase::Name() const
{ {
// We protect name_ under g_gmock_mutex in case this mock // We protect name_ under g_gmock_mutex in case this mock
// function is called from two threads concurrently. // function is called from two threads concurrently.
MutexLock l(&g_gmock_mutex); MutexLock l(g_gmock_mutex);
Assert(name_ != nullptr, __FILE__, __LINE__, Assert(name_ != nullptr, __FILE__, __LINE__,
"Name() must not be called before SetOwnerAndName() has " "Name() must not be called before SetOwnerAndName() has "
"been called."); "been called.");
@ -436,9 +436,9 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
UntypedExpectations expectations_to_delete; UntypedExpectations expectations_to_delete;
untyped_expectations_.swap(expectations_to_delete); untyped_expectations_.swap(expectations_to_delete);
g_gmock_mutex.Unlock(); g_gmock_mutex.unlock();
expectations_to_delete.clear(); expectations_to_delete.clear();
g_gmock_mutex.Lock(); g_gmock_mutex.lock();
return expectations_met; return expectations_met;
} }
@ -502,7 +502,7 @@ class MockObjectRegistry {
// a test failure, unless the user has explicitly asked to ignore it. // a test failure, unless the user has explicitly asked to ignore it.
~MockObjectRegistry() { ~MockObjectRegistry() {
if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return; if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return;
internal::MutexLock l(&internal::g_gmock_mutex); internal::MutexLock l(internal::g_gmock_mutex);
int leaked_count = 0; int leaked_count = 0;
for (StateMap::const_iterator it = states_.begin(); it != states_.end(); for (StateMap::const_iterator it = states_.begin(); it != states_.end();
@ -574,7 +574,7 @@ UninterestingCallReactionMap() {
void SetReactionOnUninterestingCalls(uintptr_t mock_obj, void SetReactionOnUninterestingCalls(uintptr_t mock_obj,
internal::CallReaction reaction) internal::CallReaction reaction)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex); internal::MutexLock l(internal::g_gmock_mutex);
UninterestingCallReactionMap()[mock_obj] = reaction; UninterestingCallReactionMap()[mock_obj] = reaction;
} }
@ -605,7 +605,7 @@ void Mock::FailUninterestingCalls(uintptr_t mock_obj)
// entry in the call-reaction table should be removed. // entry in the call-reaction table should be removed.
void Mock::UnregisterCallReaction(uintptr_t mock_obj) void Mock::UnregisterCallReaction(uintptr_t mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex); internal::MutexLock l(internal::g_gmock_mutex);
UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj)); UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj));
} }
@ -613,7 +613,7 @@ void Mock::UnregisterCallReaction(uintptr_t mock_obj)
// made on the given mock object. // made on the given mock object.
internal::CallReaction Mock::GetReactionOnUninterestingCalls( 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); internal::MutexLock l(internal::g_gmock_mutex);
return (UninterestingCallReactionMap().count( return (UninterestingCallReactionMap().count(
reinterpret_cast<uintptr_t>(mock_obj)) == 0) reinterpret_cast<uintptr_t>(mock_obj)) == 0)
? internal::intToCallReaction( ? internal::intToCallReaction(
@ -626,7 +626,7 @@ internal::CallReaction Mock::GetReactionOnUninterestingCalls(
// objects. // objects.
void Mock::AllowLeak(const void* mock_obj) void Mock::AllowLeak(const void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex); internal::MutexLock l(internal::g_gmock_mutex);
g_mock_object_registry.states()[mock_obj].leakable = true; g_mock_object_registry.states()[mock_obj].leakable = true;
} }
@ -635,7 +635,7 @@ void Mock::AllowLeak(const void* mock_obj)
// Test non-fatal failures and returns false. // Test non-fatal failures and returns false.
bool Mock::VerifyAndClearExpectations(void* mock_obj) bool Mock::VerifyAndClearExpectations(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex); internal::MutexLock l(internal::g_gmock_mutex);
return VerifyAndClearExpectationsLocked(mock_obj); return VerifyAndClearExpectationsLocked(mock_obj);
} }
@ -644,7 +644,7 @@ bool Mock::VerifyAndClearExpectations(void* mock_obj)
// verification was successful. // verification was successful.
bool Mock::VerifyAndClear(void* mock_obj) bool Mock::VerifyAndClear(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex); internal::MutexLock l(internal::g_gmock_mutex);
ClearDefaultActionsLocked(mock_obj); ClearDefaultActionsLocked(mock_obj);
return VerifyAndClearExpectationsLocked(mock_obj); return VerifyAndClearExpectationsLocked(mock_obj);
} }
@ -694,7 +694,7 @@ bool Mock::IsStrict(void* mock_obj)
void Mock::Register(const void* mock_obj, void Mock::Register(const void* mock_obj,
internal::UntypedFunctionMockerBase* mocker) internal::UntypedFunctionMockerBase* mocker)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex); internal::MutexLock l(internal::g_gmock_mutex);
g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker); g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
} }
@ -704,7 +704,7 @@ void Mock::Register(const void* mock_obj,
void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
const char* file, int line) const char* file, int line)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex); internal::MutexLock l(internal::g_gmock_mutex);
MockObjectState& state = g_mock_object_registry.states()[mock_obj]; MockObjectState& state = g_mock_object_registry.states()[mock_obj];
if (state.first_used_file == nullptr) { if (state.first_used_file == nullptr) {
state.first_used_file = file; state.first_used_file = file;

View File

@ -30,6 +30,7 @@
# #
# Bazel Build for Google C++ Testing Framework(Google Test)-googlemock # Bazel Build for Google C++ Testing Framework(Google Test)-googlemock
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
load("@rules_python//python:defs.bzl", "py_library", "py_test") load("@rules_python//python:defs.bzl", "py_library", "py_test")
licenses(["notice"]) licenses(["notice"])

View File

@ -1822,7 +1822,7 @@ std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) { TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
MockClass mock; MockClass mock;
std::unique_ptr<int> i(new int(19)); std::unique_ptr<int> i = std::make_unique<int>(19);
EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i)))); EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
EXPECT_CALL(mock, MakeVectorUnique()) EXPECT_CALL(mock, MakeVectorUnique())
.WillOnce(Return(ByMove(VectorUniquePtrSource()))); .WillOnce(Return(ByMove(VectorUniquePtrSource())));
@ -1845,7 +1845,7 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) { TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
testing::MockFunction<void()> mock_function; testing::MockFunction<void()> mock_function;
MockClass mock; MockClass mock;
std::unique_ptr<int> i(new int(19)); std::unique_ptr<int> i = std::make_unique<int>(19);
EXPECT_CALL(mock_function, Call()); EXPECT_CALL(mock_function, Call());
EXPECT_CALL(mock, MakeUnique()) EXPECT_CALL(mock, MakeUnique())
.WillOnce(DoAll(InvokeWithoutArgs(&mock_function, .WillOnce(DoAll(InvokeWithoutArgs(&mock_function,

View File

@ -545,7 +545,7 @@ TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) {
void OnCallLogger() { void OnCallLogger() {
DummyMock mock; DummyMock mock;
ON_CALL(mock, TestMethod()); (void)ON_CALL(mock, TestMethod());
} }
// Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info". // Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info".
@ -568,7 +568,7 @@ TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) {
void OnCallAnyArgumentLogger() { void OnCallAnyArgumentLogger() {
DummyMock mock; DummyMock mock;
ON_CALL(mock, TestMethodArg(_)); (void)ON_CALL(mock, TestMethodArg(_));
} }
// Verifies that ON_CALL prints provided _ argument. // Verifies that ON_CALL prints provided _ argument.

View File

@ -770,7 +770,8 @@ TEST_P(AllOfTestP, ExplainsResult) {
// Failed match. The first matcher, which failed, needs to // Failed match. The first matcher, which failed, needs to
// explain. // explain.
m = AllOf(GreaterThan(10), GreaterThan(20)); m = AllOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 less than 10", Explain(m, 5)); EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
Explain(m, 5));
// Failed match. The second matcher, which failed, needs to // Failed match. The second matcher, which failed, needs to
// explain. Since it doesn't given an explanation, the matcher text is // explain. Since it doesn't given an explanation, the matcher text is
@ -1625,7 +1626,7 @@ TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
} }
TEST(NotTest, WorksOnMoveOnlyType) { TEST(NotTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3)); std::unique_ptr<int> p = std::make_unique<int>(3);
EXPECT_THAT(p, Pointee(Eq(3))); EXPECT_THAT(p, Pointee(Eq(3)));
EXPECT_THAT(p, Not(Pointee(Eq(2)))); EXPECT_THAT(p, Not(Pointee(Eq(2))));
} }
@ -1681,13 +1682,13 @@ TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
} // namespace adl_test } // namespace adl_test
TEST(AllOfTest, WorksOnMoveOnlyType) { TEST(AllOfTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3)); std::unique_ptr<int> p = std::make_unique<int>(3);
EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5)))); 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))))); EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
} }
TEST(AnyOfTest, WorksOnMoveOnlyType) { TEST(AnyOfTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3)); std::unique_ptr<int> p = std::make_unique<int>(3);
EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5)))); 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))))); EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
} }

View File

@ -2389,22 +2389,19 @@ PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
return MakePolymorphicMatcher(DivisibleByImpl(n)); return MakePolymorphicMatcher(DivisibleByImpl(n));
} }
// Tests that when AllOf() fails, only the first failing matcher is // Tests that when AllOf() fails, all failing matchers are asked to explain why.
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_False_False) { TEST(ExplainMatchResultTest, AllOf_False_False) {
const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3)); const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
EXPECT_EQ("which is 1 modulo 4", Explain(m, 5)); EXPECT_EQ("which is 1 modulo 4, and which is 2 modulo 3", Explain(m, 5));
} }
// Tests that when AllOf() fails, only the first failing matcher is // Tests that when AllOf() fails, all failing matchers are asked to explain why.
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_False_True) { TEST(ExplainMatchResultTest, AllOf_False_True) {
const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3)); const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
EXPECT_EQ("which is 2 modulo 4", Explain(m, 6)); EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
} }
// Tests that when AllOf() fails, only the first failing matcher is // Tests that when AllOf() fails, all failing matchers are asked to explain why.
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_True_False) { TEST(ExplainMatchResultTest, AllOf_True_False) {
const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3)); const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
EXPECT_EQ("which is 2 modulo 3", Explain(m, 5)); EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));

View File

@ -217,7 +217,7 @@ TEST(PointeeTest, ReferenceToNonConstRawPointer) {
TEST(PointeeTest, SmartPointer) { TEST(PointeeTest, SmartPointer) {
const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0)); const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
std::unique_ptr<int> n(new int(1)); std::unique_ptr<int> n = std::make_unique<int>(1);
EXPECT_TRUE(m.Matches(n)); EXPECT_TRUE(m.Matches(n));
} }
@ -254,7 +254,7 @@ TEST(PointerTest, RawPointerToConst) {
} }
TEST(PointerTest, SmartPointer) { TEST(PointerTest, SmartPointer) {
std::unique_ptr<int> n(new int(10)); std::unique_ptr<int> n = std::make_unique<int>(10);
int* raw_n = n.get(); int* raw_n = n.get();
const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n)); const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
@ -2796,7 +2796,7 @@ TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
} }
TEST(PointeeTest, WorksOnMoveOnlyType) { TEST(PointeeTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3)); std::unique_ptr<int> p = std::make_unique<int>(3);
EXPECT_THAT(p, Pointee(Eq(3))); EXPECT_THAT(p, Pointee(Eq(3)));
EXPECT_THAT(p, Not(Pointee(Eq(2)))); EXPECT_THAT(p, Not(Pointee(Eq(2))));
} }

View File

@ -79,7 +79,7 @@ TEST(AddressTest, Const) {
} }
TEST(AddressTest, MatcherDoesntCopy) { TEST(AddressTest, MatcherDoesntCopy) {
std::unique_ptr<int> n(new int(1)); std::unique_ptr<int> n = std::make_unique<int>(1);
const Matcher<std::unique_ptr<int>> m = Address(Eq(&n)); const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
EXPECT_TRUE(m.Matches(n)); EXPECT_TRUE(m.Matches(n));
@ -202,7 +202,7 @@ TEST(IsTrueTest, IsTrueIsFalse) {
EXPECT_THAT(nullptr, Not(IsTrue())); EXPECT_THAT(nullptr, Not(IsTrue()));
EXPECT_THAT(nullptr, IsFalse()); EXPECT_THAT(nullptr, IsFalse());
std::unique_ptr<int> null_unique; std::unique_ptr<int> null_unique;
std::unique_ptr<int> nonnull_unique(new int(0)); std::unique_ptr<int> nonnull_unique = std::make_unique<int>(0);
EXPECT_THAT(null_unique, Not(IsTrue())); EXPECT_THAT(null_unique, Not(IsTrue()));
EXPECT_THAT(null_unique, IsFalse()); EXPECT_THAT(null_unique, IsFalse());
EXPECT_THAT(nonnull_unique, IsTrue()); EXPECT_THAT(nonnull_unique, IsTrue());
@ -1665,7 +1665,7 @@ MATCHER(IsNotNull, "") { return arg != nullptr; }
// Verifies that a matcher defined using MATCHER() can work on // Verifies that a matcher defined using MATCHER() can work on
// move-only types. // move-only types.
TEST(MatcherMacroTest, WorksOnMoveOnlyType) { TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3)); std::unique_ptr<int> p = std::make_unique<int>(3);
EXPECT_THAT(p, IsNotNull()); EXPECT_THAT(p, IsNotNull());
EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull())); EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
} }
@ -1675,7 +1675,7 @@ MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
// Verifies that a matcher defined using MATCHER_P*() can work on // Verifies that a matcher defined using MATCHER_P*() can work on
// move-only types. // move-only types.
TEST(MatcherPMacroTest, WorksOnMoveOnlyType) { TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3)); std::unique_ptr<int> p = std::make_unique<int>(3);
EXPECT_THAT(p, UniquePointee(3)); EXPECT_THAT(p, UniquePointee(3));
EXPECT_THAT(p, Not(UniquePointee(2))); EXPECT_THAT(p, Not(UniquePointee(2)));
} }

View File

@ -160,7 +160,7 @@ class MockCC : public CC {
// Tests that a method with expanded name compiles. // Tests that a method with expanded name compiles.
TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
MockCC cc; MockCC cc;
ON_CALL(cc, Method()); (void)ON_CALL(cc, Method());
} }
// Tests that the method with expanded name not only compiles but runs // Tests that the method with expanded name not only compiles but runs
@ -193,7 +193,7 @@ TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
MockA a; MockA a;
MockA* pa = &a; MockA* pa = &a;
ON_CALL(*pa++, DoA(_)); (void)ON_CALL(*pa++, DoA(_));
EXPECT_EQ(&a + 1, pa); EXPECT_EQ(&a + 1, pa);
} }
@ -201,7 +201,7 @@ TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
MockA a; MockA a;
int n = 0; int n = 0;
ON_CALL(a, DoA(n++)); (void)ON_CALL(a, DoA(n++));
EXPECT_EQ(1, n); EXPECT_EQ(1, n);
} }
@ -232,7 +232,7 @@ TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
EXPECT_DEATH_IF_SUPPORTED( EXPECT_DEATH_IF_SUPPORTED(
{ {
ON_CALL(a, DoA(5)); (void)ON_CALL(a, DoA(5));
a.DoA(5); a.DoA(5);
}, },
""); "");

View File

@ -296,12 +296,12 @@ class MatcherBase : private MatcherDescriberInterface {
return *this; return *this;
} }
MatcherBase(MatcherBase&& other) MatcherBase(MatcherBase&& other) noexcept
: vtable_(other.vtable_), buffer_(other.buffer_) { : vtable_(other.vtable_), buffer_(other.buffer_) {
other.vtable_ = nullptr; other.vtable_ = nullptr;
} }
MatcherBase& operator=(MatcherBase&& other) { MatcherBase& operator=(MatcherBase&& other) noexcept {
if (this == &other) return *this; if (this == &other) return *this;
Destroy(); Destroy();
vtable_ = other.vtable_; vtable_ = other.vtable_;

View File

@ -1385,9 +1385,9 @@ class GTEST_API_ Mutex {
Mutex(); Mutex();
~Mutex(); ~Mutex();
void Lock(); void lock();
void Unlock(); void unlock();
// Does nothing if the current thread holds the mutex. Otherwise, crashes // Does nothing if the current thread holds the mutex. Otherwise, crashes
// with high probability. // with high probability.
@ -1424,12 +1424,11 @@ class GTEST_API_ Mutex {
// "MutexLock l(&mu)". Hence the typedef trick below. // "MutexLock l(&mu)". Hence the typedef trick below.
class GTestMutexLock { class GTestMutexLock {
public: public:
explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); } explicit GTestMutexLock(Mutex& mutex) : mutex_(mutex) { mutex_.lock(); }
~GTestMutexLock() { mutex_.unlock(); }
~GTestMutexLock() { mutex_->Unlock(); }
private: private:
Mutex* const mutex_; Mutex& mutex_;
GTestMutexLock(const GTestMutexLock&) = delete; GTestMutexLock(const GTestMutexLock&) = delete;
GTestMutexLock& operator=(const GTestMutexLock&) = delete; GTestMutexLock& operator=(const GTestMutexLock&) = delete;
@ -1641,14 +1640,14 @@ class ThreadLocal : public ThreadLocalBase {
class MutexBase { class MutexBase {
public: public:
// Acquires this mutex. // Acquires this mutex.
void Lock() { void lock() {
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
owner_ = pthread_self(); owner_ = pthread_self();
has_owner_ = true; has_owner_ = true;
} }
// Releases this mutex. // Releases this mutex.
void Unlock() { void unlock() {
// Since the lock is being released the owner_ field should no longer be // Since the lock is being released the owner_ field should no longer be
// considered valid. We don't protect writing to has_owner_ here, as it's // considered valid. We don't protect writing to has_owner_ here, as it's
// the caller's responsibility to ensure that the current thread holds the // the caller's responsibility to ensure that the current thread holds the
@ -1716,12 +1715,11 @@ class Mutex : public MutexBase {
// "MutexLock l(&mu)". Hence the typedef trick below. // "MutexLock l(&mu)". Hence the typedef trick below.
class GTestMutexLock { class GTestMutexLock {
public: public:
explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); } explicit GTestMutexLock(MutexBase& mutex) : mutex_(mutex) { mutex_.lock(); }
~GTestMutexLock() { mutex_.unlock(); }
~GTestMutexLock() { mutex_->Unlock(); }
private: private:
MutexBase* const mutex_; MutexBase& mutex_;
GTestMutexLock(const GTestMutexLock&) = delete; GTestMutexLock(const GTestMutexLock&) = delete;
GTestMutexLock& operator=(const GTestMutexLock&) = delete; GTestMutexLock& operator=(const GTestMutexLock&) = delete;
@ -1864,8 +1862,8 @@ class GTEST_API_ ThreadLocal {
class Mutex { class Mutex {
public: public:
Mutex() {} Mutex() {}
void Lock() {} void lock() {}
void Unlock() {} void unlock() {}
void AssertHeld() const {} void AssertHeld() const {}
}; };
@ -1881,7 +1879,7 @@ class Mutex {
// "MutexLock l(&mu)". Hence the typedef trick below. // "MutexLock l(&mu)". Hence the typedef trick below.
class GTestMutexLock { class GTestMutexLock {
public: public:
explicit GTestMutexLock(Mutex*) {} // NOLINT explicit GTestMutexLock(Mutex&) {} // NOLINT
}; };
typedef GTestMutexLock MutexLock; typedef GTestMutexLock MutexLock;
@ -2322,6 +2320,13 @@ const char* StringFromGTestEnv(const char* flag, const char* default_val);
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
#if GTEST_INTERNAL_HAVE_CPP_ATTRIBUTE(clang::annotate)
#define GTEST_INTERNAL_DEPRECATE_AND_INLINE(msg) \
[[deprecated(msg), clang::annotate("inline-me")]]
#else
#define GTEST_INTERNAL_DEPRECATE_AND_INLINE(msg) [[deprecated(msg)]]
#endif
#if defined(__cpp_lib_span) || (GTEST_INTERNAL_HAS_INCLUDE(<span>) && \ #if defined(__cpp_lib_span) || (GTEST_INTERNAL_HAS_INCLUDE(<span>) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 202002L) GTEST_INTERNAL_CPLUSPLUS_LANG >= 202002L)
#define GTEST_INTERNAL_HAS_STD_SPAN 1 #define GTEST_INTERNAL_HAS_STD_SPAN 1

View File

@ -320,13 +320,13 @@ Mutex::~Mutex() {
} }
} }
void Mutex::Lock() { void Mutex::lock() {
ThreadSafeLazyInit(); ThreadSafeLazyInit();
::EnterCriticalSection(critical_section_); ::EnterCriticalSection(critical_section_);
owner_thread_id_ = ::GetCurrentThreadId(); owner_thread_id_ = ::GetCurrentThreadId();
} }
void Mutex::Unlock() { void Mutex::unlock() {
ThreadSafeLazyInit(); ThreadSafeLazyInit();
// We don't protect writing to owner_thread_id_ here, as it's the // We don't protect writing to owner_thread_id_ here, as it's the
// caller's responsibility to ensure that the current thread holds the // caller's responsibility to ensure that the current thread holds the
@ -499,7 +499,7 @@ class ThreadLocalRegistryImpl {
MemoryIsNotDeallocated memory_is_not_deallocated; MemoryIsNotDeallocated memory_is_not_deallocated;
#endif // _MSC_VER #endif // _MSC_VER
DWORD current_thread = ::GetCurrentThreadId(); DWORD current_thread = ::GetCurrentThreadId();
MutexLock lock(&mutex_); MutexLock lock(mutex_);
ThreadIdToThreadLocals* const thread_to_thread_locals = ThreadIdToThreadLocals* const thread_to_thread_locals =
GetThreadLocalsMapLocked(); GetThreadLocalsMapLocked();
ThreadIdToThreadLocals::iterator thread_local_pos = ThreadIdToThreadLocals::iterator thread_local_pos =
@ -532,7 +532,7 @@ class ThreadLocalRegistryImpl {
// Clean up the ThreadLocalValues data structure while holding the lock, but // Clean up the ThreadLocalValues data structure while holding the lock, but
// defer the destruction of the ThreadLocalValueHolderBases. // defer the destruction of the ThreadLocalValueHolderBases.
{ {
MutexLock lock(&mutex_); MutexLock lock(mutex_);
ThreadIdToThreadLocals* const thread_to_thread_locals = ThreadIdToThreadLocals* const thread_to_thread_locals =
GetThreadLocalsMapLocked(); GetThreadLocalsMapLocked();
for (ThreadIdToThreadLocals::iterator it = for (ThreadIdToThreadLocals::iterator it =
@ -559,7 +559,7 @@ class ThreadLocalRegistryImpl {
// Clean up the ThreadIdToThreadLocals data structure while holding the // Clean up the ThreadIdToThreadLocals data structure while holding the
// lock, but defer the destruction of the ThreadLocalValueHolderBases. // lock, but defer the destruction of the ThreadLocalValueHolderBases.
{ {
MutexLock lock(&mutex_); MutexLock lock(mutex_);
ThreadIdToThreadLocals* const thread_to_thread_locals = ThreadIdToThreadLocals* const thread_to_thread_locals =
GetThreadLocalsMapLocked(); GetThreadLocalsMapLocked();
ThreadIdToThreadLocals::iterator thread_local_pos = ThreadIdToThreadLocals::iterator thread_local_pos =

View File

@ -1086,14 +1086,14 @@ void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
// Returns the global test part result reporter. // Returns the global test part result reporter.
TestPartResultReporterInterface* TestPartResultReporterInterface*
UnitTestImpl::GetGlobalTestPartResultReporter() { UnitTestImpl::GetGlobalTestPartResultReporter() {
internal::MutexLock lock(&global_test_part_result_reporter_mutex_); internal::MutexLock lock(global_test_part_result_reporter_mutex_);
return global_test_part_result_reporter_; return global_test_part_result_reporter_;
} }
// Sets the global test part result reporter. // Sets the global test part result reporter.
void UnitTestImpl::SetGlobalTestPartResultReporter( void UnitTestImpl::SetGlobalTestPartResultReporter(
TestPartResultReporterInterface* reporter) { TestPartResultReporterInterface* reporter) {
internal::MutexLock lock(&global_test_part_result_reporter_mutex_); internal::MutexLock lock(global_test_part_result_reporter_mutex_);
global_test_part_result_reporter_ = reporter; global_test_part_result_reporter_ = reporter;
} }
@ -2347,7 +2347,7 @@ void TestResult::RecordProperty(const std::string& xml_element,
if (!ValidateTestProperty(xml_element, test_property)) { if (!ValidateTestProperty(xml_element, test_property)) {
return; return;
} }
internal::MutexLock lock(&test_properties_mutex_); internal::MutexLock lock(test_properties_mutex_);
const std::vector<TestProperty>::iterator property_with_matching_key = const std::vector<TestProperty>::iterator property_with_matching_key =
std::find_if(test_properties_.begin(), test_properties_.end(), std::find_if(test_properties_.begin(), test_properties_.end(),
internal::TestPropertyKeyIs(test_property.key())); internal::TestPropertyKeyIs(test_property.key()));
@ -5088,7 +5088,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
void* caller_frame = nullptr; void* caller_frame = nullptr;
{ {
MutexLock lock(&mutex_); MutexLock lock(mutex_);
caller_frame = caller_frame_; caller_frame = caller_frame_;
} }
@ -5127,7 +5127,7 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
caller_frame = nullptr; caller_frame = nullptr;
} }
MutexLock lock(&mutex_); MutexLock lock(mutex_);
caller_frame_ = caller_frame; caller_frame_ = caller_frame;
#endif // GTEST_HAS_ABSL #endif // GTEST_HAS_ABSL
} }
@ -5390,13 +5390,13 @@ void UnitTest::UponLeavingGTest() {
// Sets the TestSuite object for the test that's currently running. // Sets the TestSuite object for the test that's currently running.
void UnitTest::set_current_test_suite(TestSuite* a_current_test_suite) { void UnitTest::set_current_test_suite(TestSuite* a_current_test_suite) {
internal::MutexLock lock(&mutex_); internal::MutexLock lock(mutex_);
impl_->set_current_test_suite(a_current_test_suite); impl_->set_current_test_suite(a_current_test_suite);
} }
// Sets the TestInfo object for the test that's currently running. // Sets the TestInfo object for the test that's currently running.
void UnitTest::set_current_test_info(TestInfo* a_current_test_info) { void UnitTest::set_current_test_info(TestInfo* a_current_test_info) {
internal::MutexLock lock(&mutex_); internal::MutexLock lock(mutex_);
impl_->set_current_test_info(a_current_test_info); impl_->set_current_test_info(a_current_test_info);
} }
@ -5435,7 +5435,7 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
Message msg; Message msg;
msg << message; msg << message;
internal::MutexLock lock(&mutex_); internal::MutexLock lock(mutex_);
if (!impl_->gtest_trace_stack().empty()) { if (!impl_->gtest_trace_stack().empty()) {
msg << "\n" << GTEST_NAME_ << " trace:"; msg << "\n" << GTEST_NAME_ << " trace:";
@ -5618,7 +5618,7 @@ const char* UnitTest::original_working_dir() const {
// or NULL if no test is running. // or NULL if no test is running.
const TestSuite* UnitTest::current_test_suite() const const TestSuite* UnitTest::current_test_suite() const
GTEST_LOCK_EXCLUDED_(mutex_) { GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_); internal::MutexLock lock(mutex_);
return impl_->current_test_suite(); return impl_->current_test_suite();
} }
@ -5626,7 +5626,7 @@ const TestSuite* UnitTest::current_test_suite() const
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
const TestCase* UnitTest::current_test_case() const const TestCase* UnitTest::current_test_case() const
GTEST_LOCK_EXCLUDED_(mutex_) { GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_); internal::MutexLock lock(mutex_);
return impl_->current_test_suite(); return impl_->current_test_suite();
} }
#endif #endif
@ -5635,7 +5635,7 @@ const TestCase* UnitTest::current_test_case() const
// or NULL if no test is running. // or NULL if no test is running.
const TestInfo* UnitTest::current_test_info() const const TestInfo* UnitTest::current_test_info() const
GTEST_LOCK_EXCLUDED_(mutex_) { GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_); internal::MutexLock lock(mutex_);
return impl_->current_test_info(); return impl_->current_test_info();
} }
@ -5659,13 +5659,13 @@ UnitTest::~UnitTest() { delete impl_; }
// Google Test trace stack. // Google Test trace stack.
void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
GTEST_LOCK_EXCLUDED_(mutex_) { GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_); internal::MutexLock lock(mutex_);
impl_->gtest_trace_stack().push_back(trace); impl_->gtest_trace_stack().push_back(trace);
} }
// Pops a trace from the per-thread Google Test trace stack. // 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_); internal::MutexLock lock(mutex_);
impl_->gtest_trace_stack().pop_back(); impl_->gtest_trace_stack().pop_back();
} }
@ -6088,15 +6088,17 @@ bool UnitTestImpl::RunAllTests() {
repeater->OnEnvironmentsTearDownEnd(*parent_); repeater->OnEnvironmentsTearDownEnd(*parent_);
} }
} else if (GTEST_FLAG_GET(fail_if_no_test_selected)) { } else if (GTEST_FLAG_GET(fail_if_no_test_selected)) {
// If there were no tests to run, bail if we were requested to be strict. // If there were no tests to run, bail if we were requested to be
// strict.
constexpr char kNoTestsSelectedMessage[] = constexpr char kNoTestsSelectedMessage[] =
"No tests were selected to run. Please make sure at least one test " "No tests ran. Check that tests exist and are not disabled or "
"exists and is not disabled! If the test is sharded, you may have " "filtered out.\n\n"
"defined more shards than test cases, which is wasteful. If you also " "For sharded runs, this error indicates an empty shard. This can "
"defined --gtest_filter, that filter is taken into account, so " "happen if you have more shards than tests, or if --gtest_filter "
"shards with no matching test cases will hit this error. Either " "leaves a shard with no tests.\n\n"
"disable sharding, set --gtest_fail_if_no_test_selected=false, or " "To permit empty shards (e.g., when debugging with a filter), "
"remove the filter to resolve this error."; "specify \n"
"--gtest_fail_if_no_test_selected=false.";
ColoredPrintf(GTestColor::kRed, "%s\n", kNoTestsSelectedMessage); ColoredPrintf(GTestColor::kRed, "%s\n", kNoTestsSelectedMessage);
return false; return false;
} }

View File

@ -30,6 +30,7 @@
# #
# Bazel BUILD for The Google C++ Testing Framework (Google Test) # Bazel BUILD for The Google C++ Testing Framework (Google Test)
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
load("@rules_python//python:defs.bzl", "py_library", "py_test") load("@rules_python//python:defs.bzl", "py_library", "py_test")
licenses(["notice"]) licenses(["notice"])

View File

@ -696,7 +696,7 @@ class TestGenerationEnvironment : public ::testing::Environment {
msg << "TestsExpandedAndRun/" << i; msg << "TestsExpandedAndRun/" << i;
if (UnitTestOptions::FilterMatchesTest( if (UnitTestOptions::FilterMatchesTest(
"TestExpansionModule/MultipleTestGenerationTest", "TestExpansionModule/MultipleTestGenerationTest",
msg.GetString().c_str())) { msg.GetString())) {
perform_check = true; perform_check = true;
} }
} }

View File

@ -288,8 +288,8 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
defined(GTEST_OS_OPENBSD) || defined(GTEST_OS_GNU_HURD) defined(GTEST_OS_OPENBSD) || defined(GTEST_OS_GNU_HURD)
void* ThreadFunc(void* data) { void* ThreadFunc(void* data) {
internal::Mutex* mutex = static_cast<internal::Mutex*>(data); internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
mutex->Lock(); mutex->lock();
mutex->Unlock(); mutex->unlock();
return nullptr; return nullptr;
} }
@ -308,7 +308,7 @@ TEST(GetThreadCountTest, ReturnsCorrectValue) {
internal::Mutex mutex; internal::Mutex mutex;
{ {
internal::MutexLock lock(&mutex); internal::MutexLock lock(mutex);
pthread_attr_t attr; pthread_attr_t attr;
ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_init(&attr));
ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
@ -1028,7 +1028,9 @@ TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
EXPECT_DEATH_IF_SUPPORTED( EXPECT_DEATH_IF_SUPPORTED(
{ {
Mutex m; Mutex m;
{ MutexLock lock(&m); } {
MutexLock lock(m);
}
m.AssertHeld(); m.AssertHeld();
}, },
"thread .*hold"); "thread .*hold");
@ -1036,13 +1038,13 @@ TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
Mutex m; Mutex m;
MutexLock lock(&m); MutexLock lock(m);
m.AssertHeld(); m.AssertHeld();
} }
class AtomicCounterWithMutex { class AtomicCounterWithMutex {
public: public:
explicit AtomicCounterWithMutex(Mutex* mutex) explicit AtomicCounterWithMutex(Mutex& mutex)
: value_(0), mutex_(mutex), random_(42) {} : value_(0), mutex_(mutex), random_(42) {}
void Increment() { void Increment() {
@ -1083,7 +1085,7 @@ class AtomicCounterWithMutex {
private: private:
volatile int value_; volatile int value_;
Mutex* const mutex_; // Protects value_. Mutex& mutex_; // Protects value_.
Random random_; Random random_;
}; };
@ -1094,7 +1096,7 @@ void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
// Tests that the mutex only lets one thread at a time to lock it. // Tests that the mutex only lets one thread at a time to lock it.
TEST(MutexTest, OnlyOneThreadCanLockAtATime) { TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
Mutex mutex; Mutex mutex;
AtomicCounterWithMutex locked_counter(&mutex); AtomicCounterWithMutex locked_counter(mutex);
typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType; typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
const int kCycleCount = 20; const int kCycleCount = 20;

View File

@ -1699,7 +1699,7 @@ TEST(PrintToStringTest, ContainsNonLatin) {
EXPECT_PRINT_TO_STRING_(non_ascii_str, EXPECT_PRINT_TO_STRING_(non_ascii_str,
"\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n" "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
" As Text: \"오전 4:30\""); " As Text: \"오전 4:30\"");
non_ascii_str = ::std::string("From ä — ẑ"); non_ascii_str = "From ä — ẑ";
EXPECT_PRINT_TO_STRING_(non_ascii_str, EXPECT_PRINT_TO_STRING_(non_ascii_str,
"\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\"" "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
"\n As Text: \"From ä — ẑ\""); "\n As Text: \"From ä — ẑ\"");

View File

@ -95,9 +95,9 @@ void ManyAsserts(int id) {
// RecordProperty() should interact safely with other threads as well. // RecordProperty() should interact safely with other threads as well.
// The shared_key forces property updates. // The shared_key forces property updates.
Test::RecordProperty(IdToKey(id, "string").c_str(), IdToString(id).c_str()); Test::RecordProperty(IdToKey(id, "string"), IdToString(id));
Test::RecordProperty(IdToKey(id, "int").c_str(), id); Test::RecordProperty(IdToKey(id, "int").c_str(), id);
Test::RecordProperty("shared_key", IdToString(id).c_str()); Test::RecordProperty("shared_key", IdToString(id));
// This assertion should fail kThreadCount times per thread. It // This assertion should fail kThreadCount times per thread. It
// is for testing whether Google Test can handle failed assertions in a // is for testing whether Google Test can handle failed assertions in a

View File

@ -2649,8 +2649,8 @@ TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
// Tests that IsSubstring returns the correct result when the input // Tests that IsSubstring returns the correct result when the input
// argument type is ::std::string. // argument type is ::std::string.
TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) { TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob")); EXPECT_TRUE(IsSubstring("", "", "hello", "ahellob"));
EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world"))); EXPECT_FALSE(IsSubstring("", "", "hello", "world"));
} }
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
@ -2707,8 +2707,8 @@ TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
// Tests that IsNotSubstring returns the correct result when the input // Tests that IsNotSubstring returns the correct result when the input
// argument type is ::std::string. // argument type is ::std::string.
TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) { TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob")); EXPECT_FALSE(IsNotSubstring("", "", "hello", "ahellob"));
EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world"))); EXPECT_TRUE(IsNotSubstring("", "", "hello", "world"));
} }
// Tests that IsNotSubstring() generates the correct message when the input // Tests that IsNotSubstring() generates the correct message when the input
@ -2719,8 +2719,7 @@ TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
" Actual: \"needle\"\n" " Actual: \"needle\"\n"
"Expected: not a substring of haystack_expr\n" "Expected: not a substring of haystack_expr\n"
"Which is: \"two needles\"", "Which is: \"two needles\"",
IsNotSubstring("needle_expr", "haystack_expr", ::std::string("needle"), IsNotSubstring("needle_expr", "haystack_expr", "needle", "two needles")
"two needles")
.failure_message()); .failure_message());
} }
@ -3655,8 +3654,7 @@ TEST(AssertionTest, EqFailure) {
msg4.c_str()); msg4.c_str());
const std::string msg5( const std::string msg5(
EqFailure("foo", "bar", std::string("\"x\""), std::string("\"y\""), true) EqFailure("foo", "bar", "\"x\"", "\"y\"", true).failure_message());
.failure_message());
EXPECT_STREQ( EXPECT_STREQ(
"Expected equality of these values:\n" "Expected equality of these values:\n"
" foo\n" " foo\n"

View File

@ -22,6 +22,22 @@ def googletest_deps():
urls = ["https://github.com/abseil/abseil-cpp/releases/download/20250814.0/abseil-cpp-20250814.0.tar.gz"], urls = ["https://github.com/abseil/abseil-cpp/releases/download/20250814.0/abseil-cpp-20250814.0.tar.gz"],
) )
if not native.existing_rule("bazel_features"):
http_archive(
name = "bazel_features",
sha256 = "9390b391a68d3b24aef7966bce8556d28003fe3f022a5008efc7807e8acaaf1a",
strip_prefix = "bazel_features-1.36.0",
url = "https://github.com/bazel-contrib/bazel_features/releases/download/v1.36.0/bazel_features-v1.36.0.tar.gz",
)
if not native.existing_rule("rules_cc"):
http_archive(
name = "rules_cc",
sha256 = "207ea073dd20a705f9e8bc5ac02f5203e9621fc672774bb1a0935aefab7aebfa",
strip_prefix = "rules_cc-0.2.8",
url = "https://github.com/bazelbuild/rules_cc/releases/download/0.2.8/rules_cc-0.2.8.tar.gz",
)
if not native.existing_rule("fuchsia_sdk"): if not native.existing_rule("fuchsia_sdk"):
fake_fuchsia_sdk( fake_fuchsia_sdk(
name = "fuchsia_sdk", name = "fuchsia_sdk",