0

If i test functions with glib's testharness, I always face the ugly fact, that the output of the functions I'm testign is mixed with the output of glib's functions. This code:

#include <stdlib.h>
#include <glib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

void to_test(void)
{
  printf("this function is being tested");
}

void test_to_test(void)
{
  to_test();
}

int main(int argc, char *argv[])
{
  g_test_init(&argc, &argv, NULL);

  g_test_add_func("/test", test_to_test);

  return g_test_run();
}

generates:

/test: this function is being testedOK

The only solution I found was redirecting the filedescriptors of standardout/-err to /dev/null for the time the function is called and resetting them afterwards, like:

void test_to_test(void)
{
  int backup, new;
  new = open("/dev/null", O_WRONLY);
  backup = dup(STDOUT_FILENO);
  dup2(new, STDOUT_FILENO);
  to_test();
  fflush(stdout);
  close(new);
  dup2(backup, STDOUT_FILENO);
}

The output looks as intended:

/test: OK

Unfortunately this approach is 1.) ugly and 2.) POSIX specific. So my question is: Is there any other way to do this, so that the code is portable and at the same time aestetically appealing?

Thanks in advance!

Yours in neverending, beautiful, transcendetal love floxo

floxo
  • 1
  • 1

1 Answers1

0

This is possible using freopen and/or fdopen. There isn't a cross platform way of doing this unfortunately, luckily Windows has an fdopen equivalent which you can use (Is there a Windows equivalent to fdopen for HANDLEs?).

Note that this will only work if using stdio. It won't work if for some reason something is writing directly to the fd

As a longer term recommendation, why not use fprintf instead? and maintain a FILE* field in your structure which can be directed to custom output or wherever.

Community
  • 1
  • 1
Mark Nunberg
  • 3,551
  • 15
  • 18