Last active
December 22, 2015 03:38
-
-
Save nadako/6411325 to your computer and use it in GitHub Desktop.
Haxe assertRaises with macro sugar :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TestUtils | |
{ | |
/** | |
* Макро-функция для удобного тестирования эксепшенов. | |
* | |
* Использовать так: | |
* assertExprRaises({ throw "OMG"; }); | |
* или так: | |
* assertExprRaises({ throw "OMG"; }, { assertThat(e, equalTo("OMG")) }); | |
* | |
* Т.е. в первый параметр передается любое выражение, которое должно бросать эксепшн, | |
* а во второй - опициональное выражение, проверяющее словленный эксепшн, доступный через переменную "e"; | |
* | |
* Без сахара с выражениями можно юзать функцию assertRaises, но зачем? :) | |
*/ | |
public static macro function assertExprRaises(expr:haxe.macro.Expr, ?checkExpr:haxe.macro.Expr):haxe.macro.Expr | |
{ | |
var posInfos = toPosInfos(expr.pos); | |
var noCheck = switch (checkExpr.expr) | |
{ | |
case EConst(CIdent("null")): | |
true; | |
default: | |
false; | |
}; | |
if (noCheck) | |
return macro TestUtils.assertRaises(function() { $expr; }, null, $v{posInfos}); | |
else | |
return macro TestUtils.assertRaises(function() { $expr; }, function(e) { $checkExpr; }, $v{posInfos}); | |
} | |
#if macro | |
static function toPosInfos(p:haxe.macro.Expr.Position):haxe.PosInfos | |
{ | |
var pi = haxe.macro.Context.getPosInfos(p); | |
var line = sys.io.File.getContent(pi.file).substr(0, pi.min).split("\n").length; | |
return { | |
lineNumber: line, | |
fileName: pi.file, | |
className: haxe.macro.Context.getLocalClass().get().name, | |
methodName: haxe.macro.Context.getLocalMethod() | |
}; | |
} | |
#end | |
// простейшая функция для проверки того что вызов бросает эксепшен. для макро-сахара см. assertExprRaises | |
public static function assertRaises(func:Void->Void, ?checkFunc:Dynamic->Void, ?infos:haxe.PosInfos):Void | |
{ | |
try | |
{ | |
func(); | |
} | |
catch (e:Dynamic) | |
{ | |
if (checkFunc != null) checkFunc(e); | |
return; | |
} | |
massive.munit.Assert.fail("Exception not thrown", infos); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment