How to automate downloading attachment from Rest API GET response in SoapUI - groovy

I am using SoapUI 5.5.0 and I am trying to automate the download of an .xls attachment from a Rest API GET response.
It does not appear in the attachment tab of the response.
I tried adding "Enable MTOM | true" but the request stop working with
it.
I tried some groovy scripts but I didn't get anything out of what I tried.
**RAW RESPONSE**
HTTP/1.1 201
Set-Cookie: Design_Authorization=VeryLongToken; Max-Age=93600; Expires=Tue, 12-Jan-2021 22:33:22 GMT; Path=/Redacted; HttpOnly
Set-Cookie: JSESSIONID=bunchofnumbers; Path=/Redacted; HttpOnly
Content-Disposition: attachment; filename=SoapUI_Export_DD_20210111_153209.xls
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/vnd.ms-excel
Transfer-Encoding: chunked
After this, the response has a bunch of unreadable characters.
If I look at the XML tab I get this:
**XML RESPONSE**
<data contentType="application/vnd.ms-excel" contentLength="647680">0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAOwADAP7/CQAGAAAAAAAAAAAAAAAKAAAAAAAAAAAAAAAAEAAA/v///wAAAAD+////AAAAAAEAAACAAAAAAAEAAIABAAAAAgAAgAIAAAADAACAAwAAAAQAAIAEAAD///...it's very long
Adding this here since I could not get a readable format in my thank you comment below.
I had a null error on the response.getProperty('Content-Disposition').split('=')[1] line.
Since I generate and store the name of the export earlier in the testcase, I get the property and then use it.
This is what I ended with:
import org.apache.commons.io.FileUtils
def testStep = testRunner.testCase.testSteps['test step name']
def response = testStep.testRequest.response
assert response.getContentType() == 'application/vnd.ms-excel'
def data = response.getRawResponseBody()
// define filepath/name
exportname = testRunner.testCase.getPropertyValue("exportName")
reportfolder = (System.getProperty("user.home") + File.separatorChar + "Documents" + File.separatorChar);
def filename = reportfolder + exportname +'.xls'
def file = new File(filename)
FileUtils.writeByteArrayToFile(file, data) `

The body of the response is the file. You have to extract it, something like this:
import org.apache.commons.io.FileUtils
def testStep = testRunner.testCase.testSteps['test step name']
def response = testStep.testRequest.response
assert response.getContentType() == 'application/vnd.ms-excel'
def data = response.getRawResponseBody()
// define some filename
def filename = response.getProperty('Content-Disposition').split('=')[1]
def file = new File(filename)
FileUtils.writeByteArrayToFile(file, data)

Related

How to respond to a boolean type in sanic?

I need to respond directly to True or False. How can I do this? Json, text, raw.... can't
code
if param == signature:
return True
else:
return False
Error
File "/usr/local/lib/python3.5/dist-packages/sanic/server.py", line 337, in
write_response
response.output(
AttributeError: 'bool' object has no attribute 'output'
Append:
from sanic.response import json, text
#service_bp.route('/custom', methods=['GET'])
async def cutsom(request):
signature = request.args['signature'][0]
timestamp = request.args['timestamp'][0]
nonce = request.args['nonce'][0]
token = mpSetting['custom_token']
param = [token, timestamp, nonce]
param.sort()
param = "".join(param).encode('utf-8')
sha1 = hashlib.sha1()
sha1.update(param)
param = sha1.hexdigest()
print(param, signature, param == signature)
if param == signature:
return json(True)
else:
return json(False)
I just want to simply return True or False.
I think what you are looking for is something like this:
from sanic import Sanic
from sanic.response import json
app = Sanic()
#app.route("/myroute")
async def myroute(request):
param = request.raw_args.get('param', '')
signature = 'signature'
output = True if param == signature else False
return json(output)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7777)
You just need to wrap your response in response.json.
These endpoints should work as expected:
$ curl -i http://localhost:7777/myroute
HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
Content-Length: 5
Content-Type: application/json
false
And
$ curl -i http://localhost:7777/myroute\?param\=signature
HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
Content-Length: 4
Content-Type: application/json
true

how to read response header values in feature file of karate framework?

example:
I am getting response as
HTTP/1.1 200 OK
X-Backside-Transport: OK OK,OK OK,OK OK
Server: Apache-Coyote/1.1
eventid: 24FCE4D8FA4E6E1212E71960612312321
uuid: ec00d8f0-b168-489e-996e-234234234wer
how to retreive the response header value of field eventid? it tried as " def event = response.eventid "in feature file but getting "pathnotfoundexception"
Read the documentation: responseHeaders.
* def eventId = responseHeaders['eventid'][0]

Spotify Auth + HttpPost + Gson + Client Credential Flow

I'm developing a small app to learn about request/response/gson/etc.
What i'm trying to do is: Get the token through Client Credential Flow, to get some audio features.
I followed the guide:
https://developer.spotify.com/web-api/authorization-guide/#client-credentials-flow
And worked on the same idea as the spotify api:
https://github.com/thelinmichael/spotify-web-api-java/blob/master/src/main/java/com/wrapper/spotify/SpotifyHttpManager.java
Tried diff's stuffs, but i'm stucked now.
Currently, the error is:
HttpResponseProxy{HTTP/1.1 415 Unsupported Media Type [Server: nginx, Date: Thu, 02 Mar 2017 19:59:45 GMT, Content-Length: 888, Connection: keep-alive, Keep-Alive: timeout=600] ResponseEntityProxy{[Content-Length: 888,Chunked: false]}}
Here's the actual code:
BASE64Encoder base64Encoder = new BASE64Encoder();
String encodedClientIdKey = base64Encoder.encode((clientId + ":" + clientSecretKey).getBytes());
HttpPost httpPostRequest = new HttpPost("https://accounts.spotify.com/api/token");
httpPostRequest.setHeader("Content-Type", "application/json");
httpPostRequest.addHeader("Authorization", "Basic " + encodedClientIdKey);
JsonObject json = new JsonObject();
json.addProperty("grant_type", "client_credentials");
StringEntity stringEntity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);
httpPostRequest.setEntity(stringEntity);
HttpResponse post = httpClient.execute(httpPostRequest);
I thought it was a content type problem, but couldn't solve by setting it on header or entity.
Any ideas?
PS:
Tried using form urlencoded instead of json as content type, here's the code (tried add content on header then as parameter as well):
BASE64Encoder base64Encoder = new BASE64Encoder();
String encodedClientIdKey = base64Encoder.encode((clientId + ":" + clientSecretKey).getBytes());
HttpPost httpPostRequest = new HttpPost("https://accounts.spotify.com/api/token");
httpPostRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPostRequest.addHeader("Authorization", "Basic " + encodedClientIdKey);
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("grant_type", "client_credentials"));
nameValuePairs.add(new BasicNameValuePair("Content-Type", "application/x-www-form-urlencoded"));
httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse post = httpClient.execute(httpPostRequest);
System.out.println(post);
And the error was Bad request this time:
HttpResponseProxy{HTTP/1.1 400 Bad Request [Server: nginx, Date: Thu, 02 Mar 2017 20:14:50 GMT, Content-Type: application/json, Content-Length: 70, Connection: keep-alive, Keep-Alive: timeout=600] ResponseEntityProxy{[Content-Type: application/json,Content-Length: 70,Chunked: false]}}

Stripping quotes from response and transferring to request endpoint

I'm using SoapUI for testing some REST api. As a response I'm getting the URL that should be an endpoint of the next request.
I made the following Property Transfer step
source : myApiCall
property : response
target : myHttpCall
property : endpoint
Everything would be ok, but when transferred the endpoint looks like "www.myurl.com" (with quotes) and thus is invalid. How do I strip the quotes from there?
Raw response :
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 98
Content-Type: application/json; charset=utf-8
Expires: Tue, 25 Oct 2016 09:04:28 GMT
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
Date: Tue, 25 Oct 2016 09:04:28 GMT
"http://myurl.com/query?queryUid=90e97bdb-00a3-47c2-8809-c15ceec6ea1b"
The problem is that your Raw response include the " quotes in the String. Then you've two possible solutions, remove the " from the Raw response and keep using the same property transfer.
Or if you can not change the response then you can use a Groovy script testStep to get the Raw response and manipulated it to remove the additional " quotes before set the endpoint:
// get your api call
def myApiCall = context.testCase.getTestStepByName('myApiCall')
// get the raw response
def responseUrl = myApiCall.getPropertyValue('Response')
// since your response contains the `"` remove it
responseUrl = responseUrl.replace('"','')
// set the endpoint correctly
def httpCall = context.testCase.getTestStepByName('myHttpCall')
httpCall.setPropertyValue("endpoint",responseUrl)

How do I implement redirect image using Express?

I want to make GET request to my nodejs server.
I want to implement redirecting image.
On client I have
var body = document.getElementsByTagName('body')[0];
var childElement = document.createElement('img');
childElement.width = 1;
childElement.height = 1;
childElement.style.daiplay = 'none';
childElement.src = 'http://myendpoint.com/api/endpoint?token=token';
body.appendChild(childElement);
My endpoint should redirect client to some URL.
in server code I have
app.route('/api/endpoint').get(function(req, res) {
res.redirect('http://google.com')
});
As a result I get
General
Request URL:http://myurl.com
Request Method:GET
Status Code:302 Found
Remote Address:127.0.0.1:1340
Response Headers
HTTP/1.1 302 Found
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Download-Options: noopen
Location: http://google.com
Vary: Accept, Accept-Encoding
Content-Type: text/plain; charset=utf-8
Content-Length: 41
Date: Tue, 02 Feb 2016 10:50:13 GMT
Connection: keep-alive
But client is not actually redirected..
After this request GET to redirect page happens, but I receive html in response, not being redirected..
What am I doing wrong?

Resources