Only this and nothing more with Prophecy? - drupal

So I have this in a PhpUnit test:
$alias_manager = $this->prophesize(AliasManagerInterface::class);
$alias_manager->cacheClear($source)->shouldBeCalledTimes(1);
And I would like to tell Prophecy that this is all the alias manager should be called with, no other methods should be called nor this method with any other argument. The latter I can do
$alias_manager->cacheClear(Argument::any())->shouldBeCalledTimes(1);
but how do I say "nothing else" for Prophecy?

With Prophecy, if you call reveal() on the object prophet immediately, the object is assumed to be a dummy object. This means that it'll return null for all public methods of the object it's prophesizing.
However, as soon as you add one method prophet (e.g. by doing your shouldBeCalled...() call or a willReturn() call), the returned object will be a mock or a stub object. In this case, only the configured calls will work and all other calls that are executed will trigger failure.
In other words: You don't have to do anything, this is the standard behaviour.

Related

How to mock an inlined InitiatingFlow return value during another flow

I have SomeBigFlow that calls multiple subflows inside it i.e ValidateFlowA, ValidateFlowB. Assuming it is mandatory for A and B to be initiating flows not functions.
How do I mock a return value for ValidateFlowA when I run the SomeBigFlow in Junit?
I've seen some references to using registerAnswer to mock flows' return value here. I am also curious why this function is only available for InternalMockNetwork.MockNode but not MockNetwork.StartedMockNode which is typically used during junit testing)
I thought I could replicate it by having node[1].registerAnswer(ValidateFlowA.class, 20). But when I ran node[1].startFlow(SomeBigFlow).resultFuture.getOrThrow(), the ValidateFlowA is still using its default call implementation instead of returning the mocked 20 integer value. Maybe I'm using it wrong.
Any pointers on how to make this work or is there a solution to achieve mocking inlined subflows returned values? The only other way I can think of is have a rule of thumb that whenever calling an inlined subflow, put them in an open fun that can be overridden during mocknetwork testing - this makes inlined subflow tedious, hoping for a neater way.
For now, you'd have to use a similar approach to the one outlined here: Corda with mockito_kotlin for unit test.
In summary:
Make the FlowLogic class you are testing open, and move the call to the subflow into an open method
For testing, create a subclass of the open FlowLogic class where you override the open method to return a dummy result
Use this subclass in testing

Chaining callsArgWith on stub

I have gone through the documentation understand what exactly is stub.callsArgWith here:
http://sinonjs.org/releases/v1.17.7/stubs/
But I could not not understand what it makes sense when we chain it like below:
stub.callsArgWith(1, null, "ok")
.callsArgWith(1, new Error("Error!"));
So, basically what it mean is param at index 1 is a callback function and it should be called with first param = null and 2nd param as "ok". But what I could not understand is in what situation we do chaining of callsArgWith and in what sequence are they get used.
Please help me in understanding what exactly is the meaning of above two lines how they will be executed, mean when will it take 'Ok' and when will it return an error.
In older versions of Sinon (specifically versions 1.5 - 1.7), this was how you described behaviour for consecutive calls.
Otherwise, the second callsArgWith call replaces the behaviour of the first callsArgWith.
So in the your example (and assuming the version of Sinon is v1.5 - 1.7):
stub.callsArgWith(1, null, "ok")
.callsArgWith(1, new Error("Error!"));
When the stubbed function is called for the first time,
it will call the 2nd parameter of the stubbed function with the parameters null and "ok".
The second time the stubbed function is called, it will call the 2nd parameter of the stubbed function with an Error object.
So in the your example (and assuming the version of Sinon is NOT v1.5 - 1.7):
stub.callsArgWith(1, null, "ok")
.callsArgWith(1, new Error("Error!"));
Every time the stubbed function is called it will call the 2nd parameter of the stubbed function with an Error object.
Documentation Link: http://sinonjs.org/releases/v1.17.7/stubs/#defining-stub-behavior-on-consecutive-calls

