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