前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ui自动化利用WatchService去给下载事件进行断言

ui自动化利用WatchService去给下载事件进行断言

原创
作者头像
Meccer
修改2021-03-16 09:59:12
5300
修改2021-03-16 09:59:12
举报
文章被收录于专栏:测试学习之路

项目中,存在点击后下载的业务流程,而selenium本身没有很好的方法去断言文件是否下载成功。此时我们可以通过WatchService去监听目录文件,来确定文件是否下载成功。

//监听所下载的文件名

public static String getDownloadedDocumentName(String filepath, String filename)

{

String downloadedFileName = null;

boolean valid = true;

boolean found = false;

//default timeout in seconds

long timeOut = 30;

try

{

Path downloadFolderPath = Paths.get(filepath);

WatchService watchService = FileSystems.getDefault().newWatchService();

downloadFolderPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

long startTime = System.currentTimeMillis();

do

{

WatchKey watchKey;

watchKey = watchService.poll(timeOut,TimeUnit.SECONDS);

long currentTime = (System.currentTimeMillis()-startTime)/1000;

if(currentTime>timeOut)

{

System.out.println("Download operation timed out.. Expected file was not downloaded");

return downloadedFileName;

}

for (WatchEvent<?> event: watchKey.pollEvents())

{

WatchEvent.Kind<?> kind = event.kind();

if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE))

{

String fileName = event.context().toString();

System.out.println("New File Created:" + fileName);

if(fileName.endsWith(filename))

{

downloadedFileName = fileName;

System.out.println("Downloaded file found with extension " + filename + ". File name is " + fileName);

Thread.sleep(500);

found = true;

break;

}

}

}

if(found)

{

return downloadedFileName;

}

else

{

currentTime = (System.currentTimeMillis()-startTime)/1000;

if(currentTime>timeOut)

{

System.out.println("Failed to download expected file");

return downloadedFileName;

}

valid = watchKey.reset();

}

} while (valid);

}

catch (InterruptedException e)

{

System.out.println("Interrupted error - " + e.getMessage());

e.printStackTrace();

}

catch (NullPointerException e)

{

System.out.println("Download operation timed out.. Expected file was not downloaded");

}

catch (Exception e)

{

System.out.println("Error occured - " + e.getMessage());

e.printStackTrace();

}

return downloadedFileName;

}

//确认文件下载是否完成

public static Boolean isFileDownloaded_Ext(String filepath, String filename) {

boolean flag=false;

File dir = new File(filepath);

File[] files = dir.listFiles();

if (files == null || files.length == 0) {

flag = false;

}

for (int i = 0; i <files.length; i++) {

if(files[i].getName().contains(filename)) {

flag=true;

}

}

return flag;

}

运行结果
运行结果

通过上面的方法即可得到下载后的文件名,然后通过下载的文件和用例中的预期做断言即可

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档