I have a C++ function which returns a multi-line std::string. In the test-case for this, I compare each line against the known-value – something like:
std::string known = "good\netc";
std::string output = "bad\netc";
std::vector<std::string> knownvec;
pystring::splitlines(known, knownvec); // splits on \n
std::vector<std::string> outvec;
pystring::splitlines(output, outvec);
CHECK_EQUAL(osvec.size(), resvec.size());
for(unsigned int i = 0; i < std::min(outvec.size(), knownvec.size()); ++i)
CHECK_EQUAL(pystring::strip(outvec[i]), pystring::strip(knownvec[i]));
This works, but say a single new-line is added, all subsequent CHECK_EQUAL assertions fail, which is make the output hard to read
Is there a better way to compare the two strings, ideally in a nice, self-contained way (i.e not linking against giantdifflib, or writing the strings to a file and calling the diff command!)
[Edit] I’m using OpenImageIO’s rather simple unittest.h
The data being compared is mainly either YAML, or colour lookup tables. Here’s an example test case – basically a few lines of headers, then lots of numbers:
Version 1
Format any
Type ...
LUT:
Pre {
0.0
0.1
...
1.0
}
3D {
0.0
0.1
...
1.0
}
The easiest thing to do would be to break out of your loop when strings no longer match:
If
CHECK_EQUALreturns a boolean value, then you can obviously simplify the above example a bit.If want your unit test framework to provide the same output as
diffwhen comparing multi-line strings, then I’m afraid you’re expecting too much out of your unit test framework. If you don’t want to link to an external library, or executedifffrom within your test program, then you’ll have to program some kind ofdiffalgorithm yourself.Check out this other question about information on diff algorithms and libraries.
If you find that implementing a diff algorithm yourself is not worth the trouble (it probably isn’t), then check out the Google Diff-Match-Patch libraries.