Flex unit aysnc problem: Error: Asynchronous Event Received out of Order - apache-flex

I am writing test cases to test function with flexunit 4. I am using aysnc method.
But when I add two or more asyncHandlers to the instance. I meet the problem: Error: Asynchronous Event Received out of Order. How to resolve this problem? Thanks.
Code snippets:
[Test(order=1, async, description="synchronize content on line")]
public function testSynchronizeContentOnline():void
{
var passThroughData:Object = new Object();
var asyncHandler1:Function = Async.asyncHandler(this, authFailureHandler, 60000, null, timeoutHandler);
var asyncHandler:Function = Async.asyncHandler(this, authSuccessHandler, 60000, null, timeoutHandler);
caseManager.addEventListener(CaseAuthEvent.AUTH_SUCCESS,
asyncHandler);
caseManager.addEventListener(CaseAuthEvent.AUTH_FAILURE,
asyncHandler1);
caseManager.authenticate("admin", "admin");
trace('test');
}
private function timeoutHandler(event:Event):void
{
Assert.fail( "Timeout reached before event");
}
private var authFailed:Boolean = false;
private function authFailureHandler(event:CaseAuthEvent, passThroughData:Object):void
{
trace("authFailure:" + event.type);
authFailed = true;
}
private var authSucceed:Boolean = false;
private function authSuccessHandler(event:CaseAuthEvent, passThroughData:Object):void
{
trace("authSucceed:" + event.type);
authSucceed = true;
Assert.assertTrue(true);
}

That would be because you're adding order to your test cases, which is seems something else is dispatching before the first one is complete. To quote the ordering part of the flex unit wiki:
Your tests need to act independently of each other, so the point of
ordering your tests in a custom way is not to ensure that test A sets
up some state that test B needs. If this is the reason you are reading
this section, please reconsider. Tests need to be independent of each
other and generally independent of order.
Which I completely agree with. There should not be any order in your tests. The tests themselves sets the state of what needs to be done.

Your test will work if you test success and fail separately. So basically have 2 tests, one adds an async handler for your events success, the other for the events fail. Here is an example of the 2 tests as I would approach them...
[Test(async)]
public function testEventSuccess():void
{
var passThroughData:Object = new Object();
var asyncHandler:Function = Async.asyncHandler(this, authSuccessHandler, 60000, null, timeoutHandler);
caseManager.addEventListener(CaseAuthEvent.AUTH_SUCCESS,
asyncHandler);
caseManager.authenticate("admin", "admin");
}
[Test(async)]
public function testEventFailure():void
{
var passThroughData:Object = new Object();
var asyncHandler:Function = Async.asyncHandler(this, authFailureHandler, 60000, null, timeoutHandler);
caseManager.addEventListener(CaseAuthEvent.AUTH_FAILURE,
asyncHandler);
caseManager.authenticate("admin", "admin");
}
Remember to make a new instance of your caseManager in your set up function and its good practice to remove ref to it in the tearDown as the simple code snippet shows, I've just assumed the caseManager is of type CaseManager.
[Before]
public function setUp():void
{
caseManager = new CaseManager();
}
[After]
public function tearDown():void
{
caseManager = null;
}

Related

MemoryCache.Default.AddOrGetExisiting returns null although the key is in the cache

