libmir / mir-algorithm

Dlang Core Library
http://mir-algorithm.libmir.org
Other
174 stars 37 forks source link

Replace asserts with `should`s #433

Open jmh530 opened 2 years ago

jmh530 commented 2 years ago

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);
}