How do I pass additional params to dispatch()?

An API I'm writing accepts two arguments via URL - e.g /api/targets/foo/bar
app = webapp2.WSGIApplication([
('/api/targets/(\w*?)/(\w*?)$', MainPage),
], debug=True)
This fires off a GET handler:
def get(self, url_1, url_2):
#do some stuff
The cool thing here is that I can reference url_1 (foo) and url_2 (bar) inside my GET handler and they're defined for me.
I have another page which accepts both GET and POST requests. About 90% of what happens is the same in either case, so I've opted to use def dispatch() instead of having two separate handlers.
The problem here is that (even though I still have the regex blocks enclosed in my webapp2.WSGIApplication initialisation) they are no longer passed to the request handler, so I have to define them like this:
url_1= self.request.url.split("/")[3]
url_2= self.request.url.split("/")[4]
Which makes me feel like a peon. If I tell dispatch() to expect those two params, they never arrive - what do I need to do to mimic the get behaviour in dispatch?
It would be shorter to use:
arg_one = self.request.route_args[0]
arg_two = self.request.route_args[1]
Take a look at the webapp2 docs for the Request object, specifically the route_args and route_kwargs towards the bottom of the Request section.
This is an interesting use case. If I were you, I would keep get() and post() separate. If get() and post() share code, then I would move that code to a method of the RequestHandler that can be called from both get() and post(), or move the shared code into another class (I find a lot of my RequestHandlers just call methods on my model classes).
If you still want one method to replace both get() and post(), then instead of using dispatch(), I recommend you set the handler_method for the Route (see here in the docs). I would advise against handling these requests entirely in the dispatch() method, as that is supposed to, at some point, call the "handler method", which defaults to GET/POST/etc. based on the HTTP method, but you can set your own handler method to handle GET and POST and whatever else.
If you set the handler_method, it would look like this:
# note that handler_method is the method name as a string
app = webapp2.WSGIApplication([
('/api/targets/(\w*?)/(\w*?)$', MainPage, handler_method='handle_request'),
], debug=True)
In your handler:
class MainPage(webapp2.RequestHandler):
# note that your method signature MUST have args for the route args,
# or else an exception will occur
def handle_request(self, arg_one, arg_two):
# your code here
if self.request.method == 'GET':
# do GET stuff
elif self.request.method == 'POST':
# do POST stuff
This is nice because it leaves dispatch() unchanged. I like to think of dispatch() as pre- and post-processing to occur before/after calling get()/post()/whatever handler method you specify.

need clarity implementing interface GridTask<T,R>

I need clarity in implementing reduce() and map() methods of GridTask,
How can we Pass arguments to these methods,
Map<? extends GridJob, GridNode>
map(List<GridNode> subgrid, T arg) throws GridException
R reduce(List<GridJobResult> results) throws GridException
Specifically, I need to know, how to pass/ invoke reduce method, or if it is invoked implicitly, then how and what arguments are passed to it.
The arguments are passed from GridProjection.execute(...) method.
Every time a GridJob completes, its result is passed to GridTask.result(...) method. The reduce() method is invoked whenever all results from GridJobs are received. You can also force to reduce sooner by returning REDUCE policy form GridTask.result(...) method.

Best way to implement 1:1 asynchronous callbacks/events in ActionScript 3 / Flex / AIR?