I am writing unit tests for my asp.net web API application and one of them is trying to verify that AddOrGetExisting is working correctly. According to the MSDN documentation, AddOrGetExisting returns an item if it's already saved, and if not it should write it into Cache.
The problem I am having is that if I add the key to MemoryCache object from an unit test, then call AddOrGetExisting, it will always return null and overwrite the value instead of returning the value that is already saved. I am verifying that the value is in the cache right before I call AddOrGetExisting(bool isIn evaluates to true).
Here is the code for my memory cache and the test method. Any help would be much appreciated:
public static class RequestCache
{
public static TEntity GetFromCache<TEntity>(string key, Func<TEntity> valueFactory) where TEntity : class
{
ObjectCache cache = MemoryCache.Default;
var newValue = new Lazy<TEntity>(valueFactory);
CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60) };
bool isIn = cache.Contains(key);
// Returns existing item or adds the new value if it doesn't exist
var value = cache.AddOrGetExisting(key, newValue, policy) as Lazy<TEntity>;
return (value ?? newValue).Value;
}
}
public string TestGetFromCache_Helper()
{
return "Test3and4Values";
}
[TestMethod]
public void TestGetFromCache_ShouldGetItem()
{
ObjectCache cache = MemoryCache.Default;
CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60) };
var cacheKey = "Test3";
var expectedValue = "Test3Value";
cache.AddOrGetExisting(cacheKey, expectedValue, policy);
var result = Models.RequestCache.GetFromCache(cacheKey,
() =>
{
return TestGetFromCache_Helper();
});
Assert.AreEqual(expectedValue, result);
}
The issue may be that you're passing a Lazy<TEntity> as newValue within RequestCache.GetFromCache but passing a string as expectedValue in the test method.
When running the test, the cache.Contains(key) confirms that there is a value stored for that key, which is true. However it is a string instead of a Lazy<TEntity>. Apparently AddOrGetExisting decides to overwrite the value in that case.
The fix for this particular scenario may be to adjust the expectedValue assignment in your test to something like this:
var expectedValue = new Lazy<string>(TestGetFromCache_Helper);
You'd also need to pull the value from the Lazy in the test's final equality comparison, for example:
Assert.AreEqual(expectedValue.Value, result);

Using Moq can you verify a method call with an anonymous type?

I'm trying to verify a method call using Moq, but I can't quite get the syntax right. Currently, I've got this as my verify:
repository.Verify(x => x.ExecuteNonQuery("fav_AddFavorites", new
{
fid = 123,
inputStr = "000456"
}), Times.Once());
The code compiles, but the test fails with the error:
Expected invocation on the mock once, but was 0 times:
x => x.ExecuteNonQuery("fav_AddFavorites", new <>f__AnonymousType0<Int32, String>(123, "000456"))
No setups configured.
Performed invocations:
IRepository.ExecuteNonQuery("fav_AddFavorites", { fid = 123, inputStr = 000456 })
How can I verify the method call and match the method parameters for an anonymous type?
UPDATE
To answer the questions:
I am trying to verify both that the method was called and that the parameters are correct.
The signature of the method I'm trying to verify is:
int ExecuteNonQuery(string query, object param = null);
The setup code is simply:
repository = new Mock<IRepository>();
UPDATE 2
It looks like this is a problem with Moq and how it handles anonymous types in .Net. The code posted by Paul Matovich runs fine, however, once the code and the test are in different assemblies the test fails.
This Passes
public class Class1
{
private Class2 _Class2;
public Class1(Class2 class2)
{
_Class2 = class2;
}
public void DoSomething(string s)
{
_Class2.ExecuteNonQuery(s, new { fid = 123, inputStr = "000456" });
}
}
public class Class2
{
public virtual void ExecuteNonQuery(string s, object o)
{
}
}
/// <summary>
///A test for ExecuteNonQuery
///</summary>
[TestMethod()]
public void ExecuteNonQueryTest()
{
string testString = "Hello";
var Class2Stub = new Mock<Class2>();
Class1 target = new Class1(Class2Stub.Object);
target.DoSomething(testString);
Class2Stub.Verify(x => x.ExecuteNonQuery(testString, It.Is<object>(o => o.Equals(new { fid = 123, inputStr = "000456" }))), Times.Once());
}
##Update##
That is strange, it doesn't work in different assemblies. Someone can give us the long definition about why the object.equals from different assemblies behaves differently, but for different assemblies, this will work, any variance in the object values will return a different hash code.
Class2Stub.Verify(x => x.ExecuteNonQuery(testString, It.Is<object>(o => o.GetHashCode() == (new { fid = 123, inputStr = "000456" }).GetHashCode())), Times.Once());
One option is to "verify" it in a Callback. Obviously this needs to be done at Setup time, e.g.:
aMock.Setup(x => x.Method(It.IsAny<object>())).Callback<object>(
(p1) =>
{
dynamic o = p1;
Assert.That(o.Name, Is.EqualTo("Bilbo"));
});
None of the answers are great when your test assembly is different than the system under test's assembly (really common). Here's my solution that uses JSON serialization and then strings comparison.
Test Helper Function:
using Newtonsoft.Json;
public static class VerifyHelper
{
public static bool AreEqualObjects(object expected, object actual)
{
var expectedJson = JsonConvert.SerializeObject(expected);
var actualJson = JsonConvert.SerializeObject(actual);
return expectedJson == actualJson;
}
}
Example System Under Test:
public void DoWork(string input)
{
var obj = new { Prop1 = input };
dependency.SomeDependencyFunction(obj);
}
Example Unit Test:
var expectedObject = new { Prop1 = "foo" };
sut.DoWork("foo");
dependency.Verify(x => x.SomeDependencyFunction(It.Is<object>(y => VerifyHelper.AreEqualObjects(expectedObject, y))), Times.Once());
This solution is really simple, and I think makes the unit test easier to understand as opposed to the other answers in this thread. However, because it using simple string comparison, the test's anonymous object has to be set up exactly the same as the system under the test's anonymous object. Ergo, let's say you only cared to verify the value of a single property, but your system under test sets additional properties on the anonymous object, your unit test will need to set all those other properties (and in the same exact order) for the helper function to return true.
I created a reusable method based on Pauls answer:
object ItIsAnonymousObject(object value)
{
return It.Is<object>(o => o.GetHashCode() == value.GetHashCode());
}
...
dependency.Verify(
x => x.SomeDependencyFunction(ItIsAnonymousObject(new { Prop1 = "foo" })),
Times.Once());
Also, this can be used for property name case-insensitive comparison:
protected object ItIsAnonymousObject(object value)
{
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
return It.Is<object>(o => JsonSerializer.Serialize(o, options) == JsonSerializer.Serialize(value, options));
}

