Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

globally suppress c++ std::cout when testing

I have a Struct point at numerical data with a returnNext() method that returns AND posts in stdout the next datum each time called. I also have a series of unit tests that use this method: in those tests I want to supress all Data's std::cout's so that I only check the validity of the returned values without bloating the screen with messages. e.g.

struct Data { 
  Data(int n): datum{n} {};
  int datum;
  int returnNext() { 
    std::cout << datum << " returned" << std::endl;
    return datum;
  }
}

// main.cpp
int main() {
  Data d{100};
  d.returnNext(); // I want this to print at the screen 
  return 0;
}

// test.cpp
int main() {
  TEST( ... ) {
    Data d{100};
    ASSERT_THAT(d.returnNext(), 100); // I want just to check the output, not to check
  }
std::cout << "some message" << std::endl; // I want this printed
return 0;
}

An obvious solution would be to use pre-compiler flags/commands to exclude the std::cout from TEST builds. But this would require editing several modules and would also make my code ugly.

Another case would be to use redirect stdout to dev/null from the console, but this would also suppress the stdout my test modules.

Isn't there a way to programmatically supress/redirect stdout during particular moments in a program's lifetime???

like image 448
Marinos K Avatar asked Jul 17 '15 16:07

Marinos K


2 Answers

For the general problem of suppressing std::cout, you can use std::basic_ios::rdbuf with a null buffer:

auto old_buffer = std::cout.rdbuf(nullptr);

To restore it, just do

std::cout.rdbuf(old_buffer);
like image 61
lisyarus Avatar answered Sep 21 '22 18:09

lisyarus


This is precisely why having hard-coded stdout output in your member functions is a bad idea. Now you think you have to block std::cout globally, because your class's behaviour is inflexible.

Instead, move the std::cout call someplace else (to make its use optional) or have it be an arbitrary std::ostream which you can make route to nowhere.

like image 22
Lightness Races in Orbit Avatar answered Sep 19 '22 18:09

Lightness Races in Orbit