0

I'm right now implementing a library for exporting data into various formats with a multitude of settings. I'm also using Boost.Test, but there is seemingly no function to test the file contents.

For my purposes it should be enough to check if the file at hand contains a given regular expression. I'm really looking for a very simple macro like shown below.

#define BOOST_TEST_MODULE ExportTest
#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(CsvExport) 
    BOOST_AUTO_TEST_CASE(SimpleTest) {
        // 
        // ... Code writes Simple.csv to harddisk
        // 
        // 
        //
        std::string regExpr= ... // Arbitrary regular expression
        BOOST_TEST_FILE("Simple.csv", regExpr)
}
BOOST_AUTO_TEST_SUITE_END();
  1. Is there an extension around, that can be used like that? Or do I have to write a macro on my own?

  2. How can I seamlessly endow Boost.Test with such a functionality, if there is no such macro around?

My final solution:

Finally, I included the following simple function in my tests.

#include <boost/regex.hpp>

bool fileContains(const std::string& filename, const std::string& regexp) {
    std::ifstream file(filename);
    if (file) {
        try {
            std::stringstream buffer;
            buffer << file.rdbuf();
            file.close();
            return boost::regex_search(buffer.str(), boost::regex(regexp));
        }
        catch(const std::exception&) {
            return false;
        }
    } else {
        return false;
    }
}

Usage would be as exemplified below:

    BOOST_CHECK(fileContains("Export.csv","-48.434"));
Aleph0
  • 5,816
  • 4
  • 29
  • 80

1 Answers1

2

This is really just opinion, but I think extending Boost.Test is unecessary in this case. I would just write a function match_in_file(fname, regex_as_string), maybe header only, and include it in any test files that need it. Then you could write

BOOST_ASSERT(match_in_file(fname, regexpr));

In my opinion extending Boost for such a case would be an example of overly monolithic design. In your posted example you're passing a csv file... maybe you want your find-in-file to to parse the csv elements and search within them... maybe later you'll want ot apply some subtly different rules (e.g. only in a certain column of the csv file, or in certain nodes of an xml).

If you extend Boost, you'll be getting a big and unwieldy interface. If you write a set of simple functions that do what you need, you'll have a cleaner separation of responsibilites, and better possibilities of reuse. Further, you might find that these functions belong elsewhere, or could be factored out of your other code in a clean way.

Spacemoose
  • 3,856
  • 1
  • 27
  • 48
  • Many thanks for this in-depth answer. It know became clear to me, that there will be no solution that could possibly satisfy all demands of all tests. Seems I have to rely on writing a simply function, as you suggested. – Aleph0 Feb 17 '16 at 19:25