在做web测试过程中,通常需要先登录被测系统,有的网站登录需要验证码,这无疑增加了测试时间成本,怎么才能实现免登陆?今天我为大家介绍两种方法
一、通过selenium的Cookie类的相关操作,保存和加载浏览器的cookie,实现免登陆
通过查看selenium的api或源码,可以发现cookie类有以下字段,并有相应的set, get方法和多个重载的构造方法:
1.保存登录后的浏览器cookie,代码如下:
以登录M京东为例,可以通过输入账号和密码来登录,这里通过社交账号联合登录,登录成功后记录cookie到本地文件
@DataProvider(name="getQQ")
public Object[][] getQQ() {
return new Object[][] {
// {"979320969"},
{"3454608466"},
};
}
@Test(dataProvider="getQQ")
public void saveCookie_mjd(String qq) throws IOException {
driver.get("https://plogin.m.jd.com/user/login.action?appid=100");
driver.findElement(By.linkText("QQ")).click();
try {
driver.switchTo().frame("ptlogin_iframe");
} catch (NoSuchFrameException e) {
driver.findElement(By.className("ch_uin")).click(); //切换其他账号
driver.switchTo().alert().accept();
driver.switchTo().frame("ptlogin_iframe");
}
driver.findElement(By.id("nick_"+qq)).click();
driver.switchTo().defaultContent();
Assert.assertTrue(driver.getCurrentUrl().contains("https://m.jd.com"));
Set
File cookieFile = new File("./cookies"+qq+".txt");
if (cookieFile.exists()) {
cookieFile.delete();
cookieFile.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(cookieFile));
for (Cookie cookie : set) {
String name = cookie.getName();
String value = cookie.getValue();
String domain = cookie.getDomain();
String path = cookie.getPath();
Date expiry = cookie.getExpiry();
// Date expiry = null;
// if (cookie.getExpiry()!=null) {
// expiry= DateFormatUtils.format(cookie.getExpiry(), "yyyy-MM-dd HH:mm:ss");
// }
boolean httpOnly = cookie.isHttpOnly();
boolean secure = cookie.isSecure();
bw.write(name+";"+value+";"+domain+";"+path+";"+expiry+";"+secure+";"+httpOnly);
bw.newLine();
}
bw.flush();
bw.close();
driver.manage().deleteAllCookies();
}
2.再次登录加载已保存的cookie
@Test
public void testLoadCookie() throws IOException{
driver.get("https://m.jd.com/");
loadCookies("3454608466");
driver.get("http://home.m.jd.com/myJd/newhome.action");
Assert.assertTrue(driver.getTitle().contains("京东触屏版"));
Assert.assertTrue(driver.findElement(By.className("my-info")).isDisplayed());
System.out.println("M京东登录成功");
// 其他测试步骤 略……
}
private void loadCookies(String qq) throws IOException {
driver.manage().deleteAllCookies();
File file = new File("./cookies"+qq+".txt");
BufferedReader br;
try {
br = new BufferedReader(new FileReader(file));
String line = null;
while ((line=br.readLine())!=null) {
String[] cookieFilds = line.split(";");
String name = cookieFilds[0].trim();
String value = cookieFilds[1].trim();
String domain = cookieFilds[2].trim();
String path = cookieFilds[3].trim();
Date expiry = null;
if (!cookieFilds[4].equals(null)) {
expiry = DateUtils.parseDate(cookieFilds[4]);
}
boolean httpOnly = Boolean.valueOf(cookieFilds[5]);
boolean secure = Boolean.valueOf(cookieFilds[6]);
Cookie cookie = new Cookie(name, value, domain, path, expiry, secure, httpOnly);
driver.manage().addCookie(cookie);
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("cookies文件不存在,调用saveCookie_mjd方法重新保存cookies");
saveCookie_mjd(qq);
}
}
二、通过第三方组件browsermob-proxy,这个组件是开源的,可以从https://github.com/lightbody/browsermob-proxy获取最新release源码,本地测试工程的pom.xml配置如下:
手工登录后,复制浏览器的cookienet.lightbody.bmp browsermob-core-littleproxy 2.1.0-beta-6
然后通过browsermob-proxy组件的接口修改request请求头信息添加cookie
@Test public void test22() throws Exception { // 启动 proxy BrowserMobProxyServer server = new BrowserMobProxyServer(); server.start(); // 获取一个 Selenium proxy 对象 Proxy seleniumProxy = ClientUtil.createSeleniumProxy(server); // 配置 capability DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(CapabilityType.PROXY, seleniumProxy); // 启动浏览器 WebDriver driver = new FirefoxDriver(capabilities); driver.manage().window().maximize(); // 从浏览器复制url和cookie,,设置测试url和cookie String testUrl = "测试地址url"; final String cookieValue = "从浏览器复制的cookie"; //登录后获取请求中cookie的那长串内容 server.addRequestFilter(new RequestFilter() { @Override public HttpResponse filterRequest(HttpRequest request, HttpMessageContents contents, HttpMessageInfo messageInfo) { request.headers().add("Cookie", cookieValue); return null; } }); driver.get(testUrl); Thread.sleep(3000); // 剩余测试步骤…… driver.quit(); server.stop(); }接下来,登录成功,可以继续余下测试步骤……
以上两种方法,第一种保存和设置cookie比较繁琐,但是理解起来比较直观,需要熟悉selenium从cookie类和cookie操作的常用api;第二种方法显示比较简单,但是需要学习browsermob-proxy组件及其接口。如有其它更好的方法实现免登陆,欢迎一起交流探讨!