Bitcoin Core 30.99.0
P2P Digital Currency
util_expected_tests.cpp
Go to the documentation of this file.
1// Copyright (c) The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or https://opensource.org/license/mit.
4
6#include <util/expected.h>
7
8#include <boost/test/unit_test.hpp>
9
10using namespace util;
11
12BOOST_AUTO_TEST_SUITE(util_expected_tests)
13
14BOOST_AUTO_TEST_CASE(expected_value)
15{
16 struct Obj {
17 int x;
18 };
20 BOOST_CHECK(e.value().x == 0);
21
22 e = Obj{42};
23
24 BOOST_CHECK(e.has_value());
25 BOOST_CHECK(static_cast<bool>(e));
26 BOOST_CHECK(e.value().x == 42);
27 BOOST_CHECK((*e).x == 42);
28 BOOST_CHECK(e->x == 42);
29
30 // modify value
31 e.value().x += 1;
32 (*e).x += 1;
33 e->x += 1;
34
35 const auto& read{e};
36 BOOST_CHECK(read.value().x == 45);
37 BOOST_CHECK((*read).x == 45);
38 BOOST_CHECK(read->x == 45);
39}
40
41BOOST_AUTO_TEST_CASE(expected_value_or)
42{
43 Expected<std::unique_ptr<int>, int> no_copy{std::make_unique<int>(1)};
44 const int one{*std::move(no_copy).value_or(std::make_unique<int>(2))};
45 BOOST_CHECK_EQUAL(one, 1);
46
47 const Expected<std::string, int> const_val{Unexpected{-1}};
48 BOOST_CHECK_EQUAL(const_val.value_or("fallback"), "fallback");
49}
50
51BOOST_AUTO_TEST_CASE(expected_error)
52{
54 BOOST_CHECK(e.has_value());
55
56 e = Unexpected{"fail"};
57 BOOST_CHECK(!e.has_value());
58 BOOST_CHECK(!static_cast<bool>(e));
59 BOOST_CHECK(e.error() == "fail");
60
61 // modify error
62 e.error() += "1";
63
64 const auto& read{e};
65 BOOST_CHECK(read.error() == "fail1");
66}
67
The util::Expected class provides a standard way for low-level functions to return either error value...
Definition: expected.h:34
ValueType value_or(U &&default_value) const &
Definition: expected.h:62
The util::Unexpected class represents an unexpected value stored in util::Expected.
Definition: expected.h:21
BOOST_AUTO_TEST_SUITE_END()
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
BOOST_AUTO_TEST_CASE(expected_value)