Question

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.

Was it helpful?

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.

OTHER TIPS

Well, I just think I've found a working way myself :

import std.stdio;
import std.conv;
import std.file;

//

string getOutput()
{
     auto initialStdout = stdout;

     // Redirect output to file
     string tmpfile = "tmp/test.out";
     stdout.open(tmpfile, "wt");

     //
     // Do whatever you want to,
     // that generates some output
     //

     stdout = initialStdout; // Restore stdout to what it was

     return to!string(std.file.read(tmpfile)); // Return output
}

Simply use std.process.executeShell . The example from the Phobos documentation is good enough for you to do what you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top