plus variable to string with beanshell scripting - beanshell

Can anyone help me on this case, i want to put value of variable "pass" to String "formValue", but cannot load the right body for http post request using Jmeter:
steps,
ThreadGroup with HTTP Request has ${formValue} on body tab,
add beanShell PreProcessor with script bellow:
String pass = "123456";
String formValue = "{\"userName\": \"admin\",\"password\":vars.get("pass")}";
vars.put("formValue",formValue);
thanks!

If I correctly getting the idea your code should be amended as follows:
String pass = "123456";
vars.put("pass", pass);
String formValue = "{\"userName\": \"admin\",\"password\":\"" + vars.get("pass") + "\"}";
vars.put("formValue", formValue);
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more Beanshell and JMeter related tips and tricks.

Related

What should be the java code for rest-assured api for getting the access token

I want to get access token from the given REST-API call.
I have tested this in postman and it is working fine which needs data to be entered in all 3 tabs( Authorization, Header and body and need to fire post method). Please find the attached screenshots for better clarity.
Please guide me how to automate this with java and jayaway restassured library or any other solution.
Postman screenshot- Authorization tab
Postman Screenshot - Header tab
Postman screenshot- Body tab
Note: Username and password is different in Authorization and in different in Body tab
RestAssured.baseURI = "http://URI";
Response res = given().header("Content-Type", "application/json")
.body("{" + " \"username\":\"yourmail#something.com\"," + " \"password\":\"ab#1234\""
+ "}")
.when().post("/api/token").then().log().all().assertThat().statusCode(200)
.contentType(ContentType.JSON).extract().response();
String responseString = res.asString();
System.out.println(responseString);
JsonPath js = new JsonPath(responseString);
String str = js.get("data.access_token");
System.out.println(str);
Assuming that your response will look like this:
{"token_type":"bearer","access_token":"AAAA%2FAAA%3DAAAAAAAA"}
You can try following Rest Assured example:
JsonPath jsonPath = RestAssured.given()
.auth().preemptive().basic("username", "password")
.contentType("application/x-www-form-urlencoded")
.formParam("username", "johndoe")
.formParam("password", "12345678")
.formParam("grant_type", "password")
.formParam("scope", "open_d")
.when()
.post("http://www.example.com/oauth2/token")
.then()
.statusCode(200)
.contentType("application/json")
.extract().jsonPath();
String tokenType = jsonPath.getString("token_type");
String accessToken = jsonPath.getString("access_token");

Comparing entire url through Assert.assertEquals

I want to compare the url and print, so I have used the below code. But it was comparing the whole url like as below
Actual comparison done for the below url :
https://accounts.google.com/signin/v2/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=
Code I have used :
String URL = driver.getCurrentUrl();
Assert.assertEquals(URL, "https://accounts.google.com" );
System.out.println(URL);
Solution needed:
I want compare only the 'https://accounts.google.com'
Please help me out to solve this issue
When you access the url https://accounts.google.com the url is set as :
https://accounts.google.com/signin/v2/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=
This url is dynamic in nature. So you won't be able to use assertEquals() as :
assertEquals() is defined as :
void org.testng.Assert.assertEquals(String actual, String expected)
Asserts that two Strings are equal. If they are not, an AssertionError is thrown.
Parameters:
actual the actual value
expected the expected value
So assertEquals() will validate if two Strings are identical. Hence you see the error.
Solution
To assert the presence of https://accounts.google.com within the current url you can use the function Assert.assertTrue() as follows :
String URL = driver.getCurrentUrl();
Assert.assertTrue(URL.contains("https://accounts.google.com"));
System.out.println(URL);
Explanation
assertTrue() is defined as :
void org.testng.Assert.assertTrue(boolean condition)
Asserts that a condition is true. If it isn't, an AssertionError is thrown.
Parameters:
condition the condition to evaluate
In your case, you should not use 'assertEquals' instead use 'assertTrue'
Assert.assertTrue(URL.startsWith("https://accounts.google.com"));
I have used below code and it working fine for me
String URL = driver.getCurrentUrl();
if(URL.contains("url name"))
{
System.out.println("Landed in correct URL" +
"" + URL);
}else
{
System.out.println("Landed in wrong URL");
}
If You want to remove the Assert.assertTrue and check your url then use this simple technique as below code. AssertEquals, Assertions
Assert.assertTrue(url.equals("https://www.instagram.com/hiteshsingh00/?hl=en"));
can also be written as
Assert.assertEquals(true,url.equals("https://www.instagram.com/hiteshsingh00/?hl=en"));
also assertTrue(x == 2);
assertEquals(2,x);

How to append link in current URL in Selenium using java

