我正在进行空手道测试,需要将 Excel 文件上传到 API。挑战在于每次测试运行都应生成唯一的文件名以避免冲突(例如,防止 409 冲突错误)。
我的场景: 原始设置:
原始 Excel 文件位于
src/test/resources/testdata/sample.xlsx.
我需要生成一个唯一的文件名 (e.g., sample_<UUID>.xlsx)
并将原始文件复制到具有此新名称的临时目录。
复制后,我需要通过 API 端点上传这个新命名的文件,然后清理该文件。
遇到的问题: 它将使用新名称在所需位置创建文件,但它给了我文件未找到异常,最有可能在下面一行是我猜的
And multipart file file = { read: '#(newFilePath)', filename: '#(newFileName)', contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }
空手道测试:
Feature: File Upload Endpoint with Dynamic File Name
Background:
* def UUID = Java.type('java.util.UUID')
* def Files = Java.type('java.nio.file.Files')
* def Paths = Java.type('java.nio.file.Paths')
* def StandardCopyOption = Java.type('java.nio.file.StandardCopyOption')
* def System = Java.type('java.lang.System')
# Function to generate a unique file name
* def generateUniqueFileName =
"""
function() {
var uuid = UUID.randomUUID().toString();
return 'sample_' + uuid + '.xlsx';
}
"""
# Function to copy file with a new name to a specific directory
* def copyFileWithNewName =
"""
function(sourcePath, targetDir, newFileName) {
var sourceFile = Paths.get(sourcePath);
var targetPath = Paths.get(targetDir, newFileName);
Files.createDirectories(targetPath.getParent());
Files.copy(sourceFile, targetPath, StandardCopyOption.REPLACE_EXISTING);
return targetPath.toString();
}
"""
# Set up paths
* def projectDir = System.getProperty('user.dir')
* def originalFilePath = projectDir + '/src/test/resources/testdata/sample.xlsx'
* def targetDir = projectDir + '/src/test/resources/testdata/temp'
# Generate a new file name and copy the file
* def newFileName = generateUniqueFileName()
* def newFilePath = copyFileWithNewName(originalFilePath, targetDir, newFileName)
* print 'New file created at:', newFilePath
Scenario: Upload an Excel file
Given url 'http://localhost:8080/upload/file'
And multipart file file = { read: '#(newFilePath)', filename: '#(newFileName)', contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }
When method post
Then status 202
And match response == 'File uploaded successfully'
# Clean up: delete the temporary file
* eval Files.deleteIfExists(Paths.get(newFilePath))
* print 'Temporary file deleted:', newFilePath
据我所知,如果
read
指向有效文件,它应该可以工作。所以我想你必须自己解决这个问题(或者遵循这个流程)。
另请记住,如果需要,可以推动
read
使用绝对路径(使用 file:
前缀):https://github.com/karatelabs/karate#path-prefixes
karate.toJavaFile()
并打印出传递给 read
值的文件名称。