ostream_capture.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. #pragma once
  4. #include <iostream>
  5. #include <sstream>
  6. #include <string>
  7. OPENTELEMETRY_BEGIN_NAMESPACE
  8. namespace exporter
  9. {
  10. namespace ostream
  11. {
  12. namespace test
  13. {
  14. /**
  15. * The OStreamCapture captures from the specified stream for its lifetime
  16. */
  17. class OStreamCapture
  18. {
  19. public:
  20. /**
  21. * Create a OStreamCapture which will capture the output of the ostream that it was constructed
  22. * with for the lifetime of the instance.
  23. */
  24. OStreamCapture(std::ostream &ostream) : stream_(ostream), buf_(ostream.rdbuf())
  25. {
  26. stream_.rdbuf(captured_.rdbuf());
  27. }
  28. ~OStreamCapture() { stream_.rdbuf(buf_); }
  29. /**
  30. * Returns the captured data from the stream.
  31. */
  32. std::string GetCaptured() const { return captured_.str(); }
  33. private:
  34. std::ostream &stream_;
  35. std::streambuf *buf_;
  36. std::stringstream captured_;
  37. };
  38. /**
  39. * Helper method to invoke the passed func while recording the output of the specified stream and
  40. * return the output afterwards.
  41. */
  42. template <typename Func>
  43. std::string WithOStreamCapture(std::ostream &stream, Func func)
  44. {
  45. OStreamCapture capture(stream);
  46. func();
  47. return capture.GetCaptured();
  48. }
  49. } // namespace test
  50. } // namespace ostream
  51. } // namespace exporter
  52. OPENTELEMETRY_END_NAMESPACE