Search code examples
stdoutddmd

Reroute stdout to string


OK, so here's what I'm trying to do :

  • A portion of my program outputs text to console
  • For unittest purposes, I'd like to be able to get that output into a string, so that I can use it in an assert check.

How is that possible?


NOTE:

Guys, sorry if I mislead you. I'm looking for a solution in D.


Solution

  • Here is a way to do this using pipes and threads (which, unlike the suggested duplicate, is not limited to a predefined buffer size or risks a buffer overflow vulnerabillity):

    1. Create a pipe using std.process.pipe
    2. Set stdout to the pipe's write end (back it up first)
    3. Spawn a thread which would read from the pipe's read end and append output to a string, until the pipe is closed
    4. Execute the task at hand
    5. Close the write end of the pipe
    6. Restore the old value of stdout
    7. Wait for the thread to finish execution
    8. Use the buffer created by the thread

    I have some similar code, albeit in the other direction (asynchronous writing as opposed to reading), here and here.