Best way to typecast deserialised JSON

I think I've established that in as3corelib JSON.decode I have no choice but to deserialise to a plain old flex object.
var data:Object = JSON.decode(json);
If I then want to get the data contained in the object into another type I can't use type casting. I have to instantiate a new instance and add the properties manually.
var data:Object = JSON.decode(json);
var model:Model = new Model();
model.name = data.name;
model.notes = data.notes;
A pain and a bit ugly, but I'm guessing this is the price to be paid for going from untyped json to a flex type. My first question is whether my assumption is correct and there is no prettier way to create my model instance with the data contained within the json?
My second question, if so then before I write my own method to do this, is there anything inside the flex api that will take the data object and mixin it's values to my model instance?
Cheers,
Chris
the approach I've always used proved to be part of the AMF3 serialization mechanism in ActionScript.
have a look at IExternalizable and registerClassAlias.
now what I use is the following:
interface ISerializable {
public function getRawData():Object;
public function setRawData(param:Object):void;
}
function registerType(id:String, type:Class):void {
//implementation
}
function getTypeByID(id:String):Class {
//implementation
}
function getTypeID(type:Class):String {
//implementation
}
and to the decoder/encoder you register a class alias.
serialization of an object works as follows:
var raw:Object = model.getRawData();
raw[" type"] = getTypeID(model);
var encoded:String = JSON.encode(raw);
decoding works as follows:
var raw:Object = JSON.decode(raw);
var cl:Class = getTypeByID(raw[" type"]);
if (cl == null) throw new Error("no class registered for type: "+raw[" type"]);
delete raw[" type"];
var model:ISerializable = new cl();
model.setRawData(raw);
you will need to do this recursively on the whole deserialized JSON tree, starting at the leafs.
For cyclic reference, you'll need a trick.
I had an implementation of this somewhere, but I can't find it.
You can loop within the field of you json decoded object and assign them into your model:
function json2model(json:String):Model{
var data:Object = JSON.decode(json);
var m:Model=new Model();
for (var field:String in data) {
if (m.hasOwnProperty(field)) {
m[field] = data[field];
}
}
return m;
}
var model:Model=json2model(json)
or add a static function within your Model if you preffer:
public class Model {
//...
public static function fromJSon(json:String):Model {
var data:Object = JSON.decode(json);
var m:Model=new Model();
for (var field:String in data) {
if (m.hasOwnProperty(field)) {
m[field] = data[field];
}
}
return m;
}
}
}
var model:Model=Model.fromJSon(json);

