File: ostream_capture.h

package info (click to toggle)
opentelemetry-cpp 1.23.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,372 kB
  • sloc: cpp: 96,239; sh: 1,766; makefile: 36; python: 31
file content (60 lines) | stat: -rw-r--r-- 1,304 bytes parent folder | download | duplicates (4)
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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

#pragma once

#include <iostream>
#include <sstream>
#include <string>

OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace ostream
{
namespace test
{
/**
 * The OStreamCapture captures from the specified stream for its lifetime
 */
class OStreamCapture
{
public:
  /**
   * Create a OStreamCapture which will capture the output of the ostream that it was constructed
   * with for the lifetime of the instance.
   */
  OStreamCapture(std::ostream &ostream) : stream_(ostream), buf_(ostream.rdbuf())
  {
    stream_.rdbuf(captured_.rdbuf());
  }

  ~OStreamCapture() { stream_.rdbuf(buf_); }

  /**
   * Returns the captured data from the stream.
   */
  std::string GetCaptured() const { return captured_.str(); }

private:
  std::ostream &stream_;
  std::streambuf *buf_;
  std::stringstream captured_;
};

/**
 * Helper method to invoke the passed func while recording the output of the specified stream and
 * return the output afterwards.
 */
template <typename Func>
std::string WithOStreamCapture(std::ostream &stream, Func func)
{
  OStreamCapture capture(stream);
  func();
  return capture.GetCaptured();
}

}  // namespace test
}  // namespace ostream
}  // namespace exporter
OPENTELEMETRY_END_NAMESPACE