• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Abseil 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 //      https://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 "absl/types/optional.h"
16 
17 #include "absl/base/config.h"
18 
19 // This test is a no-op when absl::optional is an alias for std::optional and
20 // when exceptions are not enabled.
21 #if !defined(ABSL_USES_STD_OPTIONAL) && defined(ABSL_HAVE_EXCEPTIONS)
22 
23 #include "gtest/gtest.h"
24 #include "absl/base/internal/exception_safety_testing.h"
25 
26 namespace absl {
27 ABSL_NAMESPACE_BEGIN
28 
29 namespace {
30 
31 using ::testing::AssertionFailure;
32 using ::testing::AssertionResult;
33 using ::testing::AssertionSuccess;
34 using ::testing::MakeExceptionSafetyTester;
35 
36 using Thrower = testing::ThrowingValue<testing::TypeSpec::kEverythingThrows>;
37 using Optional = absl::optional<Thrower>;
38 
39 using MoveThrower = testing::ThrowingValue<testing::TypeSpec::kNoThrowMove>;
40 using MoveOptional = absl::optional<MoveThrower>;
41 
42 constexpr int kInitialInteger = 5;
43 constexpr int kUpdatedInteger = 10;
44 
45 template <typename OptionalT>
ValueThrowsBadOptionalAccess(const OptionalT & optional)46 bool ValueThrowsBadOptionalAccess(const OptionalT& optional) try {
47   return (static_cast<void>(optional.value()), false);
48 } catch (const absl::bad_optional_access&) {
49   return true;
50 }
51 
52 template <typename OptionalT>
OptionalInvariants(OptionalT * optional_ptr)53 AssertionResult OptionalInvariants(OptionalT* optional_ptr) {
54   // Check the current state post-throw for validity
55   auto& optional = *optional_ptr;
56 
57   if (optional.has_value() && ValueThrowsBadOptionalAccess(optional)) {
58     return AssertionFailure()
59            << "Optional with value should not throw bad_optional_access when "
60               "accessing the value.";
61   }
62   if (!optional.has_value() && !ValueThrowsBadOptionalAccess(optional)) {
63     return AssertionFailure()
64            << "Optional without a value should throw bad_optional_access when "
65               "accessing the value.";
66   }
67 
68   // Reset to a known state
69   optional.reset();
70 
71   // Confirm that the known post-reset state is valid
72   if (optional.has_value()) {
73     return AssertionFailure()
74            << "Optional should not contain a value after being reset.";
75   }
76   if (!ValueThrowsBadOptionalAccess(optional)) {
77     return AssertionFailure() << "Optional should throw bad_optional_access "
78                                  "when accessing the value after being reset.";
79   }
80 
81   return AssertionSuccess();
82 }
83 
84 template <typename OptionalT>
CheckDisengaged(OptionalT * optional_ptr)85 AssertionResult CheckDisengaged(OptionalT* optional_ptr) {
86   auto& optional = *optional_ptr;
87 
88   if (optional.has_value()) {
89     return AssertionFailure()
90            << "Expected optional to not contain a value but a value was found.";
91   }
92 
93   return AssertionSuccess();
94 }
95 
96 template <typename OptionalT>
CheckEngaged(OptionalT * optional_ptr)97 AssertionResult CheckEngaged(OptionalT* optional_ptr) {
98   auto& optional = *optional_ptr;
99 
100   if (!optional.has_value()) {
101     return AssertionFailure()
102            << "Expected optional to contain a value but no value was found.";
103   }
104 
105   return AssertionSuccess();
106 }
107 
TEST(OptionalExceptionSafety,ThrowingConstructors)108 TEST(OptionalExceptionSafety, ThrowingConstructors) {
109   auto thrower_nonempty = Optional(Thrower(kInitialInteger));
110   testing::TestThrowingCtor<Optional>(thrower_nonempty);
111 
112   auto integer_nonempty = absl::optional<int>(kInitialInteger);
113   testing::TestThrowingCtor<Optional>(integer_nonempty);
114   testing::TestThrowingCtor<Optional>(std::move(integer_nonempty));  // NOLINT
115 
116   testing::TestThrowingCtor<Optional>(kInitialInteger);
117   using ThrowerVec = std::vector<Thrower, testing::ThrowingAllocator<Thrower>>;
118   testing::TestThrowingCtor<absl::optional<ThrowerVec>>(
119       absl::in_place,
120       std::initializer_list<Thrower>{Thrower(), Thrower(), Thrower()},
121       testing::ThrowingAllocator<Thrower>());
122 }
123 
TEST(OptionalExceptionSafety,NothrowConstructors)124 TEST(OptionalExceptionSafety, NothrowConstructors) {
125   // This constructor is marked noexcept. If it throws, the program will
126   // terminate.
127   testing::TestThrowingCtor<MoveOptional>(MoveOptional(kUpdatedInteger));
128 }
129 
TEST(OptionalExceptionSafety,Emplace)130 TEST(OptionalExceptionSafety, Emplace) {
131   // Test the basic guarantee plus test the result of optional::has_value()
132   // is false in all cases
133   auto disengaged_test = MakeExceptionSafetyTester().WithContracts(
134       OptionalInvariants<Optional>, CheckDisengaged<Optional>);
135   auto disengaged_test_empty = disengaged_test.WithInitialValue(Optional());
136   auto disengaged_test_nonempty =
137       disengaged_test.WithInitialValue(Optional(kInitialInteger));
138 
139   auto emplace_thrower_directly = [](Optional* optional_ptr) {
140     optional_ptr->emplace(kUpdatedInteger);
141   };
142   EXPECT_TRUE(disengaged_test_empty.Test(emplace_thrower_directly));
143   EXPECT_TRUE(disengaged_test_nonempty.Test(emplace_thrower_directly));
144 
145   auto emplace_thrower_copy = [](Optional* optional_ptr) {
146     auto thrower = Thrower(kUpdatedInteger, testing::nothrow_ctor);
147     optional_ptr->emplace(thrower);
148   };
149   EXPECT_TRUE(disengaged_test_empty.Test(emplace_thrower_copy));
150   EXPECT_TRUE(disengaged_test_nonempty.Test(emplace_thrower_copy));
151 }
152 
TEST(OptionalExceptionSafety,EverythingThrowsSwap)153 TEST(OptionalExceptionSafety, EverythingThrowsSwap) {
154   // Test the basic guarantee plus test the result of optional::has_value()
155   // remains the same
156   auto test =
157       MakeExceptionSafetyTester().WithContracts(OptionalInvariants<Optional>);
158   auto disengaged_test_empty = test.WithInitialValue(Optional())
159                                    .WithContracts(CheckDisengaged<Optional>);
160   auto engaged_test_nonempty = test.WithInitialValue(Optional(kInitialInteger))
161                                    .WithContracts(CheckEngaged<Optional>);
162 
163   auto swap_empty = [](Optional* optional_ptr) {
164     auto empty = Optional();
165     optional_ptr->swap(empty);
166   };
167   EXPECT_TRUE(engaged_test_nonempty.Test(swap_empty));
168 
169   auto swap_nonempty = [](Optional* optional_ptr) {
170     auto nonempty =
171         Optional(absl::in_place, kUpdatedInteger, testing::nothrow_ctor);
172     optional_ptr->swap(nonempty);
173   };
174   EXPECT_TRUE(disengaged_test_empty.Test(swap_nonempty));
175   EXPECT_TRUE(engaged_test_nonempty.Test(swap_nonempty));
176 }
177 
TEST(OptionalExceptionSafety,NoThrowMoveSwap)178 TEST(OptionalExceptionSafety, NoThrowMoveSwap) {
179   // Tests the nothrow guarantee for optional of T with non-throwing move
180   {
181     auto empty = MoveOptional();
182     auto nonempty = MoveOptional(kInitialInteger);
183     EXPECT_TRUE(testing::TestNothrowOp([&]() { nonempty.swap(empty); }));
184   }
185   {
186     auto nonempty = MoveOptional(kUpdatedInteger);
187     auto empty = MoveOptional();
188     EXPECT_TRUE(testing::TestNothrowOp([&]() { empty.swap(nonempty); }));
189   }
190   {
191     auto nonempty_from = MoveOptional(kUpdatedInteger);
192     auto nonempty_to = MoveOptional(kInitialInteger);
193     EXPECT_TRUE(
194         testing::TestNothrowOp([&]() { nonempty_to.swap(nonempty_from); }));
195   }
196 }
197 
TEST(OptionalExceptionSafety,CopyAssign)198 TEST(OptionalExceptionSafety, CopyAssign) {
199   // Test the basic guarantee plus test the result of optional::has_value()
200   // remains the same
201   auto test =
202       MakeExceptionSafetyTester().WithContracts(OptionalInvariants<Optional>);
203   auto disengaged_test_empty = test.WithInitialValue(Optional())
204                                    .WithContracts(CheckDisengaged<Optional>);
205   auto engaged_test_nonempty = test.WithInitialValue(Optional(kInitialInteger))
206                                    .WithContracts(CheckEngaged<Optional>);
207 
208   auto copyassign_nonempty = [](Optional* optional_ptr) {
209     auto nonempty =
210         Optional(absl::in_place, kUpdatedInteger, testing::nothrow_ctor);
211     *optional_ptr = nonempty;
212   };
213   EXPECT_TRUE(disengaged_test_empty.Test(copyassign_nonempty));
214   EXPECT_TRUE(engaged_test_nonempty.Test(copyassign_nonempty));
215 
216   auto copyassign_thrower = [](Optional* optional_ptr) {
217     auto thrower = Thrower(kUpdatedInteger, testing::nothrow_ctor);
218     *optional_ptr = thrower;
219   };
220   EXPECT_TRUE(disengaged_test_empty.Test(copyassign_thrower));
221   EXPECT_TRUE(engaged_test_nonempty.Test(copyassign_thrower));
222 }
223 
TEST(OptionalExceptionSafety,MoveAssign)224 TEST(OptionalExceptionSafety, MoveAssign) {
225   // Test the basic guarantee plus test the result of optional::has_value()
226   // remains the same
227   auto test =
228       MakeExceptionSafetyTester().WithContracts(OptionalInvariants<Optional>);
229   auto disengaged_test_empty = test.WithInitialValue(Optional())
230                                    .WithContracts(CheckDisengaged<Optional>);
231   auto engaged_test_nonempty = test.WithInitialValue(Optional(kInitialInteger))
232                                    .WithContracts(CheckEngaged<Optional>);
233 
234   auto moveassign_empty = [](Optional* optional_ptr) {
235     auto empty = Optional();
236     *optional_ptr = std::move(empty);
237   };
238   EXPECT_TRUE(engaged_test_nonempty.Test(moveassign_empty));
239 
240   auto moveassign_nonempty = [](Optional* optional_ptr) {
241     auto nonempty =
242         Optional(absl::in_place, kUpdatedInteger, testing::nothrow_ctor);
243     *optional_ptr = std::move(nonempty);
244   };
245   EXPECT_TRUE(disengaged_test_empty.Test(moveassign_nonempty));
246   EXPECT_TRUE(engaged_test_nonempty.Test(moveassign_nonempty));
247 
248   auto moveassign_thrower = [](Optional* optional_ptr) {
249     auto thrower = Thrower(kUpdatedInteger, testing::nothrow_ctor);
250     *optional_ptr = std::move(thrower);
251   };
252   EXPECT_TRUE(disengaged_test_empty.Test(moveassign_thrower));
253   EXPECT_TRUE(engaged_test_nonempty.Test(moveassign_thrower));
254 }
255 
TEST(OptionalExceptionSafety,NothrowMoveAssign)256 TEST(OptionalExceptionSafety, NothrowMoveAssign) {
257   // Tests the nothrow guarantee for optional of T with non-throwing move
258   {
259     auto empty = MoveOptional();
260     auto nonempty = MoveOptional(kInitialInteger);
261     EXPECT_TRUE(testing::TestNothrowOp([&]() { nonempty = std::move(empty); }));
262   }
263   {
264     auto nonempty = MoveOptional(kInitialInteger);
265     auto empty = MoveOptional();
266     EXPECT_TRUE(testing::TestNothrowOp([&]() { empty = std::move(nonempty); }));
267   }
268   {
269     auto nonempty_from = MoveOptional(kUpdatedInteger);
270     auto nonempty_to = MoveOptional(kInitialInteger);
271     EXPECT_TRUE(testing::TestNothrowOp(
272         [&]() { nonempty_to = std::move(nonempty_from); }));
273   }
274   {
275     auto thrower = MoveThrower(kUpdatedInteger);
276     auto empty = MoveOptional();
277     EXPECT_TRUE(testing::TestNothrowOp([&]() { empty = std::move(thrower); }));
278   }
279   {
280     auto thrower = MoveThrower(kUpdatedInteger);
281     auto nonempty = MoveOptional(kInitialInteger);
282     EXPECT_TRUE(
283         testing::TestNothrowOp([&]() { nonempty = std::move(thrower); }));
284   }
285 }
286 
287 }  // namespace
288 
289 ABSL_NAMESPACE_END
290 }  // namespace absl
291 
292 #endif  // #if !defined(ABSL_USES_STD_OPTIONAL) && defined(ABSL_HAVE_EXCEPTIONS)
293