/ src / test / util / common.h
common.h
 1  // Copyright (c) The Bitcoin Core developers
 2  // Distributed under the MIT software license, see the accompanying
 3  // file COPYING or https://www.opensource.org/licenses/mit-license.php.
 4  
 5  #ifndef BITCOIN_TEST_UTIL_COMMON_H
 6  #define BITCOIN_TEST_UTIL_COMMON_H
 7  
 8  #include <ostream>
 9  #include <optional>
10  #include <string>
11  
12  /**
13   * BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
14   * Use as
15   * BOOST_CHECK_EXCEPTION(code that throws, exception type, HasReason("foo"));
16   */
17  class HasReason
18  {
19  public:
20      explicit HasReason(std::string_view reason) : m_reason(reason) {}
21      bool operator()(std::string_view s) const { return s.find(m_reason) != std::string_view::npos; }
22      bool operator()(const std::exception& e) const { return (*this)(e.what()); }
23  
24  private:
25      const std::string m_reason;
26  };
27  
28  // Make types usable in BOOST_CHECK_* @{
29  namespace std {
30  template <typename T> requires std::is_enum_v<T>
31  inline std::ostream& operator<<(std::ostream& os, const T& e)
32  {
33      return os << static_cast<std::underlying_type_t<T>>(e);
34  }
35  
36  template <typename T>
37  inline std::ostream& operator<<(std::ostream& os, const std::optional<T>& v)
38  {
39      return v ? os << *v
40               : os << "std::nullopt";
41  }
42  } // namespace std
43  
44  template <typename T>
45  concept HasToString = requires(const T& t) { t.ToString(); };
46  
47  template <HasToString T>
48  inline std::ostream& operator<<(std::ostream& os, const T& obj)
49  {
50      return os << obj.ToString();
51  }
52  
53  // @}
54  
55  #endif // BITCOIN_TEST_UTIL_COMMON_H