美文网首页
selenium之导入导出

selenium之导入导出

作者: halfempty | 来源:发表于2019-04-17 19:28 被阅读0次

前言

文件导出的几个问题:

  • 导入窗口输入指定文件路径, 并确认
  • 确定导出文件路径, 便于下一步读取
  • 导出文件内容校验

导入 - autoit

一般表单的文件上传, 使用sendKeys()即可
除此外, 就需要借助autoit工具来辅助窗口操作
可以参考文章: https://www.guru99.com/use-autoit-selenium.html

导出文件定位

要找到导出的文件, 需要知道浏览器的默认下载路径

这里以java为例, 配置chrome默认下载路径

private ChromeOptions setChromeOptions() {
    String downloadPath = Paths.get(Const.rootPath, Const.downloadPath).toString();
    HashMap<String, Object> chromePrefs = new HashMap<>();
    chromePrefs.put("download.default_directory", downloadPath);
    ChromeOptions options = new ChromeOptions();
    options.setExperimentalOption("prefs", chromePrefs);
    return options;
}

有了路径, 再根据文件名便能定位到导出的文件
当导出的文件重名时, 会自动添加编号, 如xxxx(1).xlsx, 这时通过文件名定位往往有风险
换个角度, 最新导出的文件, 它的更新时间最新, 因此可以通过遍历下载目录下的最新文件来定位刚导出的文件

public static File getNewestDoc() {
    File newest = null;
    File downloadDir = Paths.get(Const.rootPath, Const.downloadPath).toFile();
    if(downloadDir.exists()) {
        File[] files = downloadDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isFile();
            }
        });

        long lastModifyTime = Long.MIN_VALUE;
        for(File f: files) {
            if(f.lastModified() > lastModifyTime) {
                newest = f;
                lastModifyTime = f.lastModified();
            }
        }
    }
    return newest;
}

导出内容校验

自动化测试, 除了完成指定的操作, 还得确保操作的结果符合预期, 因此结果校验少不了
这里以xlsx文件为例, 将每行数据解析成列表, 然后就各字段一一比对

public static List<String> parseDownloadFile(String path) {
    List<String> data = new ArrayList<>();
    try {
        Workbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));
        Sheet sheet = workbook.getSheetAt(0);
        int rowNum = sheet.getLastRowNum();
        if(rowNum > 0) {
            Row row = sheet.getRow(1);
            int colNum = row.getLastCellNum();
            for(int i=0; i<colNum; i++) {
                Cell cell = row.getCell(i);
                if(cell == null) {
                    data.add("");
                } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC &&
                        HSSFDateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = cell.getDateCellValue();
                    String dateStr = format.format(date);
                    data.add(dateStr);
                } else {
                    data.add(cell.getStringCellValue());
                }
            }
        }
    } catch (IOException e) {
        //do nothing
    }
    return data;
}

相关文章

网友评论

      本文标题:selenium之导入导出

      本文链接:https://www.haomeiwen.com/subject/eilowqtx.html