1

I have a unit test that verifies a function by reading the buffer sent by the function:

template <typename Manifold>
void print_manifold(Manifold const& manifold)
try
{
  std::cout << "Manifold has " << manifold.N0() << " vertices and "
            << manifold.N1() << " edges and " << manifold.N2() << " faces and "
            << manifold.N3() << " simplices.\n";
  // fmt::print(
  //    "Manifold has {} vertices and {} edges and {} faces and {}
  //    simplices.\n", manifold.N0(), manifold.N1(), manifold.N2(),
  //    manifold.N3());
}
catch (...)
{
  std::cerr << "print_manifold() went wrong ...\n";
  throw;
}  // print_manifold

And:

SCENARIO("Printing results", "[utility]")
{
  // redirect std::cout
  stringstream buffer;
  cout.rdbuf(buffer.rdbuf());
  GIVEN("A Manifold3")
  {
    Manifold3 const manifold(640, 4);
    WHEN("We want to print statistics on a manifold.")
    {
      THEN("Statistics are successfully printed.")
      {
        print_manifold(manifold);
        CHECK_THAT(buffer.str(), Catch::Contains("Manifold has"));
      }
    }
}

Is there a way to capture the output generated by fmt::print going to stdout?

When I comment out the cout code and uncomment the fmt code, I get the buffer produced by previous instances of cout <<.

cpplearner
  • 13,776
  • 2
  • 47
  • 72
Adam Getchell
  • 437
  • 4
  • 7

1 Answers1

1

This is more of a C stdio than {fmt} question but you can redirect stdout to a pipe and read the output from it as described in the answers to Redirecting stdout to pipe in C. This is not a great unit test though because it depends on the global state but your current test has the same problem.

vitaut
  • 49,672
  • 25
  • 199
  • 336