使用Gradle下载phantomjs

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载自夜明的孤行灯

本文链接地址: https://www.huangyunkun.com/2015/03/04/gradle-download-driver/

对于Web应用开发,测试中有一个很重要的测试是Functional Test(或者叫Integration Test)。

Functional Test除了需要相关的库以外还需要一个Driver,可以是Chrome,Firefox等等。

因为并不是每一个开发机器或者CI服务器都有浏览器的,所以保证测试的可用性是相当重要的。

常用的方法是将浏览器提前下载,放置在项目目录中,纳入版本管理。这样测试的运行就可以直接使用。

但是这种方法有两个问题:

  • 将大量文件纳入了版本管理中
  • 对于不同平台还需要下载不同平台的Driver

其实还有一个办法就是让构建工具自动下载,下载的时候可以根据平台来下载指定版本。这样即提升了易用性,也降低了切换难度。

这里以phantomjs为例,来看看怎么让Gradle去下载平台相关的phantomjs。

首先明确phantomjs的下载地址,在bitbucket上,https://bitbucket.org/ariya/phantomjs/downloads

文件名是phantomjs+版本号+平台。

首先对于平台的判断使用commons-io库来操作。

import org.apache.tools.ant.taskdefs.condition.Os

buildscript {
repositories {
jcenter()
}
dependencies {
classpath"commons-io:commons-io:2.+"
}
}

判断代码如下:

def osFilenamePart
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
osFilenamePart ="windows.zip"
}elseif (Os.isFamily(Os.FAMILY_MAC)) {
osFilenamePart ="macosx.zip"
}elseif (Os.isFamily(Os.FAMILY_UNIX)) {
osFilenamePart = Os.isArch("amd64") ?"linux-x86_64.tar.bz2":"linux-i686.tar.bz2"
}

下载文件也是common-io库中的FileUtils类。

import org.apache.commons.io.FileUtils

def filename ="phantomjs-$phantomJsVersion-$osFilenamePart"
def outputFile =file("$buildDir/webdriver/$filename")
inputs.property("phantomJsVersion", phantomJsVersion)
outputs.file(outputFile)

doLast {
FileUtils.copyURLToFile(new URL("https://bitbucket.org/ariya/phantomjs/downloads/$filename"), outputFile)
}

当然下载之后还需要一个解压过程

task unzipPhantomJs(type: Copy) {
defoutputDir =file("$buildDir/webdriver/phantomjs")dependsOndownloadPhantomJsoutputs.dir(outputDir)

defarchive =downloadPhantomJs.outputs.files.singleFile

from(Os.isFamily(Os.FAMILY_MAC) ||Os.isFamily(Os.FAMILY_WINDOWS) ?zipTree(archive) :tarTree(archive))into(outputDir)eachFile {
FileCopyDetailsfcp - >fcp.relativePath =newRelativePath(!fcp.directory, *fcp.relativePath.segments[1.. - 1])
}
}

同样的思路,对于其他情况,比如Chrome也是试用的,只不过下载地址稍有不同。

def driverOsFilenamePart
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
driverOsFilenamePart ="win32"
}elseif (Os.isFamily(Os.FAMILY_MAC)) {
driverOsFilenamePart ="mac32"
}elseif (Os.isFamily(Os.FAMILY_UNIX)) {
driverOsFilenamePart = Os.isArch("amd64") ?"linux64":"linux32"
}
FileUtils.copyURLToFile(new URL("http://chromedriver.storage.googleapis.com/${chromeDriverVersion}/chromedriver_${driverOsFilenamePart}.zip"), outputFile)

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载自夜明的孤行灯

本文链接地址: https://www.huangyunkun.com/2015/03/04/gradle-download-driver/

发表评论