xref: /aosp_15_r20/system/libbase/result_test.cpp (revision 8f0ba417480079999ba552f1087ae592091b9d02)
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "android-base/result.h"
18 #include <utils/ErrorsMacros.h>
19 #include "android-base/errors.h"
20 #include "errno.h"
21 
22 #include <istream>
23 #include <memory>
24 #include <string>
25 #include <type_traits>
26 
27 #include <gmock/gmock.h>
28 #include <gtest/gtest.h>
29 
30 #include "android-base/result-gmock.h"
31 
32 using namespace std::string_literals;
33 using ::testing::Eq;
34 using ::testing::ExplainMatchResult;
35 using ::testing::HasSubstr;
36 using ::testing::Not;
37 using ::testing::StartsWith;
38 
39 namespace android {
40 namespace base {
41 
TEST(result,result_accessors)42 TEST(result, result_accessors) {
43   Result<std::string> result = "success";
44   ASSERT_RESULT_OK(result);
45   ASSERT_TRUE(result.has_value());
46 
47   EXPECT_EQ("success", *result);
48   EXPECT_EQ("success", result.value());
49 
50   EXPECT_EQ('s', result->data()[0]);
51 }
52 
TEST(result,result_accessors_rvalue)53 TEST(result, result_accessors_rvalue) {
54   ASSERT_TRUE(Result<std::string>("success").ok());
55   ASSERT_TRUE(Result<std::string>("success").has_value());
56 
57   EXPECT_EQ("success", *Result<std::string>("success"));
58   EXPECT_EQ("success", Result<std::string>("success").value());
59 
60   EXPECT_EQ('s', Result<std::string>("success")->data()[0]);
61 }
62 
TEST(result,result_void)63 TEST(result, result_void) {
64   Result<void> ok = {};
65   EXPECT_RESULT_OK(ok);
66   ok.value();  // should not crash
67   ASSERT_DEATH(ok.error(), "");
68 
69   Result<void> fail = Error() << "failure" << 1;
70   EXPECT_FALSE(fail.ok());
71   EXPECT_EQ("failure1", fail.error().message());
72   EXPECT_EQ(0, fail.error().code());
73   EXPECT_TRUE(ok != fail);
74   ASSERT_DEATH(fail.value(), "");
75 
76   auto test = [](bool ok) -> Result<void> {
77     if (ok) return {};
78     else return Error() << "failure" << 1;
79   };
80   EXPECT_TRUE(test(true).ok());
81   EXPECT_FALSE(test(false).ok());
82   test(true).value();  // should not crash
83   ASSERT_DEATH(test(true).error(), "");
84   ASSERT_DEATH(test(false).value(), "");
85   EXPECT_EQ("failure1", test(false).error().message());
86 }
87 
TEST(result,result_error)88 TEST(result, result_error) {
89   Result<void> result = Error() << "failure" << 1;
90   ASSERT_FALSE(result.ok());
91   ASSERT_FALSE(result.has_value());
92 
93   EXPECT_EQ(0, result.error().code());
94   EXPECT_EQ("failure1", result.error().message());
95 }
96 
TEST(result,result_error_empty)97 TEST(result, result_error_empty) {
98   Result<void> result = Error();
99   ASSERT_FALSE(result.ok());
100   ASSERT_FALSE(result.has_value());
101 
102   EXPECT_EQ(0, result.error().code());
103   EXPECT_EQ("", result.error().message());
104 }
105 
TEST(result,result_error_rvalue)106 TEST(result, result_error_rvalue) {
107   // Error() and ErrnoError() aren't actually used to create a Result<T> object.
108   // Under the hood, they are an intermediate class that can be implicitly constructed into a
109   // Result<T>.  This is needed both to create the ostream and because Error() itself, by
110   // definition will not know what the type, T, of the underlying Result<T> object that it would
111   // create is.
112 
113   auto MakeRvalueErrorResult = []() -> Result<void> { return Error() << "failure" << 1; };
114   ASSERT_FALSE(MakeRvalueErrorResult().ok());
115   ASSERT_FALSE(MakeRvalueErrorResult().has_value());
116 
117   EXPECT_EQ(0, MakeRvalueErrorResult().error().code());
118   EXPECT_EQ("failure1", MakeRvalueErrorResult().error().message());
119 }
120 
TEST(result,result_errno_error)121 TEST(result, result_errno_error) {
122   constexpr int test_errno = 6;
123   errno = test_errno;
124   Result<void> result = ErrnoError() << "failure" << 1;
125 
126   ASSERT_FALSE(result.ok());
127   ASSERT_FALSE(result.has_value());
128 
129   EXPECT_EQ(test_errno, result.error().code());
130   EXPECT_EQ("failure1: "s + strerror(test_errno), result.error().message());
131 }
132 
TEST(result,result_errno_error_no_text)133 TEST(result, result_errno_error_no_text) {
134   constexpr int test_errno = 6;
135   errno = test_errno;
136   Result<void> result = ErrnoError();
137 
138   ASSERT_FALSE(result.ok());
139   ASSERT_FALSE(result.has_value());
140 
141   EXPECT_EQ(test_errno, result.error().code());
142   EXPECT_EQ(strerror(test_errno), result.error().message());
143 }
144 
TEST(result,result_error_from_other_result)145 TEST(result, result_error_from_other_result) {
146   auto error_text = "test error"s;
147   Result<void> result = Error() << error_text;
148 
149   ASSERT_FALSE(result.ok());
150   ASSERT_FALSE(result.has_value());
151 
152   Result<std::string> result2 = result.error();
153 
154   ASSERT_FALSE(result2.ok());
155   ASSERT_FALSE(result2.has_value());
156 
157   EXPECT_EQ(0, result2.error().code());
158   EXPECT_EQ(error_text, result2.error().message());
159 }
160 
TEST(result,result_error_through_ostream)161 TEST(result, result_error_through_ostream) {
162   auto error_text = "test error"s;
163   Result<void> result = Error() << error_text;
164 
165   ASSERT_FALSE(result.ok());
166   ASSERT_FALSE(result.has_value());
167 
168   Result<std::string> result2 = Error() << result.error();
169 
170   ASSERT_FALSE(result2.ok());
171   ASSERT_FALSE(result2.has_value());
172 
173   EXPECT_EQ(0, result2.error().code());
174   EXPECT_EQ(error_text, result2.error().message());
175 }
176 
TEST(result,result_errno_error_through_ostream)177 TEST(result, result_errno_error_through_ostream) {
178   auto error_text = "test error"s;
179   constexpr int test_errno = 6;
180   errno = 6;
181   Result<void> result = ErrnoError() << error_text;
182 
183   errno = 0;
184 
185   ASSERT_FALSE(result.ok());
186   ASSERT_FALSE(result.has_value());
187 
188   Result<std::string> result2 = Error() << result.error();
189 
190   ASSERT_FALSE(result2.ok());
191   ASSERT_FALSE(result2.has_value());
192 
193   EXPECT_EQ(test_errno, result2.error().code());
194   EXPECT_EQ(error_text + ": " + strerror(test_errno), result2.error().message());
195 }
196 
197 enum class CustomError { A, B };
198 
199 struct CustomErrorWrapper {
CustomErrorWrapperandroid::base::CustomErrorWrapper200   CustomErrorWrapper() : val_(CustomError::A) {}
CustomErrorWrapperandroid::base::CustomErrorWrapper201   CustomErrorWrapper(const CustomError& e) : val_(e) {}
valueandroid::base::CustomErrorWrapper202   CustomError value() const { return val_; }
operator CustomErrorandroid::base::CustomErrorWrapper203   operator CustomError() const { return value(); }
printandroid::base::CustomErrorWrapper204   std::string print() const {
205     switch (val_) {
206       case CustomError::A:
207         return "A";
208       case CustomError::B:
209         return "B";
210     }
211   }
212   CustomError val_;
213 };
214 
215 #define NewCustomError(e) Error<CustomErrorWrapper>(CustomError::e)
216 
TEST(result,result_with_custom_errorcode)217 TEST(result, result_with_custom_errorcode) {
218   Result<void, CustomError> ok = {};
219   EXPECT_RESULT_OK(ok);
220   ok.value();  // should not crash
221   EXPECT_DEATH(ok.error(), "");
222 
223   auto error_text = "test error"s;
224   Result<void, CustomError> err = NewCustomError(A) << error_text;
225 
226   EXPECT_FALSE(err.ok());
227   EXPECT_FALSE(err.has_value());
228 
229   EXPECT_EQ(CustomError::A, err.error().code());
230   EXPECT_EQ(error_text + ": A", err.error().message());
231 }
232 
success_or_fail(bool success)233 Result<std::string, CustomError> success_or_fail(bool success) {
234   if (success)
235     return "success";
236   else
237     return NewCustomError(A) << "fail";
238 }
239 
TEST(result,constructor_forwarding)240 TEST(result, constructor_forwarding) {
241   auto result = Result<std::string>(std::in_place, 5, 'a');
242 
243   ASSERT_RESULT_OK(result);
244   ASSERT_TRUE(result.has_value());
245 
246   EXPECT_EQ("aaaaa", *result);
247 }
248 
TEST(result,unwrap_or_do)249 TEST(result, unwrap_or_do) {
250   bool v = UNWRAP_OR_DO(res, Result<bool>(false), FAIL() << "Should not be reached");
251   EXPECT_FALSE(v);
252 
253   []() -> void {
254     UNWRAP_OR_DO(res, Result<bool>(ResultError("foo", 17)), {
255       EXPECT_EQ(res.error().message(), "foo");
256       EXPECT_EQ(res.error().code(), 17);
257       return;
258     });
259     FAIL() << "Should not be reached";
260   }();
261 }
262 
TEST(result,unwrap_or_assert_fail)263 TEST(result, unwrap_or_assert_fail) {
264   bool s = OR_ASSERT_FAIL(Result<bool>(true));
265   EXPECT_TRUE(s);
266   // NB: There's no (stable) way to test that an assertion failed, so cannot test the error case.
267 }
268 
TEST(result,unwrap_or_return)269 TEST(result, unwrap_or_return) {
270   auto f = [](bool success) -> Result<size_t, CustomError> {
271     return OR_RETURN(success_or_fail(success)).size();
272   };
273 
274   auto r = f(true);
275   EXPECT_TRUE(r.ok());
276   EXPECT_EQ(strlen("success"), *r);
277 
278   auto s = f(false);
279   EXPECT_FALSE(s.ok());
280   EXPECT_EQ(CustomError::A, s.error().code());
281   EXPECT_EQ("fail: A", s.error().message());
282 }
283 
TEST(result,unwrap_or_return_errorcode)284 TEST(result, unwrap_or_return_errorcode) {
285   auto f = [](bool success) -> CustomError {
286     // Note that we use the same OR_RETURN macro for different return types: Result<U, CustomError>
287     // and CustomError.
288     std::string val = OR_RETURN(success_or_fail(success));
289     EXPECT_EQ("success", val);
290     return CustomError::B;
291   };
292 
293   auto r = f(true);
294   EXPECT_EQ(CustomError::B, r);
295 
296   auto s = f(false);
297   EXPECT_EQ(CustomError::A, s);
298 }
299 
TEST(result,unwrap_or_fatal)300 TEST(result, unwrap_or_fatal) {
301   auto r = OR_FATAL(success_or_fail(true));
302   EXPECT_EQ("success", r);
303 
304   EXPECT_DEATH(OR_FATAL(success_or_fail(false)), "fail: A");
305 }
306 
TEST(result,unwrap_ambiguous_int)307 TEST(result, unwrap_ambiguous_int) {
308   const std::string firstSuccess{"a"};
309   constexpr int secondSuccess = 5;
310   auto enum_success_or_fail = [&](bool success) -> Result<std::string, StatusT> {
311     if (success) return firstSuccess;
312     return ResultError<StatusT>("Fail", 10);
313   };
314   auto f = [&](bool success) -> Result<int, StatusT> {
315     auto val = OR_RETURN(enum_success_or_fail(success));
316     EXPECT_EQ(firstSuccess, val);
317     return secondSuccess;
318   };
319 
320   auto r = f(true);
321   ASSERT_TRUE(r.ok());
322   EXPECT_EQ(r.value(), secondSuccess);
323   auto s = f(false);
324   ASSERT_TRUE(!s.ok());
325   EXPECT_EQ(s.error().code(), 10);
326 }
327 
TEST(result,unwrap_ambiguous_uint_conv)328 TEST(result, unwrap_ambiguous_uint_conv) {
329   const std::string firstSuccess{"a"};
330   constexpr size_t secondSuccess = 5ull;
331   auto enum_success_or_fail = [&](bool success) -> Result<std::string, StatusT> {
332     if (success) return firstSuccess;
333     return ResultError<StatusT>("Fail", 10);
334   };
335 
336   auto f = [&](bool success) -> Result<size_t, StatusT> {
337     auto val = OR_RETURN(enum_success_or_fail(success));
338     EXPECT_EQ(firstSuccess, val);
339     return secondSuccess;
340   };
341 
342   auto r = f(true);
343   ASSERT_TRUE(r.ok());
344   EXPECT_EQ(r.value(), secondSuccess);
345   auto s = f(false);
346   ASSERT_TRUE(!s.ok());
347   EXPECT_EQ(s.error().code(), 10);
348 }
349 
350 struct IntConst {
351     int val_;
352     template <typename T, typename = std::enable_if_t<std::is_convertible_v<T, int>>>
IntConstandroid::base::IntConst353     IntConst(T&& val) : val_(val) {}
operator status_tandroid::base::IntConst354     operator status_t() {return val_;}
355 };
356 
TEST(result,unwrap_ambiguous_constructible)357 TEST(result, unwrap_ambiguous_constructible) {
358   constexpr int firstSuccess = 5;
359   constexpr int secondSuccess = 7;
360   struct A {
361     A (int val) : val_(val) {}
362     operator status_t() { return 0; }
363     int val_;
364   };
365   // If this returns Result<A, ...> instead of Result<IntConst, ...>,
366   // compilation fails unless we compile with c++20
367   auto enum_success_or_fail = [&](bool success) -> Result<IntConst, StatusT, false> {
368     if (success) return firstSuccess;
369     return ResultError<StatusT, false>(10);
370   };
371   auto f = [&](bool success) -> Result<IntConst, StatusT, false> {
372     auto val = OR_RETURN(enum_success_or_fail(success));
373     EXPECT_EQ(firstSuccess, val.val_);
374     return secondSuccess;
375   };
376   auto r = f(true);
377   EXPECT_EQ(r.value().val_, secondSuccess);
378   auto s = f(false);
379   EXPECT_EQ(s.error().code(), 10);
380 }
381 
382 struct Dangerous {};
383 struct ImplicitFromDangerous {
384   ImplicitFromDangerous(Dangerous);
385 };
386 template <typename U>
387 struct Templated {
388     U val_;
389     template <typename T, typename=std::enable_if_t<std::is_convertible_v<T, U>>>
Templatedandroid::base::Templated390     Templated(T val) : val_(val) {}
391 };
392 
393 
TEST(result,dangerous_result_conversion)394 TEST(result, dangerous_result_conversion) {
395   ResultError<Dangerous, false> error {Dangerous{}};
396   Result<Templated<Dangerous>, Dangerous, false> surprise {error};
397   EXPECT_TRUE(!surprise.ok());
398   Result<Templated<ImplicitFromDangerous>, Dangerous, false> surprise2 {error};
399   EXPECT_TRUE(!surprise2.ok());
400 }
401 
TEST(result,generic_convertible)402 TEST(result, generic_convertible) {
403   const std::string firstSuccess{"a"};
404   struct A {};
405   struct B {
406     operator A() {return A{};}
407   };
408 
409   auto enum_success_or_fail = [&](bool success) -> Result<std::string, B> {
410     if (success) return firstSuccess;
411     return ResultError<B>("Fail", B{});
412   };
413   auto f = [&](bool success) -> Result<A, B> {
414     auto val = OR_RETURN(enum_success_or_fail(success));
415     EXPECT_EQ(firstSuccess, val);
416     return A{};
417   };
418 
419   auto r = f(true);
420   EXPECT_TRUE(r.ok());
421   auto s = f(false);
422   EXPECT_TRUE(!s.ok());
423 }
424 
TEST(result,generic_exact)425 TEST(result, generic_exact) {
426   const std::string firstSuccess{"a"};
427   struct A {};
428   auto enum_success_or_fail = [&](bool success) -> Result<std::string, A> {
429     if (success) return firstSuccess;
430     return ResultError<A>("Fail", A{});
431   };
432   auto f = [&](bool success) -> Result<A, A> {
433     auto val = OR_RETURN(enum_success_or_fail(success));
434     EXPECT_EQ(firstSuccess, val);
435     return A{};
436   };
437 
438   auto r = f(true);
439   EXPECT_TRUE(r.ok());
440   auto s = f(false);
441   EXPECT_TRUE(!s.ok());
442 }
443 
444 struct MyData {
445   const int data;
446   static int copy_constructed;
447   static int move_constructed;
MyDataandroid::base::MyData448   explicit MyData(int d) : data(d) {}
MyDataandroid::base::MyData449   MyData(const MyData& other) : data(other.data) { copy_constructed++; }
MyDataandroid::base::MyData450   MyData(MyData&& other) : data(other.data) { move_constructed++; }
451   MyData& operator=(const MyData&) = delete;
452   MyData& operator=(MyData&&) = delete;
453 };
454 
455 int MyData::copy_constructed = 0;
456 int MyData::move_constructed = 0;
457 
TEST(result,unwrap_does_not_incur_additional_copying)458 TEST(result, unwrap_does_not_incur_additional_copying) {
459   MyData::copy_constructed = 0;
460   MyData::move_constructed = 0;
461   auto f = []() -> Result<MyData> { return MyData{10}; };
462 
463   [&]() -> Result<void> {
464     int data = OR_RETURN(f()).data;
465     EXPECT_EQ(10, data);
466     EXPECT_EQ(0, MyData::copy_constructed);
467     // Moved once when MyData{10} is returned as Result<MyData> in the lambda f.
468     // Moved once again when the variable d is constructed from OR_RETURN.
469     EXPECT_EQ(2, MyData::move_constructed);
470     return {};
471   }();
472 }
473 
TEST(result,supports_move_only_type)474 TEST(result, supports_move_only_type) {
475   auto f = [](bool success) -> Result<std::unique_ptr<std::string>> {
476     if (success) return std::make_unique<std::string>("hello");
477     return Error() << "error";
478   };
479 
480   auto g = [&](bool success) -> Result<std::unique_ptr<std::string>> {
481     auto r = OR_RETURN(f(success));
482     EXPECT_EQ("hello", *(r.get()));
483     return std::make_unique<std::string>("world");
484   };
485 
486   auto s = g(true);
487   EXPECT_RESULT_OK(s);
488   EXPECT_EQ("world", *(s->get()));
489 
490   auto t = g(false);
491   EXPECT_FALSE(t.ok());
492   EXPECT_EQ("error", t.error().message());
493 }
494 
TEST(result,unique_ptr)495 TEST(result, unique_ptr) {
496   using testing::Ok;
497 
498   auto return_unique_ptr = [](bool success) -> Result<std::unique_ptr<int>> {
499     auto result = OR_RETURN(Result<std::unique_ptr<int>>(std::make_unique<int>(3)));
500     if (!success) {
501       return Error() << __func__ << " failed.";
502     }
503     return result;
504   };
505   Result<std::unique_ptr<int>> result1 = return_unique_ptr(false);
506   ASSERT_THAT(result1, Not(Ok()));
507   Result<std::unique_ptr<int>> result2 = return_unique_ptr(true);
508   ASSERT_THAT(result2, Ok());
509   EXPECT_EQ(**result2, 3);
510 }
511 
TEST(result,void)512 TEST(result, void) {
513   using testing::Ok;
514 
515   auto return_void = []() -> Result<void> {
516     OR_RETURN(Result<void>());
517     return {};
518   };
519 
520   ASSERT_THAT(return_void(), Ok());
521 }
522 
523 struct ConstructorTracker {
524   static size_t constructor_called;
525   static size_t copy_constructor_called;
526   static size_t move_constructor_called;
527   static size_t copy_assignment_called;
528   static size_t move_assignment_called;
529 
530   template <typename T>
ConstructorTrackerandroid::base::ConstructorTracker531   ConstructorTracker(T&& string) : string(string) {
532     ++constructor_called;
533   }
534 
ConstructorTrackerandroid::base::ConstructorTracker535   ConstructorTracker(const ConstructorTracker& ct) {
536     ++copy_constructor_called;
537     string = ct.string;
538   }
ConstructorTrackerandroid::base::ConstructorTracker539   ConstructorTracker(ConstructorTracker&& ct) noexcept {
540     ++move_constructor_called;
541     string = std::move(ct.string);
542   }
operator =android::base::ConstructorTracker543   ConstructorTracker& operator=(const ConstructorTracker& ct) {
544     ++copy_assignment_called;
545     string = ct.string;
546     return *this;
547   }
operator =android::base::ConstructorTracker548   ConstructorTracker& operator=(ConstructorTracker&& ct) noexcept {
549     ++move_assignment_called;
550     string = std::move(ct.string);
551     return *this;
552   }
553 
554   std::string string;
555 };
556 
557 size_t ConstructorTracker::constructor_called = 0;
558 size_t ConstructorTracker::copy_constructor_called = 0;
559 size_t ConstructorTracker::move_constructor_called = 0;
560 size_t ConstructorTracker::copy_assignment_called = 0;
561 size_t ConstructorTracker::move_assignment_called = 0;
562 
ReturnConstructorTracker(const std::string & in)563 Result<ConstructorTracker> ReturnConstructorTracker(const std::string& in) {
564   if (in.empty()) {
565     return "literal string";
566   }
567   if (in == "test2") {
568     return ConstructorTracker(in + in + "2");
569   }
570   ConstructorTracker result(in + " " + in);
571   return result;
572 };
573 
TEST(result,no_copy_on_return)574 TEST(result, no_copy_on_return) {
575   // If returning parameters that may be used to implicitly construct the type T of Result<T>,
576   // then those parameters are forwarded to the construction of Result<T>.
577 
578   // If returning an prvalue or xvalue, it will be move constructed during the construction of
579   // Result<T>.
580 
581   // This check ensures that that is the case, and particularly that no copy constructors
582   // are called.
583 
584   auto result1 = ReturnConstructorTracker("");
585   ASSERT_RESULT_OK(result1);
586   EXPECT_EQ("literal string", result1->string);
587   EXPECT_EQ(1U, ConstructorTracker::constructor_called);
588   EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
589   EXPECT_EQ(0U, ConstructorTracker::move_constructor_called);
590   EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
591   EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
592 
593   auto result2 = ReturnConstructorTracker("test2");
594   ASSERT_RESULT_OK(result2);
595   EXPECT_EQ("test2test22", result2->string);
596   EXPECT_EQ(2U, ConstructorTracker::constructor_called);
597   EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
598   EXPECT_EQ(1U, ConstructorTracker::move_constructor_called);
599   EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
600   EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
601 
602   auto result3 = ReturnConstructorTracker("test3");
603   ASSERT_RESULT_OK(result3);
604   EXPECT_EQ("test3 test3", result3->string);
605   EXPECT_EQ(3U, ConstructorTracker::constructor_called);
606   EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
607   EXPECT_EQ(2U, ConstructorTracker::move_constructor_called);
608   EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
609   EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
610 }
611 
612 // Below two tests require that we do not hide the move constructor with our forwarding reference
613 // constructor.  This is done with by disabling the forwarding reference constructor if its first
614 // and only type is Result<T>.
TEST(result,result_result_with_success)615 TEST(result, result_result_with_success) {
616   auto return_result_result_with_success = []() -> Result<Result<void>> { return Result<void>(); };
617   auto result = return_result_result_with_success();
618   ASSERT_RESULT_OK(result);
619   ASSERT_RESULT_OK(*result);
620 
621   auto inner_result = result.value();
622   ASSERT_RESULT_OK(inner_result);
623 }
624 
TEST(result,result_result_with_failure)625 TEST(result, result_result_with_failure) {
626   auto return_result_result_with_error = []() -> Result<Result<void>> {
627     return Result<void>(ResultError("failure string", 6));
628   };
629   auto result = return_result_result_with_error();
630   ASSERT_RESULT_OK(result);
631   ASSERT_FALSE(result->ok());
632   EXPECT_EQ("failure string", (*result).error().message());
633   EXPECT_EQ(6, (*result).error().code());
634 }
635 
636 // This test requires that we disable the forwarding reference constructor if Result<T> is the
637 // *only* type that we are forwarding.  In otherwords, if we are forwarding Result<T>, int to
638 // construct a Result<T>, then we still need the constructor.
TEST(result,result_two_parameter_constructor_same_type)639 TEST(result, result_two_parameter_constructor_same_type) {
640   struct TestStruct {
641     TestStruct(int value) : value_(value) {}
642     TestStruct(Result<TestStruct> result, int value) : value_(result->value_ * value) {}
643     int value_;
644   };
645 
646   auto return_test_struct = []() -> Result<TestStruct> {
647     return Result<TestStruct>(std::in_place, Result<TestStruct>(std::in_place, 6), 6);
648   };
649 
650   auto result = return_test_struct();
651   ASSERT_RESULT_OK(result);
652   EXPECT_EQ(36, result->value_);
653 }
654 
TEST(result,die_on_access_failed_result)655 TEST(result, die_on_access_failed_result) {
656   Result<std::string> result = Error();
657   ASSERT_DEATH(*result, "");
658 }
659 
TEST(result,die_on_get_error_succesful_result)660 TEST(result, die_on_get_error_succesful_result) {
661   Result<std::string> result = "success";
662   ASSERT_DEATH(result.error(), "");
663 }
664 
665 template <class CharT>
SetErrnoToTwo(std::basic_ostream<CharT> & ss)666 std::basic_ostream<CharT>& SetErrnoToTwo(std::basic_ostream<CharT>& ss) {
667   errno = 2;
668   return ss;
669 }
670 
TEST(result,preserve_errno)671 TEST(result, preserve_errno) {
672   errno = 1;
673   int old_errno = errno;
674   Result<int> result = Error() << "Failed" << SetErrnoToTwo<char>;
675   ASSERT_FALSE(result.ok());
676   EXPECT_EQ(old_errno, errno);
677 
678   errno = 1;
679   old_errno = errno;
680   Result<int> result2 = ErrnoError() << "Failed" << SetErrnoToTwo<char>;
681   ASSERT_FALSE(result2.ok());
682   EXPECT_EQ(old_errno, errno);
683   EXPECT_EQ(old_errno, result2.error().code());
684 }
685 
TEST(result,error_with_fmt)686 TEST(result, error_with_fmt) {
687   Result<int> result = Errorf("{} {}!", "hello", "world");
688   EXPECT_EQ("hello world!", result.error().message());
689 
690   result = Errorf("{} {}!", std::string("hello"), std::string("world"));
691   EXPECT_EQ("hello world!", result.error().message());
692 
693   result = Errorf("{1} {0}!", "world", "hello");
694   EXPECT_EQ("hello world!", result.error().message());
695 
696   result = Errorf("hello world!");
697   EXPECT_EQ("hello world!", result.error().message());
698 
699   Result<int> result2 = Errorf("error occurred with {}", result.error());
700   EXPECT_EQ("error occurred with hello world!", result2.error().message());
701 
702   constexpr int test_errno = 6;
703   errno = test_errno;
704   result = ErrnoErrorf("{} {}!", "hello", "world");
705   EXPECT_EQ(test_errno, result.error().code());
706   EXPECT_EQ("hello world!: "s + strerror(test_errno), result.error().message());
707 }
708 
TEST(result,error_with_fmt_carries_errno)709 TEST(result, error_with_fmt_carries_errno) {
710   constexpr int inner_errno = 6;
711   errno = inner_errno;
712   Result<int> inner_result = ErrnoErrorf("inner failure");
713   errno = 0;
714   EXPECT_EQ(inner_errno, inner_result.error().code());
715 
716   // outer_result is created with Errorf, but its error code is got from inner_result.
717   Result<int> outer_result = Errorf("outer failure caused by {}", inner_result.error());
718   EXPECT_EQ(inner_errno, outer_result.error().code());
719   EXPECT_EQ("outer failure caused by inner failure: "s + strerror(inner_errno),
720             outer_result.error().message());
721 
722   // now both result objects are created with ErrnoErrorf. errno from the inner_result
723   // is not passed to outer_result.
724   constexpr int outer_errno = 10;
725   errno = outer_errno;
726   outer_result = ErrnoErrorf("outer failure caused by {}", inner_result.error());
727   EXPECT_EQ(outer_errno, outer_result.error().code());
728   EXPECT_EQ("outer failure caused by inner failure: "s + strerror(inner_errno) + ": "s +
729                 strerror(outer_errno),
730             outer_result.error().message());
731 }
732 
TEST(result,errno_chaining_multiple)733 TEST(result, errno_chaining_multiple) {
734   constexpr int errno1 = 6;
735   errno = errno1;
736   Result<int> inner1 = ErrnoErrorf("error1");
737 
738   constexpr int errno2 = 10;
739   errno = errno2;
740   Result<int> inner2 = ErrnoErrorf("error2");
741 
742   // takes the error code of inner2 since its the last one.
743   Result<int> outer = Errorf("two errors: {}, {}", inner1.error(), inner2.error());
744   EXPECT_EQ(errno2, outer.error().code());
745   EXPECT_EQ("two errors: error1: "s + strerror(errno1) + ", error2: "s + strerror(errno2),
746             outer.error().message());
747 }
748 
TEST(result,error_without_message)749 TEST(result, error_without_message) {
750   constexpr bool include_message = false;
751   Result<void, Errno, include_message> res = Error<Errno, include_message>(10);
752   EXPECT_FALSE(res.ok());
753   EXPECT_EQ(10, res.error().code());
754   EXPECT_EQ(sizeof(int), sizeof(res.error()));
755 }
756 
757 namespace testing {
758 
759 class Listener : public ::testing::MatchResultListener {
760  public:
Listener()761   Listener() : MatchResultListener(&ss_) {}
762   ~Listener() = default;
message() const763   std::string message() const { return ss_.str(); }
764 
765  private:
766   std::stringstream ss_;
767 };
768 
769 class ResultMatchers : public ::testing::Test {
770  public:
771   Result<int> result = 1;
772   Result<int> error = Error(EBADF) << "error message";
773   Listener listener;
774 };
775 
TEST_F(ResultMatchers,ok_result)776 TEST_F(ResultMatchers, ok_result) {
777   EXPECT_TRUE(ExplainMatchResult(Ok(), result, &listener));
778   EXPECT_THAT(listener.message(), Eq("result is OK"));
779 }
780 
TEST_F(ResultMatchers,ok_error)781 TEST_F(ResultMatchers, ok_error) {
782   EXPECT_FALSE(ExplainMatchResult(Ok(), error, &listener));
783   EXPECT_THAT(listener.message(), StartsWith("error is"));
784   EXPECT_THAT(listener.message(), HasSubstr(error.error().message()));
785   EXPECT_THAT(listener.message(), HasSubstr(strerror(error.error().code())));
786 }
787 
TEST_F(ResultMatchers,not_ok_result)788 TEST_F(ResultMatchers, not_ok_result) {
789   EXPECT_FALSE(ExplainMatchResult(Not(Ok()), result, &listener));
790   EXPECT_THAT(listener.message(), Eq("result is OK"));
791 }
792 
TEST_F(ResultMatchers,not_ok_error)793 TEST_F(ResultMatchers, not_ok_error) {
794   EXPECT_TRUE(ExplainMatchResult(Not(Ok()), error, &listener));
795   EXPECT_THAT(listener.message(), StartsWith("error is"));
796   EXPECT_THAT(listener.message(), HasSubstr(error.error().message()));
797   EXPECT_THAT(listener.message(), HasSubstr(strerror(error.error().code())));
798 }
799 
TEST_F(ResultMatchers,has_value_result)800 TEST_F(ResultMatchers, has_value_result) {
801   EXPECT_TRUE(ExplainMatchResult(HasValue(*result), result, &listener));
802 }
803 
TEST_F(ResultMatchers,has_value_wrong_result)804 TEST_F(ResultMatchers, has_value_wrong_result) {
805   EXPECT_FALSE(ExplainMatchResult(HasValue(*result + 1), result, &listener));
806 }
807 
TEST_F(ResultMatchers,has_value_error)808 TEST_F(ResultMatchers, has_value_error) {
809   EXPECT_FALSE(ExplainMatchResult(HasValue(*result), error, &listener));
810   EXPECT_THAT(listener.message(), StartsWith("error is"));
811   EXPECT_THAT(listener.message(), HasSubstr(error.error().message()));
812   EXPECT_THAT(listener.message(), HasSubstr(strerror(error.error().code())));
813 }
814 
TEST_F(ResultMatchers,has_error_code_result)815 TEST_F(ResultMatchers, has_error_code_result) {
816   EXPECT_FALSE(ExplainMatchResult(HasError(WithCode(error.error().code())), result, &listener));
817   EXPECT_THAT(listener.message(), Eq("result is OK"));
818 }
819 
TEST_F(ResultMatchers,has_error_code_wrong_code)820 TEST_F(ResultMatchers, has_error_code_wrong_code) {
821   EXPECT_FALSE(ExplainMatchResult(HasError(WithCode(error.error().code() + 1)), error, &listener));
822   EXPECT_THAT(listener.message(), StartsWith("actual error is"));
823   EXPECT_THAT(listener.message(), HasSubstr(strerror(error.error().code())));
824 }
825 
TEST_F(ResultMatchers,has_error_code_correct_code)826 TEST_F(ResultMatchers, has_error_code_correct_code) {
827   EXPECT_TRUE(ExplainMatchResult(HasError(WithCode(error.error().code())), error, &listener));
828   EXPECT_THAT(listener.message(), StartsWith("actual error is"));
829   EXPECT_THAT(listener.message(), HasSubstr(strerror(error.error().code())));
830 }
831 
TEST_F(ResultMatchers,has_error_message_result)832 TEST_F(ResultMatchers, has_error_message_result) {
833   EXPECT_FALSE(
834       ExplainMatchResult(HasError(WithMessage(error.error().message())), result, &listener));
835   EXPECT_THAT(listener.message(), Eq("result is OK"));
836 }
837 
TEST_F(ResultMatchers,has_error_message_wrong_message)838 TEST_F(ResultMatchers, has_error_message_wrong_message) {
839   EXPECT_FALSE(ExplainMatchResult(HasError(WithMessage("foo")), error, &listener));
840   EXPECT_THAT(listener.message(), StartsWith("actual error is"));
841   EXPECT_THAT(listener.message(), HasSubstr(error.error().message()));
842 }
843 
TEST_F(ResultMatchers,has_error_message_correct_message)844 TEST_F(ResultMatchers, has_error_message_correct_message) {
845   EXPECT_TRUE(ExplainMatchResult(HasError(WithMessage(error.error().message())), error, &listener));
846   EXPECT_THAT(listener.message(), StartsWith("actual error is"));
847   EXPECT_THAT(listener.message(), HasSubstr(error.error().message()));
848 }
849 
850 }  // namespace testing
851 }  // namespace base
852 }  // namespace android
853