I've been utilizing the command pattern in my Flex projects, with asynchronous callback routes required between:
whoever instantiated a given command object and the command object,
the command object and the "data access" object (i.e. someone who handles the remote procedure calls over the network to the servers) that the command object calls.
Each of these two callback routes has to be able to be a one-to-one relationship. This is due to the fact that I might have several instances of a given command class running the exact same job at the same time but with slightly different parameters, and I don't want their callbacks getting mixed up. Using events, the default way of handling asynchronicity in AS3, is thus pretty much out since they're inherently based on one-to-many relationships.
Currently I have done this using callback function references with specific kinds of signatures, but I was wondering if someone knew of a better (or an alternative) way?
Here's an example to illustrate my current method:
I might have a view object that spawns a DeleteObjectCommand instance due to some user action, passing references to two of its own private member functions (one for success, one for failure: let's say "deleteObjectSuccessHandler()" and "deleteObjectFailureHandler()" in this example) as callback function references to the command class's constructor.
Then the command object would repeat this pattern with its connection to the "data access" object.
When the RPC over the network has successfully been completed (or has failed), the appropriate callback functions are called, first by the "data access" object and then the command object, so that finally the view object that instantiated the operation in the first place gets notified by having its deleteObjectSuccessHandler() or deleteObjectFailureHandler() called.
I'll try one more idea:
Have your Data Access Object return their own AsyncTokens (or some other objects that encapsulate a pending call), instead of the AsyncToken that comes from the RPC call. So, in the DAO it would look something like this (this is very sketchy code):
public function deleteThing( id : String ) : DeferredResponse {
var deferredResponse : DeferredResponse = new DeferredResponse();
var asyncToken : AsyncToken = theRemoteObject.deleteThing(id);
var result : Function = function( o : Object ) : void {
deferredResponse.notifyResultListeners(o);
}
var fault : Function = function( o : Object ) : void {
deferredResponse.notifyFaultListeners(o);
}
asyncToken.addResponder(new ClosureResponder(result, fault));
return localAsyncToken;
}
The DeferredResponse and ClosureResponder classes don't exist, of course. Instead of inventing your own you could use AsyncToken instead of DeferredResponse, but the public version of AsyncToken doesn't seem to have any way of triggering the responders, so you would probably have to subclass it anyway. ClosureResponder is just an implementation of IResponder that can call a function on success or failure.
Anyway, the way the code above does it's business is that it calls an RPC service, creates an object encapsulating the pending call, returns that object, and then when the RPC returns, one of the closures result or fault gets called, and since they still have references to the scope as it was when the RPC call was made, they can trigger the methods on the pending call/deferred response.
In the command it would look something like this:
public function execute( ) : void {
var deferredResponse : DeferredResponse = dao.deleteThing("3");
deferredResponse.addEventListener(ResultEvent.RESULT, onResult);
deferredResponse.addEventListener(FaultEvent.FAULT, onFault);
}
or, you could repeat the pattern, having the execute method return a deferred response of its own that would get triggered when the deferred response that the command gets from the DAO is triggered.
But. I don't think this is particularly pretty. You could probably do something nicer, less complex and less entangled by using one of the many application frameworks that exist to solve more or less exactly this kind of problem. My suggestion would be Mate.
Many of the Flex RPC classes, like RemoteObject, HTTPService, etc. return AsyncTokens when you call them. It sounds like this is what you're after. Basically the AsyncToken encapsulates the pending call, making it possible to register callbacks (in the form of IResponder instances) to a specific call.
In the case of HTTPService, when you call send() an AsyncToken is returned, and you can use this object to track the specific call, unlike the ResultEvent.RESULT, which gets triggered regardless of which call it is (and calls can easily come in in a different order than they were sent).
The AbstractCollection is the best way to deal with Persistent Objects in Flex / AIR. The GenericDAO provides the answer.
DAO is the Object which manages to perform CRUD Operation and other Common
Operations to be done over a ValueObject ( known as Pojo in Java ).
GenericDAO is a reusable DAO class which can be used generically.
Goal:
In JAVA IBM GenericDAO, to add a new DAO, the steps to be done is simply,
Add a valueobject (pojo).
Add a hbm.xml mapping file for the valueobject.
Add the 10-line Spring configuration file for the DAO.
Similarly, in AS3 Project Swiz DAO. We want to attain a similar feet of achievement.
Client Side GenericDAO model:
As we were working on a Client Side language, also we should be managing a persistent object Collection (for every valueObject) .
Usage:
Source:
http://github.com/nsdevaraj/SwizDAO

Resources