I want to know how to append link in current URL. For eg: me link is https://www.google.co.in/ in current program now I have to append /#q=ask+questions in this URL.
Please help.
I know how to get current url(by using getCurrentUrl() syntax)
Thanks
You could use URIBuilder. Something like this:
String someUrl = "https://www.google.co.in";
// or perhaps
// String someUrl = browser.getCurrentUrl();
URIBuilder uri = new URIBuilder(someUrl);
uri.setPath("search");
uri.addQueryParam("q", "ask+questions");
Assert.assertEquals(uri.toString(), "https://www.google.co.in/search?q=ask%2Bquestions");
// or perhaps
// browser.get(uri.toString());
getCurrentUrlUrl() has a return type of String. So you can save it's value and play around like you can with any String.
Take an example, I want to get this url and then append your string and then get() this new webpage:
String url = driver.getCurrentUrl();
String newurl = url+"/#q=ask+questions";
driver.get(newurl);

Wicket 6 - Capturing HttpServletRequest parameters in Multipart form?

USing Wicket 6.17 and servlet 2.5, I have a form that allows file upload, and also has ReCaptcha (using Recaptcha4j). When the form has ReCaptcha without file upload, it works properly using the code:
final HttpServletRequest servletRequest = (HttpServletRequest ) ((WebRequest) getRequest()).getContainerRequest();
final String remoteAddress = servletRequest.getRemoteAddr();
final String challengeField = servletRequest.getParameter("recaptcha_challenge_field");
final String responseField = servletRequest.getParameter("recaptcha_response_field");
to get the challenge and response fields so that they can be validated.
This doesn't work when the form has the file upload because the form must be multipart for the upload to work, and so when I try to get the parameters in that fashion, it fails.
I have pursued trying to get the parameters differently using ServletFileUpload:
ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory(new FileCleaner()) );
String response = IOUtils.toString(servletRequest.getInputStream());
and
ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory(new FileCleaner()) );
List<FileItem> requests = fileUpload.parseRequest(servletRequest);
both of which always return empty.
Using Chrome's network console, I see the values that I'm looking for in the Request Payload, so I know that they are there somewhere.
Any advice on why the requests are coming back empty and how to find them would be greatly appreciated.
Update: I have also tried making the ReCaptcha component multipart and left out the file upload. The result is still the same that the response is empty, leaving me with the original conclusion about multipart form submission being the problem.
Thanks to the Wicket In Action book, I have found the solution:
MultipartServletWebRequest multiPartRequest = webRequest.newMultipartWebRequest(getMaxSize(), "ignored");
// multiPartRequest.parseFileParts(); // this is needed since Wicket 6.19.0+
IRequestParameters params = multiPartRequest.getRequestParameters();
allows me to read the values now using the getParameterValue() method.

API call with name/value in url vs querystring?

im trying to convert the call to the FORVO api (forvo.com) from a hardcoded url string to assigning the request parameters one by one to a ForvoRequestClass's properties that i created in C# via .AddParameter method...but when the request is made...it turns it into querystring format like this:
http://apifree.forvo.com/?key=[mykeygoeshere]&language=en&format=json&limit=1&order=rate-desc&sex=f&type=word&word=APPLE}
instead of like this:
http://apifree.forvo.com/key/[mykeygoeshere]/language/en/format=json/limit/1/order/rate-desc/sex/f/type/word/word/APPLE
i have tried various ways to call it using RestSharp...to no avail...any ideas...??
Ok...i believe i found the answer. On the github repo for RestSharp ( [1]: https://github.com/restsharp/RestSharp/wiki/ParameterTypes-for-RestRequest) I found the following helpful section:
UrlSegment
Unlike GetOrPost, this ParameterType replaces placeholder values in
the RequestUrl:
var rq = new RestRequest("health/{entity}/status");
rq.AddParameter("entity", "s2", ParameterType.UrlSegment);
When the request executes, RestSharp will try to match any
{placeholder} with a parameter of that name (without the {}) and
replace it with the value.
So the above code results in “health/s2/status” being the Url.
So with this info, I constructed my url string with placeholders for each of the parameters for Forvo like this:
/key/{key}/format/{format}/action/{action}/language/{language}/sex/{sex}/order/{order}/limit/{limit}/type/{type}/word/{word}
My final code to then do the substitution was this:
IRestClient client = new RestClient(soundRequest.SiteUrlValue);
request.AddParameter(soundRequest.ApiKeyName, soundRequest.ApiKeyValue, ParameterType.UrlSegment);
request.AddParameter(soundRequest.ActionName, soundRequest.ActionValue, ParameterType.UrlSegment);
request.AddParameter(soundRequest.LanguageName, soundRequest.LanguageValue, ParameterType.UrlSegment);
request.AddParameter(soundRequest.FormatName, soundRequest.FormatValue, ParameterType.UrlSegment);
request.AddParameter(soundRequest.SexName, soundRequest.SexValue, ParameterType.UrlSegment);
request.AddParameter(soundRequest.OrderName, soundRequest.OrderValue, ParameterType.UrlSegment);
request.AddParameter(soundRequest.LimitName, soundRequest.LimitValue, ParameterType.UrlSegment);
request.AddParameter(soundRequest.TypeName, soundRequest.TypeValue, ParameterType.UrlSegment);
request.AddParameter(soundRequest.WordName, soundRequest.WordValue, ParameterType.UrlSegment);