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

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.

Related

Check Response code in Selenium WebDriver in Jmeter

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

Error while using searchKitManager in React

I am trying to use the searchKitManager inside react-admin I provided the parameters etc according to the docs but when I run the code it throws errors. Here is how the code works
React Admin is running on http://localhost:3000
Golang backend is running on http://localhost:3006
ElasticSearch is running on http://localhost:9200
When data is inserted in mysql database using golang code it is also inserted in elasticsearch later on in one of my display component I call the above searchkitManager as follows
let apiUrl= 'http://localhost:9200/donate' // what link should I pass, url to elasticsearch or url to my backend
const searchkit = new SearchkitManager('/', {
searchUrlPath: `${apiUrl}/_search`,
});
This code will throw 404 Not Found or 400 Bad Request error but the API works in postman
if I change the above link to
let apiUrl= 'http://localhost:9200/donate' // what link should I pass, url to elasticsearch or url to my backend
const searchkit = new SearchkitManager('/', {
searchUrlPath: `${apiUrl}/_doc/`,
});
I am not getting anything at all sometimes it no error in console and sometimes 400 Bad Request or 405 Post Not Allowed
One last thing the link I am providing as for searchUrlPath should be like that or not? or should I pass the apiUrl in place of /? I tried that as well but just to make sure.
Any kind of help will be really appreciated.
Try doing this:
const elasticSearchUrl = 'http://localhost:9200/<your_index>';
const searchkit = new SearchkitManager(elasticSearchUrl );

Getting 302 error while loading javascript library in react

I am trying to import one javascript library in my react project. I am getting the 302 status on the Network panel.
I can see the status 302 ( Not to be modified) in the dev toolbar on browser Netwrok tab.
Can anyone let me know the cause of this issue ?.
The error is not react related it is due to Ajax request.Which is returned by server.
HTTP 302 is used for redirection. My guess is that there is some sort of server error and you are being redirected to an error page using 302. Check the server logs for errors.
Else try the following,
Adding a custom header to the response:
public ActionResult Index(){
if (!HttpContext.User.Identity.IsAuthenticated)
{
HttpContext.Response.AddHeader("REQUIRES_AUTH","1");
}
return View();
}
Or:
Binding a JavaScript function to the ajaxSuccess event and checking to see if the header exists:
$(document).ajaxSuccess(function(event, request, settings) {
if (request.getResponseHeader('REQUIRES_AUTH') === '1') {
window.location = '/';
}
});

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).

How to redirect browser from POST request to GET a new location? servlet

I'm using GAE with Java servlets.
I have a form POST request, and I have to redirect the browser to a new location with GET method. How can I do this?
I got solution:
http://en.wikipedia.org/wiki/Post/Redirect/Get
This is my code sample:
private void seeOther(HttpServletResponse resp, String pathOfOtherToSee)
{
resp.setStatus(HttpServletResponse.SC_SEE_OTHER);
resp.setHeader("Location", pathOfOtherToSee);
}

Resources