blob: ef913fde2cc6a4f488c84671cba3db51c2dfe483 [file] [log] [blame]
Alexei Frolov41b32d32019-11-13 17:22:03 -08001// Copyright 2020 The Pigweed Authors
2//
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
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
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
13// the License.
14
15#include "pw_result/result.h"
16
17#include "gtest/gtest.h"
18
19namespace pw {
20namespace {
21
22TEST(Result, CreateOk) {
23 Result<const char*> res("hello");
24 EXPECT_TRUE(res.ok());
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070025 EXPECT_EQ(res.status(), Status::Ok());
Alexei Frolov41b32d32019-11-13 17:22:03 -080026 EXPECT_EQ(res.value(), "hello");
27}
28
29TEST(Result, CreateNotOk) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070030 Result<int> res(Status::DataLoss());
Alexei Frolov41b32d32019-11-13 17:22:03 -080031 EXPECT_FALSE(res.ok());
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070032 EXPECT_EQ(res.status(), Status::DataLoss());
Alexei Frolov41b32d32019-11-13 17:22:03 -080033}
34
35TEST(Result, ValueOr) {
36 Result<int> good(3);
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070037 Result<int> bad(Status::DataLoss());
Alexei Frolov41b32d32019-11-13 17:22:03 -080038 EXPECT_EQ(good.value_or(42), 3);
39 EXPECT_EQ(bad.value_or(42), 42);
40}
41
42TEST(Result, ConstructType) {
43 struct Point {
44 Point(int a, int b) : x(a), y(b) {}
45
46 int x;
47 int y;
48 };
49
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);
54}
55
56Result<float> Divide(float a, float b) {
57 if (b == 0) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070058 return Status::InvalidArgument();
Alexei Frolov41b32d32019-11-13 17:22:03 -080059 }
60 return a / b;
61}
62
63TEST(Divide, ReturnOk) {
Rob Mohr06819482020-04-06 13:25:43 -070064 Result<float> res = Divide(10, 5);
Alexei Frolov41b32d32019-11-13 17:22:03 -080065 ASSERT_TRUE(res.ok());
66 EXPECT_EQ(res.value(), 2.0f);
67}
68
69TEST(Divide, ReturnNotOk) {
Rob Mohr06819482020-04-06 13:25:43 -070070 Result<float> res = Divide(10, 0);
Alexei Frolov41b32d32019-11-13 17:22:03 -080071 EXPECT_FALSE(res.ok());
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070072 EXPECT_EQ(res.status(), Status::InvalidArgument());
Alexei Frolov41b32d32019-11-13 17:22:03 -080073}
74
75} // namespace
76} // namespace pw