Salesforce Apex: test that callout hasn't been made - salesforce

I want to write a unit test that checks that callout hasn't been made from the trigger.
I know how to test if the callout is made correctly - by implementing HttpCalloutMock:
global class MyHttpCalloutMock implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
//test HTTPRequest here
}
}
But if no HTTP request is made, then the respond() method won't be called. So this approach doesn't test if the request was made at all.
I need something like this:
HTTPRequest.assertNoRequestsHaveBeenMade();
How do I do that?

So I figured it out. It turns out that Salesforce has methods Test.startTest() and Test.stopTest() that make asynchronous callouts synchronous: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_start_stop_test.htm
After making callouts synchronous it's much easier to test them.

Related

How to call Square API method asynchronously

How to call paymentForm.requestCardNonce() method asynchronous
I am integrating square payment gateway in AngularJs, Now I have situation where I have to call paymentForm.requestCardNonce() and this method calls web service in background. Now I have to wait for background call than I can proceed with furthered process. So how can i handle callback from paymentForm.requestCardNonce() method which is provided by Square Payment Gateway https://docs.connect.squareup.com/payments/sqpaymentform/setup
Initialising code sample
var paymentForm = new SqPaymentForm({
applicationId: "sandbox-xxx-xxxxxxxxxxxx",
inputClass: 'sq-input',
callbacks: {
cardNonceResponseReceived: function (errors, nonce, cardData, billingContact, shippingContact) {
// I am receiving response of web service Here
}
}
}
How can I get success response in my custom function by calling method in it ?(Note - its working and calling a method also but i have to do next steps based on response from web service)
addCard = function () {
paymentForm.requestCardNonce();
// Till this function executes I need to wait here. how can I write promise here ?
}
Refrence LInks
https://docs.connect.squareup.com/payments/sqpaymentform/how-it-works
https://github.com/square/connect-api-examples/tree/master/templates/web-ui/payment-form/basic
For posterity, pulling from the comments.
requestCardNonce is asynchronous, and when it completes it will call cardNonceResponseReceived, so if you’re wanting to call a function after it’s finished, you should place it in cardNonceResponseReceived.

How to use sagemaker java API to invoke a endpoint?

I was trying to run this example: tensorflow_abalone_age_predictor_using_layers
, in which abalone_predictor.predict(tensor_proto) is used to call the endpoint and make the prediction. I was trying to use the java API AmazonSageMakerRuntime to achieve the same effect, but I don't know how to specify the body and contentType for the InvokeEndPointRequest. The document is not in detailed abou the format of the request. Greatly appreciate any piece of help!
I have not tried the specific example but the below snippet should help you to invoke the endpoint for predictions
InvokeEndpointRequest invokeEndpointRequest = new InvokeEndpointRequest();
invokeEndpointRequest.setContentType("application/x-image");
ByteBuffer buf = ByteBuffer.wrap(image);
invokeEndpointRequest.setBody(buf);
invokeEndpointRequest.setEndpointName(endpointName);
invokeEndpointRequest.setAccept("application/json");
AmazonSageMakerRuntime amazonSageMaker = AmazonSageMakerRuntimeClientBuilder.defaultClient();
InvokeEndpointResult invokeEndpointResult = amazonSageMaker.invokeEndpoint(invokeEndpointRequest);
I see the example you are trying creates a TensorProto and passes to the endpoint request. You can try to create a TensorProto of your invoke request and set as the body
Just figured I can override the input_fn to convert the request body string to something can be fed to the model, in this case a TensorProto object.

Can i call a method call before executing my Rest API which is coming from Angular

Can i call a method before executing my Rest API which are coming from Angular I am making a post rest call (predefined API from activiti) from angular and i need to call a method before executing the rest API based on the method response i have to decide either i have to call the API or not .Can i use spring AOP? please provide your suggestions and give me any reference links so that i can go head with the implementation
[POST] http://localhost:8080/myapp/test
before this rest call i have to call a method based on the response i have to decide whether i have to call api or not[some how i traps my request and then navigate to the api]
Continuing from the comments, #Narendra, you dont have to modify your controller, what I meant is create a aspect like this
#Pointcut("#annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void requestMapping() {}
#Pointcut("within(de.some.package.controller.*) || within(de.some.package.aspect.*)")
public void myController() {}
#Around("requestMapping() && myController()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
//This will be called before and after any method in the package controller or any method with #RequestMapping annotaion is called
Object result= joinPoint.proceed();
}
This is around advice, which give you more control over the method call. You can also use #Before.
This is done from Java Annotations. I am sure you can do the same from xml as well. Here are a few examples.
http://howtodoinjava.com/spring/spring-aop/aspectj-before-advice-example/
https://www.mkyong.com/spring/spring-aop-examples-advice/

