diff --git a/src/libutil-test-support/include/nix/util/tests/gmock-matchers.hh b/src/libutil-test-support/include/nix/util/tests/gmock-matchers.hh new file mode 100644 index 000000000..27d765e9e --- /dev/null +++ b/src/libutil-test-support/include/nix/util/tests/gmock-matchers.hh @@ -0,0 +1,56 @@ +#pragma once +///@file + +#include "nix/util/terminal.hh" +#include + +namespace nix::testing { + +namespace internal { + +/** + * GMock matcher that matches substring while stripping off all ANSI escapes. + * Useful for checking exceptions messages in unit tests. + */ +class HasSubstrIgnoreANSIMatcher +{ +public: + explicit HasSubstrIgnoreANSIMatcher(std::string substring) + : substring(std::move(substring)) + { + } + + bool MatchAndExplain(const char * s, ::testing::MatchResultListener * listener) const + { + return s != nullptr && MatchAndExplain(std::string(s), listener); + } + + template + bool MatchAndExplain(const MatcheeStringType & s, [[maybe_unused]] ::testing::MatchResultListener * listener) const + { + return filterANSIEscapes(s, /*filterAll=*/true).find(substring) != substring.npos; + } + + void DescribeTo(::std::ostream * os) const + { + *os << "has substring " << substring; + } + + void DescribeNegationTo(::std::ostream * os) const + { + *os << "has no substring " << substring; + } + +private: + std::string substring; +}; + +} // namespace internal + +inline ::testing::PolymorphicMatcher +HasSubstrIgnoreANSIMatcher(const std::string & substring) +{ + return ::testing::MakePolymorphicMatcher(internal::HasSubstrIgnoreANSIMatcher(substring)); +} + +} // namespace nix::testing diff --git a/src/libutil-test-support/include/nix/util/tests/meson.build b/src/libutil-test-support/include/nix/util/tests/meson.build index f77dedff7..e6697b517 100644 --- a/src/libutil-test-support/include/nix/util/tests/meson.build +++ b/src/libutil-test-support/include/nix/util/tests/meson.build @@ -4,6 +4,7 @@ include_dirs = [include_directories('../../..')] headers = files( 'characterization.hh', + 'gmock-matchers.hh', 'gtest-with-params.hh', 'hash.hh', 'nix_api_util.hh',