capture_std_streams.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_TESTING_BASE_CAPTURE_STD_STREAMS_H_
  5. #define CARBON_TESTING_BASE_CAPTURE_STD_STREAMS_H_
  6. #include <string>
  7. namespace Carbon::Testing {
  8. // Implementation details.
  9. namespace Internal {
  10. auto BeginStdStreamCapture() -> void;
  11. auto EndStdStreamCapture(std::string& out, std::string& err) -> void;
  12. } // namespace Internal
  13. // Calls the provided function while capturing both `stdout` and `stderr`. The
  14. // `out` and `err` strings are set to whatever is captured after the function
  15. // returns.
  16. //
  17. // Note that any output that is captured will not be visible when running, which
  18. // can make debugging tests that use this routine difficult. Make sure to either
  19. // print back out or otherwise expose any of the contents of the captured output
  20. // that are needed when debugging.
  21. template <typename FnT>
  22. static auto CallWithCapturedOutput(std::string& out, std::string& err,
  23. FnT function) -> auto {
  24. Internal::BeginStdStreamCapture();
  25. auto result = function();
  26. Internal::EndStdStreamCapture(out, err);
  27. return result;
  28. }
  29. } // namespace Carbon::Testing
  30. #endif // CARBON_TESTING_BASE_CAPTURE_STD_STREAMS_H_