Skip to content

Instantly share code, notes, and snippets.

@wolever
Created June 18, 2010 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolever/444083 to your computer and use it in GitHub Desktop.
Save wolever/444083 to your computer and use it in GitHub Desktop.
package utils {
import org.flexunit.internals.runners.statements.IAsyncStatement;
import org.flexunit.internals.runners.statements.MethodRuleBase;
import org.flexunit.rules.IMethodRule;
import org.flexunit.runners.model.FrameworkMethod;
import org.flexunit.token.AsyncTestToken;
import org.flexunit.token.ChildResult;
public class AsyncRule extends MethodRuleBase implements IMethodRule {
protected var hasWrappedFunctions:Boolean;
protected var isComplete:Boolean;
public function wrap(closure:Function):Function {
hasWrappedFunctions = true;
function asyncRuleWrapHelper(...args):* {
var result:ChildResult;
var returnValue:*;
try {
returnValue = closure.apply(null, args);
} catch (e:Error) {
complete();
sendComplete(e);
return undefined;
}
if (isComplete) {
sendComplete(null);
return undefined;
}
return returnValue;
}
return asyncRuleWrapHelper;
}
public function complete():void {
if (!hasWrappedFunctions)
throw Error("Calling 'complete' without wrapping any functions?");
// Once we are 'complete', the termination of the next 'wrapped'
// function will finish the test.
isComplete = true;
}
override public function evaluate(parentToken:AsyncTestToken):void {
super.evaluate(parentToken);
hasWrappedFunctions = false;
isComplete = false;
proceedToNextStatement();
}
override protected function handleStatementComplete(result:ChildResult):void {
if (result.error) {
// If we got an error in the test method, fail immediately.
if (hasWrappedFunctions)
complete();
sendComplete(result.error);
}
// If we didn't wrap any functions, we're done.
if (!hasWrappedFunctions || isComplete)
sendComplete(result.error);
// Otherwise, do nothing until we get a call to 'complete'.
}
}
}
package tests {
import flash.errors.IOError;
import flash.utils.setTimeout;
import utils.AsyncRule;
import utils.assertEqual;
public class TestAsyncRule {
[Rule]
public var async:AsyncRule = new AsyncRule();
[Test]
public function testWrapPassthroughArgs():void {
function toWrap(arg:*):* {
return arg;
}
var wrapped:Function = async.wrap(toWrap);
assertEqual(wrapped("hello"), "hello");
async.complete();
}
[Test(expects="flash.errors.IOError")]
public function testWrapErrors():void {
setTimeout(async.wrap(function():void {
throw new IOError("some error");
}), 100);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment