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_return)249 TEST(result, unwrap_or_return) {
250   auto f = [](bool success) -> Result<size_t, CustomError> {
251     return OR_RETURN(success_or_fail(success)).size();
252   };
253 
254   auto r = f(true);
255   EXPECT_TRUE(r.ok());
256   EXPECT_EQ(strlen("success"), *r);
257 
258   auto s = f(false);
259   EXPECT_FALSE(s.ok());
260   EXPECT_EQ(CustomError::A, s.error().code());
261   EXPECT_EQ("fail: A", s.error().message());
262 }
263 
TEST(result,unwrap_or_return_errorcode)264 TEST(result, unwrap_or_return_errorcode) {
265   auto f = [](bool success) -> CustomError {
266     // Note that we use the same OR_RETURN macro for different return types: Result<U, CustomError>
267     // and CustomError.
268     std::string val = OR_RETURN(success_or_fail(success));
269     EXPECT_EQ("success", val);
270     return CustomError::B;
271   };
272 
273   auto r = f(true);
274   EXPECT_EQ(CustomError::B, r);
275 
276   auto s = f(false);
277   EXPECT_EQ(CustomError::A, s);
278 }
279 
TEST(result,unwrap_or_fatal)280 TEST(result, unwrap_or_fatal) {
281   auto r = OR_FATAL(success_or_fail(true));
282   EXPECT_EQ("success", r);
283 
284   EXPECT_DEATH(OR_FATAL(success_or_fail(false)), "fail: A");
285 }
286 
TEST(result,unwrap_ambiguous_int)287 TEST(result, unwrap_ambiguous_int) {
288   const std::string firstSuccess{"a"};
289   constexpr int secondSuccess = 5;
290   auto enum_success_or_fail = [&](bool success) -> Result<std::string, StatusT> {
291     if (success) return firstSuccess;
292     return ResultError<StatusT>("Fail", 10);
293   };
294   auto f = [&](bool success) -> Result<int, StatusT> {
295     auto val = OR_RETURN(enum_success_or_fail(success));
296     EXPECT_EQ(firstSuccess, val);
297     return secondSuccess;
298   };
299 
300   auto r = f(true);
301   ASSERT_TRUE(r.ok());
302   EXPECT_EQ(r.value(), secondSuccess);
303   auto s = f(false);
304   ASSERT_TRUE(!s.ok());
305   EXPECT_EQ(s.error().code(), 10);
306 }
307 
TEST(result,unwrap_ambiguous_uint_conv)308 TEST(result, unwrap_ambiguous_uint_conv) {
309   const std::string firstSuccess{"a"};
310   constexpr size_t secondSuccess = 5ull;
311   auto enum_success_or_fail = [&](bool success) -> Result<std::string, StatusT> {
312     if (success) return firstSuccess;
313     return ResultError<StatusT>("Fail", 10);
314   };
315 
316   auto f = [&](bool success) -> Result<size_t, StatusT> {
317     auto val = OR_RETURN(enum_success_or_fail(success));
318     EXPECT_EQ(firstSuccess, val);
319     return secondSuccess;
320   };
321 
322   auto r = f(true);
323   ASSERT_TRUE(r.ok());
324   EXPECT_EQ(r.value(), secondSuccess);
325   auto s = f(false);
326   ASSERT_TRUE(!s.ok());
327   EXPECT_EQ(s.error().code(), 10);
328 }
329 
330 struct IntConst {
331     int val_;
332     template <typename T, typename = std::enable_if_t<std::is_convertible_v<T, int>>>
IntConstandroid::base::IntConst333     IntConst(T&& val) : val_(val) {}
operator status_tandroid::base::IntConst334     operator status_t() {return val_;}
335 };
336 
TEST(result,unwrap_ambiguous_constructible)337 TEST(result, unwrap_ambiguous_constructible) {
338   constexpr int firstSuccess = 5;
339   constexpr int secondSuccess = 7;
340   struct A {
341     A (int val) : val_(val) {}
342     operator status_t() { return 0; }
343     int val_;
344   };
345   // If this returns Result<A, ...> instead of Result<IntConst, ...>,
346   // compilation fails unless we compile with c++20
347   auto enum_success_or_fail = [&](bool success) -> Result<IntConst, StatusT, false> {
348     if (success) return firstSuccess;
349     return ResultError<StatusT, false>(10);
350   };
351   auto f = [&](bool success) -> Result<IntConst, StatusT, false> {
352     auto val = OR_RETURN(enum_success_or_fail(success));
353     EXPECT_EQ(firstSuccess, val.val_);
354     return secondSuccess;
355   };
356   auto r = f(true);
357   EXPECT_EQ(r.value().val_, secondSuccess);
358   auto s = f(false);
359   EXPECT_EQ(s.error().code(), 10);
360 }
361 
362 struct Dangerous {};
363 struct ImplicitFromDangerous {
364   ImplicitFromDangerous(Dangerous);
365 };
366 template <typename U>
367 struct Templated {
368     U val_;
369     template <typename T, typename=std::enable_if_t<std::is_convertible_v<T, U>>>
Templatedandroid::base::Templated370     Templated(T val) : val_(val) {}
371 };
372 
373 
TEST(result,dangerous_result_conversion)374 TEST(result, dangerous_result_conversion) {
375   ResultError<Dangerous, false> error {Dangerous{}};
376   Result<Templated<Dangerous>, Dangerous, false> surprise {error};
377   EXPECT_TRUE(!surprise.ok());
378   Result<Templated<ImplicitFromDangerous>, Dangerous, false> surprise2 {error};
379   EXPECT_TRUE(!surprise2.ok());
380 }
381 
TEST(result,generic_convertible)382 TEST(result, generic_convertible) {
383   const std::string firstSuccess{"a"};
384   struct A {};
385   struct B {
386     operator A() {return A{};}
387   };
388 
389   auto enum_success_or_fail = [&](bool success) -> Result<std::string, B> {
390     if (success) return firstSuccess;
391     return ResultError<B>("Fail", B{});
392   };
393   auto f = [&](bool success) -> Result<A, B> {
394     auto val = OR_RETURN(enum_success_or_fail(success));
395     EXPECT_EQ(firstSuccess, val);
396     return A{};
397   };
398 
399   auto r = f(true);
400   EXPECT_TRUE(r.ok());
401   auto s = f(false);
402   EXPECT_TRUE(!s.ok());
403 }
404 
TEST(result,generic_exact)405 TEST(result, generic_exact) {
406   const std::string firstSuccess{"a"};
407   struct A {};
408   auto enum_success_or_fail = [&](bool success) -> Result<std::string, A> {
409     if (success) return firstSuccess;
410     return ResultError<A>("Fail", A{});
411   };
412   auto f = [&](bool success) -> Result<A, A> {
413     auto val = OR_RETURN(enum_success_or_fail(success));
414     EXPECT_EQ(firstSuccess, val);
415     return A{};
416   };
417 
418   auto r = f(true);
419   EXPECT_TRUE(r.ok());
420   auto s = f(false);
421   EXPECT_TRUE(!s.ok());
422 }
423 
424 struct MyData {
425   const int data;
426   static int copy_constructed;
427   static int move_constructed;
MyDataandroid::base::MyData428   explicit MyData(int d) : data(d) {}
MyDataandroid::base::MyData429   MyData(const MyData& other) : data(other.data) { copy_constructed++; }
MyDataandroid::base::MyData430   MyData(MyData&& other) : data(other.data) { move_constructed++; }
431   MyData& operator=(const MyData&) = delete;
432   MyData& operator=(MyData&&) = delete;
433 };
434 
435 int MyData::copy_constructed = 0;
436 int MyData::move_constructed = 0;
437 
TEST(result,unwrap_does_not_incur_additional_copying)438 TEST(result, unwrap_does_not_incur_additional_copying) {
439   MyData::copy_constructed = 0;
440   MyData::move_constructed = 0;
441   auto f = []() -> Result<MyData> { return MyData{10}; };
442 
443   [&]() -> Result<void> {
444     int data = OR_RETURN(f()).data;
445     EXPECT_EQ(10, data);
446     EXPECT_EQ(0, MyData::copy_constructed);
447     // Moved once when MyData{10} is returned as Result<MyData> in the lambda f.
448     // Moved once again when the variable d is constructed from OR_RETURN.
449     EXPECT_EQ(2, MyData::move_constructed);
450     return {};
451   }();
452 }
453 
TEST(result,supports_move_only_type)454 TEST(result, supports_move_only_type) {
455   auto f = [](bool success) -> Result<std::unique_ptr<std::string>> {
456     if (success) return std::make_unique<std::string>("hello");
457     return Error() << "error";
458   };
459 
460   auto g = [&](bool success) -> Result<std::unique_ptr<std::string>> {
461     auto r = OR_RETURN(f(success));
462     EXPECT_EQ("hello", *(r.get()));
463     return std::make_unique<std::string>("world");
464   };
465 
466   auto s = g(true);
467   EXPECT_RESULT_OK(s);
468   EXPECT_EQ("world", *(s->get()));
469 
470   auto t = g(false);
471   EXPECT_FALSE(t.ok());
472   EXPECT_EQ("error", t.error().message());
473 }
474 
TEST(result,unique_ptr)475 TEST(result, unique_ptr) {
476   using testing::Ok;
477 
478   auto return_unique_ptr = [](bool success) -> Result<std::unique_ptr<int>> {
479     auto result = OR_RETURN(Result<std::unique_ptr<int>>(std::make_unique<int>(3)));
480     if (!success) {
481       return Error() << __func__ << " failed.";
482     }
483     return result;
484   };
485   Result<std::unique_ptr<int>> result1 = return_unique_ptr(false);
486   ASSERT_THAT(result1, Not(Ok()));
487   Result<std::unique_ptr<int>> result2 = return_unique_ptr(true);
488   ASSERT_THAT(result2, Ok());
489   EXPECT_EQ(**result2, 3);
490 }
491 
TEST(result,void)492 TEST(result, void) {
493   using testing::Ok;
494 
495   auto return_void = []() -> Result<void> {
496     OR_RETURN(Result<void>());
497     return {};
498   };
499 
500   ASSERT_THAT(return_void(), Ok());
501 }
502 
503 struct ConstructorTracker {
504   static size_t constructor_called;
505   static size_t copy_constructor_called;
506   static size_t move_constructor_called;
507   static size_t copy_assignment_called;
508   static size_t move_assignment_called;
509 
510   template <typename T>
ConstructorTrackerandroid::base::ConstructorTracker511   ConstructorTracker(T&& string) : string(string) {
512     ++constructor_called;
513   }
514 
ConstructorTrackerandroid::base::ConstructorTracker515   ConstructorTracker(const ConstructorTracker& ct) {
516     ++copy_constructor_called;
517     string = ct.string;
518   }
ConstructorTrackerandroid::base::ConstructorTracker519   ConstructorTracker(ConstructorTracker&& ct) noexcept {
520     ++move_constructor_called;
521     string = std::move(ct.string);
522   }
operator =android::base::ConstructorTracker523   ConstructorTracker& operator=(const ConstructorTracker& ct) {
524     ++copy_assignment_called;
525     string = ct.string;
526     return *this;
527   }
operator =android::base::ConstructorTracker528   ConstructorTracker& operator=(ConstructorTracker&& ct) noexcept {
529     ++move_assignment_called;
530     string = std::move(ct.string);
531     return *this;
532   }
533 
534   std::string string;
535 };
536 
537 size_t ConstructorTracker::constructor_called = 0;
538 size_t ConstructorTracker::copy_constructor_called = 0;
539 size_t ConstructorTracker::move_constructor_called = 0;
540 size_t ConstructorTracker::copy_assignment_called = 0;
541 size_t ConstructorTracker::move_assignment_called = 0;
542 
ReturnConstructorTracker(const std::string & in)543 Result<ConstructorTracker> ReturnConstructorTracker(const std::string& in) {
544   if (in.empty()) {
545     return "literal string";
546   }
547   if (in == "test2") {
548     return ConstructorTracker(in + in + "2");
549   }
550   ConstructorTracker result(in + " " + in);
551   return result;
552 };
553 
TEST(result,no_copy_on_return)554 TEST(result, no_copy_on_return) {
555   // If returning parameters that may be used to implicitly construct the type T of Result<T>,
556   // then those parameters are forwarded to the construction of Result<T>.
557 
558   // If returning an prvalue or xvalue, it will be move constructed during the construction of
559   // Result<T>.
560 
561   // This check ensures that that is the case, and particularly that no copy constructors
562   // are called.
563 
564   auto result1 = ReturnConstructorTracker("");
565   ASSERT_RESULT_OK(result1);
566   EXPECT_EQ("literal string", result1->string);
567   EXPECT_EQ(1U, ConstructorTracker::constructor_called);
568   EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
569   EXPECT_EQ(0U, ConstructorTracker::move_constructor_called);
570   EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
571   EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
572 
573   auto result2 = ReturnConstructorTracker("test2");
574   ASSERT_RESULT_OK(result2);
575   EXPECT_EQ("test2test22", result2->string);
576   EXPECT_EQ(2U, ConstructorTracker::constructor_called);
577   EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
578   EXPECT_EQ(1U, ConstructorTracker::move_constructor_called);
579   EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
580   EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
581 
582   auto result3 = ReturnConstructorTracker("test3");
583   ASSERT_RESULT_OK(result3);
584   EXPECT_EQ("test3 test3", result3->string);
585   EXPECT_EQ(3U, ConstructorTracker::constructor_called);
586   EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
587   EXPECT_EQ(2U, ConstructorTracker::move_constructor_called);
588   EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
589   EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
590 }
591 
592 // Below two tests require that we do not hide the move constructor with our forwarding reference
593 // constructor.  This is done with by disabling the forwarding reference constructor if its first
594 // and only type is Result<T>.
TEST(result,result_result_with_success)595 TEST(result, result_result_with_success) {
596   auto return_result_result_with_success = []() -> Result<Result<void>> { return Result<void>(); };
597   auto result = return_result_result_with_success();
598   ASSERT_RESULT_OK(result);
599   ASSERT_RESULT_OK(*result);
600 
601   auto inner_result = result.value();
602   ASSERT_RESULT_OK(inner_result);
603 }
604 
TEST(result,result_result_with_failure)605 TEST(result, result_result_with_failure) {
606   auto return_result_result_with_error = []() -> Result<Result<void>> {
607     return Result<void>(ResultError("failure string", 6));
608   };
609   auto result = return_result_result_with_error();
610   ASSERT_RESULT_OK(result);
611   ASSERT_FALSE(result->ok());
612   EXPECT_EQ("failure string", (*result).error().message());
613   EXPECT_EQ(6, (*result).error().code());
614 }
615 
616 // This test requires that we disable the forwarding reference constructor if Result<T> is the
617 // *only* type that we are forwarding.  In otherwords, if we are forwarding Result<T>, int to
618 // construct a Result<T>, then we still need the constructor.
TEST(result,result_two_parameter_constructor_same_type)619 TEST(result, result_two_parameter_constructor_same_type) {
620   struct TestStruct {
621     TestStruct(int value) : value_(value) {}
622     TestStruct(Result<TestStruct> result, int value) : value_(result->value_ * value) {}
623     int value_;
624   };
625 
626   auto return_test_struct = []() -> Result<TestStruct> {
627     return Result<TestStruct>(std::in_place, Result<TestStruct>(std::in_place, 6), 6);
628   };
629 
630   auto result = return_test_struct();
631   ASSERT_RESULT_OK(result);
632   EXPECT_EQ(36, result->value_);
633 }
634 
TEST(result,die_on_access_failed_result)635 TEST(result, die_on_access_failed_result) {
636   Result<std::string> result = Error();
637   ASSERT_DEATH(*result, "");
638 }
639 
TEST(result,die_on_get_error_succesful_result)640 TEST(result, die_on_get_error_succesful_result) {
641   Result<std::string> result = "success";
642   ASSERT_DEATH(result.error(), "");
643 }
644 
645 template <class CharT>
SetErrnoToTwo(std::basic_ostream<CharT> & ss)646 std::basic_ostream<CharT>& SetErrnoToTwo(std::basic_ostream<CharT>& ss) {
647   errno = 2;
648   return ss;
649 }
650 
TEST(result,preserve_errno)651 TEST(result, preserve_errno) {
652   errno = 1;
653   int old_errno = errno;
654   Result<int> result = Error() << "Failed" << SetErrnoToTwo<char>;
655   ASSERT_FALSE(result.ok());
656   EXPECT_EQ(old_errno, errno);
657 
658   errno = 1;
659   old_errno = errno;
660   Result<int> result2 = ErrnoError() << "Failed" << SetErrnoToTwo<char>;
661   ASSERT_FALSE(result2.ok());
662   EXPECT_EQ(old_errno, errno);
663   EXPECT_EQ(old_errno, result2.error().code());
664 }
665 
TEST(result,error_with_fmt)666 TEST(result, error_with_fmt) {
667   Result<int> result = Errorf("{} {}!", "hello", "world");
668   EXPECT_EQ("hello world!", result.error().message());
669 
670   result = Errorf("{} {}!", std::string("hello"), std::string("world"));
671   EXPECT_EQ("hello world!", result.error().message());
672 
673   result = Errorf("{1} {0}!", "world", "hello");
674   EXPECT_EQ("hello world!", result.error().message());
675 
676   result = Errorf("hello world!");
677   EXPECT_EQ("hello world!", result.error().message());
678 
679   Result<int> result2 = Errorf("error occurred with {}", result.error());
680   EXPECT_EQ("error occurred with hello world!", result2.error().message());
681 
682   constexpr int test_errno = 6;
683   errno = test_errno;
684   result = ErrnoErrorf("{} {}!", "hello", "world");
685   EXPECT_EQ(test_errno, result.error().code());
686   EXPECT_EQ("hello world!: "s + strerror(test_errno), result.error().message());
687 }
688 
TEST(result,error_with_fmt_carries_errno)689 TEST(result, error_with_fmt_carries_errno) {
690   constexpr int inner_errno = 6;
691   errno = inner_errno;
692   Result<int> inner_result = ErrnoErrorf("inner failure");
693   errno = 0;
694   EXPECT_EQ(inner_errno, inner_result.error().code());
695 
696   // outer_result is created with Errorf, but its error code is got from inner_result.
697   Result<int> outer_result = Errorf("outer failure caused by {}", inner_result.error());
698   EXPECT_EQ(inner_errno, outer_result.error().code());
699   EXPECT_EQ("outer failure caused by inner failure: "s + strerror(inner_errno),
700             outer_result.error().message());
701 
702   // now both result objects are created with ErrnoErrorf. errno from the inner_result
703   // is not passed to outer_result.
704   constexpr int outer_errno = 10;
705   errno = outer_errno;
706   outer_result = ErrnoErrorf("outer failure caused by {}", inner_result.error());
707   EXPECT_EQ(outer_errno, outer_result.error().code());
708   EXPECT_EQ("outer failure caused by inner failure: "s + strerror(inner_errno) + ": "s +
709                 strerror(outer_errno),
710             outer_result.error().message());
711 }
712 
TEST(result,errno_chaining_multiple)713 TEST(result, errno_chaining_multiple) {
714   constexpr int errno1 = 6;
715   errno = errno1;
716   Result<int> inner1 = ErrnoErrorf("error1");
717 
718   constexpr int errno2 = 10;
719   errno = errno2;
720   Result<int> inner2 = ErrnoErrorf("error2");
721 
722   // takes the error code of inner2 since its the last one.
723   Result<int> outer = Errorf("two errors: {}, {}", inner1.error(), inner2.error());
724   EXPECT_EQ(errno2, outer.error().code());
725   EXPECT_EQ("two errors: error1: "s + strerror(errno1) + ", error2: "s + strerror(errno2),
726             outer.error().message());
727 }
728 
TEST(result,error_without_message)729 TEST(result, error_without_message) {
730   constexpr bool include_message = false;
731   Result<void, Errno, include_message> res = Error<Errno, include_message>(10);
732   EXPECT_FALSE(res.ok());
733   EXPECT_EQ(10, res.error().code());
734   EXPECT_EQ(sizeof(int), sizeof(res.error()));
735 }
736 
737 namespace testing {
738 
739 class Listener : public ::testing::MatchResultListener {
740  public:
Listener()741   Listener() : MatchResultListener(&ss_) {}
742   ~Listener() = default;
message() const743   std::string message() const { return ss_.str(); }
744 
745  private:
746   std::stringstream ss_;
747 };
748 
749 class ResultMatchers : public ::testing::Test {
750  public:
751   Result<int> result = 1;
752   Result<int> error = Error(EBADF) << "error message";
753   Listener listener;
754 };
755 
TEST_F(ResultMatchers,ok_result)756 TEST_F(ResultMatchers, ok_result) {
757   EXPECT_TRUE(ExplainMatchResult(Ok(), result, &listener));
758   EXPECT_THAT(listener.message(), Eq("result is OK"));
759 }
760 
TEST_F(ResultMatchers,ok_error)761 TEST_F(ResultMatchers, ok_error) {
762   EXPECT_FALSE(ExplainMatchResult(Ok(), error, &listener));
763   EXPECT_THAT(listener.message(), StartsWith("error is"));
764   EXPECT_THAT(listener.message(), HasSubstr(error.error().message()));
765   EXPECT_THAT(listener.message(), HasSubstr(strerror(error.error().code())));
766 }
767 
TEST_F(ResultMatchers,not_ok_result)768 TEST_F(ResultMatchers, not_ok_result) {
769   EXPECT_FALSE(ExplainMatchResult(Not(Ok()), result, &listener));
770   EXPECT_THAT(listener.message(), Eq("result is OK"));
771 }
772 
TEST_F(ResultMatchers,not_ok_error)773 TEST_F(ResultMatchers, not_ok_error) {
774   EXPECT_TRUE(ExplainMatchResult(Not(Ok()), error, &listener));
775   EXPECT_THAT(listener.message(), StartsWith("error is"));
776   EXPECT_THAT(listener.message(), HasSubstr(error.error().message()));
777   EXPECT_THAT(listener.message(), HasSubstr(strerror(error.error().code())));
778 }
779 
TEST_F(ResultMatchers,has_value_result)780 TEST_F(ResultMatchers, has_value_result) {
781   EXPECT_TRUE(ExplainMatchResult(HasValue(*result), result, &listener));
782 }
783 
TEST_F(ResultMatchers,has_value_wrong_result)784 TEST_F(ResultMatchers, has_value_wrong_result) {
785   EXPECT_FALSE(ExplainMatchResult(HasValue(*result + 1), result, &listener));
786 }
787 
TEST_F(ResultMatchers,has_value_error)788 TEST_F(ResultMatchers, has_value_error) {
789   EXPECT_FALSE(ExplainMatchResult(HasValue(*result), error, &listener));
790   EXPECT_THAT(listener.message(), StartsWith("error is"));
791   EXPECT_THAT(listener.message(), HasSubstr(error.error().message()));
792   EXPECT_THAT(listener.message(), HasSubstr(strerror(error.error().code())));
793 }
794 
TEST_F(ResultMatchers,has_error_code_result)795 TEST_F(ResultMatchers, has_error_code_result) {
796   EXPECT_FALSE(ExplainMatchResult(HasError(WithCode(error.error().code())), result, &listener));
797   EXPECT_THAT(listener.message(), Eq("result is OK"));
798 }
799 
TEST_F(ResultMatchers,has_error_code_wrong_code)800 TEST_F(ResultMatchers, has_error_code_wrong_code) {
801   EXPECT_FALSE(ExplainMatchResult(HasError(WithCode(error.error().code() + 1)), error, &listener));
802   EXPECT_THAT(listener.message(), StartsWith("actual error is"));
803   EXPECT_THAT(listener.message(), HasSubstr(strerror(error.error().code())));
804 }
805 
TEST_F(ResultMatchers,has_error_code_correct_code)806 TEST_F(ResultMatchers, has_error_code_correct_code) {
807   EXPECT_TRUE(ExplainMatchResult(HasError(WithCode(error.error().code())), error, &listener));
808   EXPECT_THAT(listener.message(), StartsWith("actual error is"));
809   EXPECT_THAT(listener.message(), HasSubstr(strerror(error.error().code())));
810 }
811 
TEST_F(ResultMatchers,has_error_message_result)812 TEST_F(ResultMatchers, has_error_message_result) {
813   EXPECT_FALSE(
814       ExplainMatchResult(HasError(WithMessage(error.error().message())), result, &listener));
815   EXPECT_THAT(listener.message(), Eq("result is OK"));
816 }
817 
TEST_F(ResultMatchers,has_error_message_wrong_message)818 TEST_F(ResultMatchers, has_error_message_wrong_message) {
819   EXPECT_FALSE(ExplainMatchResult(HasError(WithMessage("foo")), error, &listener));
820   EXPECT_THAT(listener.message(), StartsWith("actual error is"));
821   EXPECT_THAT(listener.message(), HasSubstr(error.error().message()));
822 }
823 
TEST_F(ResultMatchers,has_error_message_correct_message)824 TEST_F(ResultMatchers, has_error_message_correct_message) {
825   EXPECT_TRUE(ExplainMatchResult(HasError(WithMessage(error.error().message())), error, &listener));
826   EXPECT_THAT(listener.message(), StartsWith("actual error is"));
827   EXPECT_THAT(listener.message(), HasSubstr(error.error().message()));
828 }
829 
830 }  // namespace testing
831 }  // namespace base
832 }  // namespace android
833