ColourImpl.tests.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright Catch2 Authors
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // https://www.boost.org/LICENSE_1_0.txt)
  5. // SPDX-License-Identifier: BSL-1.0
  6. #include <catch2/catch_test_macros.hpp>
  7. #include <catch2/internal/catch_console_colour.hpp>
  8. #include <catch2/internal/catch_istream.hpp>
  9. #include <sstream>
  10. namespace {
  11. class TestColourImpl : public Catch::ColourImpl {
  12. using Catch::ColourImpl::ColourImpl;
  13. // Inherited via ColourImpl
  14. void use( Catch::Colour::Code colourCode ) const override {
  15. m_stream->stream() << "Using code: " << colourCode << '\n';
  16. }
  17. };
  18. class TestStringStream : public Catch::IStream {
  19. std::stringstream m_stream;
  20. public:
  21. std::ostream& stream() override {
  22. return m_stream;
  23. }
  24. std::string str() const { return m_stream.str(); }
  25. };
  26. }
  27. TEST_CASE("ColourGuard behaviour", "[console-colours]") {
  28. TestStringStream streamWrapper;
  29. TestColourImpl colourImpl( &streamWrapper );
  30. auto& stream = streamWrapper.stream();
  31. SECTION("ColourGuard is disengaged by default") {
  32. { auto guard = colourImpl.guardColour( Catch::Colour::Red ); }
  33. REQUIRE( streamWrapper.str().empty() );
  34. }
  35. SECTION("ColourGuard is engaged by op<<") {
  36. stream << "1\n" << colourImpl.guardColour( Catch::Colour::Red ) << "2\n";
  37. stream << "3\n";
  38. REQUIRE( streamWrapper.str() == "1\nUsing code: 2\n2\nUsing code: 0\n3\n" );
  39. }
  40. SECTION("ColourGuard can be engaged explicitly") {
  41. {
  42. auto guard =
  43. colourImpl.guardColour( Catch::Colour::Red ).engage( stream );
  44. stream << "A\n"
  45. << "B\n";
  46. }
  47. stream << "C\n";
  48. REQUIRE( streamWrapper.str() ==
  49. "Using code: 2\nA\nB\nUsing code: 0\nC\n" );
  50. }
  51. }