Software APIs
status_unittest.cc
1 // Copyright lowRISC contributors (OpenTitan project).
2 // Licensed under the Apache License, Version 2.0, see LICENSE for details.
3 // SPDX-License-Identifier: Apache-2.0
4 
5 #include "sw/device/lib/base/status.h"
6 
7 #include <ostream>
8 #include <stdint.h>
9 #include <tuple>
10 
11 #include "gtest/gtest.h"
12 
13 namespace status_unittest {
14 namespace {
15 
16 TEST(Status, OkValues) {
18 
19  // The no-argument form should have a value of zero.
20  status = OK_STATUS();
21  EXPECT_EQ(status_ok(status), true);
22  EXPECT_EQ(status_err(status), absl_status_t::kOk);
23  EXPECT_EQ(status.value, 0);
24 
25  // The one-argument form should have the value of the argument.
26  status = OK_STATUS(5);
27  EXPECT_EQ(status_ok(status), true);
28  EXPECT_EQ(status_err(status), absl_status_t::kOk);
29  EXPECT_EQ(status.value, 5);
30 
31  // Any negative value for OK is not permitted and will result
32  // in an error value.
33  status = OK_STATUS(-1);
34  EXPECT_EQ(status_ok(status), false);
35 }
36 
37 TEST(Status, ErrorValues) {
38  int32_t arg;
40  bool err;
41  const char *message;
42  char mod_id[4]{};
43 
44  // The no-argument form should carry the line number on which the error
45  // was created and a module-id of the first three letters of the filename.
46  status = UNKNOWN();
47  int32_t expected_line = __LINE__ - 1;
48  err = status_extract(status, &message, &arg, mod_id);
49  EXPECT_EQ(status_ok(status), false);
50  EXPECT_EQ(status_err(status), absl_status_t::kUnknown);
51  EXPECT_EQ(err, true);
52  EXPECT_EQ(arg, expected_line);
53  EXPECT_EQ(std::string(mod_id), "STA");
54 
55  // The one-argument form should carry the value of that argument.
56  status = CANCELLED(1);
57  err = status_extract(status, &message, &arg, mod_id);
58  EXPECT_EQ(status_ok(status), false);
59  EXPECT_EQ(status_err(status), absl_status_t::kCancelled);
60  EXPECT_EQ(err, true);
61  EXPECT_EQ(arg, 1);
62  EXPECT_EQ(std::string(mod_id), "STA");
63 }
64 
65 TEST(Status, ErrorValuesInModule) {
66  int32_t arg;
68  bool err;
69  const char *message;
70  char mod_id[4]{};
71 
72  // Normally, MODULE_ID should be defined at the top of your file, thus
73  // causing all uses of the error creation macros to substitute in your
74  // module ID. In this test, we're doing it here to override the
75  // value for this test.
76 #define MODULE_ID MAKE_MODULE_ID('z', 'z', 'z')
77  status = UNKNOWN();
78  int32_t expected_line = __LINE__ - 1;
79  err = status_extract(status, &message, &arg, mod_id);
80  EXPECT_EQ(status_ok(status), false);
81  EXPECT_EQ(status_err(status), absl_status_t::kUnknown);
82  EXPECT_EQ(err, true);
83  EXPECT_EQ(arg, expected_line);
84  EXPECT_EQ(std::string(mod_id), "ZZZ");
85 }
86 
87 } // namespace
88 } // namespace status_unittest