I try to unittest a terminal output function. The function streams data to stdout, so my idea was to get control of the stdout buffer and to check if the function properly writes the correct data into the buffer.
setvbuf seemed to me to be the ideal thing to achieve this.
I used setvbuf to redirect stdout to use my own specified buffer.
I used streaming mode _IOFBF so that theoretically an internal flush only happens if the buffer is full. BUFSIZ on my system has a size of 8192 bytes ... which is more than big enough for the output of the function under test, without internal flush during invocation.
My source currently looks like :
char buffer [BUFSIZ] = {0};
/* any outputs before redirecting */
printf("0\n");
/* output any remaining data */
fflush(stdout);
/* redirect to my buffer with full buffering */
setvbuf(stdout,buffer,_IOFBF,BUFSIZ);
/* testcode ... output of the function under test */
printf("1\n");
printf("2\n");
/* output any remaining data */
fflush(stdout);
/* restore internal buffering with line buffering */
setvbuf(stdout,NULL,_IOLBF,BUFSIZ);
/* let us see what is in our buffer */
printf("%s",buffer);
Debugging this code shows that "2\n" overwrites "1\n" in the buffer during the testcode section (gcc 5.4.0 x64 GNU libc version: 2.23)
Output is :
0
1
2
2
But I expected :
0
1
2
1
2
I would be appreciated for any hint.