Click here to Skip to main content
13,150,622 members (44,745 online)
Click here to Skip to main content
Add your own
alternative version

Stats

4.2K views
3 bookmarked
Posted 20 Jun 2016

Redirecting std::clog to Test Framework Output

, 20 Jun 2016
Rate this:
Please Sign up or sign in to vote.
Wrap writing to the test logger with std::streambuf then substitute in std::clog

Introduction

You may have code that usually writes to std::cout, etc. but is lost in when using a test framework. This tip extracts some code from my article on using Gherkin DSL to show how a test frameworks' logging function can be wrapped and substituted into std::clog, std::cout, etc. to enhance the test log.

The Wrapper

The content of LogStream.h is a class containing a buffer and two overloaded functions:

#pragma once

#include "stdafx.h"
#include "CppUnitTest.h"

#include <vector>

namespace TestUtils
{
    class LogStream : public std::streambuf
    {
        std::vector<char> buffer;

        int_type overflow(int_type ch)
        {
            if (ch != traits_type::eof())
                buffer.push_back(ch);
            return ch;
        }

        int sync()
        {
            if (buffer.back() == '\n')
                buffer.pop_back();
            buffer.emplace_back('\0');
            Microsoft::VisualStudio::CppUnitTestFramework::Logger::WriteMessage(&buffer[0]);
            buffer.clear();
            return 0;
        }
    };
}

Usage

// Initialise then swap
newBuffer = std::make_shared<TestUtils::LogStream>();
oldBuffer = std::clog.rdbuf(newBuffer.get());
std::clog << "Entering Tests" << std::endl;

// Run the tests
// ...

// Swap and free
std::clog << "Exiting Tests" << std::endl;
std::clog.rdbuf(oldBuffer);
newBuffer = nullptr;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Zebedee Mason
United Kingdom United Kingdom
Mathematician turned freelance Software Engineer with over 20 years experience, mainly in the development of CAD/CAM/CAE software. Generally worked for smaller businesses - although have been at Lloyd's Register, Siemens and Rolls-Royce. Enjoy living on the edge of the Peak District where I go cycling and hiking.

You may also be interested in...

Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170924.2 | Last Updated 20 Jun 2016
Article Copyright 2016 by Zebedee Mason
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid