Setting status code in grpc server method call - go

How do I set the response status code in a grpc method in golang. For example lets say I have the following grpc method
func (i *ItemServerImp) Register(ct context.Context, it *item.RegisterItemRequest) (*item.RegisterItemReply, error) {
}
How do I set the response status to 200 or a 400 based on the input or some processing. I had a look around and could not find a proper way to do this.
However I did find the following https://chromium.googlesource.com/external/github.com/grpc/grpc/+/refs/heads/chromium-deps/2016-07-27/doc/statuscodes.md which says the status code can be set.

You can return a gRPC error using the google.golang.org/grpc/status package as follows:
return nil, status.Error(codes.InvalidArgument, "Incorrect request argument")
The different status codes are available in the google.golang.org/grpc/codes package.

Related

How to set http status code 200, 400, 422, 202 set as success in JMeter

In my test plan I want to mark all the response with, http status code 200, 400, 422, 202 set as success.
Is there any way I can achieve this in a single assertion ?
You should also include what you have tried so far, to resolve this it is very simple,
Need to include a JSR223 assertion with the following script,
if("400".equals(SampleResult.getResponseCode()) || "200".equals(SampleResult.getResponseCode()) || "202".equals(SampleResult.getResponseCode()) || "422".equals(SampleResult.getResponseCode())) {
SampleResult.setSuccessful(true);
AssertionResult.setFailure(false);
}
else {
AssertionResult.setFailure(true);
}
Another solution could be with a Response Assertion
Add the Response Assertion into the Test Plan. This will ensure the Assertion is applied to all the Samplers (Responses)
Then configure the Response Assertion
Field to Test as Response Code
Pattern matching rules to Equals and Or
Click the Add button and add the response codes
In addition to the above configuration, you may check the Ignore Status if you want to Instructs JMeter to set the status to success initially.
Here is another solution based on the previous answer.
//Expected Response codes
def lstExpectedResponseCodes= ["400", "200", "202","422"]
//Actual Response code
String actualResponseCode=SampleResult.getResponseCode()
boolean hasResponseCode = lstExpectedResponseCodes.contains(actualResponseCode)
AssertionResult.setFailure(!hasResponseCode)
SampleResult.setSuccessful(hasResponseCode);

Handle negative cases in JMETER, for example my expected output response is 400

How to handle negative cases in JMETER, for example my expected output response is 400("There are no records") for an GET API?
In JMETER response is coming as failure or warning.
Is JMeter only handle positive scenarios like for all GET API response code should be 200 ?
Add Response Assertion as a child of the HTTP Request sampler which returns HTTP Status Code 400
Configure it as follows:
Tick Ignore status box
Set "Field to test" to Response code
Set "Pattern matching rules" to Equals
Add 400 as a "Pattern to test"
This way JMeter will pass only if the parent HTTP Request sampler returns 400 status code, otherwise it will fail.
You can add to HTTP Request Response Assertion with Ignore status checked
HTTP Responses with statuses in the 4xx and 5xx ranges are normally regarded as unsuccessful. The "Ignore status" checkbox can be used to set the status successful before performing further checks. Note that this will have the effect of clearing any previous assertion failures, so make sure that this is only set on the first assertion.
I tried with this, by adding a BeanShell Assertion with following code.
import org.apache.jmeter.assertions.AssertionResult;
String failureMessage = "";
String ResCode = SampleResult.getResponseCode();
if (!ResCode.equals("400")) {
failureMessage = "Got Response Code" + ResCode;
AssertionResult result = new AssertionResult("Expected Response 400");
result.setFailure(true);
result.setFailureMessage(failureMessage);
prev.addAssertionResult(result);
prev.setSuccessful(false);
SampleResult.setStartNextThreadLoop(true);
} else {
//failure criteria
}

golang get only one stat from json

i tried to get one stat from web api request in json.
This is what called https://api.coinmarketcap.com/v1/ticker/ethereum/
I use this github code example // Get info about coin
coinInfo, err := coinApi.GetCoinData("ethereum")
if err != nil {
log.Println(err)
} else {
fmt.Println(coinInfo)
}
My result in log says
{ethereum Ethereum ETH 2 830.48 0.100287 3.23573e+09 8.0977392218e+10 9.7506734e+07 9.7506734e+07 0.61 -0.65 -7.36 1518176353}
But i want only the price_usd if you look at the api domain. Why cannot get only price?
Already tried coinInfo['price_usd'] but its all not working
Here you find the functions to run the GetCoinData
https://github.com/miguelmota/go-coinmarketcap/blob/master/coinmarketcap.go
Can someone help me to get only the price_usd from api in golang?
According to the docs, you can use the PriceUsd field of the Coin type for this.

