test_raw_ostream.h 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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_COMMON_TEST_RAW_OSTREAM_H_
  5. #define CARBON_COMMON_TEST_RAW_OSTREAM_H_
  6. #include <gtest/gtest.h>
  7. #include <string>
  8. #include "common/ostream.h"
  9. namespace Carbon::Testing {
  10. // A raw_ostream that makes it easy to repeatedly check streamed output.
  11. class TestRawOstream : public llvm::raw_string_ostream {
  12. public:
  13. explicit TestRawOstream() : llvm::raw_string_ostream(buffer_) {}
  14. ~TestRawOstream() override {
  15. if (!buffer_.empty()) {
  16. ADD_FAILURE() << "Unchecked output:\n" << buffer_;
  17. }
  18. }
  19. // Flushes the stream and returns the contents so far, clearing the stream
  20. // back to empty.
  21. auto TakeStr() -> std::string {
  22. std::string result = std::move(buffer_);
  23. buffer_.clear();
  24. return result;
  25. }
  26. private:
  27. std::string buffer_;
  28. };
  29. } // namespace Carbon::Testing
  30. #endif // CARBON_COMMON_TEST_RAW_OSTREAM_H_