1 // Copyright 2022 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "src/core/lib/gprpp/single_set_ptr.h"
16
17 #include <algorithm>
18 #include <thread>
19 #include <vector>
20
21 #include "gtest/gtest.h"
22
23 namespace grpc_core {
24 namespace testing {
25
TEST(SingleSetPtrTest,NoOp)26 TEST(SingleSetPtrTest, NoOp) { SingleSetPtr<int>(); }
27
TEST(SingleSetPtrTest,CanSet)28 TEST(SingleSetPtrTest, CanSet) {
29 SingleSetPtr<int> p;
30 EXPECT_FALSE(p.is_set());
31 EXPECT_DEATH_IF_SUPPORTED(gpr_log(GPR_ERROR, "%d", *p), "");
32 p.Set(new int(42));
33 EXPECT_EQ(*p, 42);
34 }
35
TEST(SingleSetPtrTest,CanReset)36 TEST(SingleSetPtrTest, CanReset) {
37 SingleSetPtr<int> p;
38 EXPECT_FALSE(p.is_set());
39 p.Set(new int(42));
40 EXPECT_TRUE(p.is_set());
41 p.Set(new int(43));
42 EXPECT_EQ(*p, 42);
43 p.Reset();
44 EXPECT_FALSE(p.is_set());
45 }
46
TEST(SingleSetPtrTest,LotsOfSetters)47 TEST(SingleSetPtrTest, LotsOfSetters) {
48 SingleSetPtr<int> p;
49 std::vector<std::thread> threads;
50 threads.reserve(10);
51 for (int i = 0; i < 10; i++) {
52 threads.emplace_back([&p, i]() { p.Set(new int(i)); });
53 }
54 for (auto& t : threads) {
55 t.join();
56 }
57 }
58
59 } // namespace testing
60 } // namespace grpc_core
61
main(int argc,char ** argv)62 int main(int argc, char** argv) {
63 ::testing::InitGoogleTest(&argc, argv);
64 return RUN_ALL_TESTS();
65 }
66