Skip to content

Replace asserts with shoulds #433

Open
@jmh530

Description

@jmh530

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions