/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "rtc_base/memory/always_valid_pointer.h" #include #include "test/gtest.h" namespace webrtc { TEST(AlwaysValidPointerTest, DefaultToEmptyValue) { AlwaysValidPointer ptr(nullptr); EXPECT_EQ(*ptr, ""); } TEST(AlwaysValidPointerTest, DefaultWithForwardedArgument) { AlwaysValidPointer ptr(nullptr, "test"); EXPECT_EQ(*ptr, "test"); } TEST(AlwaysValidPointerTest, DefaultToSubclass) { struct A { virtual ~A() {} virtual int f() = 0; }; struct B : public A { int b = 0; explicit B(int val) : b(val) {} virtual ~B() {} int f() override { return b; } }; AlwaysValidPointer ptr(nullptr, 3); EXPECT_EQ(ptr->f(), 3); EXPECT_EQ((*ptr).f(), 3); EXPECT_EQ(ptr.get()->f(), 3); } TEST(AlwaysValidPointerTest, NonDefaultValue) { std::string str("keso"); AlwaysValidPointer ptr(&str, "test"); EXPECT_EQ(*ptr, "keso"); } TEST(AlwaysValidPointerTest, TakeOverOwnershipOfInstance) { std::string str("keso"); std::unique_ptr str2 = std::make_unique("kent"); AlwaysValidPointer ptr(std::move(str2), &str); EXPECT_EQ(*ptr, "kent"); EXPECT_EQ(str2, nullptr); } TEST(AlwaysValidPointerTest, TakeOverOwnershipFallbackOnPointer) { std::string str("keso"); std::unique_ptr str2; AlwaysValidPointer ptr(std::move(str2), &str); EXPECT_EQ(*ptr, "keso"); } TEST(AlwaysValidPointerTest, TakeOverOwnershipFallbackOnDefault) { std::unique_ptr str; std::string* str_ptr = nullptr; AlwaysValidPointer ptr(std::move(str), str_ptr); EXPECT_EQ(*ptr, ""); } TEST(AlwaysValidPointerTest, TakeOverOwnershipFallbackOnDefaultWithForwardedArgument) { std::unique_ptr str2; AlwaysValidPointer ptr(std::move(str2), nullptr, "keso"); EXPECT_EQ(*ptr, "keso"); } TEST(AlwaysValidPointerTest, TakeOverOwnershipDoesNotForwardDefaultArguments) { std::unique_ptr str = std::make_unique("kalle"); std::unique_ptr str2 = std::make_unique("anka"); AlwaysValidPointer ptr(std::move(str), nullptr, *str2); EXPECT_EQ(*ptr, "kalle"); EXPECT_TRUE(!str); EXPECT_EQ(*str2, "anka"); } TEST(AlwaysValidPointerTest, DefaultToLambda) { AlwaysValidPointer ptr( nullptr, []() { return std::make_unique("onkel skrue"); }); EXPECT_EQ(*ptr, "onkel skrue"); } } // namespace webrtc