Returning from Flex/ActionScript 3 Responder objects

I need to return the value from my Responder object. Right now, I have:
private function pro():int {
gateway.connect('http://10.0.2.2:5000/gateway');
var id:int = 0;
function ret_pr(result:*):int {
return result
}
var responder:Responder = new Responder(ret_pr);
gateway.call('sx.xj', responder);
return id
}
Basically, I need to know how to get the return value of ret_pr into id or anything that I return from that function. The responder just seems to eat it. I can't use a public variable somewhere else because this will be running multiple times at once, so I need local scope.
This is how I'd write a connection to the AMF server, call it and store the resulting value. Remember that the result won't be available instantly so you'll set up the responder to "respond" to the data once it returns from the server.
public function init():void
{
connection = new NetConnection();
connection.connect('http://10.0.2.2:5000/gateway');
setSessionID( 1 );
}
public function setSessionID(user_id:String):void
{
var amfResponder:Responder = new Responder(setSessionIDResult, onFault);
connection.call("ServerService.setSessionID", amfResponder , user_id);
}
private function setSessionIDResult(result:Object):void {
id = result.id;
// here you'd do something to notify that the data has been downloaded. I'll usually
// use a custom Event class that just notifies that the data is ready,but I'd store
// it here in the class with the AMF call to keep all my data in one place.
}
private function onFault(fault:Object):void {
trace("AMFPHP error: "+fault);
}
I hope that can point you in the right direction.
private function pro():int {
gateway.connect('http://10.0.2.2:5000/gateway');
var id:int = 0;
function ret_pr(result:*):int {
return result
}
var responder:Responder = new Responder(ret_pr);
gateway.call('sx.xj', responder);
return id
}
This code is never going to get you what you want. You need to use a proper result function. The anonymous function responder return value will not be used by the surrounding function. It will always return 0 in this case. You are dealing with an asynchronous call here, and your logic needs to handle that accordingly.
private function pro():void {
gateway.connect('http://10.0.2.2:5000/gateway');
var responder:Responder = new Responder(handleResponse);
gateway.call('sx.xj', responder);
}
private function handleResponse(result:*):void
{
var event:MyCustomNotificationEvent = new MyCustomNotificationEvent(
MyCustomNotificationEvent.RESULTS_RECEIVED, result);
dispatchEvent(event);
//a listener responds to this and does work on your result
//or maybe here you add the result to an array, or some other
//mechanism
}
The point there being using anon functions/closures isn't going to give you some sort of pseudo-syncronous behavior.

How can I test a SWF URL before Loading Styles From if (or catching the error)?

