Skip to content

Instantly share code, notes, and snippets.

@rioki
Created June 6, 2022 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rioki/5a4267d0a4713241d122c1266cb67208 to your computer and use it in GitHub Desktop.
Save rioki/5a4267d0a4713241d122c1266cb67208 to your computer and use it in GitHub Desktop.
Better Google Test Support for std::optional.
// std gtest comparators
// Copyright 2022 Sean Farrell <sean.farrell@rioki.org>
//
// This program is free software. It comes without any warranty, to
// the extent permitted by applicable law. You can redistribute it
// and/or modify it under the terms of the Do What The Fuck You Want
// To Public License, Version 2, as published by Sam Hocevar. See
// http://www.wtfpl.net/ for more details.
#pragma once
#include <string>
#include <iostream>
#include <sstream>
namespace std
{
template <typename T>
std::ostream& operator << (std::ostream& os, const std::optional<T>& v)
{
if (v)
{
os << *v;
}
else
{
os << "nullopt";
}
return os;
}
}
namespace std::test
{
template <typename T>
bool is_nullopt(const std::optional<T>& v)
{
return v == std::nullopt;
}
template <typename T>
bool is_nullopt(const T& v)
{
return false;
}
template <typename T1, typename T2>
testing::AssertionResult compare_optional(const char* lhs_expression, const char* rhs_expression, const T1& lhs_value, const T2& rhs_value)
{
if (lhs_value == rhs_value)
{
return testing::AssertionSuccess();
}
if (is_nullopt(lhs_value))
{
return testing::AssertionFailure()
<< "The value " << lhs_expression << " is nullopt,"
<< " but the value " << rhs_expression << " has the value " << rhs_value << ".";
}
if (is_nullopt(rhs_value))
{
return testing::AssertionFailure()
<< "The value " << lhs_expression << " has the value " << lhs_value
<< " but the value " << rhs_expression << " is nullopt.";
}
::std::stringstream lhs_ss;
lhs_ss << lhs_value;
::std::stringstream rhs_ss;
rhs_ss << rhs_value;
return testing::internal::EqFailure(lhs_expression,
rhs_expression,
testing::internal::StringStreamToString(&lhs_ss),
testing::internal::StringStreamToString(&rhs_ss),
false);
}
}
#define EXPECT_OPTIONAL_EQ(val1, val2) EXPECT_PRED_FORMAT2(::std::test::compare_optional, val1, val2)
#define ASSERT_OPTIONAL_EQ(val1, val2) ASSERT_PRED_FORMAT2(::std::test::compare_optional, val1, val2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment