Home > Software engineering >  Is there any way to catch errors that come in HTTP reponse for example status code 500, and then fai
Is there any way to catch errors that come in HTTP reponse for example status code 500, and then fai

Time:10-27

I'm writing a simple script and I want selenium to fail the script or at least log the errors that come in http response.

CodePudding user response:

Stable Selenium versions (below 4) are not supporting such functionality.
It has no ability to read HTTP responses.
Tools like Rest Assured are used for such things.

CodePudding user response:

You can use browsermob-proxy tool to achieve that. You only should understand that when you call a page is actually causes a lot of requests to (different) servers and each responds with its own code.

For example the code could look like:

@BeforeTest
public void setUp(){
    /*
    Create and start proxy instance here
    Configure driver to use that created proxy here
     */
}

@Test
public void testHeaders(){
    // Create a map that would be storing url-to-status association
    Map<String, Integer> urlToStatuses = new HashMap<>();
    
    // Configure handler that would be listening for responses
    // and fill the map
    browserMobProxy.addResponseFilter((response, contents, messageInfo) -> {
        urlToStatuses.put(messageInfo.getOriginalUrl(), response.status().code());
    });
    
    // Call a page
    driver.get("https://google.com");
    
    // Test the code of required URL
    Assert.assertEquals(urlToStatuses.get("https://google.com").intValue(), 200);
    
    // Do no forget to clear the map before the next assertion
    urlToStatuses.clear();        
}
  • Related