observable.subscribe(onNext: { _ in
somePrivateFunction()
})
What is the RxSwift way to test that when observable receives an event the somePrivateFunction actually gets called or not? Since the subscription and the function are in the same class I can't mock it.
You need to check if any logic is placed in a subscription that can block call of this function. If there is - it may be worth to extract it to a parameter (eg. filter) so that logic can be a part of stream itself.
I assume that observable (source) is injected/redirected from another component (if it's not, most probably it should be). To mock that signal you can use TestableObservable, you can read more here: http://adamborek.com/rxtests-rxactionsheet/
Last but not least - you need to identify what kind of action somePrivateFunction() does. If it's setting some external values - then you can test that outgoing connection from that function. If it sets some internal flags - you can test if value of that flag has changed.
Related
I register callback as event handler in my game, like this:
--register event handler
EventDispatcher:register("fire", mt.onPlayerFire, self)
--this is the event handler
mt:onPlayerFire()
print("play fire")
end
--unregister event handler
EventDispachter:unregister("fire", mt.onPlayerFire, self)
When the event handler is a function in module mt, it is fine to unregister it, because I can find the same function in mt to unregister it, but when I use this form:
EventDispatcher:register("fire", function() doSomething() end, nil)
I could not unregister the event handler, because it is anonymous, so I want to add some checks in my register function to prevent anonymous function as the event handler.
I have found the Proto struct in lua source code may be helpful, but I do not know what each piece means.
https://www.lua.org/source/5.3/lobject.h.html#Proto
I could not unregister the event handler, because it is anonymouse
Every function in Lua is anonymous value. So you can't unregister not because it is anonymous but because you didn't save any reference to it.
There is no way to detect inside of EventDispatcher:register() if the passed value (of function type) is also saved elsewhere. So if you really have multiple callbacks for the same event, and you want to unregister one specific callback, then you must have a way to identify that exact callback function.
That means you should either save the function value somewhere, so its own value could be used later as identifier for unregister(), as it is now, or return new callback's instance id, generated inside of register() when callback was added. Either way, there's something to be stored outside of EventDispatcher to identify exact callback.
This kind of avoids your question a bit, but it might solve your problem nonetheless.
When registering a new callback you could simply return some sort of identifying value, like an ID, a table or even the function itself. This could allow you to unregister it at a later moment.
local firehandler = EventDispatcher:register("fire", function() do('something') end)
-- Do some stuff here...
EventDispatcher:unregister(firehandler)
The downside is that you may have to change the way your event dispatcher keeps track of its registered events, but at worst this means implementing some linked list, and at best you can just use a Lua table to keep track of your handlers.
As for detecting anonymous functions, that's not really possible. Lua doesn't distinguish a function you define in-place from one stored in a variable; it's ultimately the same thing.
It might be possible by using the debug library, by comparing the file/line where a function is defined with the call stack, but that's just inviting bugs into your code and would probably be rather slow.
I have been unable to find a definitive answer to how one would go about unsubscribing from an Observable, which was subscribed to with Observable.subscribe(...). There is another SO answer here (Event and Observable in FSharp), which comes tantalisingly close, but does not explicitly state as to how this is achieved, unless I'm missing something.
The call to Observable.subscribe( someSubscriptionFunction ) returns an IDisposable. Do I simply need to .Dispose() it to remove someSubscriptionFunction (and only it), or does this have effect on the Observable as well, or any of the other subscriptions to this Observable?
First of all, you only need to unsubscribe if you want to stop receiving notifications before the observer would normally stop sending them (e.g. before triggering OnCompleted or OnError).
In order to get a handle on how observables behave, it's probably clearest to look behind the F# interface to the underlying library.
The intention of the IDisposable returned by Observable.subscribe is that it unsubscribes a single IObserver from the IObservable.
The provider must implement a single method, Subscribe, that indicates
that an observer wants to receive push-based notifications. Callers to
the method pass an instance of the observer. The method returns an
IDisposable implementation that enables observers to cancel
notifications at any time before the provider has stopped sending
them.
(Source)
You can see this behaviour from the example implementation provided here (in C#, sadly the page is lacking F# samples):
The relevant snippet is:
private class Unsubscriber : IDisposable
{
private List<IObserver<Location>>_observers;
private IObserver<Location> _observer;
public Unsubscriber(List<IObserver<Location>> observers, IObserver<Location> observer)
{
this._observers = observers;
this._observer = observer;
}
public void Dispose()
{
if (_observer != null && _observers.Contains(_observer))
_observers.Remove(_observer);
}
}
Of course, because these are interfaces, you're totally at the mercy of the implementer in terms of actual behaviour.
So, in terms of actually removing the subscription, yes, all you need to do is to Dispose() the IDisposable and no, it should not have an impact on any other observers.
You could also use the use or using keywords rather than explicitly called dispose. See this page for more.
I am using Cmocka for unit test and that cannot be changed.
I am testing part of my software which invokes callback functions, if a value changes, indicating which data item changed and what the new value is.
The callback functions have this signature:
typedef void (* Value_changed_call_back) (int item_Id, int new_value);
For unit test, I want to register some callback functions and ensure that they are actually invoked, and that they receive the correct parameters.
I can use expect_int() in my mocks, to validate that they are invoked with the correct parameters.
But, I don't see how I can use will_return() since my call back functions are of type void (and that can't be changed).
How would I declare a mock callback function and verify that it is called with the correct parameters? Note that if the function is not called, then the test should fail.
I saw this post and thought about this in CMocka API.
You can use expect_function_call(func) to indicates which function should be called and function_called() in the callback to mark the function as called.
I'm not sure since how long this feature is available (but present in 1.1.5 version).
I answered to this question in case someone comes across this topic even if it's a 2016 ask.
I think the best way to do what you want is to create a stub for the callback and register that. Then inside the callback you set some global variable to a value. Then you would be able to assert that value that gets set in your stub function. This works so long as the assert and the callback are executed on the same thread to make sure that the assert is not a race condition.
[Bindable]
/**
* Display output of video device.
*/
public var videoLocal : Video;
Anyone knows?
[Bindable] is a one of several meta tags that you can use in flex ActionScript code. It can be applied to properties, or methods that are marked in any scope. It cannot be used with static class members.
The key to using the [Bindable] meta tag is understanding what is going on under the hood when you use it. Essentially using data binding is a type of shorthand for adding event listeners and dispatching events.
There are two basic forms of the [Bindable] tag. The first is just [Bindable] followed by a var/property declaration. The Second is [Bindable(event="eventname")] followed by either a var/property declaration, a function/method declaration or one half of a getter/setter declaration.
I'll explain the longer notation first since the other builds on the same concept but with even more shorthand.
When you use [Bindable(event="eventname")] you are essentially telling the compiler that this var/property/function/method (call this the instance member) is 'available' to be used as the source for data binding. You are also telling it that when the value of the instance member has been invalidated/changed and it needs to be re-read that the "eventname" event will be dispatched.
In this longer form this all you are doing. You the developer are responsible for actually dispatching the "eventname" event whenever the value needs to be updated in the binding subscribers.
The real efficiency of using data binding comes on the subscribing side. The typical notation you will see in MXML is value="{instance.propertyName}" When you use the notation { } you are telling the compiler to do the following:
Create an event listener that listens to the event named in the bindable meta tag
In that event listener re-read the instance.propertyName and update this value
If you use the shorter form [Bindable], and you add the tag before a property/var, the compiler fills in the blanks and adds some additional functionality to make the property bindable. Essentially you are telling the compiler "add the events and methods you need to make this property bindable"
Now the way to think of what the compiler will do under the hood is this.
make a private version of your var
create an "event" to trigger the binding
create a getter function with scope and name of your original var that returns the private verson of the var when called.
create a setter function with scope and name of your original var that sets the private version of the var when called AND dispatches the triggering event.
In essence the compiler will do much of the work for you.
[Bindable]
public var xyz
is equivalent to
private var _xyz:String;
[Bindable(event="updateXYZValue")]
public function get xyz():String{
return _xyz;
}
public function set xyz(newxyz:String):void{
_xyz = newxyz;
dispatchEvent(new Event("updateXYZValue"));
}
The only functional differences in these is that in the first instance;
you do not know the name of the event that will be dispatched to trigger the binding
there is no way to update the underlying value without triggering the data binding
This second example also demonstrates one special case of the [Bindable] meta tag. This is that when you are applying it to a getter/setter pair defined for the same variable name you need only apply it to one or the other, it will apply to both. Typically you should set it on the getter.
You can use either notation on a function/method however if you do not specify an event the binding will never be triggered so if you are trying to bind to a function you should alway specify an event. It is also possible to specify more than one triggering event by stacking the tag. eg.
[Bindable(event="metaDataChanged")]
[Bindable(event="metaObjectUpdated")]
public function readMyMetaData():MetaDataObject{
var myMetaDataObject:MetaDataObject;
.
.
.
return myMetaDataObject;
}
This would presume that somewhere else you your class you will dispatch this metaDataChanged event or the metaObjectUpdated event when you want trigger the binding.
Also note that with this notation you can tie the binding of any instance member to any event that the instance will dispatch. Even inherited events that you yourself do not generate such as FrameEnter, OnChange, etc...
Data bindings can also be setup and destroyed during runtime. If you are interested in this take a look at the mx.binding.utils classes.
It is used in Databinding with Flex, you can read more about it here
http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_2.html
Creating properties to use as the source for data binding
When you create a property that you
want to use as the source of a data
binding expression, Flex can
automatically copy the value of the
source property to any destination
property when the source property
changes. To signal to Flex to perform
the copy, you must use the [Bindable]
data tag to register the property with
Flex.
As an addition to what Justin said, you can actually use two ways data binding in Flex with the # character. Here's an example:
<s:TextInput id="txt1" text="#{txt2.text}" />
For a working example with source code enabled you can check out this article I wrote a while back:
Two-ways data binding in Flex
The question is how could I stop a method being called twice, where the first call has not "completed" because its handler is waiting for a url to load for example?
Here is the situation:
I have written a flash client which interfaces with a java server using a binary encrypted protocol (I would love to not have had to re-invent the whole client/server object communcation stack, but I had to encrypt the data in such a way that simple tools like tamper data and charles proxy could not pick them up if using SSL).
The API presents itself to flas as an actionscript swf file, and the API itself is a singleton.
the api exposes some simple methods, including:
login()
getBalance()
startGame()
endGame()
Each method will call my HttpCommunicator class.
HttpCommunicator.as (with error handling and stuff removed):
public class HttpCommunicator {
private var _externalHalder:function;
public function communicate(data:String, externalHandler:APIHandler):void {
// do encryption
// add message numbers etc to data.
this._externalHalder = externalHandler;
request.data = encrypt(addMessageNumers(data)));
loader.addEventListener(Event.COMPLETE, handleComplete);
loader.load(request);
}
private function handleComplete(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
String data = decrypt(loader.data);
// check message numbers match etc.
_externalHandler(data);
}
The problem with this is I cant protect the same HttpCommunicator object from being called twice before the first has handled the complete event, unless:
I create a new HttpCommunicator object every single time I want to send a message. I also want to avoid creating a URLLoader each time, but this is not my code so will be more problematic to know how it behaves).
I can do something like syncronize on communicate. This would effectivly block, but this is better than currupting the data transmission. In theory, the Flash client should not call the same api function twice in a row, but I but it will happen.
I implement a queue of messages. However, this also needs syncronization around the push and pop methods, which I cant find how to do.
Will option 1. even work? If I have a singleton with a method say getBalance, and the getBalance method has:
// class is instantiated through a factory as a singleton
public class API{
var balanceCommunicator:HttpCommunicator = new HttpCommunicator(); // create one for all future calls.
public funciton getBalance(playerId:uint, hander:Fuction):Number {
balanceCommunicator.communicate(...); // this doesnt block
// do other stuff
}
Will the second call trounce the first calls communicator variable? i.e. will it behave as if its static, as there is onlyone copy of the API object?
If say there was a button on the GUI which had "update balance", and the user kept clicking on it, at the same time as say a URLLoader complete event hander being called which also cals the apis getBalance() function (i.e. flash being multithreaded).
Well, first off, with the exception of the networking APIs, Flash is not multithreaded. All ActionScript runs in the same one thread.
You could fairly easily create a semaphore-like system where each call to communicate passed in a "key" as well as the arguments you already specified. That "key" would just be a string that represented the type of call you're doing (getBalance, login, etc). The "key" would be a property in a generic object (Object or Dictionary) and would reference an array (it would have to be created if it didn't exist).
If the array was empty then the call would happen as normal. If not then the information about the call would be placed into an object and pushed into the array. Your complete handler would then have to just check, after it finished a call, if there were more requests in the queue and if so dequeue one of them and run that request.
One thing about this system would be that it would still allow different types of requests to happen in parallel - but you would have to have a new URLLoader per request (which is perfectly reasonable as long as you clean it up after each request is done).