Check Response code in Selenium WebDriver in Jmeter - selenium-webdriver

I am logging into a webPage using Selenium WebDriver in Jmeter, and want to check that all the links are working fine. For that, i wanted to check the response code returned when clicked on the link.
var links = WDS.browser.findElements(pkg.By.cssSelector("a"));
var href;
links.forEach(myFunction);
function myFunction(item) {
WDS.log.info("link value" + item);
href = item.getAttribute("href");
statusCode = new HttpResponseCode().httpResponseCodeViaGet(href);
if(200 != statusCode) {
System.out.println(href + " gave a response code of " + statusCode);
}
}
But the above code doesn't seem to be working. I would be glad if anyone could help me with this.
Also, is there any alternate way to check if all the links are working fine, in Jmeter Selenium Webdriver using javascript?

we're not able to help you unless you show us the code of the HttpResponseCode().httpResponseCodeViaGet beast and the relevant error message from the jmeter.log file.
If the above function is something you copied and pasted from StackOverflow, I strongly doubt that it will ever work because the language of the WebDriver Sampler is not that JavaScript which is being executed by your browser, it's a limited subset of the browser version of JavaScript (for example there is no XMLHttpRequest there)
Instead you have full access to underlying Java SDK and JMeter API so I would recommend amending your function as follows:
var links = WDS.browser.findElements(org.openqa.selenium.By.cssSelector("a"));
var href;
links.forEach(myFunction);
function myFunction(item) {
WDS.log.info("link value" + item);
href = item.getAttribute("href");
var client = org.apache.http.impl.client.HttpClientBuilder.create().build()
var request = new org.apache.http.client.methods.HttpGet(href)
var response = client.execute(request)
var statusCode = response.getStatusLine().getStatusCode()
if(200 != statusCode) {
WDS.log.error(href + " gave a response code of " + statusCode);
}
}
More information:
The WebDriver Sampler: Your Top 10 Questions Answered
HttpClient Tutorial

Related

cefsharp sometimes overlooked js update and will still go to the cache

my problems
cefsharp sometimes overlooked js update and will still go to the cache.
I observed that the site has not been updated for some time, modify js will have this problem.
my environment
win10+vs2015+winforms+cefsharp49
my Configure the code
var settings = new CefSettings { Locale = "zh-CN" };
if (!string.IsNullOrEmpty(HapContext.Configuration.ProxyAdress)
&& !string.IsNullOrEmpty(HapContext.Configuration.Port))
{
settings.CefCommandLineArgs.Add("proxy-server",
HapContext.Configuration.ProxyAdress + ":" + HapContext.Configuration.Port);
}
//settings.CefCommandLineArgs.Add("enable-media-stream", "1");
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = "webbrowser",
SchemeHandlerFactory = new SchemeHandlerFactory()
});
settings.UserAgent = UrlManage.UserAgent;
settings.IgnoreCertificateErrors = true;
settings.CachePath = AppDomain.CurrentDomain.BaseDirectory + #"cache\";
Cef.Initialize(settings, true, false);
my attempt
1.In the browser and cefsharp enter the same URL, get a different js
enter image description here
2.search stackoverflow,I found the problem is similar to mineenter link description here
But there is no answer to this question.
3.Search github also did not find the relevant information
4.When I call Browser.load (Browser.Address), js loads again,Everything is normal again
Any help is much appreciated.
sorry for my english.

Solr 4.3.1 Data-Import command

