Karate js file: org.graalvm.polyglot.PolyglotException: Cannot read the array length because "src" is null - karate

I'm using this util feature:
Feature: Set headers
Scenario:
* def authToken = call read('classpath:basic-auth.js') api.credentials
With the javascript basic-auth.js:
function auth(credentials){
var temp = credentials.username + ':' + credentials.password;
var Base64 = Java.type('java.util.Base64');
var encoded = Base64.getEncoder().encodeToString(temp.bytes);
return 'Basic ' + encoded;
}
That worked fine until I update the Karate version to 1.2.0.RC4 and Java version to 17. Now I'm getting the following exception while running the tests:
org.graalvm.polyglot.PolyglotException: Cannot read the array length because "src" is null
- java.base/java.util.Base64$Encoder.encode(Base64.java:291)
- java.base/java.util.Base64$Encoder.encodeToString(Base64.java:345)
- <js>.auth(Unnamed:4)
Thanks in advance!

I fix it replacing:
var encoded = Base64.getEncoder().encodeToString(temp.bytes);
with:
var encoded = Base64.getEncoder().encodeToString(temp.getBytes());
Maybe someone can help me explaining why this works now.

Related

How to get the response body from network tab using Selenium 4 (devTools)

I am using devTools in selenium 4 to retrieve the responses from the network tab.
While I am getting the url, response code, headers etc,
I could not find a way to retrieve the actual response body. (My intention is to validate the key value pairs in the response.)
Any help is much appreciated.
Below is a snippet from my code.
devTools.addListener(Network.responseReceived(),
response -> {
Response res= response.getResponse();
System.out.println("URL - " + res.getUrl());
System.out.println("Status - " + res.getStatus());
System.out.println("Headers - " + res.getHeaders());
System.out.println("Header text - " + res.getHeadersText());
});
devTools = ((ChromeDriver) driver).getDevTools();
devTools.createSession();
devTools.send(Network.clearBrowserCache());
devTools.send(Network.setCacheDisabled(true));
final RequestId[] requestIds = new RequestId[1];
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.of(100000000)));
devTools.addListener(Network.responseReceived(), responseReceived -> {
requestIds[0] = responseReceived.getRequestId();
String url = responseReceived.getResponse().getUrl();
int status = responseReceived.getResponse().getStatus();
String type = responseReceived.getType().toJson();
String headers = responseReceived.getResponse().getHeaders().toString();
String responseBody = devTools.send(Network.getResponseBody(requestIds[0])).getBody();

In Karate - Feature file calling from another feature file along with variable value

My apologies it seems repetitive question but it is really troubling me.
I am trying to call one feature file from another feature file along with variable values. and it is not working at all.
Below is the structure I am using.
my request json having variable name. Filename:InputRequest.json
{
"transaction" : "123",
"transactionDateTime" : "#(sTransDateTime)"
}
my featurefile1 : ABC.Feature
Background:
* def envValue = env
* def config = { username: '#(dbUserName)', password: '#(dbPassword)', url: '#(dbJDBCUrl)', driverClassName: "oracle.jdbc.driver.OracleDriver"};
* def dbUtils = Java.type('Common.DbUtils')
* def request1= read(karate.properties['user.dir'] + 'InputRequest.json')
* def endpoint= '/v1/ABC'
* def appDb = new dbUtils(config);
Scenario: ABC call
* configure cookies = null
Given url endpoint
And request request1
When method Post
Then status 200
Feature file from which I am calling ABC.Feature
#tag1
**my featurefile1: XYZ.Feature**
`Background`:
* def envValue = env
Scenario: XYZ call
* def sTransDateTime = function() { var SimpleDateFormat = Java.type('java.text.SimpleDateFormat'); var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'+00:00'"); return sdf.format(new java.util.Date()); }
* def result = call read(karate.properties['user.dir'] + 'ABC.feature') { sTransDateTime: sTransDateTime }
Problem is,
While executing it, runnerTest has tag1 configured to execute.
Currently, it is ignoring entire ABC.feature to execute and also not generating cucumber report.
If I mention the same tag for ABC.feature (Which is not expected for me as this is just reusable component for me ) then it is being executed but sTransDateTime value is not being passed from XYZ.feature to ABC.feature. Eventually, InputRequest.json should have that value while communicating with the server as a part of the request.
I am using 0.9.4 Karate version. Any help please.
Change to this:
{ sTransDateTime: '#(sTransDateTime)' }
And read this explanation: https://github.com/intuit/karate#call-vs-read
I'm sorry the other part doesn't make sense and shouldn't happen, please follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

Karate: Multipart file : read works but passing content in value fails

I have a endpoint with a multipart request which takes two files as part of the request parameter.
I tried with the below snippet with read and it worked, but my use case is to take content from a file and pass it to the value parameter.
Can I pass the content as a file?
The working code if my I try to read the file from directory is
Working feature::
Scenario:
* configure headers = {'Content-Type' : 'multipart/form-data', 'Authorization': 'Bearer sgahshshshs'}
Given url "http://filecompare.com/compare"
And multipart file oldfile = { read: './oldfile.json', filename: 'oldfile.json'}
And multipart file newfile = { read: './newfile.json', filename: newfile.json'}
When method post
Then status 200
Not working feature::
Scenario:
Given url "http://download-oldfile/oldfile"
When method get
* def oldfile = response
Given url "http://download-newfile/newfile"
When method get
* def newfile = response
* configure headers = {'Content-Type' : 'multipart/form-data', 'Authorization': 'Bearer sgahshshshs'}
Given url "http://filecompare.com/compare"
And multipart file oldfile = { value: '#(oldfile)', filename: 'oldfile.json'}
And multipart file newfile = { value: '#(newfile)', filename: newfile.json'}
When method post
Then status 200
The contents are printed correctly but api returns error when I use value
Please let me know if I am missing something as part of running with the value keyword in multipart file.
Thank you
Can't think of anything other than try to convert the value to a string:
* string oldfile = response
If still stuck, follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue
Had the same issue, resolved without needing to save to file by defining a variable holding the JSON object and using set to manipulate its value.
In your case this would look like:
* def temp = {value: '', filename: 'oldfile.json'}
* set temp.value = oldFile
#[...]
And multipart file oldFile = temp

POSTMAN: Extracting Values from body

I'm trying to recreate a scenario with the postman and there is a _csrf value in the previous GET request response body to be passed with the next POST request.
I Can't find a way to extract the value from POSTMAN.
NOTE: What I want is something similar to Regular Expression Extractor in Jmeter.If you have any Idea about extracting a value form the response body and setting it to a variable. Please let me know.
Cheers,
Muditha
This might help you https://media.readthedocs.org/pdf/postman-quick-reference-guide/latest/postman-quick-reference-guide.pdf
They use Cheerio
2.2.5 How to parse a HTML response to extract a specific value?
Presumed you want to get the _csrf hidden field value for assertions or later use from the response below:
To parse and retrive the value, we will use the cherrio JavaScript library:
responseHTML = cheerio(pm.response.text());
console.log(responseHTML.find('[name="_csrf"]').val());
Cheerio is designed for non-browser use and implements a subset of the jQuery functionality. Read more about it at
https://github.com/cheeriojs/cheerio
responseHTML = cheerio(pm.response.text());
var po= responseHTML.find('[name="_csrf"]').val();
console.log(po);
pm.environment.set("token", po);
/* You need to set the environment in Postman and capture the CSRF token in variable "here po" using a get request. Next in post request the environment variable token can be used */
Just made this JS in post man to parse Without a REGEx. Hope it will help people in the futur
Text to parse : Json : Extract data-id :
{
"code": "OK",
"response": {
"append": {
"html": {
"< .folders": "<a class=\"folder\" href=\"/foobarfoo\" data-id=\"ToExtract\"><div><i class=\"far fa-fw fa-folder\"></i></div><div class=\"folder-name\">blabla</div><div><div class=\"badge\">0</div></div></a>"
}
}
}
}
console.log(responseBody.response);
var jsonData = JSON.parse(responseBody);
var iStart = responseBody.indexOf("response\":")+10;
var scenarioId = responseBody.substr(iStart,10);
var iEnd = scenarioId.indexOf("}");
var scenarioId = scenarioId.substr(0,iEnd);
console.log("scenarioId:" + scenarioId + "iStart: "+ iStart + " scenarioId : " + scenarioId);
pm.environment.set("scenario", scenarioId);

Getting junk value(com.intuit.karate.ScriptObjectMap#XXXX ) when i call karate feature( using Karate.call) in javascript

I am trying to call a karate feature in javascript and capture its response as below, but while doing, the response from karate.call is showing junk value(com.intuit.karate.ScriptObjectMap#XXXX ) . kindly help to get the actual values from karate.call or suggest me any best idea ?
function RequestMandator(featurepath,data) {
var Mandator = [];
data.forEach(function(data){
var TransferId = data.TransferID;
var FocusKey = data.TransferID + ':';
var TimeStamp = data.LastUpdate;
var result = karate.call(featurepath, { input: [TransferId, FocusKey,TimeStamp ] });
karate.log('Added Mandator :', result);
Mandator.push(result);
})
return Mandator;
}
Output:
11:32:53.307 [main] WARN com.intuit.karate - xml parsing failed, response data type set to string: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 15; Open quote is expected for attribute "border" associated with an element type "table".
11:32:53.310 [main] INFO com.intuit.karate - Added Mandator : com.intuit.karate.ScriptObjectMap#102d92c4
Error:
com.intuit.karate.exception.KarateFileNotFoundException: C:\XXXXXXXX\com.intuit.karate.ScriptObjectMap#7808fb9,com.intuit.karate.ScriptObjectMap#25d958c6,com.intuit.karate.ScriptObjectMap#5eeedb60,com.intuit.karate.ScriptObjectMap#6ad6fa53,com.intuit.karate.ScriptObjectMap#6f099cef,com.intuit.karate.ScriptObjectMap#2d66530f,com.intuit.karate.ScriptObjectMap#25b865b5 (The filename, directory name, or volume label syntax is incorrect)
at com.intuit.karate.FileUtils.getFileStream(FileUtils.java:146)
at com.intuit.karate.FileUtils.readFile(FileUtils.java:110)
at com.intuit.karate.ScriptBridge.read(ScriptBridge.java:67)
Please refer to the documentation on type-conversion: https://github.com/intuit/karate#type-conversion
It is not possible to figure out based on the incomplete information you have provided. Still let me try, I think you have done some mistake in string concatenation before calling this function. And the value of featurepath is completely wrong.
In the example below, see how a string concatenation within a JS function leads to what you call "junk value":
* def fun = function(){ var temp = { hello: 'world' }; return temp + '' }
* def bar = fun()
* print "bar:", bar
Results in output:
13:52:50.912 [main] INFO com.intuit.karate - [print] bar: [object Object]
If you still are stuck, the only suggestion I have is follow the instructions here please: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue