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 
19 #include "errno.h"
20 
21 #include <istream>
22 #include <string>
23 
24 #include <gtest/gtest.h>
25 
26 using namespace std::string_literals;
27 
28 namespace android {
29 namespace base {
30 
TEST(result,result_accessors)31 TEST(result, result_accessors) {
32   Result<std::string> result = "success";
33   ASSERT_RESULT_OK(result);
34   ASSERT_TRUE(result.has_value());
35 
36   EXPECT_EQ("success", *result);
37   EXPECT_EQ("success", result.value());
38 
39   EXPECT_EQ('s', result->data()[0]);
40 }
41 
TEST(result,result_accessors_rvalue)42 TEST(result, result_accessors_rvalue) {
43   ASSERT_TRUE(Result<std::string>("success").ok());
44   ASSERT_TRUE(Result<std::string>("success").has_value());
45 
46   EXPECT_EQ("success", *Result<std::string>("success"));
47   EXPECT_EQ("success", Result<std::string>("success").value());
48 
49   EXPECT_EQ('s', Result<std::string>("success")->data()[0]);
50 }
51 
TEST(result,result_void)52 TEST(result, result_void) {
53   Result<void> ok = {};
54   EXPECT_RESULT_OK(ok);
55   ok.value();  // should not crash
56   ASSERT_DEATH(ok.error(), "");
57 
58   Result<void> fail = Error() << "failure" << 1;
59   EXPECT_FALSE(fail.ok());
60   EXPECT_EQ("failure1", fail.error().message());
61   EXPECT_EQ(0, fail.error().code());
62   EXPECT_TRUE(ok != fail);
63   ASSERT_DEATH(fail.value(), "");
64 
65   auto test = [](bool ok) -> Result<void> {
66     if (ok) return {};
67     else return Error() << "failure" << 1;
68   };
69   EXPECT_TRUE(test(true).ok());
70   EXPECT_FALSE(test(false).ok());
71   test(true).value();  // should not crash
72   ASSERT_DEATH(test(true).error(), "");
73   ASSERT_DEATH(test(false).value(), "");
74   EXPECT_EQ("failure1", test(false).error().message());
75 }
76 
TEST(result,result_error)77 TEST(result, result_error) {
78   Result<void> result = Error() << "failure" << 1;
79   ASSERT_FALSE(result.ok());
80   ASSERT_FALSE(result.has_value());
81 
82   EXPECT_EQ(0, result.error().code());
83   EXPECT_EQ("failure1", result.error().message());
84 }
85 
TEST(result,result_error_empty)86 TEST(result, result_error_empty) {
87   Result<void> result = Error();
88   ASSERT_FALSE(result.ok());
89   ASSERT_FALSE(result.has_value());
90 
91   EXPECT_EQ(0, result.error().code());
92   EXPECT_EQ("", result.error().message());
93 }
94 
TEST(result,result_error_rvalue)95 TEST(result, result_error_rvalue) {
96   // Error() and ErrnoError() aren't actually used to create a Result<T> object.
97   // Under the hood, they are an intermediate class that can be implicitly constructed into a
98   // Result<T>.  This is needed both to create the ostream and because Error() itself, by
99   // definition will not know what the type, T, of the underlying Result<T> object that it would
100   // create is.
101 
102   auto MakeRvalueErrorResult = []() -> Result<void> { return Error() << "failure" << 1; };
103   ASSERT_FALSE(MakeRvalueErrorResult().ok());
104   ASSERT_FALSE(MakeRvalueErrorResult().has_value());
105 
106   EXPECT_EQ(0, MakeRvalueErrorResult().error().code());
107   EXPECT_EQ("failure1", MakeRvalueErrorResult().error().message());
108 }
109 
TEST(result,result_errno_error)110 TEST(result, result_errno_error) {
111   constexpr int test_errno = 6;
112   errno = test_errno;
113   Result<void> result = ErrnoError() << "failure" << 1;
114 
115   ASSERT_FALSE(result.ok());
116   ASSERT_FALSE(result.has_value());
117 
118   EXPECT_EQ(test_errno, result.error().code());
119   EXPECT_EQ("failure1: "s + strerror(test_errno), result.error().message());
120 }
121 
TEST(result,result_errno_error_no_text)122 TEST(result, result_errno_error_no_text) {
123   constexpr int test_errno = 6;
124   errno = test_errno;
125   Result<void> result = ErrnoError();
126 
127   ASSERT_FALSE(result.ok());
128   ASSERT_FALSE(result.has_value());
129 
130   EXPECT_EQ(test_errno, result.error().code());
131   EXPECT_EQ(strerror(test_errno), result.error().message());
132 }
133 
TEST(result,result_error_from_other_result)134 TEST(result, result_error_from_other_result) {
135   auto error_text = "test error"s;
136   Result<void> result = Error() << error_text;
137 
138   ASSERT_FALSE(result.ok());
139   ASSERT_FALSE(result.has_value());
140 
141   Result<std::string> result2 = result.error();
142 
143   ASSERT_FALSE(result2.ok());
144   ASSERT_FALSE(result2.has_value());
145 
146   EXPECT_EQ(0, result2.error().code());
147   EXPECT_EQ(error_text, result2.error().message());
148 }
149 
TEST(result,result_error_through_ostream)150 TEST(result, result_error_through_ostream) {
151   auto error_text = "test error"s;
152   Result<void> result = Error() << error_text;
153 
154   ASSERT_FALSE(result.ok());
155   ASSERT_FALSE(result.has_value());
156 
157   Result<std::string> result2 = Error() << result.error();
158 
159   ASSERT_FALSE(result2.ok());
160   ASSERT_FALSE(result2.has_value());
161 
162   EXPECT_EQ(0, result2.error().code());
163   EXPECT_EQ(error_text, result2.error().message());
164 }
165 
TEST(result,result_errno_error_through_ostream)166 TEST(result, result_errno_error_through_ostream) {
167   auto error_text = "test error"s;
168   constexpr int test_errno = 6;
169   errno = 6;
170   Result<void> result = ErrnoError() << error_text;
171 
172   errno = 0;
173 
174   ASSERT_FALSE(result.ok());
175   ASSERT_FALSE(result.has_value());
176 
177   Result<std::string> result2 = Error() << result.error();
178 
179   ASSERT_FALSE(result2.ok());
180   ASSERT_FALSE(result2.has_value());
181 
182   EXPECT_EQ(test_errno, result2.error().code());
183   EXPECT_EQ(error_text + ": " + strerror(test_errno), result2.error().message());
184 }
185 
TEST(result,constructor_forwarding)186 TEST(result, constructor_forwarding) {
187   auto result = Result<std::string>(std::in_place, 5, 'a');
188 
189   ASSERT_RESULT_OK(result);
190   ASSERT_TRUE(result.has_value());
191 
192   EXPECT_EQ("aaaaa", *result);
193 }
194 
195 struct ConstructorTracker {
196   static size_t constructor_called;
197   static size_t copy_constructor_called;
198   static size_t move_constructor_called;
199   static size_t copy_assignment_called;
200   static size_t move_assignment_called;
201 
202   template <typename T>
ConstructorTrackerandroid::base::ConstructorTracker203   ConstructorTracker(T&& string) : string(string) {
204     ++constructor_called;
205   }
206 
ConstructorTrackerandroid::base::ConstructorTracker207   ConstructorTracker(const ConstructorTracker& ct) {
208     ++copy_constructor_called;
209     string = ct.string;
210   }
ConstructorTrackerandroid::base::ConstructorTracker211   ConstructorTracker(ConstructorTracker&& ct) noexcept {
212     ++move_constructor_called;
213     string = std::move(ct.string);
214   }
operator =android::base::ConstructorTracker215   ConstructorTracker& operator=(const ConstructorTracker& ct) {
216     ++copy_assignment_called;
217     string = ct.string;
218     return *this;
219   }
operator =android::base::ConstructorTracker220   ConstructorTracker& operator=(ConstructorTracker&& ct) noexcept {
221     ++move_assignment_called;
222     string = std::move(ct.string);
223     return *this;
224   }
225 
226   std::string string;
227 };
228 
229 size_t ConstructorTracker::constructor_called = 0;
230 size_t ConstructorTracker::copy_constructor_called = 0;
231 size_t ConstructorTracker::move_constructor_called = 0;
232 size_t ConstructorTracker::copy_assignment_called = 0;
233 size_t ConstructorTracker::move_assignment_called = 0;
234 
ReturnConstructorTracker(const std::string & in)235 Result<ConstructorTracker> ReturnConstructorTracker(const std::string& in) {
236   if (in.empty()) {
237     return "literal string";
238   }
239   if (in == "test2") {
240     return ConstructorTracker(in + in + "2");
241   }
242   ConstructorTracker result(in + " " + in);
243   return result;
244 };
245 
TEST(result,no_copy_on_return)246 TEST(result, no_copy_on_return) {
247   // If returning parameters that may be used to implicitly construct the type T of Result<T>,
248   // then those parameters are forwarded to the construction of Result<T>.
249 
250   // If returning an prvalue or xvalue, it will be move constructed during the construction of
251   // Result<T>.
252 
253   // This check ensures that that is the case, and particularly that no copy constructors
254   // are called.
255 
256   auto result1 = ReturnConstructorTracker("");
257   ASSERT_RESULT_OK(result1);
258   EXPECT_EQ("literal string", result1->string);
259   EXPECT_EQ(1U, ConstructorTracker::constructor_called);
260   EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
261   EXPECT_EQ(0U, ConstructorTracker::move_constructor_called);
262   EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
263   EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
264 
265   auto result2 = ReturnConstructorTracker("test2");
266   ASSERT_RESULT_OK(result2);
267   EXPECT_EQ("test2test22", result2->string);
268   EXPECT_EQ(2U, ConstructorTracker::constructor_called);
269   EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
270   EXPECT_EQ(1U, ConstructorTracker::move_constructor_called);
271   EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
272   EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
273 
274   auto result3 = ReturnConstructorTracker("test3");
275   ASSERT_RESULT_OK(result3);
276   EXPECT_EQ("test3 test3", result3->string);
277   EXPECT_EQ(3U, ConstructorTracker::constructor_called);
278   EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
279   EXPECT_EQ(2U, ConstructorTracker::move_constructor_called);
280   EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
281   EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
282 }
283 
284 // Below two tests require that we do not hide the move constructor with our forwarding reference
285 // constructor.  This is done with by disabling the forwarding reference constructor if its first
286 // and only type is Result<T>.
TEST(result,result_result_with_success)287 TEST(result, result_result_with_success) {
288   auto return_result_result_with_success = []() -> Result<Result<void>> { return Result<void>(); };
289   auto result = return_result_result_with_success();
290   ASSERT_RESULT_OK(result);
291   ASSERT_RESULT_OK(*result);
292 
293   auto inner_result = result.value();
294   ASSERT_RESULT_OK(inner_result);
295 }
296 
TEST(result,result_result_with_failure)297 TEST(result, result_result_with_failure) {
298   auto return_result_result_with_error = []() -> Result<Result<void>> {
299     return Result<void>(ResultError("failure string", 6));
300   };
301   auto result = return_result_result_with_error();
302   ASSERT_RESULT_OK(result);
303   ASSERT_FALSE(result->ok());
304   EXPECT_EQ("failure string", (*result).error().message());
305   EXPECT_EQ(6, (*result).error().code());
306 }
307 
308 // This test requires that we disable the forwarding reference constructor if Result<T> is the
309 // *only* type that we are forwarding.  In otherwords, if we are forwarding Result<T>, int to
310 // construct a Result<T>, then we still need the constructor.
TEST(result,result_two_parameter_constructor_same_type)311 TEST(result, result_two_parameter_constructor_same_type) {
312   struct TestStruct {
313     TestStruct(int value) : value_(value) {}
314     TestStruct(Result<TestStruct> result, int value) : value_(result->value_ * value) {}
315     int value_;
316   };
317 
318   auto return_test_struct = []() -> Result<TestStruct> {
319     return Result<TestStruct>(std::in_place, Result<TestStruct>(std::in_place, 6), 6);
320   };
321 
322   auto result = return_test_struct();
323   ASSERT_RESULT_OK(result);
324   EXPECT_EQ(36, result->value_);
325 }
326 
TEST(result,die_on_access_failed_result)327 TEST(result, die_on_access_failed_result) {
328   Result<std::string> result = Error();
329   ASSERT_DEATH(*result, "");
330 }
331 
TEST(result,die_on_get_error_succesful_result)332 TEST(result, die_on_get_error_succesful_result) {
333   Result<std::string> result = "success";
334   ASSERT_DEATH(result.error(), "");
335 }
336 
337 template <class CharT>
SetErrnoToTwo(std::basic_ostream<CharT> & ss)338 std::basic_ostream<CharT>& SetErrnoToTwo(std::basic_ostream<CharT>& ss) {
339   errno = 2;
340   return ss;
341 }
342 
TEST(result,preserve_errno)343 TEST(result, preserve_errno) {
344   errno = 1;
345   int old_errno = errno;
346   Result<int> result = Error() << "Failed" << SetErrnoToTwo<char>;
347   ASSERT_FALSE(result.ok());
348   EXPECT_EQ(old_errno, errno);
349 
350   errno = 1;
351   old_errno = errno;
352   Result<int> result2 = ErrnoError() << "Failed" << SetErrnoToTwo<char>;
353   ASSERT_FALSE(result2.ok());
354   EXPECT_EQ(old_errno, errno);
355   EXPECT_EQ(old_errno, result2.error().code());
356 }
357 
TEST(result,error_with_fmt)358 TEST(result, error_with_fmt) {
359   Result<int> result = Errorf("{} {}!", "hello", "world");
360   EXPECT_EQ("hello world!", result.error().message());
361 
362   result = Errorf("{} {}!", std::string("hello"), std::string("world"));
363   EXPECT_EQ("hello world!", result.error().message());
364 
365   result = Errorf("{1} {0}!", "world", "hello");
366   EXPECT_EQ("hello world!", result.error().message());
367 
368   result = Errorf("hello world!");
369   EXPECT_EQ("hello world!", result.error().message());
370 
371   Result<int> result2 = Errorf("error occurred with {}", result.error());
372   EXPECT_EQ("error occurred with hello world!", result2.error().message());
373 
374   constexpr int test_errno = 6;
375   errno = test_errno;
376   result = ErrnoErrorf("{} {}!", "hello", "world");
377   EXPECT_EQ(test_errno, result.error().code());
378   EXPECT_EQ("hello world!: "s + strerror(test_errno), result.error().message());
379 }
380 
TEST(result,error_with_fmt_carries_errno)381 TEST(result, error_with_fmt_carries_errno) {
382   constexpr int inner_errno = 6;
383   errno = inner_errno;
384   Result<int> inner_result = ErrnoErrorf("inner failure");
385   errno = 0;
386   EXPECT_EQ(inner_errno, inner_result.error().code());
387 
388   // outer_result is created with Errorf, but its error code is got from inner_result.
389   Result<int> outer_result = Errorf("outer failure caused by {}", inner_result.error());
390   EXPECT_EQ(inner_errno, outer_result.error().code());
391   EXPECT_EQ("outer failure caused by inner failure: "s + strerror(inner_errno),
392             outer_result.error().message());
393 
394   // now both result objects are created with ErrnoErrorf. errno from the inner_result
395   // is not passed to outer_result.
396   constexpr int outer_errno = 10;
397   errno = outer_errno;
398   outer_result = ErrnoErrorf("outer failure caused by {}", inner_result.error());
399   EXPECT_EQ(outer_errno, outer_result.error().code());
400   EXPECT_EQ("outer failure caused by inner failure: "s + strerror(inner_errno) + ": "s +
401                 strerror(outer_errno),
402             outer_result.error().message());
403 }
404 
TEST(result,errno_chaining_multiple)405 TEST(result, errno_chaining_multiple) {
406   constexpr int errno1 = 6;
407   errno = errno1;
408   Result<int> inner1 = ErrnoErrorf("error1");
409 
410   constexpr int errno2 = 10;
411   errno = errno2;
412   Result<int> inner2 = ErrnoErrorf("error2");
413 
414   // takes the error code of inner2 since its the last one.
415   Result<int> outer = Errorf("two errors: {}, {}", inner1.error(), inner2.error());
416   EXPECT_EQ(errno2, outer.error().code());
417   EXPECT_EQ("two errors: error1: "s + strerror(errno1) + ", error2: "s + strerror(errno2),
418             outer.error().message());
419 }
420 
421 }  // namespace base
422 }  // namespace android
423