mir-algorithm icon indicating copy to clipboard operation
mir-algorithm copied to clipboard

Replace asserts with `should`s

Open jmh530 opened this issue 3 years ago • 0 comments

I've been using shouldApprox recently and thought it was a nice addition, but realized that changing all my functions to use shouldApprox instead of approxEqual would be pretty annoying manually.

Would it be worth it to write a script that can replace assert with == and approxEqual with should and shouldApprox, respectively? If so, should said script be located as part of libmir?

It would be pretty easy to do with regex for the simple cases, as in below (does not handle the imports). It would also be possible to only replace within unittest blocks. Probably also would be good to replace in pre- and post-conditions.

import std.regex;
import std.stdio: writeln;

string replaceAssertWithShould(Captures!(string) m)
{
    auto rEqual = regex(r" == ");
    auto x = m.hit[7..($ - 2)].split(rEqual);
    return x[0] ~ ".should == " ~ x[1] ~ ";";
}

string replaceAssertWithShouldApprox(Captures!(string) m)
{
    auto rApproxEqual = regex(r"\.approxEqual\(");
    auto x = m.hit[7..($ - 3)].split(rApproxEqual);
    return x[0] ~ ".shouldApprox == " ~ x[1] ~ ";";
}

void main()
{
    string x = "assert(x == y); \nassert(x.approxEqual(y));";

    auto rAssertEqual = regex(r"assert\(.* \== .*\);");
    auto rAssertApproxEqual = regex(r"assert\(.*\.approxEqual\(.*\);");

    auto a = x.replaceAll!replaceAssertWithShould(rAssertEqual);
    auto b = a.replaceAll!replaceAssertWithShouldApprox(rAssertApproxEqual);
    writeln(x);
    writeln(b);
}

jmh530 avatar Jul 14 '22 14:07 jmh530