aboutsummaryrefslogtreecommitdiff
path: root/pw_unit_test
diff options
context:
space:
mode:
authorCarlos Chinchilla <cachinchilla@google.com>2023-11-06 22:21:49 +0000
committerCQ Bot Account <pigweed-scoped@luci-project-accounts.iam.gserviceaccount.com>2023-11-06 22:21:49 +0000
commit741063cb923f5794b3724d10e1968dcb1e72bc84 (patch)
tree2732c42cbbc7e7a387f8e9e50947d4df1d338e2e /pw_unit_test
parentf84b844862813d4989e0ca5f5968912b6bae2b3e (diff)
downloadpigweed-741063cb923f5794b3724d10e1968dcb1e72bc84.tar.gz
pw_unit_test: Add more googletest test matchers
Add googletest test matchers to make it easy to assert and assign in unit tests, as well as verifying the internal values of result objects. Change-Id: I21910fff4b85161b00fe3745d346b14196a37109 Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/179151 Pigweed-Auto-Submit: Carlos Chinchilla <cachinchilla@google.com> Commit-Queue: Auto-Submit <auto-submit@pigweed-service-accounts.iam.gserviceaccount.com> Reviewed-by: Taylor Cramer <cramertj@google.com>
Diffstat (limited to 'pw_unit_test')
-rw-r--r--pw_unit_test/docs.rst6
-rw-r--r--pw_unit_test/googletest_test_matchers_test.cc49
-rw-r--r--pw_unit_test/public/pw_unit_test/googletest_test_matchers.h148
3 files changed, 202 insertions, 1 deletions
diff --git a/pw_unit_test/docs.rst b/pw_unit_test/docs.rst
index 0f89e76b5..ee7c1093b 100644
--- a/pw_unit_test/docs.rst
+++ b/pw_unit_test/docs.rst
@@ -40,7 +40,11 @@ pw_unit_test implements a subset of GoogleTest. Supported features include:
* Test and test suite declarations.
* Most ``EXPECT`` and ``ASSERT`` macros, including ``EXPECT_OK`` and
``ASSERT_OK`` for functions returning a status.
-* ``StatusIs`` matcher to expect a specific ``pw::Status`` other that `OK`.
+* ``ASSERT_OK_AND_ASSIGN`` to test assigning a value when status is ``OK`` or
+ fail the test.
+* ``StatusIs`` matcher to expect a specific ``pw::Status`` other that ``OK``.
+* ``IsOkAndHolds`` matcher to expect an object's status is ``OK`` and the value
+ matches an expected value.
* Stream-style expectation messages, such as
``EXPECT_EQ(val, 5) << "Inputs: " << input``. Messages are currently ignored.
diff --git a/pw_unit_test/googletest_test_matchers_test.cc b/pw_unit_test/googletest_test_matchers_test.cc
index c7f8fde3e..58d7a5bdf 100644
--- a/pw_unit_test/googletest_test_matchers_test.cc
+++ b/pw_unit_test/googletest_test_matchers_test.cc
@@ -20,6 +20,9 @@
namespace pw::unit_test {
namespace {
+using ::testing::Eq;
+using ::testing::Not;
+
TEST(TestMatchers, AssertOk) { ASSERT_OK(OkStatus()); }
TEST(TestMatchers, AssertOkStatusWithSize) { ASSERT_OK(StatusWithSize(123)); }
TEST(TestMatchers, AssertOkResult) { ASSERT_OK(Result<int>(123)); }
@@ -112,6 +115,52 @@ TEST(TestMatchers, StatusIsSuccessResult) {
StatusIs(Status::Unauthenticated()));
}
+TEST(IsOkAndHoldsTest, StatusWithSize) {
+ const auto status_with_size = StatusWithSize{OkStatus(), 42};
+ EXPECT_THAT(status_with_size, IsOkAndHolds(Eq(42u)));
+}
+
+TEST(IsOkAndHoldsTest, Result) {
+ auto value = Result<int>{42};
+ EXPECT_THAT(value, IsOkAndHolds(Eq(42)));
+}
+
+TEST(IsOkAndHoldsTest, BadStatusWithSize) {
+ const auto status_with_size = StatusWithSize{Status::InvalidArgument(), 0};
+ EXPECT_THAT(status_with_size, Not(IsOkAndHolds(Eq(42u))));
+}
+
+TEST(IsOkAndHoldsTest, WrongStatusWithSize) {
+ const auto status_with_size = StatusWithSize{OkStatus(), 100};
+ EXPECT_THAT(status_with_size, IsOkAndHolds(Not(Eq(42u))));
+ EXPECT_THAT(status_with_size, Not(IsOkAndHolds(Eq(42u))));
+}
+
+TEST(IsOkAndHoldsTest, BadResult) {
+ const auto value = Result<int>{Status::InvalidArgument()};
+ EXPECT_THAT(value, Not(IsOkAndHolds(Eq(42))));
+}
+
+TEST(IsOkAndHoldsTest, WrongResult) {
+ const auto value = Result<int>{100};
+ EXPECT_THAT(value, IsOkAndHolds(Not(Eq(42))));
+ EXPECT_THAT(value, Not(IsOkAndHolds(Eq(42))));
+}
+
+TEST(AssertOkAndAssignTest, OkResult) {
+ const auto value = Result<int>(5);
+
+ int existing_value = 0;
+ ASSERT_OK_AND_ASSIGN(existing_value, value);
+ EXPECT_EQ(5, existing_value);
+
+ ASSERT_OK_AND_ASSIGN(int declare_and_assign, value);
+ EXPECT_EQ(5, declare_and_assign);
+
+ ASSERT_OK_AND_ASSIGN(auto& declare_auto_ref_and_assign, value);
+ EXPECT_EQ(5, declare_auto_ref_and_assign);
+}
+
// The following test is commented out and is only for checking what
// failure cases would look like. For example, when uncommenting the test,
// the output is:
diff --git a/pw_unit_test/public/pw_unit_test/googletest_test_matchers.h b/pw_unit_test/public/pw_unit_test/googletest_test_matchers.h
index bb912c389..dfc1be45c 100644
--- a/pw_unit_test/public/pw_unit_test/googletest_test_matchers.h
+++ b/pw_unit_test/public/pw_unit_test/googletest_test_matchers.h
@@ -37,6 +37,22 @@ inline constexpr Status GetStatus(const Result<T>& result) {
return result.status();
}
+// Gets the value of an object whose value is guarded by a ``pw::OkStatus()``.
+// Used by Matchers.
+constexpr size_t GetValue(StatusWithSize status_with_size) {
+ return status_with_size.size();
+}
+
+template <typename V>
+constexpr const V& GetValue(const Result<V>& result) {
+ return result.value();
+}
+
+template <typename V>
+constexpr V GetValue(Result<V>&& result) {
+ return std::move(result).value();
+}
+
// Implements IsOk().
class IsOkMatcher {
public:
@@ -58,6 +74,78 @@ class IsOkMatcher {
}
};
+// Implements IsOkAndHolds(m) as a monomorphic matcher.
+template <typename StatusType>
+class IsOkAndHoldsMatcherImpl {
+ public:
+ using is_gtest_matcher = void;
+ using ValueType = decltype(GetValue(std::declval<StatusType>()));
+
+ // NOLINTBEGIN(bugprone-forwarding-reference-overload)
+ template <typename InnerMatcher>
+ explicit IsOkAndHoldsMatcherImpl(InnerMatcher&& inner_matcher)
+ : inner_matcher_(::testing::SafeMatcherCast<const ValueType&>(
+ std::forward<InnerMatcher>(inner_matcher))) {}
+ // NOLINTEND(bugprone-forwarding-reference-overload)
+
+ void DescribeTo(std::ostream* os) const {
+ *os << "is OK and has a value that ";
+ inner_matcher_.DescribeTo(os);
+ }
+
+ void DescribeNegationTo(std::ostream* os) const {
+ *os << "isn't OK or has a value that ";
+ inner_matcher_.DescribeNegationTo(os);
+ }
+
+ bool MatchAndExplain(const StatusType& actual_value,
+ ::testing::MatchResultListener* listener) const {
+ const auto& status = GetStatus(actual_value);
+ if (!status.ok()) {
+ *listener << "which has status " << pw_StatusString(status);
+ return false;
+ }
+
+ const auto& value = GetValue(actual_value);
+ *listener << "which contains value " << ::testing::PrintToString(value);
+
+ ::testing::StringMatchResultListener inner_listener;
+ const bool matches = inner_matcher_.MatchAndExplain(value, &inner_listener);
+ const std::string inner_explanation = inner_listener.str();
+ if (!inner_explanation.empty()) {
+ *listener << ", " << inner_explanation;
+ }
+
+ return matches;
+ }
+
+ private:
+ const ::testing::Matcher<const ValueType&> inner_matcher_;
+};
+
+// Implements IsOkAndHolds(m) as a polymorphic matcher.
+//
+// We have to manually create it as a class instead of using the
+// `::testing::MakePolymorphicMatcher()` helper because of the custom conversion
+// to Matcher<T>.
+template <typename InnerMatcher>
+class IsOkAndHoldsMatcher {
+ public:
+ explicit IsOkAndHoldsMatcher(InnerMatcher inner_matcher)
+ : inner_matcher_(std::move(inner_matcher)) {}
+
+ // NOLINTBEGIN(google-explicit-constructor)
+ template <typename StatusType>
+ operator ::testing::Matcher<StatusType>() const {
+ return ::testing::Matcher<StatusType>(
+ internal::IsOkAndHoldsMatcherImpl<const StatusType&>(inner_matcher_));
+ }
+ // NOLINTEND(google-explicit-constructor)
+
+ private:
+ const InnerMatcher inner_matcher_;
+};
+
// Implements StatusIs().
class StatusIsMatcher {
public:
@@ -105,4 +193,64 @@ inline auto StatusIs(Status expected_status) {
internal::StatusIsMatcher(expected_status));
}
+/// Returns a gMock matcher that matches a `pw::StatusWithSize` or
+/// `pw::Result<T>` (for any T) which is OK and holds a value matching the inner
+/// matcher.
+template <typename InnerMatcher>
+inline internal::IsOkAndHoldsMatcher<InnerMatcher> IsOkAndHolds(
+ InnerMatcher&& inner_matcher) {
+ return internal::IsOkAndHoldsMatcher<InnerMatcher>(
+ std::forward<InnerMatcher>(inner_matcher));
+}
+
+/// Executes an expression that returns a `pw::Result` or `pw::StatusWithSize`
+/// and assigns or moves that value to lhs if the error code is OK. If the
+// status is non-OK, generates a test failure and returns from the current
+/// function, which must have a void return type.
+///
+/// The MOVE variant moves the content out of the `pw::Result` and into lhs.
+/// This variant is required for move-only types.
+//
+/// Example: Declaring and initializing a new value. E.g.:
+/// ASSERT_OK_AND_ASSIGN(auto value, MaybeGetValue(arg));
+/// ASSERT_OK_AND_ASSIGN(const ValueType& value, MaybeGetValue(arg));
+/// ASSERT_OK_AND_MOVE(auto ptr, MaybeGetUniquePtr(arg))
+///
+/// Example: Assigning to an existing value
+/// ValueType value;
+/// ASSERT_OK_AND_ASSIGN(value, MaybeGetValue(arg));
+///
+/// The value assignment example would expand into something like:
+/// auto status_or_value = MaybeGetValue(arg);
+/// ASSERT_OK(status_or_value.status());
+/// value = status_or_value.ValueOrDie();
+///
+/// WARNING: ASSERT_OK_AND_ASSIGN (and the move variant) expand into multiple
+/// statements; it cannot be used in a single statement (e.g. as the body of
+/// an if statement without {})!
+#define ASSERT_OK_AND_ASSIGN(lhs, rexpr) \
+ ASSERT_OK_AND_ASSIGN_DETAIL(UNIQUE_IDENTIFIER_DETAIL(__LINE__), lhs, rexpr)
+#define ASSERT_OK_AND_MOVE(lhs, rexpr) \
+ ASSERT_OK_AND_MOVE_DETAIL(UNIQUE_IDENTIFIER_DETAIL(__LINE__), lhs, rexpr)
+
+// NOLINTBEGIN(bugprone-macro-parentheses)
+// The suggestion would produce bad code.
+#define ASSERT_OK_AND_ASSIGN_DETAIL(result, lhs, rexpr) \
+ const auto& result = (rexpr); \
+ if (!result.ok()) { \
+ FAIL() << #rexpr << " is not OK."; \
+ } \
+ lhs = ::pw::unit_test::internal::GetValue(result);
+#define ASSERT_OK_AND_MOVE_DETAIL(result, lhs, rexpr) \
+ auto&& result = (rexpr); \
+ if (!result.ok()) { \
+ FAIL() << #rexpr << " is not OK."; \
+ } \
+ lhs = ::pw::unit_test::internal::GetValue(std::move(result));
+// NOLINTEND(bugprone-macro-parentheses)
+
+#define UNIQUE_IDENTIFIER_DETAIL(line) UNIQUE_IDENTIFIER_EXPANDED_DETAIL(line)
+#define UNIQUE_IDENTIFIER_EXPANDED_DETAIL(line) \
+ _assert_ok_and_assign_unique_name_##line
+
} // namespace pw::unit_test \ No newline at end of file