Making calls from the Javascript client library with #Named and unnamed parameters makes no sense

I have a Cloud Endpoints method that looks like this:
//HTTP POST
#ApiMethod(name = "hylyts.insert")
public Hylyt insertHylyt(#Named("url") String url, Hylyt hylyt, User user)
throws OAuthRequestException{
log.info("Trying to save hylyt '"+hylyt+"' with id '"+hylyt.getId());
if (user== null) throw new OAuthRequestException("Your token is no good here.");
hylyt.setArticle(getArticleKey(url, user));
ofy().save().entity(hylyt);
return hylyt;
}
I call it from the Javascript Client Library using this:
gapi.client.hylytit.hylyts.insert({PARAMS}).execute(callback);
Now, if I structure {PARAMS} as suggested in the docs (second example),
{
'url': url,
'resource': {
'hylyt': {
'contentType': 'application/json',
'data': hylyt
}
}
}
I get a null object in the endpoint (not to mention that the whole point of this library is to make these calls simple, which this structure clearly violates).
When I structure {PARAMS} as these answers suggest,
{
'url': url,
'resource': hylyt
}
I get a null object in the endpoint again. The correct syntax is this:
{
'url': url,
'id': hylyt.id
'text': hylyt.text
}
Which just blows my mind. Am I doing this all wrong? Is this a bug? Is it only happening because gapi is also passing the auth token in the background?
Yes, I could use the request syntax instead, but, again, why even use the library if it's just as complex as making the XHRs in pure javascript? I wouldn't mind the complexity if Google explained in the docs why things are happening. But the docs, paraphrased, just say use these methods and the auth, CORS, and XHR magic will happen behind closed doors.
Is the API method correctly recognized as POST method?
The resource parameter which is sent as POST body won't work correctly in a GET request.
The way it looks you are actually sending a GET request with the Hylyt properties in the query string.
To make sure you can change the method annotation to this:
#ApiMethod(name = "hylyts.insert", httpMethod = HttpMethod.POST)
Yup, agreed it's a bug. caused me great pains as well.
So i guess the work around is to create a combined object to pass to your api all named and un named parameters. Rather than hardcode each.. a quick loop might be better.
var param = {};
param["url"] = url;
for (var prop in hylyt) {
param[prop] = hylyt[prop];
}
gapi.client.hylytit.hylyts.insert(param).execute(callback);
That mashing together of parameters / objects can become a slick function if you really want.. but it's a band aid for what I'd consider a defect.
I see in the related question (cloud endpoints resource attribute for transmitting named params & body not working), you actually logged a defect.. Good stuff. Though there still appears no movement on this one. fingers crossed for someday!
The bug has been resolved. The correct syntax is
gapi.client.hylytit.hylyts.insert({url: url}, hylyt).execute(callback);

How to know if a Kohana request is an internal one?

I'm writing an API using Kohana. Each external request must be signed by the client to be accepted.
However, I also sometime need to do internal requests by building a Request object and calling execute(). In these cases, the signature is unnecessary since I know the request is safe. So I need to know that the request was internal so that I can skip the signature check.
So is there any way to find out if the request was manually created using a Request object?
Can you use the is_initial() method of the request object? Using this method, you can determine if a request is a sub request.
Kohana 3.2 API, Request - is_initial()
It sounds like you could easily solve this issue by setting some sort of static variable your app can check. If it's not FALSE, then you know it's internal.
This is how I ended up doing it: I've overridden the Request object and added a is_server_side property to it. Now, when I create the request, I just set this to true so that I know it's been created server-side:
$request = Request::factory($url);
$request->is_server_side(true);
$response = $request->execute();
Then later in the controller receiving the request:
if ($this->request->is_server_side()) {
// Skip signature check
} else {
// Do signature check
}
And here is the overridden request class in application/classes/request.php:
<?php defined('SYSPATH') or die('No direct script access.');
class Request extends Kohana_Request {
protected $is_server_side_ = false;
public function is_server_side($v = null) {
if ($v === null) return $this->is_server_side_;
$this->is_server_side_ = $v;
}
}
Looking through Request it looks like your new request would be considered an internal request but does not have any special flags it sets to tell you this. Look at 782 to 832 in Kohana_Request...nothing to help you.
With that, I'd suggest extending the Kohana_Request_Internal to add a flag that shows it as internal and pulling that in your app when you need to check if it is internal/all others.
Maybe you are looking for is_external method:
http://kohanaframework.org/3.2/guide/api/Request#is_external
Kohana 3.3 in the controller :
$this->request->is_initial()
http://kohanaframework.org/3.3/guide-api/Request#is_initial

Resources