gRPC context on the client side

I am building a client/server system in go, using gRPC and protobuf (and with a gRPC gateway to REST).
I use metadata in the context on the server side to carry authentication data from the client, and that works perfectly well.
Now, I'd like the server to set some metadata keys/values so that the client can get them, alongside with the response. How can I do that? Using SetHeader and SendHeader? Ideally, I'd like every single response from the server to integrate that metadata (can be seen as some kind of UnaryInterceptor, but on the response rather than the request?)
Here is the code for the server and for the client.
I finally found my way: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md
So basically, grpc.SetHeader() + grpc.SendHeader() and grpc.SetTrailer() are totally what I was looking for. On the client side, grpc.Header() and grpc.Trailer() functions need to be passed to the RPC call, and their argument is a metadata.MD object to be filled.
On the client side, define your receiving metadata:
var header, trailer metadata.MD
Then, pass it to the SomeRPCCall() unary RPC:
response, err := client.SomeRPCCall(
context.Background(),
proto.MyMessage{},
grpc.Header(&header),
grpc.Trailer(&trailer),
)
And now, you can check what's in your metadata:
for key, value := range header {
fmt.Printf("%s => %s", key, value)
}
for key, value := range trailer {
fmt.Printf("%s => %s", key, value)
}
On the server side, you can:
force the data to be sent right after the RPC is received (but before it's processed):
grpc.SendHeader(ctx, metadata.New(map[string]string{"my-key": "my-value"}))
or set & send the metadata at the end of the RPC process (along with the Status):
grpc.SetTrailer(ctx, metadata.New(map[string]string{"my-key": "my-value"}))

How to change the status of Jmeter Result

I created a script in jmeter, few positive cases and few are negative cases.
For Positive Cases - Response Code will come as 200
For Negative Cases - Response Code will come as 412.
As per Jmeter if Response Code 4xx or 5xx will be considered as Fail but in my case i am expecting result as 412 in negative cases and i want to consider that as Pass.
I tried with BeanShell Assertion but i didn't get the expected.
Code is as below:
String ErrorValue = "${ExpectedError}";
if((ErrorValue.equals("ERROR")) && (ResponseCode.equals("412")))
{
Failure = false;
}
else if(ErrorValue.equals("NO ERROR") && ResponseCode.equals("200"))
{
Failure = false;
}
else
{
Failure=true;
}
with about code i am able to check the expected error and response is same but if that is same how to change the status to pass i didn't get.
Please anyone help me.
Thanks
Sarada
Your Failure = false bit sets only Beanshell Assertion success. As far as I understand you need to change status of the parent sampler. In order to do so you need to invoke SampleResult.setSuccessful() method and set it to "true" as follows:
SampleResult.setSuccessful(true);
Full code:
String ErrorValue = "${ExpectedError}";
if((ErrorValue.equals("ERROR")) && (ResponseCode.equals("412")))
{
Failure = false;
SampleResult.setSuccessful(true);
}
else if(ErrorValue.equals("NO ERROR") && ResponseCode.equals("200"))
{
Failure = false;
SampleResult.setSuccessful(true);
}
else
{
Failure=true;
}
References:
SampleResult class JavaDoc
How to Use JMeter Assertions in 3 Easy Steps
If you are expecting a HTTP Response Code "failure" in JMeter but wish to flag the sample as successful this can be accomplished by a response assertion:
For example:
When validating a DELETE call works, we might want to re-try a GET and validate 404 as expected. Normally JMeter would consider this a failure, but in the context of our test it is not.
Add A Response Assertion to the after-delete GET call.
Apply To: Main Sample
Response Field to Test: Response Code
Check off "Ignore Status"
Pattern Matching Rules: Equals
Pattern to Test: 404
The status of failed or not is always ignored. However, only if the assertion of 404 matches will the request be a success.
For example, if the call returned a 500 jmeter would still ignore the "failed" status, but mark the sample as a failure because 500 != 404.
-Addled

Resources