approvals / ApprovalTests.cpp

Native ApprovalTests for C++ on Linux, Mac and Windows
https://approvaltestscpp.readthedocs.io/en/latest/
Apache License 2.0
312 stars 51 forks source link

Make verifyExistingFile() support scrubbers #141

Closed claremacrae closed 4 years ago

claremacrae commented 4 years ago

For my talks on ApprovalTests, I have some example code that uses a custom ApprovalWriter to remove date-and-time values from a log file.

I tried updating it to use a Scrubber instead, and because verifyExistingFile() doesn't use any supplied scrubber, it turned out to be moderately complicated code:

TEST_CASE("Deal with dates and times in output with scrubber")
{
    // As above, but this time we will use a Scrubber to replace the
    // date and time with a fixed string

    // This class has a calculate() method that writes out its result
    // and a date-and-time-stamp, to an output file.
    // This calculate() method is the code that we are testing.
    FibonacciCalculator calculator(12);
    const auto filename = Approvals::getDefaultNamer()->getReceivedFile(".txt");
    calculator.calculate(filename);

    // As of v.10.0.1, ApprovalTests does not use Scrubbers
    // in verifyExistingFile(), so we have to read in the contents
    // of the file in to a string, and verify that.
    const auto logText = FileUtils::readFileThrowIfMissing(filename);

    // Create a "Scrubber" object that will convert date-and-time strings
    // to some fixed text:
    const auto dateRegex =
        R"(([A-Za-z]{3}) ([A-Za-z]{3}) ([0-9 ]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) ([0-9]{4}))";
    const std::string replacementText = "[date-time-removed]";
    auto scrubber = Scrubbers::createRegexScrubber(dateRegex, replacementText);

    Approvals::verify(logText, Options(scrubber));
}

It would be great to be able to remove the readFile step, and do this instead:

...
    Approvals::verifyExistingFile(filename, Options(scrubber));
claremacrae commented 4 years ago

Also, the use of Approvals::verify() in the first block of code in the example above gives an extra blank line in the approved file, so differing from the file written out by the function being tested - as reported in #50

claremacrae commented 4 years ago

This is fixed and is about to be released in v.10.1.0