test_raw_ostream.h 1.1 KB

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