I'm currently using Solr 4.3.1. i have configured dih for my solr. i would like to do a full import through command prompt. I know the url will be something like this http://localhost:8983/solr/corename/dataimport?command=full-import&clean=true&commit=true is there any method i can do this without using curl ?
Thanks
Edit
string Text = "http://localhost:8983/solr/Latest_TextBox/dataimport?command=full-import&clean=true&commit=true";
var wc = new WebClient();
var Import = wc.DownloadString(Text);
Currently using the above code
Call it like a normal REST url that's it !! I am using it in my application for importing and indexing data from my Local drive and it just works fine ! :) . Use HttpURLConnection to make a request and capture response to see whether it was successful or not . You don't need any specific API to do that . This is a sample code to make a GET request correctly in C# .Try data import handler url with this, it may work !
Console.WriteLine("Making API Call...");
using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
{
client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
response.EnsureSuccessStatusCode();
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine("Result: " + result);
}
Console.ReadLine();
}
}
}
You'll have to call the URL in some way - Solr only operates through a REST API. There is no command line API (the command line tools available just talk to the API). So use your preferred way to talk to a HTTP endpoint, that being curl, wget, GET or what's available for your programming language of choice.
The bundled solrCli application does not have any existing command for triggering a full-import as far as I were able to see (which would just talk to the REST API by calling the URL you've already referenced).

Dart and Client Side File Handling (with authorization)

A server side application requires authorization on file download links. This means a normal <a ng-href="{{createLinkToFile()}}"> is no longer sufficient to get enough parameters passed to the server.
When trying to use a programmatic call to the file download, I get the response data back to Dart client application. Using a simple http GET:
var url = "http://example.com/file";
headers.putIfAbsent("Authorization", () => "bearer " + token;
_http.get(url: url, headers : headers);
The future returned by the GET will hold the data, but how do I instruct the browser to download it as a file, instead of just trying to keep it in memory?
Or is there a way to just do it in a normal link?
After downloading the data from the server like shown in Using Dart to Download a PNG File (Binary File) and displaying it not working you can create a download link like shown at http://blog.butlermatt.me/2014/03/dynamically-generating-download-files/
import 'dart:html';
void main() {
List body = [ 'Some test data ...\n'];
// Create a new blob from the data.
Blob blob = new Blob(body, 'text/plain', 'native');
// Create a data:url which points to that data.
String url = Url.createObjectUrlFromBlob(blob);
// Create a link to navigate to that data and download it.
AnchorElement link = new AnchorElement()
..href = url
..download = 'random_file.txt'
..text = 'Download Now!';
// Insert the link into the DOM.
var p = querySelector('#text');
p.append(link);
}
The code of Seth solves indeed part of the problem. To make it a bit more complete, I'm now using the following:
void doPdfFileRequest(String url) {
var request = new HttpRequest();
request.open('GET', url);
request.responseType = "blob";
request.withCredentials = false;
request.setRequestHeader("Accept", _httpAcceptHeader);
request.setRequestHeader("Authorization", "bearer " + token);
request.onReadyStateChange
.listen((r) => onData(request, "filename.pdf"));
request.send();
}
void onData(HttpRequest request, String filename) {
if (request.readyState == HttpRequest.DONE && request.status == 200) {
if (!isIE()) {
var contentType = request.getResponseHeader("content-type");
AnchorElement downloadLink = new AnchorElement(
href: Url.createObjectUrlFromBlob(request.response));
downloadLink.rel = contentType;
downloadLink.download = filename;
var event = new MouseEvent("click", view: window, cancelable: false);
downloadLink.dispatchEvent(event);
} else {
var href = Url.createObjectUrlFromBlob(request.response);
window.open(href, "_self");
}
}
}
A few things to notice. Instead of using the downloadLink.click(), a mouse event is constructed to ensure that it works on Firefox as well as on Safari and Chrome. Firefox seems not to handle the click() otherwise. Binding it to the DOM as is done in the code of Seth isn't necessary.
Internet Explorer doesn't understand the download attribute, so nothing will happen, therefore a window.open is used to at least have it work (though not ideal) on IE, it's redirecting to self to avoid being hit by the pop up blocker.
There are solutions that convert the result download result to Base64 first and put it in a data:mimetype href, using the blob this isn't necessary.
A nice way to set the filename on the file to download would be through the content disposition header, but this header is marked as unsafe, so cannot be used. The filename is now set in the code.
Another note, notice that a HttpRequest is used instead http.get(), The HttpRequest allows you to set the responseType, in this case blob, which can be transformed into a object url.

Checking HttpResponse OK (200) with Selenium WebDriver [duplicate]

This question already has answers here:
Checking HTTP Status Code in Selenium
(7 answers)
Closed 7 years ago.
I am using Selenium Remote WebDriver. I read all links from csv file and run test against those links. But sometimes I get 404 response.
Is there any way in Selenium WebDriver to check that we get HTTP response 200?
There is no way to get HTTP status codes directly in the WebDriver API. It has been a long-standing feature request, which will likely never be implemented in the project. The correct solution to your problem is to configure your browser to use a proxy which can intercept and log the network traffic, and have your code query that proxy for he result you're after.
Of course, if all you are interested in is checking a link to make sure it returns a 200 status code, you could easily just use an HTTP client library in whatever language you desire to navigate to the link. There's no need to use WebDriver unless you need to manipulate the resulting page in some way.
before using selenium, you could use something like:
public static boolean linkExists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
Using it in this way:
WebDriver driver = new FirefoxDriver();
for(String url : csvArray){
if(linkExists(url)){
driver.get(url);
.
.
.
}
}
Our site has a custom error page for 404 responses. The page title on that page says "404 - Page Not Found". I use driver.Title and check for the text "not found".
Using C#, I wrote the following:
// Check for 404 page:
var pageNotFoundTitleText = "not found";
if (driver.Title.ToLower().Contains(pageNotFoundTitleText)) throw new Exception("### 404 - Page Not found: " + link);
You can do it using RestAssured
import static com.jayway.restassured.RestAssured.given;
int returnCode = given().when().baseUri(url).get().getStatusCode();
if (returnCode == 200) {
webDriver.get(url);
helper.asserts.assertTrue(helper.finder.isElementPresent(By.className("ticketType")));
} else {
helper.asserts.fail("This url "+url+" is returning the following code: " + returnCode);
};
It's a way for that(i think:P).
You can use JavaScript for check http status on page. JS can be called in Java in the following way:
((JavascriptExecutor) webDriver).executeScript(js);
Best option is create dummy webpage on node hard disk with JS function and call that function in executeScript() on that page.
You can also try send all JS code in executeScript(), but i'm not sure that will work.

WebClient issue

I am trying to get contents of http://www.yahoo.com using WebClient#DownloadStringAsync(). However as Silverlight doesn't allow cross domain calls i am getting TargetInvocationException. I know we have to put clientaccesspolicy.xml and crossdomain.xml in our web server root but that is possible only if i have control on my services. Currently Google is not under my control ;), so how do i handle it?
I've did a workaround by making a WCF service in my web application and then calling WebClient. This works perfectly but it is rather ineffecient. Is there any other better way than this?
Thanks in advance :)
Silverlight's cross domain restricitions cause many developers to implement workarounds. If you need to display the html page you get back you should look into Silverlight 4 (WebBrowser) control although this only seems to work when running out-of-browser mode.
If you need to parse through the content you can try some of the following:
For a managed code solution the proxy service you have already implemented is your best option.
Write a Java applet that returns this information. Silverlight can interopt to javascript which can interopt into Java applets. This also works in the reverse but a little difficult to setup. (If you need more info on this let me know).
Use javascript XmlHttpRequest to get the data you want from the source. This can be difficult when supporting multiple browsers. This link shows an example of how to do this (you will need to scroll down). Javascript get Html
Code:
var xmlHttpRequestHandler = new Object();
var requestObject;
xmlHttpRequestHandler.createXmlHttpRequest = function(){
var XmlHttpRequestObject;
if(typeof XMLHttpRequest != "undefined")
{
XmlHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
var tryPossibleVersions =["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp","Microsoft.XMLHttp"];
for(i=0;i<tryPossibleVersions.length;i++)
{
try
{
XmlHttpRequestObject = new ActiveXObject(tryPossibleVersions[i]);
break;
}
catch(xmlHttpRequestObjectError)
{
// Ignore Exception
}
}
}
return XmlHttpRequestObject;}
function getHtml(){
var url = document.getElementById('url').value;
if(url.length > 0)
{
requestObject = xmlHttpRequestHandler.createXmlHttpRequest();
requestObject.onreadystatechange=onReadyStateChangeResponse;
requestObject.open("Get",url, true);
requestObject.send(null);
}}
function onReadyStateChangeResponse(){
var ready, status;
try
{
ready = requestObject.readyState;
status = requestObject.status;
}
catch(e) {}
if(ready == 4 && status == 200)
{
alert(requestObject.responseText);
}}

Resources