Add a CHECK for the cases when null service is accessed unconditionally.

PiperOrigin-RevId: 513956583
This commit is contained in:
MediaPipe Team 2023-03-03 17:03:18 -08:00 committed by Copybara-Service
parent 9c3abcd06f
commit 5b2678a49f
2 changed files with 18 additions and 1 deletions

View File

@ -107,7 +107,10 @@ template <typename T>
class ServiceBinding { class ServiceBinding {
public: public:
bool IsAvailable() { return service_ != nullptr; } bool IsAvailable() { return service_ != nullptr; }
T& GetObject() { return *service_; } T& GetObject() {
CHECK(service_) << "Service is unavailable.";
return *service_;
}
ServiceBinding() {} ServiceBinding() {}
explicit ServiceBinding(std::shared_ptr<T> service) : service_(service) {} explicit ServiceBinding(std::shared_ptr<T> service) : service_(service) {}

View File

@ -343,5 +343,19 @@ TEST(DisallowDefaultInitializationGraphServiceTest,
HasSubstr("was not provided and cannot be created"))); HasSubstr("was not provided and cannot be created")));
} }
TEST(ServiceBindingTest, CrashesWhenGettingNullServiceObject) {
ASSERT_DEATH(
{
ServiceBinding<TestServiceData> binding(nullptr);
(void)binding.GetObject();
},
testing::ContainsRegex("Check failed: [a-z_]* Service is unavailable"));
}
TEST(ServiceBindingTest, IsAvailableReturnsFalsOnNullServiceObject) {
ServiceBinding<TestServiceData> binding(nullptr);
EXPECT_FALSE(binding.IsAvailable());
}
} // namespace } // namespace
} // namespace mediapipe } // namespace mediapipe