Read-only mirrors. Development, issues and pull requests are on GitHub.

summaryrefslogtreecommitdiffhomepage
path: root/src/Progmasoft/Catch3/Internal/OutputRedirect.hpp
blob: 4d9df38484d8e2abb9989e90543c51fead2d193d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

//              Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
//   (See accompanying file LICENSE.txt or copy at
//        https://www.boost.org/LICENSE_1_0.txt)

// SPDX-License-Identifier: BSL-1.0
#pragma once

#include <Progmasoft/Catch3/Internal/UniquePtr.hpp>

#include <cassert>
#include <string>

namespace Catch {

    class OutputRedirect {
        bool m_redirectActive = false;
        virtual void activateImpl() = 0;
        virtual void deactivateImpl() = 0;
    public:
        enum Kind {
            //! No redirect (noop implementation)
            None,
            //! Redirect std::cout/std::cerr/std::clog streams internally
            Streams,
            //! Redirect the stdout/stderr file descriptors into files
            FileDescriptors,
        };

        virtual ~OutputRedirect(); // = default;

        // TODO: Do we want to check that redirect is not active before retrieving the output?
        virtual std::string getStdout() = 0;
        virtual std::string getStderr() = 0;
        virtual void clearBuffers() = 0;
        bool isActive() const { return m_redirectActive; }
        void activate() {
            assert( !m_redirectActive && "redirect is already active" );
            activateImpl();
            m_redirectActive = true;
        }
        void deactivate() {
            assert( m_redirectActive && "redirect is not active" );
            deactivateImpl();
            m_redirectActive = false;
        }
    };

    bool isRedirectAvailable( OutputRedirect::Kind kind);
    Detail::unique_ptr<OutputRedirect> makeOutputRedirect( bool actual );

    class RedirectGuard {
        OutputRedirect* m_redirect;
        bool m_activate;
        bool m_previouslyActive;
        bool m_moved = false;

    public:
        RedirectGuard( bool activate, OutputRedirect& redirectImpl );
        ~RedirectGuard() noexcept( false );

        RedirectGuard( RedirectGuard const& ) = delete;
        RedirectGuard& operator=( RedirectGuard const& ) = delete;

        // C++14 needs move-able guards to return them from functions
        RedirectGuard( RedirectGuard&& rhs ) noexcept;
        RedirectGuard& operator=( RedirectGuard&& rhs ) noexcept;
    };

    RedirectGuard scopedActivate( OutputRedirect& redirectImpl );
    RedirectGuard scopedDeactivate( OutputRedirect& redirectImpl );

} // end namespace Catch