I am trying to use the following code to load styles from an external SWF, but I keep getting an ActionScript error when the URL is invalid:
Error: Unable to load style(Error #2036: Load Never Completed. URL: http://localhost/css/styles.swf): ../css/styles.swf.
at <anonymous>()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\styles\StyleManagerImpl.as:858]
private function loadStyles(): void
{
try
{
var styleEvent:IEventDispatcher =
StyleManager.loadStyleDeclarations("../styles.swf");
styleEvent.addEventListener(StyleEvent.COMPLETE,
loadStyle_completeHandler);
styleEvent.addEventListener(StyleEvent.ERROR,
loadStyle_errorHandler);
}
catch (error:Error)
{
useDefault();
}
}
private function loadStyle_completeHandler(event:StyleEvent): void
{
IEventDispatcher(event.currentTarget).removeEventListener(
event.type, loadStyle_completeHandler);
goToNextStep();
}
private function loadStyle_errorHandler(event:StyleEvent): void
{
IEventDispatcher(event.currentTarget).removeEventListener(
event.type, loadStyle_errorHandler);
useDefault();
}
I basically want to go ahead an use the default styles w/o the user seeing the error if this file can't be loaded - but I can't seem to find any way to do this.
Interesting problem. Try removing the removeEventListener call, or commenting it out; in my brief tests it appeared the event handler was being called twice (I'm not immediately sure why, although I suspect it has to do with style inheritance), and commenting that line did the trick.
If you have the same result, you might try just checking for the listener (using hasEventListener) first, before attaching it in your loadStyles() function, instead. Hope it helps!
** Not an answer, but an update:
FYI, this is the ActionScript code in the Source of mx.styles.StyleManagerImpl that is run when you call StyleManager.loadStyleDeclarations(). I ran the debugger and added a breakpoint at the Line 858("throw new Error(errorText);"), and the breakpoint was caught. I'm thinking it shouldn't be caught there, but the previous IF ("if (styleEventDispatcher.willTrigger(StyleEvent.ERROR))") should be run instead.
public function loadStyleDeclarations2(
url:String, update:Boolean = true,
applicationDomain:ApplicationDomain = null,
securityDomain:SecurityDomain = null):
IEventDispatcher
{
var module:IModuleInfo = ModuleManager.getModule(url);
var readyHandler:Function = function(moduleEvent:ModuleEvent):void
{
var styleModule:IStyleModule =
IStyleModule(moduleEvent.module.factory.create());
styleModules[moduleEvent.module.url].styleModule = styleModule;
if (update)
styleDeclarationsChanged();
};
module.addEventListener(ModuleEvent.READY, readyHandler,
false, 0, true);
var styleEventDispatcher:StyleEventDispatcher =
new StyleEventDispatcher(module);
var errorHandler:Function = function(moduleEvent:ModuleEvent):void
{
var errorText:String = resourceManager.getString(
"styles", "unableToLoad", [ moduleEvent.errorText, url ]);
if (styleEventDispatcher.willTrigger(StyleEvent.ERROR))
{
var styleEvent:StyleEvent = new StyleEvent(
StyleEvent.ERROR, moduleEvent.bubbles, moduleEvent.cancelable);
styleEvent.bytesLoaded = 0;
styleEvent.bytesTotal = 0;
styleEvent.errorText = errorText;
styleEventDispatcher.dispatchEvent(styleEvent);
}
else
{
throw new Error(errorText);
}
};
module.addEventListener(ModuleEvent.ERROR, errorHandler,
false, 0, true);
styleModules[url] =
new StyleModuleInfo(module, readyHandler, errorHandler);
// This Timer gives the loadStyleDeclarations() caller a chance
// to add event listeners to the return value, before the module
// is loaded.
var timer:Timer = new Timer(0);
var timerHandler:Function = function(event:TimerEvent):void
{
timer.removeEventListener(TimerEvent.TIMER, timerHandler);
timer.stop();
module.load(applicationDomain, securityDomain);
};
timer.addEventListener(TimerEvent.TIMER, timerHandler, false, 0, true);
timer.start();
return styleEventDispatcher;
}
I debugged the source, and found that the ERROR Event is being triggered twice. So, I simply set a flag the first time the ERROR event handler is triggered, and check that flag for a value of true before continuing:
private var isErrorTriggered:Boolean; // Default is false
private function loadStyle_completeHandler(event:StyleEvent):void
{
IEventDispatcher(event.currentTarget).removeEventListener(
event.type, loadStyle_completeHandler);
goToNextStep();
}
private function loadStyle_errorHandler(event:StyleEvent):void
{
if (isErrorTriggered)
return;
isErrorTriggered = true;
useDefault();
}

Resources