Loading...
вівторок, 12 листопада 2013 р.

Intercepting HTTP requests with Selenium

I have searched for this a long time. And I found the solution, at last! So, we need to intercept traffic from web-site under test. Actually, there are selenium tests (Selenium WebDriver + PhantomJS) and i need to know about requests to data on third-party resources. I'm using LightBody BrowserMob for this reason.

First of all, you need to add some dependency to pom.xml (I'm using Maven) or just download jar file and add it to the project:

<!-- proxy -->
       <dependency>
            <groupId>net.lightbody.bmp</groupId>
            <artifactId>browsermob-proxy</artifactId>
            <version>2.0-beta-8</version>
            <scope>test</scope>
                <exclusions>
      </dependency>
Now you can import stuff from net.lightbody.bmp.proxy.* and  net.lightbody.bmp.proxy.http.* packages and here we go.

First, prepare selenium for work with proxy:
@Before
public void setUp() {
// Handle all requests
requests = new ArrayList<String>();
// Proxy for requests monitoring
server = new ProxyServer(4545);
try {
server.start();
} catch (Exception e) {
fail("Can't start LightBody proxy");
}
Proxy proxy = null;
try {
proxy = server.seleniumProxy();
} catch (UnknownHostException e) {
fail("Unknown selenium proxy host");
}
DesiredCapabilities caps = new DesiredCapabilities();
 // Set proxy to selenium
  caps.setCapability(CapabilityType.PROXY, proxy);
  driver = new PhantomJSDriver(caps);

}
Now just use selenium for browsing site and intercept traffic (thhp requests) as following:

@Test
 public static void testVideo() {
  // HTTP-Requests intercept
  server.addRequestInterceptor(new RequestInterceptor() {
   @Override
   public void process(BrowserMobHttpRequest request) {
    String query = request.getProxyRequest().getQuery();
    String host = request.getProxyRequest().getHost();
    if ((query != null) && (query.length() > 0)) {
     requests.add(query);
    }
   }
  });
// Browsing
  driver.get(HOST);
  assertEquals(requests.size(), 4);// 4 requests sent
}

0 коментарі:

 
TOP