From c8941cccb592a58b4bfaff97abf114fecab64edc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ho=C5=99e=C5=88ovsk=C3=BD?= Date: Sun, 8 Jul 2018 13:35:40 +0200 Subject: [PATCH] Add an example on providing streams with `CATCH_CONFIG_NOSTDOUT` Related to #1037 Closes #1290 --- docs/list-of-examples.md | 2 +- examples/231-Cfg-OutputStreams.cpp | 49 ++++++++++++++++++++++++++++++ examples/CMakeLists.txt | 1 + 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 examples/231-Cfg-OutputStreams.cpp diff --git a/docs/list-of-examples.md b/docs/list-of-examples.md index 81f5a903..e1725a86 100644 --- a/docs/list-of-examples.md +++ b/docs/list-of-examples.md @@ -10,7 +10,7 @@ - Fixture: [Class-based fixtures](../examples/110-Fix-ClassFixture.cpp) - BDD: [SCENARIO, GIVEN, WHEN, THEN](../examples/120-Bdd-ScenarioGivenWhenThen.cpp) - Listener: [Listeners](../examples/210-Evt-EventListeners.cpp) - +- Configuration: [Provide your own output streams](../examples/231-Cfg-OutputStreams.cpp) ## Planned diff --git a/examples/231-Cfg-OutputStreams.cpp b/examples/231-Cfg-OutputStreams.cpp new file mode 100644 index 00000000..efa99971 --- /dev/null +++ b/examples/231-Cfg-OutputStreams.cpp @@ -0,0 +1,49 @@ +// 231-Cfg-OutputStreams.cpp +// Show how to replace the streams with a simple custom made streambuf. + +// Note that this reimplementation _does not_ follow `std::cerr` +// semantic, because it buffers the output. For most uses however, +// there is no important difference between having `std::cerr` buffered +// or unbuffered. + +#define CATCH_CONFIG_NOSTDOUT +#define CATCH_CONFIG_MAIN +#include + +class out_buff : public std::stringbuf { + std::FILE* m_stream; +public: + out_buff(std::FILE* stream) :m_stream(stream) {} + ~out_buff() { pubsync(); } + int sync() { + int ret = 0; + for (unsigned char c : str()) { + if (putc(c, m_stream) == EOF) { + ret = -1; + break; + } + } + // Reset the buffer to avoid printing it multiple times + str(""); + return ret; + } +}; + +namespace Catch { + std::ostream& cout() { + static std::ostream ret(new out_buff(stdout)); + return ret; + } + std::ostream& clog() { + static std::ostream ret(new out_buff(stderr)); + return ret; + } + std::ostream& cerr() { + return clog(); + } +} + + +TEST_CASE("This binary uses putc to write out output", "[compilation-only]") { + SUCCEED("Nothing to test."); +} diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 72d04763..5c471b4f 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -17,6 +17,7 @@ set( HEADER_DIR ${CATCH_DIR}/single_include ) set( SOURCES_SINGLE_FILE 010-TestCase.cpp + 231-Cfg-OutputStreams.cpp ) # multiple-file modules: