platform_system_core/init/result_test.cpp
Tom Cherry 62ca663475 init: introduce Result<T> for return values and error handling
init tries to propagate error information up to build context before
logging errors.  This is a good thing, however too often init has the
overly verbose paradigm for error handling, below:

bool CalculateResult(const T& input, U* output, std::string* err)

bool CalculateAndUseResult(const T& input, std::string* err) {
  U output;
  std::string calculate_result_err;
  if (!CalculateResult(input, &output, &calculate_result_err)) {
    *err = "CalculateResult " + input + " failed: " +
      calculate_result_err;
      return false;
  }
  UseResult(output);
  return true;
}

Even more common are functions that return only true/false but also
require passing a std::string* err in order to see the error message.

This change introduces a Result<T> that is use to either hold a
successful return value of type T or to hold an error message as a
std::string.  If the functional only returns success or a failure with
an error message, Result<Success> may be used.  The classes Error and
ErrnoError are used to indicate a failed Result<T>.

A successful Result<T> is constructed implicitly from any type that
can be implicitly converted to T or from the constructor arguments for
T.  This allows you to return a type T directly from a function that
returns Result<T>.

Error and ErrnoError are used to construct a Result<T> has
failed. Each of these classes take an ostream as an input and are
implicitly cast to a Result<T> containing that failure.  ErrnoError()
additionally appends ": " + strerror(errno) to the end of  the failure
string to aid in interacting with C APIs.

The end result is that the above code snippet is turned into the much
clearer example below:

Result<U> CalculateResult(const T& input);

Result<Success> CalculateAndUseResult(const T& input) {
  auto output = CalculateResult(input);
  if (!output) {
    return Error() << "CalculateResult " << input << " failed: "
                   << output.error();
  }
  UseResult(*output);
  return Success();
}

This change also makes this conversion for some of the util.cpp
functions that used the old paradigm.

Test: boot bullhead, init unit tests
Change-Id: I1e7d3a8820a79362245041251057fbeed2f7979b
2017-08-14 10:26:57 -07:00

222 lines
7.1 KiB
C++

