6

我为我的管道创建了一个集成测试,以检查是否生成了正确的 CSV 文件:

class CsvBatchSinkTest {

    @RegisterExtension
    static SparkExtension spark = new SparkExtension();

    @TempDir
    static Path directory;

    //this checks if the file is already available
    static boolean isFileWithSuffixAvailable(File directory, String suffix) throws IOException {
        return Files.walk(directory.toPath()).anyMatch(f -> f.toString().endsWith(suffix));
    }

    //this gets content of file
    static List<String> extractFileWithSuffixContent(File file, String suffix) throws IOException {
        return Files.readAllLines(
                Files.walk(file.toPath())
                        .filter(f -> f.toString().endsWith(suffix))
                        .findFirst()
                        .orElseThrow(AssertionException::new));
    }

    @Test
    @DisplayName("When correct dataset is sent to sink, then correct csv file should be generated.")
    void testWrite() throws IOException, InterruptedException {

        File file = new File(directory.toFile(), "output");


        List<Row> data =
                asList(RowFactory.create("value1", "value2"), RowFactory.create("value3", "value4"));

        Dataset<Row> dataset =
                spark.session().createDataFrame(data, CommonTestSchemas.SCHEMA_2_STRING_FIELDS);

         dataset.coalesce(1)
                .write()
                .option("header", "true")
                .option("delimiter", ";")
                .csv(file.getAbsolutePath());

        Awaitility.await()
                .atMost(10, TimeUnit.SECONDS)
                .until(() -> isFileWithSuffixAvailable(file, ".csv"));

        Awaitility.await()
                .atMost(10, TimeUnit.SECONDS)
                .untilAsserted(
                        () ->
                                assertThat(extractFileWithSuffixContent(file, ".csv"))
                                        .containsExactlyInAnyOrder("field1;field2", "value1;value2", "value3;value4"));
    }
}

真实的代码看起来有点不同,这只是一个可重现的例子。

Spark 扩展只是在每次测试之前启动本地 Spark,然后在之后关闭。

测试通过,但是当 junit 尝试清理@TempDir以下异常时:

删除临时目录 C:\Users\RK03GJ\AppData\Local\Temp\junit596680345801656194 失败。无法删除以下路径

在此处输入图像描述

我可以以某种方式修复此错误吗?我试图等待 spark 停止使用awaility,但我并没有真正帮助。

也许我可以以某种方式忽略这个错误?

4

1 回答 1

4

快速猜测:您需要关闭Files.walk返回的流。从文档中引用:

如果需要及时处理文件系统资源,则应使用 try-with-resources 构造来确保close在流操作完成后调用流的方法。

-- https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-java.nio.file.FileVisitOption... -

要解决此问题,请在方法中添加 try-with-resources isFileWithSuffixAvailable

static boolean isFileWithSuffixAvailable(File directory, String suffix) throws IOException {
    try (Stream<Path> walk = Files.walk(directory.toPath())) {
        return walk.anyMatch(f -> f.toString().endsWith(suffix));
    }
}
于 2019-05-24T14:23:57.653 回答