1 // Copyright 2020 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
15 #include "pw_result/result.h"
17 #include "gtest/gtest.h"
22 TEST(Result, CreateOk) {
23 Result<const char*> res("hello");
24 EXPECT_TRUE(res.ok());
25 EXPECT_EQ(res.status(), OkStatus());
26 EXPECT_EQ(res.value(), "hello");
29 TEST(Result, CreateNotOk) {
30 Result<int> res(Status::DataLoss());
31 EXPECT_FALSE(res.ok());
32 EXPECT_EQ(res.status(), Status::DataLoss());
35 TEST(Result, ValueOr) {
37 Result<int> bad(Status::DataLoss());
38 EXPECT_EQ(good.value_or(42), 3);
39 EXPECT_EQ(bad.value_or(42), 42);
42 TEST(Result, ConstructType) {
44 Point(int a, int b) : x(a), y(b) {}
50 Result<Point> origin{std::in_place, 0, 0};
51 ASSERT_TRUE(origin.ok());
52 ASSERT_EQ(origin.value().x, 0);
53 ASSERT_EQ(origin.value().y, 0);
56 Result<float> Divide(float a, float b) {
58 return Status::InvalidArgument();
63 TEST(Divide, ReturnOk) {
64 Result<float> res = Divide(10, 5);
65 ASSERT_TRUE(res.ok());
66 EXPECT_EQ(res.value(), 2.0f);
69 TEST(Divide, ReturnNotOk) {
70 Result<float> res = Divide(10, 0);
71 EXPECT_FALSE(res.ok());
72 EXPECT_EQ(res.status(), Status::InvalidArgument());