istream for testing

Jul 3, 2020 at 2:43am
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?
Jul 3, 2020 at 3:18am
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
Jul 3, 2020 at 4:36am
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
Jul 3, 2020 at 5:26pm
Use a stringstream, you can read/write on it. However, you'll need to synchronise access from different threads.
Jul 7, 2020 at 5:32pm
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 Jul 7, 2020 at 5:35pm
Jul 7, 2020 at 8:39pm
Doesn't boost have something like Java's piped streams?
Jul 7, 2020 at 9:15pm
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 Jul 7, 2020 at 9:17pm
Jul 8, 2020 at 3:22pm
+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.
Jul 11, 2020 at 1:25pm
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.
Jul 11, 2020 at 10:32pm
So use a pipe.
Jul 12, 2020 at 12:29am
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 Jul 12, 2020 at 12:30am
Jul 12, 2020 at 5:15am
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.