Dominik Laskowski | 9bb429a | 2024-01-28 15:20:47 -0500 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2024 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 <ftl/expected.h> |
| 18 | #include <gtest/gtest.h> |
| 19 | |
| 20 | #include <string> |
| 21 | #include <system_error> |
| 22 | |
| 23 | namespace android::test { |
| 24 | |
| 25 | using IntExp = ftl::Expected<int, std::errc>; |
| 26 | using StringExp = ftl::Expected<std::string, std::errc>; |
| 27 | |
| 28 | using namespace std::string_literals; |
| 29 | |
| 30 | TEST(Expected, Construct) { |
| 31 | // Default value. |
| 32 | EXPECT_TRUE(IntExp().has_value()); |
| 33 | EXPECT_EQ(IntExp(), IntExp(0)); |
| 34 | |
| 35 | EXPECT_TRUE(StringExp().has_value()); |
| 36 | EXPECT_EQ(StringExp(), StringExp("")); |
| 37 | |
| 38 | // Value. |
| 39 | ASSERT_TRUE(IntExp(42).has_value()); |
| 40 | EXPECT_EQ(42, IntExp(42).value()); |
| 41 | |
| 42 | ASSERT_TRUE(StringExp("test").has_value()); |
| 43 | EXPECT_EQ("test"s, StringExp("test").value()); |
| 44 | |
| 45 | // Error. |
| 46 | const auto exp = StringExp(ftl::Unexpected(std::errc::invalid_argument)); |
| 47 | ASSERT_FALSE(exp.has_value()); |
| 48 | EXPECT_EQ(std::errc::invalid_argument, exp.error()); |
| 49 | } |
| 50 | |
| 51 | TEST(Expected, HasError) { |
| 52 | EXPECT_FALSE(IntExp(123).has_error([](auto) { return true; })); |
| 53 | EXPECT_FALSE(IntExp(ftl::Unexpected(std::errc::io_error)).has_error([](auto) { return false; })); |
| 54 | |
| 55 | EXPECT_TRUE(StringExp(ftl::Unexpected(std::errc::permission_denied)).has_error([](auto e) { |
| 56 | return e == std::errc::permission_denied; |
| 57 | })); |
| 58 | } |
| 59 | |
| 60 | TEST(Expected, ValueOpt) { |
| 61 | EXPECT_EQ(ftl::Optional(-1), IntExp(-1).value_opt()); |
| 62 | EXPECT_EQ(std::nullopt, IntExp(ftl::Unexpected(std::errc::broken_pipe)).value_opt()); |
| 63 | |
| 64 | { |
| 65 | const StringExp exp("foo"s); |
| 66 | EXPECT_EQ(ftl::Optional('f'), |
| 67 | exp.value_opt().transform([](const auto& s) { return s.front(); })); |
| 68 | EXPECT_EQ("foo"s, exp.value()); |
| 69 | } |
| 70 | { |
| 71 | StringExp exp("foobar"s); |
| 72 | EXPECT_EQ(ftl::Optional(6), std::move(exp).value_opt().transform(&std::string::length)); |
| 73 | EXPECT_TRUE(exp.value().empty()); |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | } // namespace android::test |