/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "result.h"
#include "errno.h"
#include <string>
#include <gtest/gtest.h>
using namespace std::string_literals;
namespace android {
namespace init {
TEST(result, result_accessors) {
Result<std::string> result = "success";
ASSERT_TRUE(result);
ASSERT_TRUE(result.has_value());
EXPECT_EQ("success", *result);
EXPECT_EQ("success", result.value());
EXPECT_EQ('s', result->data()[0]);
}
TEST(result, result_accessors_rvalue) {
ASSERT_TRUE(Result<std::string>("success"));
ASSERT_TRUE(Result<std::string>("success").has_value());
EXPECT_EQ("success", *Result<std::string>("success"));
EXPECT_EQ("success", Result<std::string>("success").value());
EXPECT_EQ('s', Result<std::string>("success")->data()[0]);
}
TEST(result, result_success) {
Result<Success> result = Success();
ASSERT_TRUE(result);
ASSERT_TRUE(result.has_value());
EXPECT_EQ(Success(), *result);
EXPECT_EQ(Success(), result.value());
}
TEST(result, result_success_rvalue) {
// Success() doesn't actually create a Result<Success> object, but rather an object that can be
// implicitly constructed into a Result<Success> object.
auto MakeRvalueSuccessResult = []() -> Result<Success> { return Success(); };
ASSERT_TRUE(MakeRvalueSuccessResult());
ASSERT_TRUE(MakeRvalueSuccessResult().has_value());
EXPECT_EQ(Success(), *MakeRvalueSuccessResult());
EXPECT_EQ(Success(), MakeRvalueSuccessResult().value());
}
TEST(result, result_error) {
Result<Success> result = Error() << "failure" << 1;
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
EXPECT_EQ("failure1", result.error());
}
TEST(result, result_error_empty) {
Result<Success> result = Error();
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
EXPECT_EQ("", result.error());
}
TEST(result, result_error_rvalue) {
// Error() and ErrnoError() aren't actually used to create a Result<T> object.
// Under the hood, they are an intermediate class that can be implicitly constructed into a
// Result<T>. This is needed both to create the ostream and because Error() itself, by
// definition will not know what the type, T, of the underlying Result<T> object that it would
// create is.
auto MakeRvalueErrorResult = []() -> Result<Success> { return Error() << "failure" << 1; };
ASSERT_FALSE(MakeRvalueErrorResult());
ASSERT_FALSE(MakeRvalueErrorResult().has_value());
EXPECT_EQ("failure1", MakeRvalueErrorResult().error());
}
TEST(result, result_errno_error) {
constexpr int test_errno = 6;
errno = test_errno;
Result<Success> result = ErrnoError() << "failure" << 1;
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
EXPECT_EQ("failure1: "s + strerror(test_errno), result.error());
}
TEST(result, constructor_forwarding) {
auto result = Result<std::string>(5, 'a');
ASSERT_TRUE(result);
ASSERT_TRUE(result.has_value());
EXPECT_EQ("aaaaa", *result);
}
struct ConstructorTracker {
static size_t constructor_called;
static size_t copy_constructor_called;
static size_t move_constructor_called;
static size_t copy_assignment_called;
static size_t move_assignment_called;
template <typename T>
ConstructorTracker(T&& string) : string(string) {
++constructor_called;
}
ConstructorTracker(const ConstructorTracker& ct) {
++copy_constructor_called;
string = ct.string;
}
ConstructorTracker(ConstructorTracker&& ct) noexcept {
++move_constructor_called;
string = std::move(ct.string);
}
ConstructorTracker& operator=(const ConstructorTracker& ct) {
++copy_assignment_called;
string = ct.string;
return *this;
}
ConstructorTracker& operator=(ConstructorTracker&& ct) noexcept {
++move_assignment_called;
string = std::move(ct.string);
return *this;
}
std::string string;
};
size_t ConstructorTracker::constructor_called = 0;
size_t ConstructorTracker::copy_constructor_called = 0;
size_t ConstructorTracker::move_constructor_called = 0;
size_t ConstructorTracker::copy_assignment_called = 0;
size_t ConstructorTracker::move_assignment_called = 0;
Result<ConstructorTracker> ReturnConstructorTracker(const std::string& in) {
if (in.empty()) {
return "literal string";
}
if (in == "test2") {
return ConstructorTracker(in + in + "2");
}
ConstructorTracker result(in + " " + in);
return result;
};
TEST(result, no_copy_on_return) {
// If returning parameters that may be used to implicitly construct the type T of Result<T>,
// then those parameters are forwarded to the construction of Result<T>.
// If returning an prvalue or xvalue, it will be move constructed during the construction of
// Result<T>.
// This check ensures that that is the case, and particularly that no copy constructors
// are called.
auto result1 = ReturnConstructorTracker("");
ASSERT_TRUE(result1);
EXPECT_EQ("literal string", result1->string);
EXPECT_EQ(1U, ConstructorTracker::constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
EXPECT_EQ(0U, ConstructorTracker::move_constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
auto result2 = ReturnConstructorTracker("test2");
ASSERT_TRUE(result2);
EXPECT_EQ("test2test22", result2->string);
EXPECT_EQ(2U, ConstructorTracker::constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
EXPECT_EQ(1U, ConstructorTracker::move_constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
auto result3 = ReturnConstructorTracker("test3");
ASSERT_TRUE(result3);
EXPECT_EQ("test3 test3", result3->string);
EXPECT_EQ(3U, ConstructorTracker::constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
EXPECT_EQ(2U, ConstructorTracker::move_constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
}
TEST(result, die_on_access_failed_result) {
Result<std::string> result = Error();
ASSERT_DEATH(*result, "");
}
TEST(result, die_on_get_error_succesful_result) {
Result<std::string> result = "success";
ASSERT_DEATH(result.error(), "");
}
} // namespace init
} // namespace android