Skip to content

Commit

Permalink
Added expect and expectErr override variants accepting custom han…
Browse files Browse the repository at this point in the history
…dler
  • Loading branch information
tchaloupka committed Nov 27, 2019
1 parent 49cf20f commit 131ddee
Showing 1 changed file with 50 additions and 7 deletions.
57 changes: 50 additions & 7 deletions source/expected.d
Original file line number Diff line number Diff line change
Expand Up @@ -1449,8 +1449,9 @@ unittest
If there is none, or error value, it throws $(D assert(0)) with the provided message.
Params:
res = $(LREF Expected) to check the result of
msg = message to use with assert
res = $(LREF Expected) to check the result of
msg = message to use with assert
handler = custom handler to be called on error
+/
T expect(EX : Expected!(T, E, H), T, E, H)(auto ref EX res, lazy string msg)
{
Expand All @@ -1468,6 +1469,21 @@ T expect(EX : Expected!(T, E, H), T, E, H)(auto ref EX res, lazy string msg)
}
}

/// ditto
T expect(alias handler, EX : Expected!(T, E, H), T, E, H)(auto ref EX res)
{
static if (!is(T == void)) { if (res.hasValue) return res.value; }
else { if (!res.hasError) return; }

static if (!is(typeof(handler(res.error)) == void))
return handler(res.error);
else
{
handler(res.error);
return T.init;
}
}

version (D_Exceptions)
{
///
Expand All @@ -1487,6 +1503,7 @@ version (D_Exceptions)
Params:
res = $(LREF Expected) to check the result of
msg = message to use with assert
handler = custom handler to be called on value
+/
E expectErr(EX : Expected!(T, E, H), T, E, H)(auto ref EX res, lazy string msg)
{
Expand All @@ -1506,17 +1523,43 @@ E expectErr(EX : Expected!(T, E, H), T, E, H)(auto ref EX res, lazy string msg)
}
}

version (D_Exceptions)
/// ditto
E expectErr(alias handler, EX : Expected!(T, E, H), T, E, H)(auto ref EX res)
{
///
@("expectErr")
@system unittest
if (res.hasError) return res.error;

static if (!is(typeof(handler(T.init)) == void))
{
static if (!is(T == void)) return handler(res.hasValue ? res.value : T.init);
else return handler();
}
else
{
static if (!is(T == void)) handler(res.hasValue ? res.value : T.init);
else handler();
return T.init;
}
}

///
@("expectErr")
@system unittest
{
assert(err("foo").expectErr("oops") == "foo");
version (D_Exceptions)
{
assert(err("foo").expectErr("oops") == "foo");
assert(collectExceptionMsg!Throwable(Expected!int.init.expectErr("oops")) == "oops: empty");
assert(collectExceptionMsg!Throwable(ok(42).expectErr("oops")) == "oops: 42");
assert(collectExceptionMsg!Throwable(ok().expectErr("oops")) == "oops: empty"); // void value
}

assert(ok("foo").expect!(a => "bar") == "foo");
assert(err!string("foo").expect!(a => "bar") == "bar");
assert(err!string("foo").expect!((a) {}) is null);

assert(ok("foo").expectErr!(a => "bar") == "bar");
assert(err!string("foo").expectErr!(a => "bar") == "foo");
assert(ok!string("foo").expectErr!((a) {}) is null);
}

/++
Expand Down

0 comments on commit 131ddee

Please sign in to comment.