Feasible Idea?: Range Tester

Jonathan M Davis jmdavisProg at gmx.com
Fri Mar 22 00:41:52 PDT 2013


On Friday, March 22, 2013 08:07:01 timotheecour wrote:
> >>  testing that a conformant range throws a RangeError from
> >> 
> >> popFront when it's empty (as Nick was suggesting) would not be
> >> correct at this point
> 
> ok what about the following: should work regardless it's
> RangeError or an assert(0) in th eparticular implementation of a
> range.
> 
> ----
> bool isThrown(E)(lazy E expression){
>          import std.exception;
>          import core.exception : RangeError;
> 	try
> 		expression();
> 	catch(RangeError t)	return true;
> 	catch(Error t)	return true;
> 	return false;
> }
> unittest(){
>      int[]x;
>      assert(isThrown(x[1]));
> }
> ----

Sure, you could do that, but I'd be completely against putting anything in 
Phobos to test ranges which tested anything which wasn't agreed upon as the 
correct way to do it. That being the case, it would have to be agreed upon 
whether assertions should be used or whether RangeError should be used (or 
that using either was valid, though that's a bad idea IMHO).

As for the implementation, it would make more sense to simply do

assertThrown!Error(x[1]);

if you don't care which type of Error is thrown, and if you do care but are 
allowing both (since you can only give one type to assertThrown), then you 
could use

auto e = collectException!Error(x[1]);
assert((cast(AssertError)e) !is null || (cast(RangeError)) !is null);

But if you're writing try-catch blocks in unit tests to test exceptions being 
thrown, odds are that you're not taking proper advantage of std.exception.

- Jonathan M Davis


More information about the Digitalmars-d mailing list