Add "consume all captured output" callback to CaptureFD
[folly.git] / folly / experimental / TestUtil.h
index e1bd1b9b59885528d1880f8b148393eea5e04781..3fa6a9f5dac4ea52638ea876040b292713bd0339 100644 (file)
@@ -157,12 +157,22 @@ inline std::string glogErrOrWarnPattern() { return ".*(^|\n)[EW][0-9].*"; }
 
 /**
  * Temporarily capture a file descriptor by redirecting it into a file.
- * You can consume its output either all-at-once or incrementally.
+ * You can consume its entire output thus far via read(), incrementally
+ * via readIncremental(), or via callback using chunk_cob.
  * Great for testing logging (see also glog*Pattern()).
  */
 class CaptureFD {
+private:
+  struct NoOpChunkCob { void operator()(StringPiece) {} };
 public:
-  explicit CaptureFD(int fd);
+  using ChunkCob = std::function<void(folly::StringPiece)>;
+
+  /**
+   * chunk_cob is is guaranteed to consume all the captured output. It is
+   * invoked on each readIncremental(), and also on FD release to capture
+   * as-yet unread lines.  Chunks can be empty.
+   */
+  explicit CaptureFD(int fd, ChunkCob chunk_cob = NoOpChunkCob());
   ~CaptureFD();
 
   /**
@@ -175,7 +185,7 @@ public:
   /**
    * Reads the whole file into a string, but does not remove the redirect.
    */
-  std::string read();
+  std::string read() const;
 
   /**
    * Read any bytes that were appended to the file since the last
@@ -184,6 +194,7 @@ public:
   std::string readIncremental();
 
 private:
+  ChunkCob chunkCob_;
   TemporaryFile file_;
 
   int fd_;