[Selenium] 如何起Driver的时候加header?

我们的automation中有这样一个scenario:

Given a user with user agent "Googlebot/2.X (+http://www.googlebot.com/bot.html)"
Given an ad in category "Children's Books" and waiting for indexing           
When I navigate to browse "Children's Books" in "Australia"          
And I click on the first ad in SearchPage
Then I should see element "lnkVIP_SeeAllResultsOnTop" in ViewItemPage          
And I should see text "You may also be interested in..." in ViewItemPage


在第一步的时候,特别慢,然后从log中看,都是用于去连接browsermob server. 原来以前对于这类case,由于Chrome和FF都不支持直接加header, 所以我们的实现方式,是通过外加proxy —— browsermob来实现的。code如下:

 @Given("a user with user agent \"$useragent\"")
 public void givenUserWithUserAgent(String useragent)throws Exception {
	trackHelper.set(new TrackingHelper());       
	WebUXDriver.getWebUXDriver().setTrackingHelper(trackHelper.get());        
	trackHelper.get().setHeader("User-Agent", useragent);        
	trackHelper.get().init();            
 }


TrackingHelper:

   

     public void init()throwsException { 
           WebUXDriver.getWebUXDriver().setUseTracking(true);        
	   if(runMode.equals("ExistingGrid")) {            
	   // connect to proxy server            
	       socket = newSocket(TrackingPortFactory.PRODXY_MACHINE_IP, TrackingPortFactory.PROXY_MACHINE_PORT);            
		   System.out.println("Start to connect to proxy server...");            
	       socket.setSoTimeout(TIME_OUT);            
	       ips = socket.getInputStream();            
	       ops = socket.getOutputStream();            
	       dos = newDataOutputStream(ops);           
	       brNet = newBufferedReader(newInputStreamReader(ips));        
	   }    
	}


其实这个地方,我们只是想加个header, 完全没必要借助于browsermob,于是改了一下code:

    #browser=*phantomjs
    #header=User-Agent||Googlebot/2.X (+http://www.googlebot.com/bot.html)   
       Given a user      
       When I navigate to browse "Children's Books" in "Australia"   
       And I click on the first normal ad in SearchPage   
       Then I should see element "lnkVIP_SeeAllResultsOnTop" in ViewItemPage   
       And I should see text "You may also be interested in..." in ViewItemPage
 
  

这里用到了browser —— phantomjs, 这个具体可以google一下。加header:

   DesiredCapabilities capability = DesiredCapabilities.phantomjs();
   capability.setCapability("phantomjs.page.customHeaders." + name, value);
   driver = createRemoteWebDriver(url, capability);

再run这个case的时候,时间节约了将近一半,不过这个仅仅针对加header这样简单的request,如果想并发跑tracking类的case,还是需要借助browsermob。

你可能感兴趣的:(Automation,Selenium,JBehave)