istream for testing

I want to unit test my program that reads from istream(cin).

As istream reading is blocking I will run my function in separate thread and I need istream version that is more like a pipe - I can send data/commands from unit test thread so it can be read from app thread.

Is there something like this?
If your interactive program would be tested by typing in manually

1 2
apple red


Then all you need do is put that into a file called say test_input.txt

So your test run would be
prog.exe < test_input.txt > test_output.txt

You can then go further to check your results with
diff expected_output.txt test_output.txt
I use Boost testing framework. therefore it is programmatic. So in my test I will create thread that will start my app, and in main test thread I want send data to input stream that my program will read on other side of the thread, I need something like Piped streams in Java
Use a stringstream, you can read/write on it. However, you'll need to synchronise access from different threads.
I think you can putback() onto it as well, or something like that, so the next time it is read you get what you stuffed onto it. Been a while, these tools may all be one letter at a time so the stream may be much cleaner?
Last edited on
Doesn't boost have something like Java's piped streams?
Boost has asynchronous and non-block I/O streams. Not fully implemented it appears:
https://www.boost.org/doc/libs/1_73_0/libs/iostreams/doc/guide/asynchronous.html
Last edited on
+1 Salem C's comment. Windows and Linux and UNIX and probably any other modern system will let you direct cin to a file or a pipe. Just do it. That's what it's there for.
I tried to use boost device but it is not clear to me how to make it blocking so one thread waits if there is no data till another thread writes. Now reading thread just reads empty string.
So use a pipe.
the stream has a bunch of methods for this stuff. You can see how many chars you read with your cin statement via gcount() and if that is zero, skip it and read again in a bit. It feels like you are doing whatever it is you want to accomplish the hard way, but the tools do exist to do it the hard way.
Last edited on
Why don't you show us the code of the function you want to test?
Maybe there is an easier solution.
Topic archived. No new replies allowed.