diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/FesodSheetTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/FesodSheetTest.java index 7724fcc5f..b6a11b9be 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/FesodSheetTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/FesodSheetTest.java @@ -189,7 +189,7 @@ void testRead_noArgs_shouldReturnBuilder() { } @Test - void testRead_withFile_shouldConfigureFile() throws Exception { + void testRead_withFile_shouldConfigureFile() { ExcelReaderBuilder builder = FesodSheet.read(tempFile); assertNotNull(builder); ReadWorkbook workbook = writeWorkbook(builder); diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationDataListener.java deleted file mode 100644 index 90b948a7d..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationDataListener.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.annotation; - -import com.alibaba.fastjson2.JSON; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.exception.ExcelCommonException; -import org.apache.fesod.sheet.util.DateUtils; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class AnnotationDataListener extends AnalysisEventListener { - List list = new ArrayList(); - - @Override - public void invoke(AnnotationData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(1, list.size()); - AnnotationData data = list.get(0); - try { - Assertions.assertEquals(data.getDate(), DateUtils.parseDate("2020-01-01 01:01:01")); - } catch (ParseException e) { - throw new ExcelCommonException("Test Exception", e); - } - Assertions.assertEquals(99.99, data.getNumber(), 0.00); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationDataTest.java deleted file mode 100644 index 980d29584..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationDataTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.annotation; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.util.DateUtils; -import org.apache.fesod.sheet.util.StyleTestUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class AnnotationDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - private static File fileStyle07; - private static File fileStyle03; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("annotation07.xlsx"); - file03 = TestFileUtil.createNewFile("annotation03.xls"); - fileStyle07 = TestFileUtil.createNewFile("annotationStyle07.xlsx"); - fileStyle03 = TestFileUtil.createNewFile("annotationStyle03.xls"); - fileCsv = TestFileUtil.createNewFile("annotationCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() throws Exception { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() throws Exception { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() throws Exception { - readAndWrite(fileCsv); - } - - @Test - public void t11WriteStyle07() throws Exception { - writeStyle(fileStyle07); - } - - @Test - public void t12Write03() throws Exception { - writeStyle(fileStyle03); - } - - private void writeStyle(File file) throws Exception { - FesodSheet.write().file(file).head(AnnotationStyleData.class).sheet().doWrite(dataStyle()); - - Workbook workbook = WorkbookFactory.create(file); - Sheet sheet = workbook.getSheetAt(0); - - Row row0 = sheet.getRow(0); - Cell cell00 = row0.getCell(0); - Assertions.assertArrayEquals(new byte[] {-1, 0, -1}, StyleTestUtils.getFillForegroundColor(cell00)); - Assertions.assertArrayEquals(new byte[] {-1, -52, 0}, StyleTestUtils.getFontColor(cell00, workbook)); - Assertions.assertEquals(40, StyleTestUtils.getFontHeightInPoints(cell00, workbook)); - - Cell cell01 = row0.getCell(1); - Assertions.assertArrayEquals(new byte[] {-1, 0, 0}, StyleTestUtils.getFillForegroundColor(cell01)); - Assertions.assertArrayEquals(new byte[] {0, -1, -1}, StyleTestUtils.getFontColor(cell01, workbook)); - Assertions.assertEquals(20, StyleTestUtils.getFontHeightInPoints(cell01, workbook)); - - Row row1 = sheet.getRow(1); - Cell cell10 = row1.getCell(0); - Assertions.assertArrayEquals(new byte[] {0, -52, -1}, StyleTestUtils.getFillForegroundColor(cell10)); - Assertions.assertArrayEquals(new byte[] {0, 0, -1}, StyleTestUtils.getFontColor(cell10, workbook)); - Assertions.assertEquals(50, StyleTestUtils.getFontHeightInPoints(cell10, workbook)); - Cell cell11 = row1.getCell(1); - Assertions.assertArrayEquals(new byte[] {0, -128, 0}, StyleTestUtils.getFillForegroundColor(cell11)); - Assertions.assertArrayEquals(new byte[] {-64, -64, -64}, StyleTestUtils.getFontColor(cell11, workbook)); - Assertions.assertEquals(30, StyleTestUtils.getFontHeightInPoints(cell11, workbook)); - } - - private void readAndWrite(File file) throws Exception { - FesodSheet.write().file(file).head(AnnotationData.class).sheet().doWrite(dataStyle()); - - if (file == fileCsv) { - return; - } - - Workbook workbook = WorkbookFactory.create(file); - Sheet sheet = workbook.getSheetAt(0); - Assertions.assertEquals(50 * 256, sheet.getColumnWidth(0), 0); - - Row row0 = sheet.getRow(0); - Assertions.assertEquals(1000, row0.getHeight(), 0); - - Row row1 = sheet.getRow(1); - Assertions.assertEquals(2000, row1.getHeight(), 0); - } - - private List dataStyle() throws Exception { - List list = new ArrayList<>(); - AnnotationStyleData data = new AnnotationStyleData(); - data.setString("string"); - data.setString1("string1"); - list.add(data); - return list; - } - - private List data() throws Exception { - List list = new ArrayList<>(); - AnnotationData data = new AnnotationData(); - data.setDate(DateUtils.parseDate("2020-01-01 01:01:01")); - data.setNumber(99.99); - data.setIgnore("忽略"); - data.setTransientString("忽略"); - list.add(data); - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationIndexAndNameDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationIndexAndNameDataListener.java deleted file mode 100644 index face1498a..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationIndexAndNameDataListener.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.annotation; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class AnnotationIndexAndNameDataListener extends AnalysisEventListener { - - List list = new ArrayList(); - - @Override - public void invoke(AnnotationIndexAndNameData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(1, list.size()); - AnnotationIndexAndNameData data = list.get(0); - Assertions.assertEquals("第0个", data.getIndex0()); - Assertions.assertEquals("第1个", data.getIndex1()); - Assertions.assertEquals("第2个", data.getIndex2()); - Assertions.assertEquals("第4个", data.getIndex4()); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationIndexAndNameDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationIndexAndNameDataTest.java deleted file mode 100644 index 3eb7f69d4..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationIndexAndNameDataTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.annotation; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * Annotation data test - * - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class AnnotationIndexAndNameDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("annotationIndexAndName07.xlsx"); - file03 = TestFileUtil.createNewFile("annotationIndexAndName03.xls"); - fileCsv = TestFileUtil.createNewFile("annotationIndexAndNameCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() { - readAndWrite(fileCsv); - } - - private void readAndWrite(File file) { - FesodSheet.write(file, AnnotationIndexAndNameData.class).sheet().doWrite(data()); - FesodSheet.read(file, AnnotationIndexAndNameData.class, new AnnotationIndexAndNameDataListener()) - .sheet() - .doRead(); - } - - private List data() { - List list = new ArrayList(); - AnnotationIndexAndNameData data = new AnnotationIndexAndNameData(); - data.setIndex0("第0个"); - data.setIndex1("第1个"); - data.setIndex2("第2个"); - data.setIndex4("第4个"); - list.add(data); - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/bom/BomData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/bom/BomData.java deleted file mode 100644 index 4e05f6464..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/bom/BomData.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.bom; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -@Getter -@Setter -@EqualsAndHashCode -public class BomData { - @ExcelProperty("姓名") - private String name; - - @ExcelProperty("年纪") - private Long age; -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/bom/BomDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/bom/BomDataTest.java deleted file mode 100644 index b5259c62f..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/bom/BomDataTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.bom; - -import java.io.File; -import java.io.FileOutputStream; -import java.nio.charset.Charset; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.compress.utils.Lists; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.metadata.data.ReadCellData; -import org.apache.fesod.sheet.read.listener.ReadListener; -import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * bom test - * - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -@Slf4j -public class BomDataTest { - - @Test - public void t01ReadCsv() { - readCsv(TestFileUtil.readFile("bom" + File.separator + "no_bom.csv")); - readCsv(TestFileUtil.readFile("bom" + File.separator + "office_bom.csv")); - } - - @Test - public void t02ReadAndWriteCsv() throws Exception { - readAndWriteCsv(TestFileUtil.createNewFile("bom" + File.separator + "bom_default.csv"), null, null); - readAndWriteCsv(TestFileUtil.createNewFile("bom" + File.separator + "bom_utf_8.csv"), "UTF-8", null); - readAndWriteCsv(TestFileUtil.createNewFile("bom" + File.separator + "bom_utf_8_lower_case.csv"), "utf-8", null); - readAndWriteCsv(TestFileUtil.createNewFile("bom" + File.separator + "bom_gbk.csv"), "GBK", null); - readAndWriteCsv(TestFileUtil.createNewFile("bom" + File.separator + "bom_gbk_lower_case.csv"), "gbk", null); - readAndWriteCsv(TestFileUtil.createNewFile("bom" + File.separator + "bom_utf_16be.csv"), "UTF-16BE", null); - readAndWriteCsv( - TestFileUtil.createNewFile("bom" + File.separator + "bom_utf_8_not_with_bom.csv"), - "UTF-8", - Boolean.FALSE); - } - - private void readAndWriteCsv(File file, String charsetName, Boolean withBom) throws Exception { - Charset charset = null; - if (charsetName != null) { - charset = Charset.forName(charsetName); - } - FesodSheet.write(new FileOutputStream(file), BomData.class) - .charset(charset) - .withBom(withBom) - .excelType(ExcelTypeEnum.CSV) - .sheet() - .doWrite(data()); - - FesodSheet.read(file, BomData.class, new ReadListener() { - - private final List dataList = Lists.newArrayList(); - - @Override - public void invokeHead(Map> headMap, AnalysisContext context) { - String head = headMap.get(0).getStringValue(); - Assertions.assertEquals("姓名", head); - } - - @Override - public void invoke(BomData data, AnalysisContext context) { - dataList.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(10, dataList.size()); - BomData bomData = dataList.get(0); - Assertions.assertEquals("姓名0", bomData.getName()); - Assertions.assertEquals(20, (long) bomData.getAge()); - } - }) - .charset(charset) - .sheet() - .doRead(); - } - - private void readCsv(File file) { - FesodSheet.read(file, BomData.class, new ReadListener() { - - private final List dataList = Lists.newArrayList(); - - @Override - public void invokeHead(Map> headMap, AnalysisContext context) { - String head = headMap.get(0).getStringValue(); - Assertions.assertEquals("姓名", head); - } - - @Override - public void invoke(BomData data, AnalysisContext context) { - dataList.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(10, dataList.size()); - BomData bomData = dataList.get(0); - Assertions.assertEquals("姓名0", bomData.getName()); - Assertions.assertEquals(20L, (long) bomData.getAge()); - } - }) - .sheet() - .doRead(); - } - - private List data() { - List list = ListUtils.newArrayList(); - for (int i = 0; i < 10; i++) { - BomData data = new BomData(); - data.setName("姓名" + i); - data.setAge(20L); - list.add(data); - } - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheDataTest.java deleted file mode 100644 index 3899ba8c4..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheDataTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.cache; - -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.data.DemoData; -import org.apache.fesod.sheet.enums.CacheLocationEnum; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.metadata.FieldCache; -import org.apache.fesod.sheet.read.listener.PageReadListener; -import org.apache.fesod.sheet.util.ClassUtils; -import org.apache.fesod.sheet.util.FieldUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -@Slf4j -public class CacheDataTest { - - private static File file07; - private static File fileCacheInvoke; - private static File fileCacheInvoke2; - private static File fileCacheInvokeMemory; - private static File fileCacheInvokeMemory2; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("cache/cache.xlsx"); - fileCacheInvoke = TestFileUtil.createNewFile("cache/fileCacheInvoke.xlsx"); - fileCacheInvoke2 = TestFileUtil.createNewFile("cache/fileCacheInvoke2.xlsx"); - fileCacheInvokeMemory = TestFileUtil.createNewFile("cache/fileCacheInvokeMemory.xlsx"); - fileCacheInvokeMemory2 = TestFileUtil.createNewFile("cache/fileCacheInvokeMemory2.xlsx"); - } - - @Test - public void t01ReadAndWrite() throws Exception { - Field field = FieldUtils.getField(ClassUtils.class, "FIELD_THREAD_LOCAL", true); - ThreadLocal, FieldCache>> fieldThreadLocal = - (ThreadLocal, FieldCache>>) field.get(ClassUtils.class.newInstance()); - Assertions.assertNull(fieldThreadLocal.get()); - FesodSheet.write(file07, CacheData.class).sheet().doWrite(data()); - FesodSheet.read(file07, CacheData.class, new PageReadListener(dataList -> { - Assertions.assertNotNull(fieldThreadLocal.get()); - })) - .sheet() - .doRead(); - Assertions.assertNull(fieldThreadLocal.get()); - } - - @Test - public void t02ReadAndWriteInvoke() throws Exception { - FesodSheet.write(fileCacheInvoke, CacheInvokeData.class).sheet().doWrite(dataInvoke()); - FesodSheet.read(fileCacheInvoke, CacheInvokeData.class, new AnalysisEventListener() { - - @Override - public void invokeHeadMap(Map headMap, AnalysisContext context) { - Assertions.assertEquals(2, headMap.size()); - Assertions.assertEquals("姓名", headMap.get(0)); - Assertions.assertEquals("年龄", headMap.get(1)); - } - - @Override - public void invoke(CacheInvokeData data, AnalysisContext context) {} - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} - }) - .sheet() - .doRead(); - - Field name = FieldUtils.getField(CacheInvokeData.class, "name", true); - ExcelProperty annotation = name.getAnnotation(ExcelProperty.class); - InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation); - Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues"); - memberValues.setAccessible(true); - Map map = (Map) memberValues.get(invocationHandler); - map.put("value", new String[] {"姓名2"}); - - FesodSheet.write(fileCacheInvoke2, CacheInvokeData.class).sheet().doWrite(dataInvoke()); - FesodSheet.read(fileCacheInvoke2, CacheInvokeData.class, new AnalysisEventListener() { - - @Override - public void invokeHeadMap(Map headMap, AnalysisContext context) { - Assertions.assertEquals(2, headMap.size()); - Assertions.assertEquals("姓名2", headMap.get(0)); - Assertions.assertEquals("年龄", headMap.get(1)); - } - - @Override - public void invoke(CacheInvokeData data, AnalysisContext context) {} - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} - }) - .sheet() - .doRead(); - } - - @Test - public void t03ReadAndWriteInvokeMemory() throws Exception { - FesodSheet.write(fileCacheInvokeMemory, CacheInvokeMemoryData.class) - .filedCacheLocation(CacheLocationEnum.MEMORY) - .sheet() - .doWrite(dataInvokeMemory()); - FesodSheet.read( - fileCacheInvokeMemory, - CacheInvokeMemoryData.class, - new AnalysisEventListener() { - - @Override - public void invokeHeadMap(Map headMap, AnalysisContext context) { - Assertions.assertEquals(2, headMap.size()); - Assertions.assertEquals("姓名", headMap.get(0)); - Assertions.assertEquals("年龄", headMap.get(1)); - } - - @Override - public void invoke(CacheInvokeMemoryData data, AnalysisContext context) {} - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} - }) - .filedCacheLocation(CacheLocationEnum.MEMORY) - .sheet() - .doRead(); - - Field name = FieldUtils.getField(CacheInvokeMemoryData.class, "name", true); - ExcelProperty annotation = name.getAnnotation(ExcelProperty.class); - InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation); - Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues"); - memberValues.setAccessible(true); - Map map = (Map) memberValues.get(invocationHandler); - map.put("value", new String[] {"姓名2"}); - - FesodSheet.write(fileCacheInvokeMemory2, CacheInvokeMemoryData.class) - .filedCacheLocation(CacheLocationEnum.MEMORY) - .sheet() - .doWrite(dataInvokeMemory()); - FesodSheet.read( - fileCacheInvokeMemory2, - CacheInvokeMemoryData.class, - new AnalysisEventListener() { - - @Override - public void invokeHeadMap(Map headMap, AnalysisContext context) { - Assertions.assertEquals(2, headMap.size()); - Assertions.assertEquals("姓名", headMap.get(0)); - Assertions.assertEquals("年龄", headMap.get(1)); - } - - @Override - public void invoke(CacheInvokeMemoryData data, AnalysisContext context) {} - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} - }) - .filedCacheLocation(CacheLocationEnum.MEMORY) - .sheet() - .doRead(); - } - - private List data() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - CacheData simpleData = new CacheData(); - simpleData.setName("姓名" + i); - simpleData.setAge((long) i); - list.add(simpleData); - } - return list; - } - - private List dataInvoke() { - List list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - CacheInvokeData simpleData = new CacheInvokeData(); - simpleData.setName("姓名" + i); - simpleData.setAge((long) i); - list.add(simpleData); - } - return list; - } - - private List dataInvokeMemory() { - List list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - CacheInvokeMemoryData simpleData = new CacheInvokeMemoryData(); - simpleData.setName("姓名" + i); - simpleData.setAge((long) i); - list.add(simpleData); - } - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheInvokeData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheInvokeData.java deleted file mode 100644 index ef7cd4301..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheInvokeData.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.cache; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -public class CacheInvokeData { - @ExcelProperty("姓名") - private String name; - - @ExcelProperty("年龄") - private Long age; -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheInvokeMemoryData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheInvokeMemoryData.java deleted file mode 100644 index 18cff5145..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheInvokeMemoryData.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.cache; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -public class CacheInvokeMemoryData { - @ExcelProperty("姓名") - private String name; - - @ExcelProperty("年龄") - private Long age; -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataDataListener.java deleted file mode 100644 index 12b1b4991..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataDataListener.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.celldata; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class CellDataDataListener extends AnalysisEventListener { - - List list = new ArrayList<>(); - - @Override - public void invoke(CellDataReadData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(1, list.size()); - CellDataReadData cellDataData = list.get(0); - - Assertions.assertEquals("2020年01月01日", cellDataData.getDate().getData()); - Assertions.assertEquals(2L, (long) cellDataData.getInteger1().getData()); - Assertions.assertEquals(2L, (long) cellDataData.getInteger2()); - if (context.readWorkbookHolder().getExcelType() != ExcelTypeEnum.CSV) { - Assertions.assertEquals( - "B2+C2", cellDataData.getFormulaValue().getFormulaData().getFormulaValue()); - } else { - Assertions.assertNull(cellDataData.getFormulaValue().getData()); - } - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataDataTest.java deleted file mode 100644 index 050e25e50..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataDataTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.celldata; - -import java.io.File; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.enums.CellDataTypeEnum; -import org.apache.fesod.sheet.metadata.data.FormulaData; -import org.apache.fesod.sheet.metadata.data.WriteCellData; -import org.apache.fesod.sheet.util.DateUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class CellDataDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("cellData07.xlsx"); - file03 = TestFileUtil.createNewFile("cellData03.xls"); - fileCsv = TestFileUtil.createNewFile("cellDataCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() throws Exception { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() throws Exception { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() throws Exception { - readAndWrite(fileCsv); - } - - private void readAndWrite(File file) throws Exception { - FesodSheet.write(file, CellDataWriteData.class).sheet().doWrite(data()); - FesodSheet.read(file, CellDataReadData.class, new CellDataDataListener()) - .sheet() - .doRead(); - } - - private List data() throws Exception { - List list = new ArrayList<>(); - CellDataWriteData cellDataData = new CellDataWriteData(); - cellDataData.setDate(new WriteCellData<>(DateUtils.parseDate("2020-01-01 01:01:01"))); - WriteCellData integer1 = new WriteCellData<>(); - integer1.setType(CellDataTypeEnum.NUMBER); - integer1.setNumberValue(BigDecimal.valueOf(2L)); - cellDataData.setInteger1(integer1); - cellDataData.setInteger2(2); - WriteCellData formulaValue = new WriteCellData<>(); - FormulaData formulaData = new FormulaData(); - formulaValue.setFormulaData(formulaData); - formulaData.setFormulaValue("B2+C2"); - cellDataData.setFormulaValue(formulaValue); - list.add(cellDataData); - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/charset/CharsetData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/charset/CharsetData.java deleted file mode 100644 index 24d2e055b..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/charset/CharsetData.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.charset; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -@Getter -@Setter -@EqualsAndHashCode -public class CharsetData { - @ExcelProperty("姓名") - private String name; - - @ExcelProperty("年纪") - private Integer age; -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/charset/CharsetDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/charset/CharsetDataTest.java deleted file mode 100644 index e9bc80be6..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/charset/CharsetDataTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.charset; - -import java.io.File; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.compress.utils.Lists; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.metadata.data.ReadCellData; -import org.apache.fesod.sheet.read.listener.ReadListener; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * charset - * - * - */ -@Slf4j -@TestMethodOrder(MethodOrderer.MethodName.class) -public class CharsetDataTest { - private static final Charset GBK = Charset.forName("GBK"); - private static File fileCsvGbk; - private static File fileCsvUtf8; - private static File fileCsvError; - - @BeforeAll - public static void init() { - fileCsvGbk = TestFileUtil.createNewFile("charset" + File.separator + "fileCsvGbk.csv"); - fileCsvUtf8 = TestFileUtil.createNewFile("charset" + File.separator + "fileCsvUtf8.csv"); - fileCsvError = TestFileUtil.createNewFile("charset" + File.separator + "fileCsvError.csv"); - } - - @Test - public void t01ReadAndWriteCsv() { - readAndWrite(fileCsvGbk, GBK); - readAndWrite(fileCsvUtf8, StandardCharsets.UTF_8); - } - - @Test - public void t02ReadAndWriteCsvError() { - FesodSheet.write(fileCsvError, CharsetData.class).charset(GBK).sheet().doWrite(data()); - FesodSheet.read(fileCsvError, CharsetData.class, new ReadListener() { - - private final List dataList = Lists.newArrayList(); - - @Override - public void invokeHead(Map> headMap, AnalysisContext context) { - String head = headMap.get(0).getStringValue(); - Assertions.assertNotEquals("姓名", head); - } - - @Override - public void invoke(CharsetData data, AnalysisContext context) { - dataList.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} - }) - .charset(StandardCharsets.UTF_8) - .sheet() - .doRead(); - } - - private void readAndWrite(File file, Charset charset) { - FesodSheet.write(file, CharsetData.class).charset(charset).sheet().doWrite(data()); - FesodSheet.read(file, CharsetData.class, new ReadListener() { - - private final List dataList = Lists.newArrayList(); - - @Override - public void invokeHead(Map> headMap, AnalysisContext context) { - String head = headMap.get(0).getStringValue(); - Assertions.assertEquals("姓名", head); - } - - @Override - public void invoke(CharsetData data, AnalysisContext context) { - dataList.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(10, dataList.size()); - CharsetData charsetData = dataList.get(0); - Assertions.assertEquals("姓名0", charsetData.getName()); - Assertions.assertEquals(0, (long) charsetData.getAge()); - } - }) - .charset(charset) - .sheet() - .doRead(); - } - - private List data() { - List list = Lists.newArrayList(); - for (int i = 0; i < 10; i++) { - CharsetData data = new CharsetData(); - data.setName("姓名" + i); - data.setAge(i); - list.add(data); - } - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CellDataDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CellDataDataTest.java new file mode 100644 index 000000000..85efa97ee --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CellDataDataTest.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.converter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import java.io.File; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.support.ExcelTypeEnum; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.listeners.CollectingReadListener; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * + */ +public class CellDataDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile(format); + FesodSheet.write(file, CellDataWriteData.class).sheet().doWrite(TestDataBuilder.cellDataWriteData()); + + CollectingReadListener listener = new CollectingReadListener<>(); + FesodSheet.read(file, CellDataReadData.class, listener).sheet().doRead(); + + assertEquals(1, listener.getRowCount()); + CellDataReadData row = listener.getFirstRow(); + + assertEquals("2020年01月01日", row.getDate().getData()); + assertEquals(2L, (long) row.getInteger1().getData()); + assertEquals(2L, (long) row.getInteger2()); + if (format.toExcelTypeEnum() != ExcelTypeEnum.CSV) { + assertEquals("B2+C2", row.getFormulaValue().getFormulaData().getFormulaValue()); + } else { + assertNull(row.getFormulaValue().getData()); + } + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataReadData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CellDataReadData.java similarity index 97% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataReadData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CellDataReadData.java index d34a58880..15f85306a 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataReadData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CellDataReadData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.celldata; +package org.apache.fesod.sheet.converter; import lombok.EqualsAndHashCode; import lombok.Getter; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataWriteData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CellDataWriteData.java similarity index 97% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataWriteData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CellDataWriteData.java index 9f1c4e9df..67d5f0934 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/celldata/CellDataWriteData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CellDataWriteData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.celldata; +package org.apache.fesod.sheet.converter; import java.util.Date; import lombok.EqualsAndHashCode; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterDataListener.java deleted file mode 100644 index ed4408400..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterDataListener.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.converter; - -import com.alibaba.fastjson2.JSON; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.util.TestUtil; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class ConverterDataListener extends AnalysisEventListener { - private final List list = new ArrayList<>(); - - @Override - public void invoke(ConverterReadData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(1, list.size()); - ConverterReadData data = list.get(0); - Assertions.assertEquals(TestUtil.TEST_DATE, data.getDate()); - Assertions.assertEquals(TestUtil.TEST_LOCAL_DATE, data.getLocalDate()); - Assertions.assertEquals(TestUtil.TEST_LOCAL_DATE_TIME, data.getLocalDateTime()); - Assertions.assertEquals(Boolean.TRUE, data.getBooleanData()); - Assertions.assertEquals(data.getBigDecimal().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0); - Assertions.assertEquals(data.getBigInteger().intValue(), BigInteger.ONE.intValue(), 0.0); - Assertions.assertEquals(1L, (long) data.getLongData()); - Assertions.assertEquals(1L, (long) data.getIntegerData()); - Assertions.assertEquals(1L, (long) data.getShortData()); - Assertions.assertEquals(1L, (long) data.getByteData()); - Assertions.assertEquals(1.0, data.getDoubleData(), 0.0); - Assertions.assertEquals((float) 1.0, data.getFloatData(), 0.0); - Assertions.assertEquals("测试", data.getString()); - Assertions.assertEquals("自定义", data.getCellData().getStringValue()); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterDataTest.java index 1038a1624..d9a795121 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterDataTest.java @@ -25,6 +25,8 @@ package org.apache.fesod.sheet.converter; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.InputStream; import java.math.BigDecimal; @@ -32,84 +34,111 @@ import java.util.ArrayList; import java.util.List; import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.metadata.data.WriteCellData; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.helpers.RoundTripHelper; +import org.apache.fesod.sheet.util.DateUtils; import org.apache.fesod.sheet.util.FileUtils; import org.apache.fesod.sheet.util.TestFileUtil; import org.apache.fesod.sheet.util.TestUtil; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** - * + * Test converter read/write for all Excel formats using parameterized tests. */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class ConverterDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - private static File fileImage07; - private static File fileImage03; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("converter07.xlsx"); - file03 = TestFileUtil.createNewFile("converter03.xls"); - fileCsv = TestFileUtil.createNewFile("converterCsv.csv"); - fileImage07 = TestFileUtil.createNewFile("converterImage07.xlsx"); - fileImage03 = TestFileUtil.createNewFile("converterImage03.xls"); - } - - @Test - public void t01ReadAndWrite07() throws Exception { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() throws Exception { - readAndWrite(file03); +public class ConverterDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile(format); + List data = TestDataBuilder.converterWriteData(); + + RoundTripHelper.write(file, ConverterWriteData.class, data); + List result = RoundTripHelper.read(file, ConverterReadData.class); + + assertEquals(1, result.size()); + ConverterReadData row = result.get(0); + assertEquals(TestUtil.TEST_DATE, row.getDate()); + assertEquals(TestUtil.TEST_LOCAL_DATE, row.getLocalDate()); + assertEquals(TestUtil.TEST_LOCAL_DATE_TIME, row.getLocalDateTime()); + assertEquals(Boolean.TRUE, row.getBooleanData()); + assertEquals(row.getBigDecimal().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0); + assertEquals(row.getBigInteger().intValue(), BigInteger.ONE.intValue(), 0.0); + assertEquals(1L, (long) row.getLongData()); + assertEquals(1L, (long) row.getIntegerData()); + assertEquals(1L, (long) row.getShortData()); + assertEquals(1L, (long) row.getByteData()); + assertEquals(1.0, row.getDoubleData(), 0.0); + assertEquals((float) 1.0, row.getFloatData(), 0.0); + assertEquals("test", row.getString()); + assertEquals("custom", row.getCellData().getStringValue()); } - @Test - public void t03ReadAndWriteCsv() throws Exception { - readAndWrite(fileCsv); - } - - private void readAndWrite(File file) throws Exception { - FesodSheet.write(file, ConverterWriteData.class).sheet().doWrite(data()); - FesodSheet.read(file, ConverterReadData.class, new ConverterDataListener()) + @ParameterizedTest + @MethodSource("allFormats") + void readAllConverter(ExcelFormat format) throws Exception { + String fileName = "converter" + File.separator + "converter" + + format.name().toLowerCase().replace("xlsx", "07").replace("xls", "03") + + format.getExtension(); + List list = FesodSheet.read(TestFileUtil.readFile(fileName)) + .head(ReadAllConverterData.class) .sheet() - .doRead(); - } - - @Test - public void t11ReadAllConverter07() { - readAllConverter("converter" + File.separator + "converter07.xlsx"); - } - - @Test - public void t12ReadAllConverter03() { - readAllConverter("converter" + File.separator + "converter03.xls"); - } - - @Test - public void t13ReadAllConverterCsv() { - readAllConverter("converter" + File.separator + "converterCsv.csv"); - } - - @Test - public void t21WriteImage07() throws Exception { - writeImage(fileImage07); - } - - @Test - public void t22WriteImage03() throws Exception { - writeImage(fileImage03); + .doReadSync(); + assertEquals(1, list.size()); + ReadAllConverterData data = list.get(0); + assertEquals(data.getBigDecimalBoolean().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0); + assertEquals(data.getBigDecimalNumber().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0); + assertEquals(data.getBigDecimalString().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0); + assertEquals(data.getBigIntegerBoolean().intValue(), BigInteger.ONE.intValue(), 0.0); + assertEquals(data.getBigIntegerNumber().intValue(), BigInteger.ONE.intValue(), 0.0); + assertEquals(data.getBigIntegerString().intValue(), BigInteger.ONE.intValue(), 0.0); + assertTrue(data.getBooleanBoolean()); + assertTrue(data.getBooleanNumber()); + assertTrue(data.getBooleanString()); + assertEquals(1L, (long) data.getByteBoolean()); + assertEquals(1L, (long) data.getByteNumber()); + assertEquals(1L, (long) data.getByteString()); + assertEquals(data.getDateNumber(), DateUtils.parseDate("2020-01-01 01:01:01")); + assertEquals(data.getDateString(), DateUtils.parseDate("2020-01-01 01:01:01")); + assertEquals(data.getLocalDateTimeNumber(), DateUtils.parseLocalDateTime("2020-01-01 01:01:01", null, null)); + assertEquals(data.getLocalDateTimeString(), DateUtils.parseLocalDateTime("2020-01-01 01:01:01", null, null)); + assertEquals(1.0, data.getDoubleBoolean(), 0.0); + assertEquals(1.0, data.getDoubleNumber(), 0.0); + assertEquals(1.0, data.getDoubleString(), 0.0); + assertEquals((float) 1.0, data.getFloatBoolean(), 0.0); + assertEquals((float) 1.0, data.getFloatNumber(), 0.0); + assertEquals((float) 1.0, data.getFloatString(), 0.0); + assertEquals(1L, (long) data.getIntegerBoolean()); + assertEquals(1L, (long) data.getIntegerNumber()); + assertEquals(1L, (long) data.getIntegerString()); + assertEquals(1L, (long) data.getLongBoolean()); + assertEquals(1L, (long) data.getLongNumber()); + assertEquals(1L, (long) data.getLongString()); + assertEquals(1L, (long) data.getShortBoolean()); + assertEquals(1L, (long) data.getShortNumber()); + assertEquals(1L, (long) data.getShortString()); + assertEquals("true", data.getStringBoolean().toLowerCase()); + assertEquals("测试", data.getStringString()); + assertEquals("#VALUE!", data.getStringError()); + if (format != ExcelFormat.CSV) { + assertEquals("2020-1-1 1:01", data.getStringNumberDate()); + } else { + assertEquals("2020-01-01 01:01:01", data.getStringNumberDate()); + } + double doubleStringFormulaNumber = new BigDecimal(data.getStringFormulaNumber()).doubleValue(); + assertEquals(2.0, doubleStringFormulaNumber, 0.0); + assertEquals("1测试", data.getStringFormulaString()); } - private void writeImage(File file) throws Exception { + @ParameterizedTest + @MethodSource("allFormats") + void writeImage(ExcelFormat format) throws Exception { + Assumptions.assumeTrue(format.supportsImages(), "Format does not support images"); + File file = createTempFile(format); InputStream inputStream = null; try { List list = new ArrayList<>(); @@ -128,31 +157,4 @@ private void writeImage(File file) throws Exception { } } } - - private void readAllConverter(String fileName) { - FesodSheet.read(TestFileUtil.readFile(fileName), ReadAllConverterData.class, new ReadAllConverterDataListener()) - .sheet() - .doRead(); - } - - private List data() throws Exception { - List list = new ArrayList(); - ConverterWriteData converterWriteData = new ConverterWriteData(); - converterWriteData.setDate(TestUtil.TEST_DATE); - converterWriteData.setLocalDate(TestUtil.TEST_LOCAL_DATE); - converterWriteData.setLocalDateTime(TestUtil.TEST_LOCAL_DATE_TIME); - converterWriteData.setBooleanData(Boolean.TRUE); - converterWriteData.setBigDecimal(BigDecimal.ONE); - converterWriteData.setBigInteger(BigInteger.ONE); - converterWriteData.setLongData(1L); - converterWriteData.setIntegerData(1); - converterWriteData.setShortData((short) 1); - converterWriteData.setByteData((byte) 1); - converterWriteData.setDoubleData(1.0); - converterWriteData.setFloatData((float) 1.0); - converterWriteData.setString("测试"); - converterWriteData.setCellData(new WriteCellData<>("自定义")); - list.add(converterWriteData); - return list; - } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterReadData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterReadData.java index e76bdccc8..0b293c6fb 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterReadData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterReadData.java @@ -25,63 +25,21 @@ package org.apache.fesod.sheet.converter; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Date; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.fesod.sheet.annotation.ExcelProperty; import org.apache.fesod.sheet.metadata.data.ReadCellData; +import org.apache.fesod.sheet.testkit.models.ConverterBaseData; /** - * + * Data model for testing converter functionality during Excel reading operations. + * Extends {@link ConverterBaseData} and adds a custom cell data field. */ @Getter @Setter -@EqualsAndHashCode -public class ConverterReadData { - @ExcelProperty("日期") - private Date date; - - @ExcelProperty("本地日期") - private LocalDate localDate; - - @ExcelProperty("本地日期时间") - private LocalDateTime localDateTime; - - @ExcelProperty("布尔") - private Boolean booleanData; - - @ExcelProperty("大数") - private BigDecimal bigDecimal; - - @ExcelProperty("大整数") - private BigInteger bigInteger; - - @ExcelProperty("长整型") - private long longData; - - @ExcelProperty("整型") - private Integer integerData; - - @ExcelProperty("短整型") - private Short shortData; - - @ExcelProperty("字节型") - private Byte byteData; - - @ExcelProperty("双精度浮点型") - private double doubleData; - - @ExcelProperty("浮点型") - private Float floatData; - - @ExcelProperty("字符串") - private String string; - - @ExcelProperty("自定义") +@EqualsAndHashCode(callSuper = true) +public class ConverterReadData extends ConverterBaseData { + @ExcelProperty("Custom Cell Data") private ReadCellData cellData; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterTest.java index a67e573a9..f2ae2ad41 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterTest.java @@ -29,19 +29,17 @@ import org.apache.fesod.sheet.converters.WriteConverterContext; import org.apache.fesod.sheet.converters.floatconverter.FloatNumberConverter; import org.apache.fesod.sheet.metadata.data.WriteCellData; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; /** * */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class ConverterTest { +public class ConverterTest extends AbstractExcelTest { @Test - public void t01FloatNumberConverter() { + public void floatNumberConverter() { FloatNumberConverter floatNumberConverter = new FloatNumberConverter(); WriteConverterContext context = new WriteConverterContext<>(); context.setValue(95.62F); diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterWriteData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterWriteData.java index 13a24a82a..b2deae5ee 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterWriteData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ConverterWriteData.java @@ -25,63 +25,21 @@ package org.apache.fesod.sheet.converter; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Date; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.fesod.sheet.annotation.ExcelProperty; import org.apache.fesod.sheet.metadata.data.WriteCellData; +import org.apache.fesod.sheet.testkit.models.ConverterBaseData; /** - * + * Data model for testing converter functionality during Excel writing operations. + * Extends {@link ConverterBaseData} and adds a custom cell data field. */ @Getter @Setter -@EqualsAndHashCode -public class ConverterWriteData { - @ExcelProperty("日期") - private Date date; - - @ExcelProperty("本地日期") - private LocalDate localDate; - - @ExcelProperty("本地日期时间") - private LocalDateTime localDateTime; - - @ExcelProperty("布尔") - private Boolean booleanData; - - @ExcelProperty("大数") - private BigDecimal bigDecimal; - - @ExcelProperty("大整数") - private BigInteger bigInteger; - - @ExcelProperty("长整型") - private long longData; - - @ExcelProperty("整型") - private Integer integerData; - - @ExcelProperty("短整型") - private Short shortData; - - @ExcelProperty("字节型") - private Byte byteData; - - @ExcelProperty("双精度浮点型") - private double doubleData; - - @ExcelProperty("浮点型") - private Float floatData; - - @ExcelProperty("字符串") - private String string; - - @ExcelProperty("自定义") +@EqualsAndHashCode(callSuper = true) +public class ConverterWriteData extends ConverterBaseData { + @ExcelProperty("Custom Cell Data") private WriteCellData cellData; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CustomConverterTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CustomConverterTest.java index 2c7801c56..e9de87747 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CustomConverterTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CustomConverterTest.java @@ -28,35 +28,18 @@ import org.apache.fesod.sheet.FesodSheet; import org.apache.fesod.sheet.converters.Converter; import org.apache.fesod.sheet.converters.ConverterKeyBuild; -import org.apache.fesod.sheet.util.TestFileUtil; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; import org.apache.fesod.sheet.write.builder.ExcelWriterSheetBuilder; import org.apache.fesod.sheet.write.metadata.holder.WriteSheetHolder; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; -@TestMethodOrder(MethodOrderer.MethodName.class) -public class CustomConverterTest { - - private static File converterCsvFile10; - private static File converterExcelFile11; - private static File converterExcelFile12; - private static File converterExcelFile13; - private static File converterCsvFile14; - - @BeforeAll - static void init() { - converterCsvFile10 = TestFileUtil.createNewFile("converter10.csv"); - converterExcelFile11 = TestFileUtil.createNewFile("converter11.xls"); - converterExcelFile12 = TestFileUtil.createNewFile("converter12.xlsx"); - converterExcelFile13 = TestFileUtil.createNewFile("converter13.xlsx"); - converterCsvFile14 = TestFileUtil.createNewFile("converter14.csv"); - } +public class CustomConverterTest extends AbstractExcelTest { @Test - void t01ConverterMapTest() throws Exception { + void converterMapTest() { + File converterCsvFile10 = new File(tempDir, "converter10.csv"); TimestampStringConverter timestampStringConverter = new TimestampStringConverter(); TimestampNumberConverter timestampNumberConverter = new TimestampNumberConverter(); ExcelWriter excelWriter = FesodSheet.write(converterCsvFile10) @@ -74,22 +57,23 @@ void t01ConverterMapTest() throws Exception { } @Test - void t02Write10() throws Exception { - writeFile(converterCsvFile10); + void writeCsv() throws Exception { + writeFile(new File(tempDir, "converter10.csv")); } @Test - void t03Write11() throws Exception { - writeFile(converterExcelFile11); + void writeXls() throws Exception { + writeFile(new File(tempDir, "converter11.xls")); } @Test - void t04Write12() throws Exception { - writeFile(converterExcelFile12); + void writeXlsx() throws Exception { + writeFile(new File(tempDir, "converter12.xlsx")); } @Test - void t05GlobalConverterInSheetHolder() throws Exception { + void globalConverterInSheetHolder() { + File converterExcelFile13 = new File(tempDir, "converter13.xlsx"); TimestampStringConverter timestampStringConverter = new TimestampStringConverter(); ExcelWriter excelWriter = FesodSheet.write(converterExcelFile13) .registerConverter(timestampStringConverter) @@ -103,14 +87,14 @@ void t05GlobalConverterInSheetHolder() throws Exception { } @Test - void t06GlobalConverterWriteWithoutFieldLevelConverter() throws Exception { - FesodSheet.write(converterCsvFile14) + void globalConverterWriteWithoutFieldLevelConverter() throws Exception { + FesodSheet.write(new File(tempDir, "converter14.csv")) .registerConverter(new TimestampStringConverter()) .sheet() .doWrite(globalData()); } - private void writeFile(File file) throws Exception { + private void writeFile(File file) { FesodSheet.write(file) .registerConverter(new TimestampNumberConverter()) .registerConverter(new TimestampStringConverter()) @@ -118,7 +102,7 @@ private void writeFile(File file) throws Exception { .doWrite(data()); } - private List globalData() throws Exception { + private List globalData() { List list = new ArrayList<>(); GlobalConverterWriteData writeData = new GlobalConverterWriteData(); writeData.setTimestampData(Timestamp.valueOf("2020-01-01 01:00:00")); @@ -126,12 +110,7 @@ private List globalData() throws Exception { return list; } - private List data() throws Exception { - List list = new ArrayList<>(); - CustomConverterWriteData writeData = new CustomConverterWriteData(); - writeData.setTimestampStringData(Timestamp.valueOf("2020-01-01 01:00:00")); - writeData.setTimestampNumberData(Timestamp.valueOf("2020-12-01 12:12:12")); - list.add(writeData); - return list; + private List data() { + return TestDataBuilder.customConverterWriteData(); } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CustomConverterWriteData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CustomConverterWriteData.java index dceeb2594..3bef2b789 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CustomConverterWriteData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/CustomConverterWriteData.java @@ -29,9 +29,9 @@ @Setter @EqualsAndHashCode public class CustomConverterWriteData { - @ExcelProperty(value = "时间戳-字符串", converter = TimestampStringConverter.class) + @ExcelProperty(value = "TimestampString", converter = TimestampStringConverter.class) private Timestamp timestampStringData; - @ExcelProperty(value = "时间戳-数字", converter = TimestampNumberConverter.class) + @ExcelProperty(value = "TimestampNumber", converter = TimestampNumberConverter.class) private Timestamp timestampNumberData; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/excludeorinclude/ExcludeOrIncludeData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExcludeOrIncludeData.java similarity index 96% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/excludeorinclude/ExcludeOrIncludeData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExcludeOrIncludeData.java index 4b51154a2..06e1fa1a4 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/excludeorinclude/ExcludeOrIncludeData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExcludeOrIncludeData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.excludeorinclude; +package org.apache.fesod.sheet.converter; import lombok.EqualsAndHashCode; import lombok.Getter; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExcludeOrIncludeDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExcludeOrIncludeDataTest.java new file mode 100644 index 000000000..9705d2ac9 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExcludeOrIncludeDataTest.java @@ -0,0 +1,172 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.converter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * + */ +public class ExcludeOrIncludeDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void excludeIndex(ExcelFormat format) throws Exception { + File file = createTempFile(format); + Set excludeColumnIndexes = new HashSet(); + excludeColumnIndexes.add(0); + excludeColumnIndexes.add(3); + FesodSheet.write(file, ExcludeOrIncludeData.class) + .excludeColumnIndexes(excludeColumnIndexes) + .sheet() + .doWrite(data()); + List> dataMap = FesodSheet.read(file).sheet().doReadSync(); + assertEquals(1, dataMap.size()); + Map record = dataMap.get(0); + assertEquals(2, record.size()); + assertEquals("column2", record.get(0)); + assertEquals("column3", record.get(1)); + } + + @ParameterizedTest + @MethodSource("allFormats") + void excludeFieldName(ExcelFormat format) throws Exception { + File file = createTempFile(format); + Set excludeColumnFieldNames = new HashSet(); + excludeColumnFieldNames.add("column1"); + excludeColumnFieldNames.add("column3"); + excludeColumnFieldNames.add("column4"); + FesodSheet.write(file, ExcludeOrIncludeData.class) + .excludeColumnFieldNames(excludeColumnFieldNames) + .sheet() + .doWrite(data()); + List> dataMap = FesodSheet.read(file).sheet().doReadSync(); + assertEquals(1, dataMap.size()); + Map record = dataMap.get(0); + assertEquals(1, record.size()); + assertEquals("column2", record.get(0)); + } + + @ParameterizedTest + @MethodSource("allFormats") + void includeIndex(ExcelFormat format) throws Exception { + File file = createTempFile(format); + Set includeColumnIndexes = new HashSet(); + includeColumnIndexes.add(1); + includeColumnIndexes.add(2); + FesodSheet.write(file, ExcludeOrIncludeData.class) + .includeColumnIndexes(includeColumnIndexes) + .sheet() + .doWrite(data()); + List> dataMap = FesodSheet.read(file).sheet().doReadSync(); + assertEquals(1, dataMap.size()); + Map record = dataMap.get(0); + assertEquals(2, record.size()); + assertEquals("column2", record.get(0)); + assertEquals("column3", record.get(1)); + } + + @ParameterizedTest + @MethodSource("allFormats") + void includeFieldName(ExcelFormat format) throws Exception { + File file = createTempFile(format); + Set includeColumnFieldNames = new HashSet(); + includeColumnFieldNames.add("column2"); + includeColumnFieldNames.add("column3"); + FesodSheet.write(file, ExcludeOrIncludeData.class) + .sheet() + .includeColumnFieldNames(includeColumnFieldNames) + .doWrite(data()); + List> dataMap = FesodSheet.read(file).sheet().doReadSync(); + assertEquals(1, dataMap.size()); + Map record = dataMap.get(0); + assertEquals(2, record.size()); + assertEquals("column2", record.get(0)); + assertEquals("column3", record.get(1)); + } + + @ParameterizedTest + @MethodSource("allFormats") + void includeFieldNameOrderIndex(ExcelFormat format) throws Exception { + File file = createTempFile(format); + List includeColumnIndexes = new ArrayList<>(); + includeColumnIndexes.add(3); + includeColumnIndexes.add(1); + includeColumnIndexes.add(2); + includeColumnIndexes.add(0); + FesodSheet.write(file, ExcludeOrIncludeData.class) + .includeColumnIndexes(includeColumnIndexes) + .orderByIncludeColumn(true) + .sheet() + .doWrite(data()); + List> dataMap = FesodSheet.read(file).sheet().doReadSync(); + assertEquals(1, dataMap.size()); + Map record = dataMap.get(0); + assertEquals(4, record.size()); + assertEquals("column4", record.get(0)); + assertEquals("column2", record.get(1)); + assertEquals("column3", record.get(2)); + assertEquals("column1", record.get(3)); + } + + @ParameterizedTest + @MethodSource("allFormats") + void includeFieldNameOrder(ExcelFormat format) throws Exception { + File file = createTempFile(format); + List includeColumnFieldNames = new ArrayList<>(); + includeColumnFieldNames.add("column4"); + includeColumnFieldNames.add("column2"); + includeColumnFieldNames.add("column3"); + FesodSheet.write(file, ExcludeOrIncludeData.class) + .includeColumnFieldNames(includeColumnFieldNames) + .orderByIncludeColumn(true) + .sheet() + .doWrite(data()); + List> dataMap = FesodSheet.read(file).sheet().doReadSync(); + assertEquals(1, dataMap.size()); + Map record = dataMap.get(0); + assertEquals(3, record.size()); + assertEquals("column4", record.get(0)); + assertEquals("column2", record.get(1)); + assertEquals("column3", record.get(2)); + } + + private List data() { + return TestDataBuilder.excludeOrIncludeData(1); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/extra/ExtraData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExtraData.java similarity index 96% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/extra/ExtraData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExtraData.java index 107f67c64..5b6437d2b 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/extra/ExtraData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExtraData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.extra; +package org.apache.fesod.sheet.converter; import lombok.EqualsAndHashCode; import lombok.Getter; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleDataSheetNameListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExtraDataListener.java similarity index 69% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleDataSheetNameListener.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExtraDataListener.java index 76e76671b..667bf3290 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleDataSheetNameListener.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExtraDataListener.java @@ -23,32 +23,35 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.simple; +package org.apache.fesod.sheet.converter; import com.alibaba.fastjson2.JSON; import java.util.ArrayList; import java.util.List; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.fesod.sheet.context.AnalysisContext; import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; +import org.apache.fesod.sheet.metadata.CellExtra; /** * */ +@Getter @Slf4j -public class SimpleDataSheetNameListener extends AnalysisEventListener { - List list = new ArrayList(); +public class ExtraDataListener extends AnalysisEventListener { + + private final List extras = new ArrayList(); @Override - public void invoke(SimpleData data, AnalysisContext context) { - list.add(data); - } + public void invoke(ExtraData data, AnalysisContext context) {} + + @Override + public void doAfterAllAnalysed(AnalysisContext context) {} @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(1, list.size()); - Assertions.assertEquals("张三", list.get(0).getName()); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); + public void extra(CellExtra extra, AnalysisContext context) { + log.info("extra data:{}", JSON.toJSONString(extra)); + extras.add(extra); } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExtraDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExtraDataTest.java new file mode 100644 index 000000000..b38be904c --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ExtraDataTest.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.converter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import java.io.File; +import java.util.List; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.context.AnalysisContext; +import org.apache.fesod.sheet.enums.CellExtraTypeEnum; +import org.apache.fesod.sheet.metadata.CellExtra; +import org.apache.fesod.sheet.read.listener.ReadListener; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.util.TestFileUtil; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * + */ +public class ExtraDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("binaryFormats") + void read(ExcelFormat format) { + File file = TestFileUtil.readFile("extra" + File.separator + "extra" + format.getExtension()); + ExtraDataListener listener = new ExtraDataListener(); + FesodSheet.read(file, ExtraData.class, listener) + .extraRead(CellExtraTypeEnum.COMMENT) + .extraRead(CellExtraTypeEnum.HYPERLINK) + .extraRead(CellExtraTypeEnum.MERGE) + .sheet() + .doRead(); + + List extras = listener.getExtras(); + for (CellExtra extra : extras) { + switch (extra.getType()) { + case COMMENT: + assertEquals("批注的内容", extra.getText()); + assertEquals(4, (int) extra.getRowIndex()); + assertEquals(0, (int) extra.getColumnIndex()); + break; + case HYPERLINK: + if ("Sheet1!A1".equals(extra.getText())) { + assertEquals(1, (int) extra.getRowIndex()); + assertEquals(0, (int) extra.getColumnIndex()); + } else if ("Sheet2!A1".equals(extra.getText())) { + assertEquals(2, (int) extra.getFirstRowIndex()); + assertEquals(0, (int) extra.getFirstColumnIndex()); + assertEquals(3, (int) extra.getLastRowIndex()); + assertEquals(1, (int) extra.getLastColumnIndex()); + } else { + fail("Unknown hyperlink!"); + } + break; + case MERGE: + assertEquals(5, (int) extra.getFirstRowIndex()); + assertEquals(0, (int) extra.getFirstColumnIndex()); + assertEquals(6, (int) extra.getLastRowIndex()); + assertEquals(1, (int) extra.getLastColumnIndex()); + break; + default: + } + } + } + + @Test + void readExtraRelationships() { + File extraRelationships = TestFileUtil.readFile("extra" + File.separator + "extraRelationships.xlsx"); + FesodSheet.read(extraRelationships, ExtraData.class, new ReadListener() { + @Override + public void invoke(Object data, AnalysisContext context) {} + + @Override + public void doAfterAllAnalysed(AnalysisContext context) {} + + @Override + public void extra(CellExtra extra, AnalysisContext context) { + switch (extra.getType()) { + case HYPERLINK: + if ("222222222".equals(extra.getText())) { + assertEquals(1, (int) extra.getRowIndex()); + assertEquals(0, (int) extra.getColumnIndex()); + } else if ("333333333333".equals(extra.getText())) { + assertEquals(1, (int) extra.getRowIndex()); + assertEquals(1, (int) extra.getColumnIndex()); + } else { + fail("Unknown hyperlink!"); + } + break; + default: + } + } + }) + .extraRead(CellExtraTypeEnum.HYPERLINK) + .sheet() + .doRead(); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/GlobalConverterWriteData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/GlobalConverterWriteData.java index c13f7fbec..7bbbf4828 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/GlobalConverterWriteData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/GlobalConverterWriteData.java @@ -29,6 +29,6 @@ @Setter @EqualsAndHashCode public class GlobalConverterWriteData { - @ExcelProperty("时间戳-字符串") + @ExcelProperty("TimestampString") private Timestamp timestampData; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ReadAllConverterDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ReadAllConverterDataListener.java deleted file mode 100644 index e820f1b88..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/ReadAllConverterDataListener.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.converter; - -import com.alibaba.fastjson2.JSON; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.exception.ExcelCommonException; -import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.apache.fesod.sheet.util.DateUtils; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class ReadAllConverterDataListener extends AnalysisEventListener { - List list = new ArrayList(); - - @Override - public void invoke(ReadAllConverterData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(1, list.size()); - ReadAllConverterData data = list.get(0); - Assertions.assertEquals(data.getBigDecimalBoolean().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0); - Assertions.assertEquals(data.getBigDecimalNumber().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0); - Assertions.assertEquals(data.getBigDecimalString().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0); - Assertions.assertEquals(data.getBigIntegerBoolean().intValue(), BigInteger.ONE.intValue(), 0.0); - Assertions.assertEquals(data.getBigIntegerNumber().intValue(), BigInteger.ONE.intValue(), 0.0); - Assertions.assertEquals(data.getBigIntegerString().intValue(), BigInteger.ONE.intValue(), 0.0); - Assertions.assertTrue(data.getBooleanBoolean()); - Assertions.assertTrue(data.getBooleanNumber()); - Assertions.assertTrue(data.getBooleanString()); - Assertions.assertEquals(1L, (long) data.getByteBoolean()); - Assertions.assertEquals(1L, (long) data.getByteNumber()); - Assertions.assertEquals(1L, (long) data.getByteString()); - try { - Assertions.assertEquals(data.getDateNumber(), DateUtils.parseDate("2020-01-01 01:01:01")); - Assertions.assertEquals(data.getDateString(), DateUtils.parseDate("2020-01-01 01:01:01")); - } catch (ParseException e) { - throw new ExcelCommonException("Test Exception", e); - } - Assertions.assertEquals( - data.getLocalDateTimeNumber(), DateUtils.parseLocalDateTime("2020-01-01 01:01:01", null, null)); - Assertions.assertEquals( - data.getLocalDateTimeString(), DateUtils.parseLocalDateTime("2020-01-01 01:01:01", null, null)); - Assertions.assertEquals(1.0, data.getDoubleBoolean(), 0.0); - Assertions.assertEquals(1.0, data.getDoubleNumber(), 0.0); - Assertions.assertEquals(1.0, data.getDoubleString(), 0.0); - Assertions.assertEquals((float) 1.0, data.getFloatBoolean(), 0.0); - Assertions.assertEquals((float) 1.0, data.getFloatNumber(), 0.0); - Assertions.assertEquals((float) 1.0, data.getFloatString(), 0.0); - Assertions.assertEquals(1L, (long) data.getIntegerBoolean()); - Assertions.assertEquals(1L, (long) data.getIntegerNumber()); - Assertions.assertEquals(1L, (long) data.getIntegerString()); - Assertions.assertEquals(1L, (long) data.getLongBoolean()); - Assertions.assertEquals(1L, (long) data.getLongNumber()); - Assertions.assertEquals(1L, (long) data.getLongString()); - Assertions.assertEquals(1L, (long) data.getShortBoolean()); - Assertions.assertEquals(1L, (long) data.getShortNumber()); - Assertions.assertEquals(1L, (long) data.getShortString()); - Assertions.assertEquals("true", data.getStringBoolean().toLowerCase()); - Assertions.assertEquals("测试", data.getStringString()); - Assertions.assertEquals("#VALUE!", data.getStringError()); - if (context.readWorkbookHolder().getExcelType() != ExcelTypeEnum.CSV) { - Assertions.assertEquals("2020-1-1 1:01", data.getStringNumberDate()); - } else { - Assertions.assertEquals("2020-01-01 01:01:01", data.getStringNumberDate()); - } - double doubleStringFormulaNumber = new BigDecimal(data.getStringFormulaNumber()).doubleValue(); - Assertions.assertEquals(2.0, doubleStringFormulaNumber, 0.0); - Assertions.assertEquals("1测试", data.getStringFormulaString()); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/sort/SortData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/SortData.java similarity index 97% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/sort/SortData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/SortData.java index 11920b11b..83f302a1f 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/sort/SortData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/SortData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.sort; +package org.apache.fesod.sheet.converter; import lombok.EqualsAndHashCode; import lombok.Getter; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/SortDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/SortDataTest.java new file mode 100644 index 000000000..cdb0773ab --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/SortDataTest.java @@ -0,0 +1,117 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.converter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.listeners.CollectingReadListener; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * + */ +public class SortDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile(format); + FesodSheet.write(file, SortData.class).sheet().doWrite(data()); + + List> dataMap = FesodSheet.read(file).sheet().doReadSync(); + assertEquals(1, dataMap.size()); + Map record = dataMap.get(0); + assertEquals("column1", record.get(0)); + assertEquals("column2", record.get(1)); + assertEquals("column3", record.get(2)); + assertEquals("column4", record.get(3)); + assertEquals("column5", record.get(4)); + assertEquals("column6", record.get(5)); + + CollectingReadListener listener = new CollectingReadListener<>(); + FesodSheet.read(file, SortData.class, listener).sheet().doRead(); + assertEquals(1, listener.getRowCount()); + SortData sortData = listener.getFirstRow(); + assertEquals("column1", sortData.getColumn1()); + assertEquals("column2", sortData.getColumn2()); + assertEquals("column3", sortData.getColumn3()); + assertEquals("column4", sortData.getColumn4()); + assertEquals("column5", sortData.getColumn5()); + assertEquals("column6", sortData.getColumn6()); + } + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWriteNoHead(ExcelFormat format) throws Exception { + File file = createTempFile(format); + FesodSheet.write(file).head(head()).sheet().doWrite(data()); + + List> dataMap = FesodSheet.read(file).sheet().doReadSync(); + assertEquals(1, dataMap.size()); + Map record = dataMap.get(0); + assertEquals("column1", record.get(0)); + assertEquals("column2", record.get(1)); + assertEquals("column3", record.get(2)); + assertEquals("column4", record.get(3)); + assertEquals("column5", record.get(4)); + assertEquals("column6", record.get(5)); + + CollectingReadListener listener = new CollectingReadListener<>(); + FesodSheet.read(file, SortData.class, listener).sheet().doRead(); + assertEquals(1, listener.getRowCount()); + SortData sortData = listener.getFirstRow(); + assertEquals("column1", sortData.getColumn1()); + assertEquals("column2", sortData.getColumn2()); + assertEquals("column3", sortData.getColumn3()); + assertEquals("column4", sortData.getColumn4()); + assertEquals("column5", sortData.getColumn5()); + assertEquals("column6", sortData.getColumn6()); + } + + private List> head() { + List> head = new ArrayList>(); + head.add(Collections.singletonList("column1")); + head.add(Collections.singletonList("column2")); + head.add(Collections.singletonList("column3")); + head.add(Collections.singletonList("column4")); + head.add(Collections.singletonList("column5")); + head.add(Collections.singletonList("column6")); + return head; + } + + private List data() { + return TestDataBuilder.sortData(1); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/skip/ClassUtilsFieldOverrideTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/ClassUtilsFieldOverrideTest.java similarity index 85% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/skip/ClassUtilsFieldOverrideTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/core/ClassUtilsFieldOverrideTest.java index 9691acf50..e2bbe6151 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/skip/ClassUtilsFieldOverrideTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/ClassUtilsFieldOverrideTest.java @@ -17,8 +17,10 @@ * under the License. */ -package org.apache.fesod.sheet.skip; +package org.apache.fesod.sheet.core; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -28,11 +30,11 @@ import org.apache.fesod.sheet.FesodSheet; import org.apache.fesod.sheet.annotation.ExcelIgnore; import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.junit.jupiter.api.Assertions; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -public class ClassUtilsFieldOverrideTest { +public class ClassUtilsFieldOverrideTest extends AbstractExcelTest { @Getter @Setter @@ -138,7 +140,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data1.add(new Parent1()); FesodSheet.write(file1.toString(), Parent1.class).sheet().doWrite(data1); List header1 = readHeader.apply(file1); - Assertions.assertTrue(header1.contains("parent1Field"), "Parent1 should contain parent1Field"); + assertTrue(header1.contains("parent1Field"), "Parent1 should contain parent1Field"); // Child1: should NOT contain parent1Field Path file2 = tempDir.resolve("child1.xlsx"); @@ -146,7 +148,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data2.add(new Child1()); FesodSheet.write(file2.toString(), Child1.class).sheet().doWrite(data2); List header2 = readHeader.apply(file2); - Assertions.assertFalse(header2.contains("parent1Field"), "Child1 should NOT contain parent1Field"); + assertFalse(header2.contains("parent1Field"), "Child1 should NOT contain parent1Field"); // Parent2: should NOT contain field Path file3 = tempDir.resolve("parent2.xlsx"); @@ -154,7 +156,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data3.add(new Parent2()); FesodSheet.write(file3.toString(), Parent2.class).sheet().doWrite(data3); List header3 = readHeader.apply(file3); - Assertions.assertFalse(header3.contains("field"), "Parent2 should NOT contain field"); + assertFalse(header3.contains("field"), "Parent2 should NOT contain field"); // Child2: should NOT contain field Path file4 = tempDir.resolve("child2.xlsx"); @@ -162,7 +164,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data4.add(new Child2()); FesodSheet.write(file4.toString(), Child2.class).sheet().doWrite(data4); List header4 = readHeader.apply(file4); - Assertions.assertFalse(header4.contains("field"), "Child2 should NOT contain field"); + assertFalse(header4.contains("field"), "Child2 should NOT contain field"); // Parent3: should contain parent3Field Path file5 = tempDir.resolve("parent3.xlsx"); @@ -170,7 +172,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data5.add(new Parent3()); FesodSheet.write(file5.toString(), Parent3.class).sheet().doWrite(data5); List header5 = readHeader.apply(file5); - Assertions.assertTrue(header5.contains("parent3Field"), "Parent3 should contain parent3Field"); + assertTrue(header5.contains("parent3Field"), "Parent3 should contain parent3Field"); // Child3: should contain child3Field Path file6 = tempDir.resolve("child3.xlsx"); @@ -178,7 +180,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data6.add(new Child3()); FesodSheet.write(file6.toString(), Child3.class).sheet().doWrite(data6); List header6 = readHeader.apply(file6); - Assertions.assertTrue(header6.contains("child3Field"), "Child3 should contain child3Field"); + assertTrue(header6.contains("child3Field"), "Child3 should contain child3Field"); // Parent4: should NOT contain field Path file7 = tempDir.resolve("parent4.xlsx"); @@ -186,7 +188,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data7.add(new Parent4()); FesodSheet.write(file7.toString(), Parent4.class).sheet().doWrite(data7); List header7 = readHeader.apply(file7); - Assertions.assertFalse(header7.contains("field"), "Parent4 should NOT contain field"); + assertFalse(header7.contains("field"), "Parent4 should NOT contain field"); // Child4: should contain child4Field Path file8 = tempDir.resolve("child4.xlsx"); @@ -194,7 +196,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data8.add(new Child4()); FesodSheet.write(file8.toString(), Child4.class).sheet().doWrite(data8); List header8 = readHeader.apply(file8); - Assertions.assertTrue(header8.contains("child4Field"), "Child4 should contain child4Field"); + assertTrue(header8.contains("child4Field"), "Child4 should contain child4Field"); // Parent5: should contain parent5Field Path file9 = tempDir.resolve("parent5.xlsx"); @@ -202,7 +204,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data9.add(new Parent5()); FesodSheet.write(file9.toString(), Parent5.class).sheet().doWrite(data9); List header9 = readHeader.apply(file9); - Assertions.assertTrue(header9.contains("parent5Field"), "Parent5 should contain parent5Field"); + assertTrue(header9.contains("parent5Field"), "Parent5 should contain parent5Field"); // Child5: should contain field Path file10 = tempDir.resolve("child5.xlsx"); @@ -210,7 +212,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data10.add(new Child5()); FesodSheet.write(file10.toString(), Child5.class).sheet().doWrite(data10); List header10 = readHeader.apply(file10); - Assertions.assertTrue(header10.contains("field"), "Child5 should contain field"); + assertTrue(header10.contains("field"), "Child5 should contain field"); // Parent6: should NOT contain field Path file11 = tempDir.resolve("parent6.xlsx"); @@ -218,7 +220,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data11.add(new Parent6()); FesodSheet.write(file11.toString(), Parent6.class).sheet().doWrite(data11); List header11 = readHeader.apply(file11); - Assertions.assertFalse(header11.contains("field"), "Parent6 should NOT contain field"); + assertFalse(header11.contains("field"), "Parent6 should NOT contain field"); // Child6: should contain field Path file12 = tempDir.resolve("child6.xlsx"); @@ -226,7 +228,7 @@ public void validateHeaderWithExcelIgnore(@TempDir Path tempDir) { data12.add(new Child6()); FesodSheet.write(file12.toString(), Child6.class).sheet().doWrite(data12); List header12 = readHeader.apply(file12); - Assertions.assertTrue(header12.contains("field"), "Child6 should contain field"); + assertTrue(header12.contains("field"), "Child6 should contain field"); } private static Function> extractExcelHeader() { diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/NoModelDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/NoModelDataTest.java new file mode 100644 index 000000000..acd58d3b7 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/NoModelDataTest.java @@ -0,0 +1,106 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.enums.ReadDefaultReturnEnum; +import org.apache.fesod.sheet.metadata.data.ReadCellData; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * + */ +public class NoModelDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + boolean isCsv = (format == ExcelFormat.CSV); + File file = createTempFile(format); + File fileRepeat = createTempFile("repeat", format); + + FesodSheet.write(file).sheet().doWrite(TestDataBuilder.noModelData(10)); + List> result = + FesodSheet.read(file).headRowNumber(0).sheet().doReadSync(); + assertEquals(10, result.size()); + Map data10 = result.get(9); + assertEquals("string19", data10.get(0)); + assertEquals("109", data10.get(1)); + assertEquals("2020-01-01 01:01:01", data10.get(2)); + + List> actualDataList = FesodSheet.read(file) + .headRowNumber(0) + .readDefaultReturn(ReadDefaultReturnEnum.ACTUAL_DATA) + .sheet() + .doReadSync(); + assertEquals(10, actualDataList.size()); + Map actualData10 = actualDataList.get(9); + assertEquals("string19", actualData10.get(0)); + if (isCsv) { + assertEquals("109", actualData10.get(1)); + assertEquals("2020-01-01 01:01:01", actualData10.get(2)); + } else { + assertEquals(0, new BigDecimal("109").compareTo((BigDecimal) actualData10.get(1))); + assertEquals(LocalDateTime.of(2020, 1, 1, 1, 1, 1), actualData10.get(2)); + } + + List>> readCellDataList = FesodSheet.read(file) + .headRowNumber(0) + .readDefaultReturn(ReadDefaultReturnEnum.READ_CELL_DATA) + .sheet() + .doReadSync(); + assertEquals(10, readCellDataList.size()); + Map> readCellData10 = readCellDataList.get(9); + assertEquals("string19", readCellData10.get(0).getData()); + if (isCsv) { + assertEquals("109", readCellData10.get(1).getData()); + assertEquals("2020-01-01 01:01:01", readCellData10.get(2).getData()); + } else { + assertEquals(0, new BigDecimal("109").compareTo((BigDecimal) + readCellData10.get(1).getData())); + assertEquals( + LocalDateTime.of(2020, 1, 1, 1, 1, 1), readCellData10.get(2).getData()); + } + + FesodSheet.write(fileRepeat).sheet().doWrite(result); + result = FesodSheet.read(fileRepeat).headRowNumber(0).sheet().doReadSync(); + assertEquals(10, result.size()); + data10 = result.get(9); + assertEquals("string19", data10.get(0)); + assertEquals("109", data10.get(1)); + assertEquals("2020-01-01 01:01:01", data10.get(2)); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/repetition/RepetitionData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/RepetitionData.java similarity index 94% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/repetition/RepetitionData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/core/RepetitionData.java index ccea62ba9..92cf4c41f 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/repetition/RepetitionData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/RepetitionData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.repetition; +package org.apache.fesod.sheet.core; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -37,6 +37,6 @@ @Setter @EqualsAndHashCode public class RepetitionData { - @ExcelProperty("字符串") + @ExcelProperty("String") private String string; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/RepetitionDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/RepetitionDataTest.java new file mode 100644 index 000000000..301c49482 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/RepetitionDataTest.java @@ -0,0 +1,96 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import java.util.List; +import org.apache.fesod.sheet.ExcelReader; +import org.apache.fesod.sheet.ExcelWriter; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.read.metadata.ReadSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.listeners.CollectingReadListener; +import org.apache.fesod.sheet.write.metadata.WriteSheet; +import org.apache.fesod.sheet.write.metadata.WriteTable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * + */ +public class RepetitionDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile(format); + List data = TestDataBuilder.repetitionData(1); + try (ExcelWriter excelWriter = + FesodSheet.write(file, RepetitionData.class).build()) { + WriteSheet writeSheet = FesodSheet.writerSheet(0).build(); + excelWriter.write(data, writeSheet).write(data, writeSheet); + } + + CollectingReadListener listener = new CollectingReadListener<>(); + try (ExcelReader excelReader = + FesodSheet.read(file, RepetitionData.class, listener).build()) { + ReadSheet readSheet = FesodSheet.readSheet(0).build(); + excelReader.read(readSheet); + } + + assertEquals(2, listener.getRowCount()); + assertEquals("String0", listener.getRows().get(0).getString()); + assertEquals("String0", listener.getRows().get(1).getString()); + } + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWriteTable(ExcelFormat format) throws Exception { + File file = createTempFile(format); + List data = TestDataBuilder.repetitionData(1); + try (ExcelWriter excelWriter = + FesodSheet.write(file, RepetitionData.class).build()) { + WriteSheet writeSheet = FesodSheet.writerSheet(0).build(); + WriteTable writeTable = + FesodSheet.writerTable(0).relativeHeadRowIndex(0).build(); + excelWriter.write(data, writeSheet, writeTable).write(data, writeSheet, writeTable); + } + + CollectingReadListener listener = new CollectingReadListener<>(); + try (ExcelReader excelReader = + FesodSheet.read(file, RepetitionData.class, listener).build()) { + ReadSheet readSheet = FesodSheet.readSheet(0).headRowNumber(2).build(); + excelReader.read(readSheet); + } + + assertEquals(2, listener.getRowCount()); + assertEquals("String0", listener.getRows().get(0).getString()); + assertEquals("String0", listener.getRows().get(1).getString()); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/SimpleDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/SimpleDataTest.java new file mode 100644 index 000000000..c89cf49c7 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/SimpleDataTest.java @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import java.io.File; +import java.util.List; +import java.util.Map; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.read.listener.PageReadListener; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ApiMode; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.helpers.RoundTripHelper; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.apache.fesod.sheet.util.TestFileUtil; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Test simple read/write for all Excel formats using parameterized tests. + */ +public class SimpleDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + List data = TestDataBuilder.simpleData(10); + List result = writeAndRead(format, SimpleData.class, data); + + assertEquals(10, result.size()); + assertEquals("Name0", result.get(0).getName()); + } + + @ParameterizedTest + @MethodSource("allFormatsWithApiMode") + void readAndWriteWithApiMode(ExcelFormat format, ApiMode mode) throws Exception { + File file = createTempFile(format); + List data = TestDataBuilder.simpleData(10); + List result = RoundTripHelper.writeAndRead(file, format, mode, SimpleData.class, data); + + assertEquals(10, result.size()); + assertEquals("Name0", result.get(0).getName()); + } + + @ParameterizedTest + @MethodSource("allFormats") + void synchronousRead(ExcelFormat format) throws Exception { + List data = TestDataBuilder.simpleData(10); + List result = RoundTripHelper.writeAndReadSync(createTempFile(format), SimpleData.class, data); + + assertEquals(10, result.size()); + assertInstanceOf(SimpleData.class, result.get(0)); + assertEquals("Name0", result.get(0).getName()); + } + + @Test + void sheetNameRead07() { + List> list = FesodSheet.read( + TestFileUtil.readFile("simple" + File.separator + "simple07.xlsx")) + .sheet("simple") + .doReadSync(); + Assertions.assertEquals(1, list.size()); + } + + @Test + void sheetNoRead07() { + List> list = FesodSheet.read( + TestFileUtil.readFile("simple" + File.separator + "simple07.xlsx")) + .sheet(1) + .doReadSync(); + Assertions.assertEquals(1, list.size()); + } + + @Test + void pageReadListener07() throws Exception { + File file = createTempFile(ExcelFormat.XLSX); + List data = TestDataBuilder.simpleData(10); + RoundTripHelper.write(file, SimpleData.class, data); + + FesodSheet.read( + file, + SimpleData.class, + new PageReadListener( + dataList -> { + Assertions.assertEquals(5, dataList.size()); + }, + 5)) + .sheet() + .doRead(); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/skip/SkipDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/SkipDataTest.java similarity index 52% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/skip/SkipDataTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/core/SkipDataTest.java index 6467edf4b..d6e105288 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/skip/SkipDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/SkipDataTest.java @@ -23,10 +23,11 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.skip; +package org.apache.fesod.sheet.core; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; -import java.util.ArrayList; import java.util.List; import org.apache.fesod.sheet.ExcelReader; import org.apache.fesod.sheet.ExcelWriter; @@ -34,83 +35,67 @@ import org.apache.fesod.sheet.event.SyncReadListener; import org.apache.fesod.sheet.exception.ExcelGenerateException; import org.apache.fesod.sheet.read.metadata.ReadSheet; -import org.apache.fesod.sheet.simple.SimpleData; -import org.apache.fesod.sheet.util.TestFileUtil; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.models.SimpleData; import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class SkipDataTest { +public class SkipDataTest extends AbstractExcelTest { - private static File file07; - private static File file03; - private static File fileCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("skip.xlsx"); - file03 = TestFileUtil.createNewFile("skip.xls"); - fileCsv = TestFileUtil.createNewFile("skip.csv"); - } - - @Test - public void t01ReadAndWrite07() { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() { - readAndWrite(file03); + @ParameterizedTest + @MethodSource("binaryFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile(format); + readAndWriteImpl(file); } @Test - public void t03ReadAndWriteCsv() { - Assertions.assertThrows(ExcelGenerateException.class, () -> readAndWrite(fileCsv)); + void readAndWriteCsvThrows() throws Exception { + File file = createTempFile(ExcelFormat.CSV); + assertThrows(ExcelGenerateException.class, () -> readAndWriteImpl(file)); } - private void readAndWrite(File file) { - try (ExcelWriter excelWriter = FesodSheet.write(file, SimpleData.class).build(); ) { - WriteSheet writeSheet0 = FesodSheet.writerSheet(0, "第一个").build(); - WriteSheet writeSheet1 = FesodSheet.writerSheet(1, "第二个").build(); - WriteSheet writeSheet2 = FesodSheet.writerSheet(2, "第三个").build(); - WriteSheet writeSheet3 = FesodSheet.writerSheet(3, "第四个").build(); + private void readAndWriteImpl(File file) { + try (ExcelWriter excelWriter = FesodSheet.write(file, SimpleData.class).build()) { + WriteSheet writeSheet0 = FesodSheet.writerSheet(0, "Sheet1").build(); + WriteSheet writeSheet1 = FesodSheet.writerSheet(1, "Sheet2").build(); + WriteSheet writeSheet2 = FesodSheet.writerSheet(2, "Sheet3").build(); + WriteSheet writeSheet3 = FesodSheet.writerSheet(3, "Sheet4").build(); excelWriter.write(data("name1"), writeSheet0); excelWriter.write(data("name2"), writeSheet1); excelWriter.write(data("name3"), writeSheet2); excelWriter.write(data("name4"), writeSheet3); } - List list = - FesodSheet.read(file, SkipData.class, null).sheet("第二个").doReadSync(); - Assertions.assertEquals(1, list.size()); - Assertions.assertEquals("name2", list.get(0).getName()); + List list = + FesodSheet.read(file, SimpleData.class, null).sheet("Sheet2").doReadSync(); + assertEquals(1, list.size()); + assertEquals("name2", list.get(0).getName()); SyncReadListener syncReadListener = new SyncReadListener(); - try (ExcelReader excelReader = FesodSheet.read(file, SkipData.class, null) + try (ExcelReader excelReader = FesodSheet.read(file, SimpleData.class, null) .registerReadListener(syncReadListener) .build()) { - ReadSheet readSheet1 = FesodSheet.readSheet("第二个").build(); - ReadSheet readSheet3 = FesodSheet.readSheet("第四个").build(); + ReadSheet readSheet1 = FesodSheet.readSheet("Sheet2").build(); + ReadSheet readSheet3 = FesodSheet.readSheet("Sheet4").build(); excelReader.read(readSheet1, readSheet3); List syncList = syncReadListener.getList(); - Assertions.assertEquals(2, syncList.size()); - Assertions.assertEquals("name2", ((SkipData) syncList.get(0)).getName()); - Assertions.assertEquals("name4", ((SkipData) syncList.get(1)).getName()); + assertEquals(2, syncList.size()); + assertEquals("name2", ((SimpleData) syncList.get(0)).getName()); + assertEquals("name4", ((SimpleData) syncList.get(1)).getName()); } } - private List data(String name) { - List list = new ArrayList(); - SkipData data = new SkipData(); - data.setName(name); - list.add(data); + private List data(String name) { + List list = TestDataBuilder.simpleData(1); + list.get(0).setName(name); return list; } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/noncamel/UnCamelData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/UnCamelData.java similarity index 96% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/noncamel/UnCamelData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/core/UnCamelData.java index 2eba51b71..fe55af1a7 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/noncamel/UnCamelData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/UnCamelData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.noncamel; +package org.apache.fesod.sheet.core; import lombok.EqualsAndHashCode; import lombok.Getter; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/UnCamelDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/UnCamelDataTest.java new file mode 100644 index 000000000..bea1446f7 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/core/UnCamelDataTest.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.listeners.CollectingReadListener; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * + */ +public class UnCamelDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile(format); + FesodSheet.write(file, UnCamelData.class).sheet().doWrite(TestDataBuilder.unCamelData(10)); + + CollectingReadListener listener = new CollectingReadListener<>(); + FesodSheet.read(file, UnCamelData.class, listener).sheet().doRead(); + + assertEquals(10, listener.getRowCount()); + UnCamelData row = listener.getFirstRow(); + assertEquals("string1", row.getString1()); + assertEquals("string2", row.getString2()); + assertEquals("string3", row.getSTring3()); + assertEquals("string4", row.getSTring4()); + assertEquals("string5", row.getSTRING5()); + assertEquals("string6", row.getSTRing6()); + } + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWriteHeadMap(ExcelFormat format) throws Exception { + File file = createTempFile(format); + FesodSheet.write(file, UnCamelData.class).sheet().doWrite(TestDataBuilder.unCamelData(10)); + + List> headMaps = new ArrayList<>(); + FesodSheet.read(file, UnCamelData.class, new CollectingReadListener() { + @Override + public void invokeHeadMap( + Map headMap, org.apache.fesod.sheet.context.AnalysisContext context) { + headMaps.add(headMap); + } + }) + .sheet() + .doRead(); + + assertEquals(1, headMaps.size()); + Map headMap = headMaps.get(0); + assertEquals("string1", headMap.get(0)); + assertEquals("string2", headMap.get(1)); + assertEquals("STring3", headMap.get(2)); + assertEquals("STring4", headMap.get(3)); + assertEquals("STRING5", headMap.get(4)); + assertEquals("STRing6", headMap.get(5)); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/dataformat/DateFormatTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/dataformat/DateFormatTest.java deleted file mode 100644 index e1f2c70b3..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/dataformat/DateFormatTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.dataformat; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -@Slf4j -public class DateFormatTest { - - private static File file07V2; - private static File file07; - private static File file03; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.readFile("dataformat" + File.separator + "dataformat.xlsx"); - file03 = TestFileUtil.readFile("dataformat" + File.separator + "dataformat.xls"); - file07V2 = TestFileUtil.readFile("dataformat" + File.separator + "dataformatv2.xlsx"); - } - - @Test - public void t01Read07() { - readCn(file07); - readUs(file07); - } - - @Test - public void t02Read03() { - readCn(file03); - readUs(file03); - } - - @Test - public void t03Read() { - List> dataMap = - FesodSheet.read(file07V2).headRowNumber(0).doReadAllSync(); - log.info("dataMap:{}", JSON.toJSONString(dataMap)); - Assertions.assertEquals("15:00", dataMap.get(0).get(0)); - Assertions.assertEquals("2023-1-01 00:00:00", dataMap.get(1).get(0)); - Assertions.assertEquals("2023-1-01 00:00:00", dataMap.get(2).get(0)); - Assertions.assertEquals("2023-1-01 00:00:01", dataMap.get(3).get(0)); - Assertions.assertEquals("2023-1-01 00:00:00", dataMap.get(4).get(0)); - Assertions.assertEquals("2023-1-01 00:00:00", dataMap.get(5).get(0)); - Assertions.assertEquals("2023-1-01 00:00:01", dataMap.get(6).get(0)); - } - - private void readCn(File file) { - List list = FesodSheet.read(file, DateFormatData.class, null) - .locale(Locale.CHINA) - .sheet() - .doReadSync(); - for (DateFormatData data : list) { - if (!Objects.equals(data.getDateStringCn(), data.getDate()) - && !Objects.equals(data.getDateStringCn2(), data.getDate())) { - log.info("date:cn:{},{},{}", data.getDateStringCn(), data.getDateStringCn2(), data.getDate()); - } - if (data.getNumberStringCn() != null && !data.getNumberStringCn().equals(data.getNumber())) { - log.info("number:cn{},{}", data.getNumberStringCn(), data.getNumber()); - } - } - for (DateFormatData data : list) { - // The way dates are read in Chinese is different on Linux and Mac, so it is acceptable if it matches - // either one. - // For example, on Linux: 1-Jan -> 1-1月 - // On Mac: 1-Jan -> 1-一月 - Assertions.assertTrue(Objects.equals(data.getDateStringCn(), data.getDate()) - || Objects.equals(data.getDateStringCn2(), data.getDate())); - Assertions.assertEquals(data.getNumberStringCn(), data.getNumber()); - } - } - - private void readUs(File file) { - List list = FesodSheet.read(file, DateFormatData.class, null) - .locale(Locale.US) - .sheet() - .doReadSync(); - for (DateFormatData data : list) { - if (data.getDateStringUs() != null && !data.getDateStringUs().equals(data.getDate())) { - log.info("date:us:{},{}", data.getDateStringUs(), data.getDate()); - } - if (data.getNumberStringUs() != null && !data.getNumberStringUs().equals(data.getNumber())) { - log.info("number:us{},{}", data.getNumberStringUs(), data.getNumber()); - } - } - for (DateFormatData data : list) { - Assertions.assertEquals(data.getDateStringUs(), data.getDate()); - Assertions.assertEquals(data.getNumberStringUs(), data.getNumber()); - } - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/encrypt/EncryptData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/encrypt/EncryptData.java deleted file mode 100644 index aff35d15d..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/encrypt/EncryptData.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.encrypt; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -@ToString -public class EncryptData { - @ExcelProperty("姓名") - private String name; -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/encrypt/EncryptDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/encrypt/EncryptDataListener.java deleted file mode 100644 index e8eb17b82..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/encrypt/EncryptDataListener.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.encrypt; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class EncryptDataListener extends AnalysisEventListener { - List list = new ArrayList(); - - @Override - public void invoke(EncryptData data, AnalysisContext context) { - log.info("data:{}", data.toString()); - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(10, list.size()); - Assertions.assertEquals("Name0", list.get(0).getName()); - Assertions.assertEquals(0, (int) (context.readSheetHolder().getSheetNo())); - Assertions.assertEquals( - "姓名", - context.readSheetHolder() - .getExcelReadHeadProperty() - .getHeadMap() - .get(0) - .getHeadNameList() - .get(0)); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/encrypt/EncryptDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/encrypt/EncryptDataTest.java deleted file mode 100644 index a64b92c26..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/encrypt/EncryptDataTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.encrypt; - -import java.io.File; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.read.builder.ExcelReaderBuilder; -import org.apache.fesod.sheet.simple.SimpleData; -import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.builder.ExcelWriterBuilder; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@Slf4j -@TestMethodOrder(MethodOrderer.MethodName.class) -public class EncryptDataTest { - private static final String PASSWORD = "123456"; - private static File file07; - private static File file03; - private static File fileCsv; - private static File file07OutputStream; - private static File file03OutputStream; - private static File fileCsvOutputStream; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("encrypt07.xlsx"); - file03 = TestFileUtil.createNewFile("encrypt03.xls"); - fileCsv = TestFileUtil.createNewFile("encryptCsv.csv"); - file07OutputStream = TestFileUtil.createNewFile("encryptOutputStream07.xlsx"); - file03OutputStream = TestFileUtil.createNewFile("encryptOutputStream03.xls"); - fileCsvOutputStream = TestFileUtil.createNewFile("encryptOutputStreamCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() throws Exception { - readAndWrite(file07, null, false, false); - readAndWrite(file07, null, true, false); - readAndWrite(file07, ExcelTypeEnum.XLSX, false, false); - readAndWrite(file07, ExcelTypeEnum.XLSX, true, false); - - readAndWrite(file07OutputStream, null, false, true); - readAndWrite(file07OutputStream, null, true, true); - readAndWrite(file07OutputStream, ExcelTypeEnum.XLSX, false, true); - readAndWrite(file07OutputStream, ExcelTypeEnum.XLSX, true, true); - } - - @Test - public void t02ReadAndWrite03() throws Exception { - readAndWrite(file03, null, false, false); - readAndWrite(file03, null, true, false); - readAndWrite(file03, ExcelTypeEnum.XLS, false, false); - readAndWrite(file03, ExcelTypeEnum.XLS, true, false); - - readAndWrite(file03OutputStream, null, false, true); - readAndWrite(file03OutputStream, null, true, true); - readAndWrite(file03OutputStream, ExcelTypeEnum.XLSX, false, true); - readAndWrite(file03OutputStream, ExcelTypeEnum.XLSX, true, true); - } - - @Test - public void t03ReadAndWriteCSV() throws Exception { - readAndWrite(fileCsv, null, false, false); - readAndWrite(fileCsv, null, true, false); - readAndWrite(fileCsv, ExcelTypeEnum.CSV, false, false); - readAndWrite(fileCsv, ExcelTypeEnum.CSV, true, false); - - readAndWrite(fileCsvOutputStream, null, false, true); - readAndWrite(fileCsvOutputStream, null, true, true); - readAndWrite(fileCsvOutputStream, ExcelTypeEnum.CSV, false, true); - readAndWrite(fileCsvOutputStream, ExcelTypeEnum.CSV, true, true); - } - - private void readAndWrite(File file, ExcelTypeEnum excelType, boolean hasPassword, boolean isStream) - throws Exception { - log.info( - "file:{}, isStream:{}, excelType:{}, hasPassword:{}", file.getName(), isStream, excelType, hasPassword); - ExcelWriterBuilder excelWriterBuilder = isStream - ? FesodSheet.write(Files.newOutputStream(file.toPath()), EncryptData.class) - : FesodSheet.write(file, EncryptData.class); - - ExcelReaderBuilder readerBuilder = isStream - ? FesodSheet.read(Files.newInputStream(file.toPath()), EncryptData.class, new EncryptDataListener()) - : FesodSheet.read(file, EncryptData.class, new EncryptDataListener()); - if (excelType != null) { - excelWriterBuilder.excelType(excelType); - readerBuilder.excelType(excelType); - } - if (hasPassword) { - excelWriterBuilder.password(PASSWORD); - readerBuilder.password(PASSWORD); - } - - excelWriterBuilder.sheet().doWrite(data()); - List dataList = readerBuilder.sheet().doReadSync(); - Assertions.assertEquals(10, dataList.size()); - Assertions.assertNotNull(dataList.get(0).getName()); - } - - private List data() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - SimpleData simpleData = new SimpleData(); - simpleData.setName("Name" + i); - list.add(simpleData); - } - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionData.java deleted file mode 100644 index 170bbfa8b..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionData.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.exception; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -public class ExceptionData { - @ExcelProperty("姓名") - private String name; -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionDataTest.java deleted file mode 100644 index 7fbcb5cc8..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionDataTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.exception; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class ExceptionDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - private static File fileExcelAnalysisStopSheetException07; - private static File fileExcelAnalysisStopSheetException03; - private static File fileExcelAnalysisStopSheetExceptionCsv; - private static File fileException07; - private static File fileException03; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("exception.xlsx"); - file03 = TestFileUtil.createNewFile("exception.xls"); - fileCsv = TestFileUtil.createNewFile("exception.csv"); - fileExcelAnalysisStopSheetException07 = TestFileUtil.createNewFile("excelAnalysisStopSheetException.xlsx"); - fileExcelAnalysisStopSheetException03 = TestFileUtil.createNewFile("excelAnalysisStopSheetException.xls"); - fileException07 = TestFileUtil.createNewFile("exceptionThrow.xlsx"); - fileException03 = TestFileUtil.createNewFile("exceptionThrow.xls"); - } - - @Test - public void t01ReadAndWrite07() throws Exception { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() throws Exception { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() throws Exception { - readAndWrite(fileCsv); - } - - @Test - public void t11ReadAndWrite07() throws Exception { - readAndWriteException(fileException07); - } - - @Test - public void t12ReadAndWrite03() throws Exception { - readAndWriteException(fileException03); - } - - @Test - public void t21ReadAndWrite07() throws Exception { - readAndWriteExcelAnalysisStopSheetException(fileExcelAnalysisStopSheetException07); - } - - @Test - public void t22ReadAndWrite03() throws Exception { - readAndWriteExcelAnalysisStopSheetException(fileExcelAnalysisStopSheetException03); - } - - private void readAndWriteExcelAnalysisStopSheetException(File file) throws Exception { - try (ExcelWriter excelWriter = - FesodSheet.write(file, ExceptionData.class).build()) { - for (int i = 0; i < 5; i++) { - String sheetName = "sheet" + i; - WriteSheet writeSheet = FesodSheet.writerSheet(i, sheetName).build(); - List data = data(sheetName); - excelWriter.write(data, writeSheet); - } - } - - ExcelAnalysisStopSheetExceptionDataListener excelAnalysisStopSheetExceptionDataListener = - new ExcelAnalysisStopSheetExceptionDataListener(); - FesodSheet.read(file, ExceptionData.class, excelAnalysisStopSheetExceptionDataListener) - .doReadAll(); - Map> dataMap = excelAnalysisStopSheetExceptionDataListener.getDataMap(); - Assertions.assertEquals(5, dataMap.size()); - for (int i = 0; i < 5; i++) { - List sheetDataList = dataMap.get(i); - Assertions.assertNotNull(sheetDataList); - Assertions.assertEquals(5, sheetDataList.size()); - String sheetName = "sheet" + i; - - for (String sheetData : sheetDataList) { - Assertions.assertTrue(sheetData.startsWith(sheetName)); - } - } - } - - private void readAndWriteException(File file) throws Exception { - FesodSheet.write(new FileOutputStream(file), ExceptionData.class) - .sheet() - .doWrite(data()); - ArithmeticException exception = Assertions.assertThrows(ArithmeticException.class, () -> FesodSheet.read( - new FileInputStream(file), ExceptionData.class, new ExceptionThrowDataListener()) - .sheet() - .doRead()); - Assertions.assertEquals("/ by zero", exception.getMessage()); - } - - private void readAndWrite(File file) throws Exception { - FesodSheet.write(new FileOutputStream(file), ExceptionData.class) - .sheet() - .doWrite(data()); - FesodSheet.read(new FileInputStream(file), ExceptionData.class, new ExceptionDataListener()) - .sheet() - .doRead(); - } - - private List data() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - ExceptionData simpleData = new ExceptionData(); - simpleData.setName("姓名" + i); - list.add(simpleData); - } - return list; - } - - private List data(String prefix) { - List list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - ExceptionData simpleData = new ExceptionData(); - simpleData.setName(prefix + "-姓名" + i); - list.add(simpleData); - } - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/excludeorinclude/ExcludeOrIncludeDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/excludeorinclude/ExcludeOrIncludeDataTest.java deleted file mode 100644 index 792ca8aee..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/excludeorinclude/ExcludeOrIncludeDataTest.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.excludeorinclude; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class ExcludeOrIncludeDataTest { - - private static File excludeIndex07; - private static File excludeIndex03; - private static File excludeIndexCsv; - private static File excludeFieldName07; - private static File excludeFieldName03; - private static File excludeFieldNameCsv; - private static File includeIndex07; - private static File includeIndex03; - private static File includeIndexCsv; - private static File includeFieldName07; - private static File includeFieldName03; - private static File includeFieldNameCsv; - private static File includeFieldNameOrder07; - private static File includeFieldNameOrder03; - private static File includeFieldNameOrderCsv; - - private static File includeFieldNameOrderIndex07; - private static File includeFieldNameOrderIndex03; - private static File includeFieldNameOrderIndexCsv; - - @BeforeAll - public static void init() { - excludeIndex07 = TestFileUtil.createNewFile("excludeIndex.xlsx"); - excludeIndex03 = TestFileUtil.createNewFile("excludeIndex.xls"); - excludeIndexCsv = TestFileUtil.createNewFile("excludeIndex.csv"); - excludeFieldName07 = TestFileUtil.createNewFile("excludeFieldName.xlsx"); - excludeFieldName03 = TestFileUtil.createNewFile("excludeFieldName.xls"); - excludeFieldNameCsv = TestFileUtil.createNewFile("excludeFieldName.csv"); - includeIndex07 = TestFileUtil.createNewFile("includeIndex.xlsx"); - includeIndex03 = TestFileUtil.createNewFile("includeIndex.xls"); - includeIndexCsv = TestFileUtil.createNewFile("includeIndex.csv"); - includeFieldName07 = TestFileUtil.createNewFile("includeFieldName.xlsx"); - includeFieldName03 = TestFileUtil.createNewFile("includeFieldName.xls"); - includeFieldNameCsv = TestFileUtil.createNewFile("includeFieldName.csv"); - includeFieldNameOrder07 = TestFileUtil.createNewFile("includeFieldNameOrder.xlsx"); - includeFieldNameOrder03 = TestFileUtil.createNewFile("includeFieldNameOrder.xls"); - includeFieldNameOrderCsv = TestFileUtil.createNewFile("includeFieldNameOrder.csv"); - includeFieldNameOrderIndex07 = TestFileUtil.createNewFile("includeFieldNameOrderIndex.xlsx"); - includeFieldNameOrderIndex03 = TestFileUtil.createNewFile("includeFieldNameOrderIndex.xls"); - includeFieldNameOrderIndexCsv = TestFileUtil.createNewFile("includeFieldNameOrderIndex.csv"); - } - - @Test - public void t01ExcludeIndex07() { - excludeIndex(excludeIndex07); - } - - @Test - public void t02ExcludeIndex03() { - excludeIndex(excludeIndex03); - } - - @Test - public void t03ExcludeIndexCsv() { - excludeIndex(excludeIndexCsv); - } - - @Test - public void t11ExcludeFieldName07() { - excludeFieldName(excludeFieldName07); - } - - @Test - public void t12ExcludeFieldName03() { - excludeFieldName(excludeFieldName03); - } - - @Test - public void t13ExcludeFieldNameCsv() { - excludeFieldName(excludeFieldNameCsv); - } - - @Test - public void t21IncludeIndex07() { - includeIndex(includeIndex07); - } - - @Test - public void t22IncludeIndex03() { - includeIndex(includeIndex03); - } - - @Test - public void t23IncludeIndexCsv() { - includeIndex(includeIndexCsv); - } - - @Test - public void t31IncludeFieldName07() { - includeFieldName(includeFieldName07); - } - - @Test - public void t32IncludeFieldName03() { - includeFieldName(includeFieldName03); - } - - @Test - public void t33IncludeFieldNameCsv() { - includeFieldName(includeFieldNameCsv); - } - - @Test - public void t41IncludeFieldNameOrder07() { - includeFieldNameOrder(includeFieldNameOrder07); - } - - @Test - public void t42IncludeFieldNameOrder03() { - includeFieldNameOrder(includeFieldNameOrder03); - } - - @Test - public void t43IncludeFieldNameOrderCsv() { - includeFieldNameOrder(includeFieldNameOrderCsv); - } - - @Test - public void t41IncludeFieldNameOrderIndex07() { - includeFieldNameOrderIndex(includeFieldNameOrderIndex07); - } - - @Test - public void t42IncludeFieldNameOrderIndex03() { - includeFieldNameOrderIndex(includeFieldNameOrderIndex03); - } - - @Test - public void t43IncludeFieldNameOrderIndexCsv() { - includeFieldNameOrderIndex(includeFieldNameOrderIndexCsv); - } - - private void excludeIndex(File file) { - Set excludeColumnIndexes = new HashSet(); - excludeColumnIndexes.add(0); - excludeColumnIndexes.add(3); - FesodSheet.write(file, ExcludeOrIncludeData.class) - .excludeColumnIndexes(excludeColumnIndexes) - .sheet() - .doWrite(data()); - List> dataMap = FesodSheet.read(file).sheet().doReadSync(); - Assertions.assertEquals(1, dataMap.size()); - Map record = dataMap.get(0); - Assertions.assertEquals(2, record.size()); - Assertions.assertEquals("column2", record.get(0)); - Assertions.assertEquals("column3", record.get(1)); - } - - private void excludeFieldName(File file) { - Set excludeColumnFieldNames = new HashSet(); - excludeColumnFieldNames.add("column1"); - excludeColumnFieldNames.add("column3"); - excludeColumnFieldNames.add("column4"); - FesodSheet.write(file, ExcludeOrIncludeData.class) - .excludeColumnFieldNames(excludeColumnFieldNames) - .sheet() - .doWrite(data()); - List> dataMap = FesodSheet.read(file).sheet().doReadSync(); - Assertions.assertEquals(1, dataMap.size()); - Map record = dataMap.get(0); - Assertions.assertEquals(1, record.size()); - Assertions.assertEquals("column2", record.get(0)); - } - - private void includeIndex(File file) { - Set includeColumnIndexes = new HashSet(); - includeColumnIndexes.add(1); - includeColumnIndexes.add(2); - FesodSheet.write(file, ExcludeOrIncludeData.class) - .includeColumnIndexes(includeColumnIndexes) - .sheet() - .doWrite(data()); - List> dataMap = FesodSheet.read(file).sheet().doReadSync(); - Assertions.assertEquals(1, dataMap.size()); - Map record = dataMap.get(0); - Assertions.assertEquals(2, record.size()); - Assertions.assertEquals("column2", record.get(0)); - Assertions.assertEquals("column3", record.get(1)); - } - - private void includeFieldName(File file) { - Set includeColumnFieldNames = new HashSet(); - includeColumnFieldNames.add("column2"); - includeColumnFieldNames.add("column3"); - FesodSheet.write(file, ExcludeOrIncludeData.class) - .sheet() - .includeColumnFieldNames(includeColumnFieldNames) - .doWrite(data()); - List> dataMap = FesodSheet.read(file).sheet().doReadSync(); - Assertions.assertEquals(1, dataMap.size()); - Map record = dataMap.get(0); - Assertions.assertEquals(2, record.size()); - Assertions.assertEquals("column2", record.get(0)); - Assertions.assertEquals("column3", record.get(1)); - } - - private void includeFieldNameOrderIndex(File file) { - List includeColumnIndexes = new ArrayList<>(); - includeColumnIndexes.add(3); - includeColumnIndexes.add(1); - includeColumnIndexes.add(2); - includeColumnIndexes.add(0); - FesodSheet.write(file, ExcludeOrIncludeData.class) - .includeColumnIndexes(includeColumnIndexes) - .orderByIncludeColumn(true) - .sheet() - .doWrite(data()); - List> dataMap = FesodSheet.read(file).sheet().doReadSync(); - Assertions.assertEquals(1, dataMap.size()); - Map record = dataMap.get(0); - Assertions.assertEquals(4, record.size()); - Assertions.assertEquals("column4", record.get(0)); - Assertions.assertEquals("column2", record.get(1)); - Assertions.assertEquals("column3", record.get(2)); - Assertions.assertEquals("column1", record.get(3)); - } - - private void includeFieldNameOrder(File file) { - List includeColumnFieldNames = new ArrayList<>(); - includeColumnFieldNames.add("column4"); - includeColumnFieldNames.add("column2"); - includeColumnFieldNames.add("column3"); - FesodSheet.write(file, ExcludeOrIncludeData.class) - .includeColumnFieldNames(includeColumnFieldNames) - .orderByIncludeColumn(true) - .sheet() - .doWrite(data()); - List> dataMap = FesodSheet.read(file).sheet().doReadSync(); - Assertions.assertEquals(1, dataMap.size()); - Map record = dataMap.get(0); - Assertions.assertEquals(3, record.size()); - Assertions.assertEquals("column4", record.get(0)); - Assertions.assertEquals("column2", record.get(1)); - Assertions.assertEquals("column3", record.get(2)); - } - - private List data() { - List list = new ArrayList(); - ExcludeOrIncludeData excludeOrIncludeData = new ExcludeOrIncludeData(); - excludeOrIncludeData.setColumn1("column1"); - excludeOrIncludeData.setColumn2("column2"); - excludeOrIncludeData.setColumn3("column3"); - excludeOrIncludeData.setColumn4("column4"); - list.add(excludeOrIncludeData); - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/extra/ExtraDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/extra/ExtraDataListener.java deleted file mode 100644 index a40c8ccb4..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/extra/ExtraDataListener.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.extra; - -import com.alibaba.fastjson2.JSON; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.metadata.CellExtra; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class ExtraDataListener extends AnalysisEventListener { - - @Override - public void invoke(ExtraData data, AnalysisContext context) {} - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} - - @Override - public void extra(CellExtra extra, AnalysisContext context) { - log.info("extra data:{}", JSON.toJSONString(extra)); - switch (extra.getType()) { - case COMMENT: - Assertions.assertEquals("批注的内容", extra.getText()); - Assertions.assertEquals(4, (int) extra.getRowIndex()); - Assertions.assertEquals(0, (int) extra.getColumnIndex()); - break; - case HYPERLINK: - if ("Sheet1!A1".equals(extra.getText())) { - Assertions.assertEquals(1, (int) extra.getRowIndex()); - Assertions.assertEquals(0, (int) extra.getColumnIndex()); - } else if ("Sheet2!A1".equals(extra.getText())) { - Assertions.assertEquals(2, (int) extra.getFirstRowIndex()); - Assertions.assertEquals(0, (int) extra.getFirstColumnIndex()); - Assertions.assertEquals(3, (int) extra.getLastRowIndex()); - Assertions.assertEquals(1, (int) extra.getLastColumnIndex()); - } else { - Assertions.fail("Unknown hyperlink!"); - } - break; - case MERGE: - Assertions.assertEquals(5, (int) extra.getFirstRowIndex()); - Assertions.assertEquals(0, (int) extra.getFirstColumnIndex()); - Assertions.assertEquals(6, (int) extra.getLastRowIndex()); - Assertions.assertEquals(1, (int) extra.getLastColumnIndex()); - break; - default: - } - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/extra/ExtraDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/extra/ExtraDataTest.java deleted file mode 100644 index dcbd6f48d..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/extra/ExtraDataTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.extra; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.enums.CellExtraTypeEnum; -import org.apache.fesod.sheet.metadata.CellExtra; -import org.apache.fesod.sheet.read.listener.ReadListener; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * - */ -@Slf4j -public class ExtraDataTest { - private static File file03; - private static File file07; - - private static File extraRelationships; - - @BeforeAll - public static void init() { - file03 = TestFileUtil.readFile("extra" + File.separator + "extra.xls"); - file07 = TestFileUtil.readFile("extra" + File.separator + "extra.xlsx"); - extraRelationships = TestFileUtil.readFile("extra" + File.separator + "extraRelationships.xlsx"); - } - - @Test - public void t01Read07() { - read(file07); - } - - @Test - public void t02Read03() { - read(file03); - } - - @Test - public void t03Read() { - FesodSheet.read(extraRelationships, ExtraData.class, new ReadListener() { - @Override - public void invoke(Object data, AnalysisContext context) {} - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} - - @Override - public void extra(CellExtra extra, AnalysisContext context) { - log.info("extra data:{}", JSON.toJSONString(extra)); - switch (extra.getType()) { - case HYPERLINK: - if ("222222222".equals(extra.getText())) { - Assertions.assertEquals(1, (int) extra.getRowIndex()); - Assertions.assertEquals(0, (int) extra.getColumnIndex()); - } else if ("333333333333".equals(extra.getText())) { - Assertions.assertEquals(1, (int) extra.getRowIndex()); - Assertions.assertEquals(1, (int) extra.getColumnIndex()); - } else { - Assertions.fail("Unknown hyperlink!"); - } - break; - default: - } - } - }) - .extraRead(CellExtraTypeEnum.HYPERLINK) - .sheet() - .doRead(); - } - - private void read(File file) { - FesodSheet.read(file, ExtraData.class, new ExtraDataListener()) - .extraRead(CellExtraTypeEnum.COMMENT) - .extraRead(CellExtraTypeEnum.HYPERLINK) - .extraRead(CellExtraTypeEnum.MERGE) - .sheet() - .doRead(); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/FillDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/FillDataTest.java deleted file mode 100644 index 3edc679cc..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/FillDataTest.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.fill; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.enums.WriteDirectionEnum; -import org.apache.fesod.sheet.exception.ExcelGenerateException; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.merge.LoopMergeStrategy; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.apache.fesod.sheet.write.metadata.fill.FillConfig; -import org.apache.fesod.sheet.write.metadata.fill.FillWrapper; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class FillDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - private static File simpleTemplate07; - private static File simpleTemplate03; - private static File simpleTemplateCsv; - private static File fileComplex07; - private static File complexFillTemplate07; - private static File fileComplex03; - private static File complexFillTemplate03; - private static File fileHorizontal07; - private static File horizontalFillTemplate07; - private static File fileHorizontal03; - private static File horizontalFillTemplate03; - private static File byName07; - private static File byName03; - private static File byNameTemplate07; - private static File byNameTemplate03; - private static File fileComposite07; - private static File compositeFillTemplate07; - private static File fileComposite03; - private static File compositeFillTemplate03; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("fill07.xlsx"); - file03 = TestFileUtil.createNewFile("fill03.xls"); - fileCsv = TestFileUtil.createNewFile("fill.csv"); - simpleTemplate07 = TestFileUtil.readFile("fill" + File.separator + "simple.xlsx"); - simpleTemplate03 = TestFileUtil.readFile("fill" + File.separator + "simple.xls"); - simpleTemplateCsv = TestFileUtil.readFile("fill" + File.separator + "simple.csv"); - fileComplex07 = TestFileUtil.createNewFile("fillComplex07.xlsx"); - complexFillTemplate07 = TestFileUtil.readFile("fill" + File.separator + "complex.xlsx"); - fileComplex03 = TestFileUtil.createNewFile("fillComplex03.xls"); - complexFillTemplate03 = TestFileUtil.readFile("fill" + File.separator + "complex.xls"); - fileHorizontal07 = TestFileUtil.createNewFile("fillHorizontal07.xlsx"); - horizontalFillTemplate07 = TestFileUtil.readFile("fill" + File.separator + "horizontal.xlsx"); - fileHorizontal03 = TestFileUtil.createNewFile("fillHorizontal03.xls"); - horizontalFillTemplate03 = TestFileUtil.readFile("fill" + File.separator + "horizontal.xls"); - byName07 = TestFileUtil.createNewFile("byName07.xlsx"); - byNameTemplate07 = TestFileUtil.readFile("fill" + File.separator + "byName.xlsx"); - byName03 = TestFileUtil.createNewFile("byName03.xls"); - byNameTemplate03 = TestFileUtil.readFile("fill" + File.separator + "byName.xls"); - fileComposite07 = TestFileUtil.createNewFile("fileComposite07.xlsx"); - compositeFillTemplate07 = TestFileUtil.readFile("fill" + File.separator + "composite.xlsx"); - fileComposite03 = TestFileUtil.createNewFile("fileComposite03.xls"); - compositeFillTemplate03 = TestFileUtil.readFile("fill" + File.separator + "composite.xls"); - } - - @Test - public void t01Fill07() { - fill(file07, simpleTemplate07); - } - - @Test - public void t02Fill03() { - fill(file03, simpleTemplate03); - } - - @Test - public void t03FillCsv() { - ExcelGenerateException excelGenerateException = - Assertions.assertThrows(ExcelGenerateException.class, () -> fill(fileCsv, simpleTemplateCsv)); - Assertions.assertEquals("csv cannot use template.", excelGenerateException.getMessage()); - } - - @Test - public void t03ComplexFill07() { - complexFill(fileComplex07, complexFillTemplate07); - } - - @Test - public void t04ComplexFill03() { - complexFill(fileComplex03, complexFillTemplate03); - } - - @Test - public void t05HorizontalFill07() { - horizontalFill(fileHorizontal07, horizontalFillTemplate07); - } - - @Test - public void t06HorizontalFill03() { - horizontalFill(fileHorizontal03, horizontalFillTemplate03); - } - - @Test - public void t07ByNameFill07() { - byNameFill(byName07, byNameTemplate07); - } - - @Test - public void t08ByNameFill03() { - byNameFill(byName03, byNameTemplate03); - } - - @Test - public void t09CompositeFill07() { - compositeFill(fileComposite07, compositeFillTemplate07); - } - - @Test - public void t10CompositeFill03() { - compositeFill(fileComposite03, compositeFillTemplate03); - } - - private void byNameFill(File file, File template) { - FillData fillData = new FillData(); - fillData.setName("Zhang San"); - fillData.setNumber(5.2); - FesodSheet.write(file, FillData.class) - .withTemplate(template) - .sheet("Sheet2") - .doFill(fillData); - } - - private void compositeFill(File file, File template) { - try (ExcelWriter excelWriter = - FesodSheet.write(file).withTemplate(template).build()) { - WriteSheet writeSheet = FesodSheet.writerSheet().build(); - - FillConfig fillConfig = FillConfig.builder() - .direction(WriteDirectionEnum.HORIZONTAL) - .build(); - excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); - excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); - excelWriter.fill(new FillWrapper("data2", data()), writeSheet); - excelWriter.fill(new FillWrapper("data2", data()), writeSheet); - excelWriter.fill(new FillWrapper("data3", data()), writeSheet); - excelWriter.fill(new FillWrapper("data3", data()), writeSheet); - Map map = new HashMap(); - map.put("date", "2019-10-09 13:28:28"); - excelWriter.fill(map, writeSheet); - } - - List list = FesodSheet.read(file) - .ignoreEmptyRow(false) - .sheet() - .headRowNumber(0) - .doReadSync(); - Map map0 = (Map) list.get(0); - Assertions.assertEquals("Zhang San", map0.get(21)); - Map map27 = (Map) list.get(27); - Assertions.assertEquals("Zhang San", map27.get(0)); - Map map29 = (Map) list.get(29); - Assertions.assertEquals("Zhang San", map29.get(3)); - } - - private void horizontalFill(File file, File template) { - try (ExcelWriter excelWriter = - FesodSheet.write(file).withTemplate(template).build()) { - WriteSheet writeSheet = FesodSheet.writerSheet().build(); - FillConfig fillConfig = FillConfig.builder() - .direction(WriteDirectionEnum.HORIZONTAL) - .build(); - excelWriter.fill(data(), fillConfig, writeSheet); - excelWriter.fill(data(), fillConfig, writeSheet); - Map map = new HashMap(); - map.put("date", "2019-10-09 13:28:28"); - excelWriter.fill(map, writeSheet); - excelWriter.finish(); - } - - List list = FesodSheet.read(file).sheet().headRowNumber(0).doReadSync(); - Assertions.assertEquals(5L, list.size()); - Map map0 = (Map) list.get(0); - Assertions.assertEquals("Zhang San", map0.get(2)); - } - - private void complexFill(File file, File template) { - try (ExcelWriter excelWriter = - FesodSheet.write(file).withTemplate(template).build()) { - WriteSheet writeSheet = FesodSheet.writerSheet() - .registerWriteHandler(new LoopMergeStrategy(2, 0)) - .build(); - FillConfig fillConfig = - FillConfig.builder().forceNewRow(Boolean.TRUE).build(); - excelWriter.fill(data(), fillConfig, writeSheet); - excelWriter.fill(data(), fillConfig, writeSheet); - Map map = new HashMap(); - map.put("date", "2019-10-09 13:28:28"); - map.put("total", 1000); - excelWriter.fill(map, writeSheet); - } - List list = FesodSheet.read(file).sheet().headRowNumber(3).doReadSync(); - Assertions.assertEquals(21L, list.size()); - Map map19 = (Map) list.get(19); - Assertions.assertEquals("Zhang San", map19.get(0)); - } - - private void fill(File file, File template) { - FillData fillData = new FillData(); - fillData.setName("Zhang San"); - fillData.setNumber(5.2); - FesodSheet.write(file, FillData.class).withTemplate(template).sheet().doFill(fillData); - } - - private List data() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - FillData fillData = new FillData(); - list.add(fillData); - fillData.setName("Zhang San"); - fillData.setNumber(5.2); - if (i == 5) { - fillData.setName(null); - } - } - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleDataTest.java deleted file mode 100644 index f07645868..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleDataTest.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.fill.style; - -import java.io.File; -import java.io.FileInputStream; -import java.util.List; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.metadata.Head; -import org.apache.fesod.sheet.util.DateUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.handler.context.CellWriteHandlerContext; -import org.apache.fesod.sheet.write.metadata.style.WriteCellStyle; -import org.apache.fesod.sheet.write.metadata.style.WriteFont; -import org.apache.fesod.sheet.write.style.AbstractVerticalCellStyleStrategy; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class FillStyleDataTest { - - private static File fileStyle07; - private static File fileStyle03; - private static File fileStyleHandler07; - private static File fileStyleHandler03; - private static File fileStyleTemplate07; - private static File fileStyleTemplate03; - - @BeforeAll - public static void init() { - fileStyle07 = TestFileUtil.createNewFile("fileStyle07.xlsx"); - fileStyle03 = TestFileUtil.createNewFile("fileStyle03.xls"); - fileStyleHandler07 = TestFileUtil.createNewFile("fileStyleHandler07.xlsx"); - fileStyleHandler03 = TestFileUtil.createNewFile("fileStyleHandler03.xls"); - fileStyleTemplate07 = TestFileUtil.readFile("fill" + File.separator + "style.xlsx"); - fileStyleTemplate03 = TestFileUtil.readFile("fill" + File.separator + "style.xls"); - } - - @Test - public void t01Fill07() throws Exception { - fill(fileStyle07, fileStyleTemplate07); - XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(fileStyle07)); - XSSFSheet sheet = workbook.getSheetAt(0); - t01Fill07check(sheet.getRow(1)); - t01Fill07check(sheet.getRow(2)); - } - - private void t01Fill07check(XSSFRow row) { - XSSFCell cell0 = row.getCell(0); - Assertions.assertEquals("Zhang San", cell0.getStringCellValue()); - Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FF00B050", cell0.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FF7030A0", cell0.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertTrue(cell0.getCellStyle().getFont().getBold()); - - XSSFCell cell1 = row.getCell(1); - Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1); - Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FF92D050", cell1.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FF4BACC6", cell1.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertFalse(cell1.getCellStyle().getFont().getBold()); - - XSSFCell cell2 = row.getCell(2); - Assertions.assertEquals( - "2020-01-01 01:01:01", DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss")); - Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString()); - Assertions.assertEquals( - "FFFFC000", cell2.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FFC0504D", cell2.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertTrue(cell2.getCellStyle().getFont().getBold()); - - XSSFCell cell3 = row.getCell(3); - Assertions.assertEquals("Zhang San is 5.2 years old this year", cell3.getStringCellValue()); - Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFFF0000", cell3.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FFEEECE1", cell3.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertTrue(cell3.getCellStyle().getFont().getBold()); - - XSSFCell cell4 = row.getCell(4); - Assertions.assertEquals("{.name} ignored,Zhang San", cell4.getStringCellValue()); - Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFC00000", cell4.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FF000000", cell4.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertFalse(cell4.getCellStyle().getFont().getBold()); - - XSSFCell cell5 = row.getCell(5); - Assertions.assertEquals("Empty", cell5.getStringCellValue()); - Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFF79646", cell5.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FF8064A2", cell5.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertFalse(cell5.getCellStyle().getFont().getBold()); - } - - @Test - public void t02Fill03() throws Exception { - fill(fileStyle03, fileStyleTemplate03); - HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileStyle03)); - HSSFSheet sheet = workbook.getSheetAt(0); - t02Fill03check(workbook, sheet.getRow(1)); - t02Fill03check(workbook, sheet.getRow(2)); - } - - private void t02Fill03check(HSSFWorkbook workbook, HSSFRow row) { - HSSFCell cell0 = row.getCell(0); - Assertions.assertEquals("Zhang San", cell0.getStringCellValue()); - Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "0:8080:0", cell0.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "8080:0:8080", - cell0.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertTrue(cell0.getCellStyle().getFont(workbook).getBold()); - - HSSFCell cell1 = row.getCell(1); - Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1); - Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "9999:CCCC:0", - cell1.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "0:8080:8080", - cell1.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertFalse(cell1.getCellStyle().getFont(workbook).getBold()); - - HSSFCell cell2 = row.getCell(2); - Assertions.assertEquals( - "2020-01-01 01:01:01", DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss")); - Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString()); - Assertions.assertEquals( - "FFFF:CCCC:0", - cell2.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "8080:0:0", - cell2.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertTrue(cell2.getCellStyle().getFont(workbook).getBold()); - - HSSFCell cell3 = row.getCell(3); - Assertions.assertEquals("Zhang San is 5.2 years old this year", cell3.getStringCellValue()); - Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFFF:0:0", cell3.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "FFFF:FFFF:9999", - cell3.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertTrue(cell3.getCellStyle().getFont(workbook).getBold()); - - HSSFCell cell4 = row.getCell(4); - Assertions.assertEquals("{.name} ignored,Zhang San", cell4.getStringCellValue()); - Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "9999:3333:0", - cell4.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "3333:3333:3333", - cell4.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertFalse(cell4.getCellStyle().getFont(workbook).getBold()); - - HSSFCell cell5 = row.getCell(5); - Assertions.assertEquals("Empty", cell5.getStringCellValue()); - Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "9999:3333:0", - cell5.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "CCCC:9999:FFFF", - cell5.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertFalse(cell5.getCellStyle().getFont(workbook).getBold()); - } - - private void fill(File file, File template) throws Exception { - FesodSheet.write(file, FillStyleData.class) - .withTemplate(template) - .sheet() - .doFill(data()); - } - - @Test - public void t11FillStyleHandler07() throws Exception { - fillStyleHandler(fileStyleHandler07, fileStyleTemplate07); - XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(fileStyleHandler07)); - XSSFSheet sheet = workbook.getSheetAt(0); - t11FillStyleHandler07check(sheet.getRow(1)); - t11FillStyleHandler07check(sheet.getRow(2)); - } - - private void t11FillStyleHandler07check(XSSFRow row) { - XSSFCell cell0 = row.getCell(0); - Assertions.assertEquals("Zhang San", cell0.getStringCellValue()); - Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFFFFF00", cell0.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FF808000", cell0.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertTrue(cell0.getCellStyle().getFont().getBold()); - - XSSFCell cell1 = row.getCell(1); - Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1); - Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFFF0000", cell1.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FF800000", cell1.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertTrue(cell1.getCellStyle().getFont().getBold()); - - XSSFCell cell2 = row.getCell(2); - Assertions.assertEquals( - "2020-01-01 01:01:01", DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss")); - Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString()); - Assertions.assertEquals( - "FF008000", cell2.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FF003300", cell2.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertTrue(cell2.getCellStyle().getFont().getBold()); - - XSSFCell cell3 = row.getCell(3); - Assertions.assertEquals("Zhang San is 5.2 years old this year", cell3.getStringCellValue()); - Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFFF0000", cell3.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FFEEECE1", cell3.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertTrue(cell3.getCellStyle().getFont().getBold()); - - XSSFCell cell4 = row.getCell(4); - Assertions.assertEquals("{.name} ignored,Zhang San", cell4.getStringCellValue()); - Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFC00000", cell4.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FF000000", cell4.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertFalse(cell4.getCellStyle().getFont().getBold()); - - XSSFCell cell5 = row.getCell(5); - Assertions.assertEquals("Empty", cell5.getStringCellValue()); - Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFF79646", cell5.getCellStyle().getFillForegroundColorColor().getARGBHex()); - Assertions.assertEquals( - "FF8064A2", cell5.getCellStyle().getFont().getXSSFColor().getARGBHex()); - Assertions.assertFalse(cell5.getCellStyle().getFont().getBold()); - } - - @Test - public void t12FillStyleHandler03() throws Exception { - fillStyleHandler(fileStyleHandler03, fileStyleTemplate03); - HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileStyleHandler03)); - HSSFSheet sheet = workbook.getSheetAt(0); - t12FillStyleHandler03check(workbook, sheet.getRow(1)); - t12FillStyleHandler03check(workbook, sheet.getRow(2)); - } - - private void t12FillStyleHandler03check(HSSFWorkbook workbook, HSSFRow row) { - HSSFCell cell0 = row.getCell(0); - Assertions.assertEquals("Zhang San", cell0.getStringCellValue()); - Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFFF:FFFF:0", - cell0.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "8080:8080:0", - cell0.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertTrue(cell0.getCellStyle().getFont(workbook).getBold()); - - HSSFCell cell1 = row.getCell(1); - Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1); - Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFFF:0:0", cell1.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "8080:0:0", - cell1.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertTrue(cell1.getCellStyle().getFont(workbook).getBold()); - - HSSFCell cell2 = row.getCell(2); - Assertions.assertEquals( - "2020-01-01 01:01:01", DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss")); - Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString()); - Assertions.assertEquals( - "0:8080:0", cell2.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "0:3333:0", - cell2.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertTrue(cell2.getCellStyle().getFont(workbook).getBold()); - - HSSFCell cell3 = row.getCell(3); - Assertions.assertEquals("Zhang San is 5.2 years old this year", cell3.getStringCellValue()); - Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "FFFF:0:0", cell3.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "FFFF:FFFF:9999", - cell3.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertTrue(cell3.getCellStyle().getFont(workbook).getBold()); - - HSSFCell cell4 = row.getCell(4); - Assertions.assertEquals("{.name} ignored,Zhang San", cell4.getStringCellValue()); - Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "9999:3333:0", - cell4.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "3333:3333:3333", - cell4.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertFalse(cell4.getCellStyle().getFont(workbook).getBold()); - - HSSFCell cell5 = row.getCell(5); - Assertions.assertEquals("Empty", cell5.getStringCellValue()); - Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat()); - Assertions.assertEquals( - "9999:3333:0", - cell5.getCellStyle().getFillForegroundColorColor().getHexString()); - Assertions.assertEquals( - "CCCC:9999:FFFF", - cell5.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); - Assertions.assertFalse(cell5.getCellStyle().getFont(workbook).getBold()); - } - - private void fillStyleHandler(File file, File template) throws Exception { - FesodSheet.write(file, FillStyleData.class) - .withTemplate(template) - .sheet() - .registerWriteHandler(new AbstractVerticalCellStyleStrategy() { - - @Override - protected WriteCellStyle contentCellStyle(CellWriteHandlerContext context) { - WriteCellStyle writeCellStyle = new WriteCellStyle(); - WriteFont writeFont = new WriteFont(); - writeCellStyle.setWriteFont(writeFont); - writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); - writeFont.setBold(true); - if (context.getColumnIndex() == 0) { - writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); - writeFont.setColor(IndexedColors.DARK_YELLOW.getIndex()); - } - if (context.getColumnIndex() == 1) { - writeCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); - writeFont.setColor(IndexedColors.DARK_RED.getIndex()); - } - if (context.getColumnIndex() == 2) { - writeCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); - writeFont.setColor(IndexedColors.DARK_GREEN.getIndex()); - } - if (context.getColumnIndex() == 3) { - writeCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex()); - writeFont.setColor(IndexedColors.DARK_BLUE.getIndex()); - } - if (context.getColumnIndex() == 4) { - writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); - writeFont.setColor(IndexedColors.DARK_YELLOW.getIndex()); - } - if (context.getColumnIndex() == 5) { - writeCellStyle.setFillForegroundColor(IndexedColors.TEAL.getIndex()); - writeFont.setColor(IndexedColors.DARK_TEAL.getIndex()); - } - return writeCellStyle; - } - - @Override - protected WriteCellStyle headCellStyle(Head head) { - return null; - } - }) - .doFill(data()); - } - - private List data() throws Exception { - List list = ListUtils.newArrayList(); - for (int i = 0; i < 10; i++) { - FillStyleData fillData = new FillStyleData(); - list.add(fillData); - fillData.setName("Zhang San"); - fillData.setNumber(5.2); - fillData.setDate(DateUtils.parseDate("2020-01-01 01:01:01")); - if (i == 5) { - fillData.setName(null); - } - } - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/BomDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/BomDataTest.java new file mode 100644 index 000000000..7689b79e4 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/BomDataTest.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.format; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import java.io.FileOutputStream; +import java.nio.charset.Charset; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.support.ExcelTypeEnum; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.listeners.CollectingReadListener; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.apache.fesod.sheet.util.TestFileUtil; +import org.junit.jupiter.api.Test; + +/** + * bom test + * + * + */ +@Slf4j +public class BomDataTest extends AbstractExcelTest { + + @Test + public void readCsv() { + readCsvImpl(TestFileUtil.readFile("bom" + File.separator + "no_bom.csv")); + readCsvImpl(TestFileUtil.readFile("bom" + File.separator + "office_bom.csv")); + } + + @Test + public void readAndWriteCsv() throws Exception { + readAndWriteCsv(createTempFile("bom_default", ExcelFormat.CSV), null, null); + readAndWriteCsv(createTempFile("bom_utf_8", ExcelFormat.CSV), "UTF-8", null); + readAndWriteCsv(createTempFile("bom_utf_8_lower_case", ExcelFormat.CSV), "utf-8", null); + readAndWriteCsv(createTempFile("bom_gbk", ExcelFormat.CSV), "GBK", null); + readAndWriteCsv(createTempFile("bom_gbk_lower_case", ExcelFormat.CSV), "gbk", null); + readAndWriteCsv(createTempFile("bom_utf_16be", ExcelFormat.CSV), "UTF-16BE", null); + readAndWriteCsv(createTempFile("bom_utf_8_not_with_bom", ExcelFormat.CSV), "UTF-8", Boolean.FALSE); + } + + private void readAndWriteCsv(File file, String charsetName, Boolean withBom) throws Exception { + Charset charset = null; + if (charsetName != null) { + charset = Charset.forName(charsetName); + } + List data = TestDataBuilder.simpleDataWithAge(10); + FesodSheet.write(new FileOutputStream(file), SimpleData.class) + .charset(charset) + .withBom(withBom) + .excelType(ExcelTypeEnum.CSV) + .sheet() + .doWrite(data); + + CollectingReadListener listener = new CollectingReadListener<>(); + FesodSheet.read(file, SimpleData.class, listener) + .charset(charset) + .sheet() + .doRead(); + assertEquals(10, listener.getRowCount()); + assertEquals("Name0", listener.getFirstRow().getName()); + assertEquals(0, (int) listener.getFirstRow().getAge()); + } + + private void readCsvImpl(File file) { + CollectingReadListener listener = new CollectingReadListener<>(); + FesodSheet.read(file, SimpleData.class, listener).sheet().doRead(); + assertEquals(10, listener.getRowCount()); + assertEquals("姓名0", listener.getFirstRow().getName()); + assertEquals(20, (int) listener.getFirstRow().getAge()); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CharsetDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CharsetDataTest.java new file mode 100644 index 000000000..767f447a6 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CharsetDataTest.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.format; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.listeners.CollectingReadListener; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.junit.jupiter.api.Test; + +/** + * charset + * + * + */ +@Slf4j +public class CharsetDataTest extends AbstractExcelTest { + private static final Charset GBK = Charset.forName("GBK"); + + @Test + public void readAndWriteCsv() throws Exception { + File fileCsvGbk = createTempFile("charsetGbk", ExcelFormat.CSV); + File fileCsvUtf8 = createTempFile("charsetUtf8", ExcelFormat.CSV); + readAndWrite(fileCsvGbk, GBK); + readAndWrite(fileCsvUtf8, StandardCharsets.UTF_8); + } + + @Test + public void readAndWriteCsvError() throws Exception { + File fileCsvError = createTempFile("charsetError", ExcelFormat.CSV); + FesodSheet.write(fileCsvError, SimpleData.class) + .charset(GBK) + .sheet() + .doWrite(TestDataBuilder.simpleDataWithAge(10)); + CollectingReadListener listener = new CollectingReadListener<>(); + FesodSheet.read(fileCsvError, SimpleData.class, listener) + .charset(StandardCharsets.UTF_8) + .sheet() + .doRead(); + } + + private void readAndWrite(File file, Charset charset) { + FesodSheet.write(file, SimpleData.class) + .charset(charset) + .sheet() + .doWrite(TestDataBuilder.simpleDataWithAge(10)); + CollectingReadListener listener = new CollectingReadListener<>(); + FesodSheet.read(file, SimpleData.class, listener) + .charset(charset) + .sheet() + .doRead(); + assertEquals(10, listener.getRowCount()); + assertEquals("Name0", listener.getFirstRow().getName()); + assertEquals(0, (int) listener.getFirstRow().getAge()); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/compatibility/CompatibilityTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CompatibilityTest.java similarity index 50% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/compatibility/CompatibilityTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CompatibilityTest.java index 7d624e38f..c201b0804 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/compatibility/CompatibilityTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CompatibilityTest.java @@ -23,161 +23,150 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.compatibility; +package org.apache.fesod.sheet.format; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.alibaba.fastjson2.JSON; import java.io.File; import java.math.BigDecimal; -import java.util.ArrayList; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.fesod.sheet.FesodSheet; import org.apache.fesod.sheet.cache.Ehcache; import org.apache.fesod.sheet.enums.ReadDefaultReturnEnum; -import org.apache.fesod.sheet.simple.SimpleData; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.models.SimpleData; import org.apache.fesod.sheet.util.FileUtils; import org.apache.fesod.sheet.util.TestFileUtil; import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; /** * Compatible with some special files * * */ -@TestMethodOrder(MethodOrderer.MethodName.class) @Slf4j -public class CompatibilityTest { +public class CompatibilityTest extends AbstractExcelTest { @Test - public void t01() { - List> list = FesodSheet.read(TestFileUtil.getPath() + "compatibility/t01.xls") - .sheet() - .doReadSync(); - Assertions.assertEquals(2, list.size()); + public void readXlsWithSpecialCharacters() { + List> list = readCompatibilityFile("t01.xls"); + assertEquals(2, list.size()); Map row1 = list.get(1); - Assertions.assertEquals("Q235(碳钢)", row1.get(0)); + assertEquals("Q235(碳钢)", row1.get(0)); } @Test - public void t02() { + public void readXlsxWithSharedStringNamespace() { // Exist in `sharedStrings.xml` `x:t` start tag, need to be compatible - List> list = FesodSheet.read(TestFileUtil.getPath() + "compatibility/t02.xlsx") - .sheet() - .headRowNumber(0) - .doReadSync(); + List> list = readCompatibilityFile("t02.xlsx", 0); log.info("data:{}", JSON.toJSONString(list)); - Assertions.assertEquals(3, list.size()); + assertEquals(3, list.size()); Map row2 = list.get(2); - Assertions.assertEquals("1,2-戊二醇", row2.get(2)); + assertEquals("1,2-戊二醇", row2.get(2)); } @Test - public void t03() { + public void readXlsxIgnoreNullColumns() { // In the presence of the first line of a lot of null columns, ignore null columns - List> list = FesodSheet.read(TestFileUtil.getPath() + "compatibility/t03.xlsx") - .sheet() - .doReadSync(); + List> list = readCompatibilityFile("t03.xlsx"); log.info("data:{}", JSON.toJSONString(list)); - Assertions.assertEquals(1, list.size()); + assertEquals(1, list.size()); Map row0 = list.get(0); - Assertions.assertEquals(12, row0.size()); + assertEquals(12, row0.size()); } @Test - public void t04() { + public void readXlsxWithNamespacedTag() { // Exist in `sheet1.xml` `ns2:t` start tag, need to be compatible - List> list = FesodSheet.read(TestFileUtil.getPath() + "compatibility/t04.xlsx") - .sheet() - .doReadSync(); + List> list = readCompatibilityFile("t04.xlsx"); log.info("data:{}", JSON.toJSONString(list)); - Assertions.assertEquals(56, list.size()); + assertEquals(56, list.size()); Map row0 = list.get(0); - Assertions.assertEquals("QQSJK28F152A012242S0081", row0.get(5)); + assertEquals("QQSJK28F152A012242S0081", row0.get(5)); } @Test - public void t05() { + public void readXlsxDateRounding() { // Excel read date needs to be rounded - List> list = FesodSheet.read(TestFileUtil.getPath() + "compatibility/t05.xlsx") - .sheet() - .doReadSync(); + List> list = readCompatibilityFile("t05.xlsx"); log.info("data:{}", JSON.toJSONString(list)); - Assertions.assertEquals("2023-01-01 00:00:00", list.get(0).get(0)); - Assertions.assertEquals("2023-01-01 00:00:00", list.get(1).get(0)); - Assertions.assertEquals("2023-01-01 00:00:00", list.get(2).get(0)); - Assertions.assertEquals("2023-01-01 00:00:01", list.get(3).get(0)); - Assertions.assertEquals("2023-01-01 00:00:01", list.get(4).get(0)); + assertEquals("2023-01-01 00:00:00", list.get(0).get(0)); + assertEquals("2023-01-01 00:00:00", list.get(1).get(0)); + assertEquals("2023-01-01 00:00:00", list.get(2).get(0)); + assertEquals("2023-01-01 00:00:01", list.get(3).get(0)); + assertEquals("2023-01-01 00:00:01", list.get(4).get(0)); } @Test - public void t06() { + public void readXlsxPrecisionFormat() { // Keep error precision digital format - List> list = FesodSheet.read(TestFileUtil.getPath() + "compatibility/t06.xlsx") - .headRowNumber(0) - .sheet() - .doReadSync(); + List> list = readCompatibilityFile("t06.xlsx", 0); log.info("data:{}", JSON.toJSONString(list)); - Assertions.assertEquals("2087.03", list.get(0).get(2)); + assertEquals("2087.03", list.get(0).get(2)); } @Test - public void t07() { + public void readXlsxActualDataReturn() { // Excel read date needs to be rounded - List> list = FesodSheet.read(TestFileUtil.getPath() + "compatibility/t07.xlsx") + List> list = FesodSheet.read(compatibilityFile("t07.xlsx")) .readDefaultReturn(ReadDefaultReturnEnum.ACTUAL_DATA) .sheet() .doReadSync(); log.info("data:{}", JSON.toJSONString(list)); - Assertions.assertEquals(0, new BigDecimal("24.1998124").compareTo((BigDecimal) + assertEquals(0, new BigDecimal("24.1998124").compareTo((BigDecimal) list.get(0).get(11))); - list = FesodSheet.read(TestFileUtil.getPath() + "compatibility/t07.xlsx") - .sheet() - .doReadSync(); + list = readCompatibilityFile("t07.xlsx"); log.info("data:{}", JSON.toJSONString(list)); - Assertions.assertEquals("24.20", list.get(0).get(11)); + assertEquals("24.20", list.get(0).get(11)); } @Test - public void t08() { + public void readWithCacheAfterTempDeletion() throws Exception { // Temporary files may be deleted if there is no operation for a long time, so they need to be recreated. - File file = TestFileUtil.createNewFile("compatibility/t08.xlsx"); - FesodSheet.write(file, SimpleData.class).sheet().doWrite(data()); + File stableDir = new File("target/test-cache"); + stableDir.mkdirs(); + File file = new File(stableDir, "compatibility-cache.xlsx"); + FesodSheet.write(file, SimpleData.class).sheet().doWrite(TestDataBuilder.simpleData(10)); List> list = FesodSheet.read(file).readCache(new Ehcache(null, 20)).sheet().doReadSync(); - Assertions.assertEquals(10L, list.size()); + assertEquals(10L, list.size()); FileUtils.delete(new File(System.getProperty(TempFile.JAVA_IO_TMPDIR))); list = FesodSheet.read(file).readCache(new Ehcache(null, 20)).sheet().doReadSync(); - Assertions.assertEquals(10L, list.size()); + assertEquals(10L, list.size()); } @Test - public void t09() { + public void readXlsxWithEscapeSequence() { // `SH_x005f_x000D_Z002` exists in `ShardingString.xml` and needs to be replaced by: `SH_x000D_Z002` - File file = TestFileUtil.readFile("compatibility/t09.xlsx"); + File file = compatibilityFile("t09.xlsx"); List> list = FesodSheet.read(file).headRowNumber(0).sheet().doReadSync(); log.info("data:{}", JSON.toJSONString(list)); - Assertions.assertEquals(1, list.size()); + assertEquals(1, list.size()); + + assertEquals("SH_x000D_Z002", list.get(0).get(0)); + } + + private File compatibilityFile(String fileName) { + return TestFileUtil.readFile("compatibility/" + fileName); + } - Assertions.assertEquals("SH_x000D_Z002", list.get(0).get(0)); + private List> readCompatibilityFile(String fileName) { + return FesodSheet.read(compatibilityFile(fileName)).sheet().doReadSync(); } - private List data() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - SimpleData simpleData = new SimpleData(); - simpleData.setName("姓名" + i); - list.add(simpleData); - } - return list; + private List> readCompatibilityFile(String fileName, int headRowNumber) { + return FesodSheet.read(compatibilityFile(fileName)) + .sheet() + .headRowNumber(headRowNumber) + .doReadSync(); } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvBenignErrorToleranceTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvBenignErrorToleranceTest.java similarity index 96% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvBenignErrorToleranceTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvBenignErrorToleranceTest.java index 012379fdc..1ae7b5237 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvBenignErrorToleranceTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvBenignErrorToleranceTest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.csv; +package org.apache.fesod.sheet.format; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -29,13 +29,14 @@ import org.apache.fesod.sheet.FesodSheet; import org.apache.fesod.sheet.exception.ExcelCommonException; import org.apache.fesod.sheet.read.builder.CsvReaderBuilder; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; import org.junit.jupiter.api.Test; /** * Tests that truncated/unfinished quoted fields in CSV are treated as benign and * end the current sheet gracefully without throwing to the caller. */ -class CsvBenignErrorToleranceTest { +class CsvBenignErrorToleranceTest extends AbstractExcelTest { @Test void shouldNotThrowOnUnclosedQuotedField_EOFBenign() { diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvData.java similarity index 89% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvData.java index ccd2bf6b8..10dcc3578 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.csv; +package org.apache.fesod.sheet.format; import java.util.Date; import lombok.EqualsAndHashCode; @@ -39,16 +39,16 @@ @Setter @EqualsAndHashCode public class CsvData { - @ExcelProperty("字符串标题") + @ExcelProperty("String") private String string; - @ExcelProperty("日期标题") + @ExcelProperty("Date") private Date date; - @ExcelProperty("数字标题") + @ExcelProperty("Number") private Double doubleData; /** - * 忽略这个字段 + * Ignore this field. */ @ExcelIgnore private String ignore; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvDataListener.java similarity index 98% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvDataListener.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvDataListener.java index 0e9c72aa3..3d5038580 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvDataListener.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvDataListener.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.csv; +package org.apache.fesod.sheet.format; import com.alibaba.fastjson2.JSON; import lombok.extern.slf4j.Slf4j; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvFormatTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvFormatTest.java similarity index 84% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvFormatTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvFormatTest.java index 3baefab62..b711a7b95 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/csv/CsvFormatTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/CsvFormatTest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.csv; +package org.apache.fesod.sheet.format; import java.io.File; import java.io.IOException; @@ -41,39 +41,39 @@ import org.apache.fesod.sheet.read.metadata.holder.ReadWorkbookHolder; import org.apache.fesod.sheet.read.metadata.holder.csv.CsvReadWorkbookHolder; import org.apache.fesod.sheet.support.ExcelTypeEnum; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; import org.apache.fesod.sheet.util.DateUtils; import org.apache.fesod.sheet.util.TestFileUtil; import org.apache.fesod.sheet.write.metadata.WriteSheet; import org.apache.fesod.sheet.write.metadata.holder.WriteWorkbookHolder; import org.apache.poi.ss.usermodel.Workbook; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @Slf4j -public class CsvFormatTest { +public class CsvFormatTest extends AbstractExcelTest { - private static File csvFile; private static final String CSV_BASE = "csv" + File.separator; private static final String STRING_PREFIX = "String"; - private static List csvDataList; + private List csvDataList; - @BeforeAll - public static void init() { + @BeforeEach + public void init() { csvDataList = dataList(10, STRING_PREFIX); } @Test - public void testSimple() { + public void testSimple() throws Exception { - csvFile = TestFileUtil.readFile(CSV_BASE + "simple.csv"); + File csvFile = TestFileUtil.readFile(CSV_BASE + "simple.csv"); doTest(false, csvFile, null, null, null, null, null); - csvFile = TestFileUtil.createNewFile(CSV_BASE + "csv-simple.csv"); + csvFile = createTempFile(ExcelFormat.CSV); doTest(true, csvFile, null, null, null, null, null); - // sheet - csvFile = TestFileUtil.createNewFile(CSV_BASE + "csv-sheet-simple.csv"); + csvFile = createTempFile("csv-sheet-simple", ExcelFormat.CSV); FesodSheet.write(csvFile, CsvData.class).sheet().doWrite(csvDataList); List dataList = FesodSheet.read(csvFile, CsvData.class, new CsvDataListener()) .sheet() @@ -83,8 +83,8 @@ public void testSimple() { } @Test - public void testDelimiter() { - csvFile = TestFileUtil.createNewFile(CSV_BASE + "csv-delimiter.csv"); + public void testDelimiter() throws Exception { + File csvFile = createTempFile(ExcelFormat.CSV); log.info("{} delimiter", CsvConstant.AT); doTest(true, csvFile, CsvConstant.AT, null, null, null, null); @@ -94,38 +94,38 @@ public void testDelimiter() { } @Test - public void testQuote() { - csvFile = TestFileUtil.readFile(CSV_BASE + "simple-quote.csv"); + public void testQuote() throws Exception { + File csvFile = TestFileUtil.readFile(CSV_BASE + "simple-quote.csv"); doTest(false, csvFile, null, '"', null, null, null); - csvFile = TestFileUtil.createNewFile(CSV_BASE + "csv-quote.csv"); + csvFile = createTempFile(ExcelFormat.CSV); doTest(true, csvFile, null, '"', null, null, null); } @Test - public void testNullString() { - csvFile = TestFileUtil.createNewFile(CSV_BASE + "csv-null-string.csv"); + public void testNullString() throws Exception { + File csvFile = createTempFile(ExcelFormat.CSV); doTest(true, csvFile, null, null, null, CsvConstant.UNICODE_EMPTY, null); doTest(true, csvFile, null, null, null, CsvConstant.SQL_NULL_STRING, null); } @Test - public void testRecordSeparator() { - csvFile = TestFileUtil.createNewFile(CSV_BASE + "csv-record-separator.csv"); + public void testRecordSeparator() throws Exception { + File csvFile = createTempFile(ExcelFormat.CSV); doTest(true, csvFile, null, '"', CsvConstant.LF, null, null); doTest(true, csvFile, null, '"', CsvConstant.CR, null, null); } @Test - public void testEscape() { - csvFile = TestFileUtil.createNewFile(CSV_BASE + "csv-escape.csv"); + public void testEscape() throws Exception { + File csvFile = createTempFile(ExcelFormat.CSV); doTest(true, csvFile, null, null, null, null, CsvConstant.BACKSLASH); doTest(true, csvFile, null, null, null, null, CsvConstant.DOUBLE_QUOTE); } @Test - public void testNoHead() { - csvFile = TestFileUtil.createNewFile(CSV_BASE + "csv-no-head.csv"); + public void testNoHead() throws Exception { + File csvFile = createTempFile(ExcelFormat.CSV); FesodSheet.write(csvFile, CsvData.class).needHead(false).csv().doWrite(csvDataList); List dataList = FesodSheet.read(csvFile, new CsvDataListener()) .headRowNumber(0) @@ -136,8 +136,8 @@ public void testNoHead() { } @Test - public void testAutoTrim() { - csvFile = TestFileUtil.createNewFile(CSV_BASE + "csv-auto-trim.csv"); + public void testAutoTrim() throws Exception { + File csvFile = createTempFile(ExcelFormat.CSV); FesodSheet.write(csvFile, CsvData.class) .autoTrim(Boolean.FALSE) .csv() @@ -151,11 +151,11 @@ public void testAutoTrim() { } @Test - public void testHolder() { + public void testHolder() throws Exception { CSVFormat csvFormat = - CSVFormat.DEFAULT.builder().setDelimiter(CsvConstant.AT).build(); + CSVFormat.DEFAULT.builder().setDelimiter(CsvConstant.AT).get(); - csvFile = TestFileUtil.createNewFile(CSV_BASE + "csv-delimiter.csv"); + File csvFile = createTempFile(ExcelFormat.CSV); try (ExcelWriter excelWriter = FesodSheet.write(csvFile, CsvData.class) .excelType(ExcelTypeEnum.CSV) .build()) { @@ -170,7 +170,6 @@ public void testHolder() { excelWriter.write(csvDataList, writeSheet); } - csvFile = TestFileUtil.readFile(CSV_BASE + "csv-delimiter.csv"); try (ExcelReader excelReader = FesodSheet.read(csvFile, CsvData.class, new CsvDataListener()).build()) { ReadWorkbookHolder readWorkbookHolder = @@ -186,12 +185,12 @@ public void testHolder() { @Test public void writeWithCommonCsv() { - csvFile = TestFileUtil.readFile(CSV_BASE + "write-common-csv.csv"); + File csvFile = TestFileUtil.readFile(CSV_BASE + "write-common-csv.csv"); CSVFormat csvFormat = CSVFormat.DEFAULT .builder() .setQuote(CsvConstant.DOUBLE_QUOTE) .setQuoteMode(QuoteMode.ALL) - .build(); + .get(); writeWithCommonCsv(csvFile, csvFormat, dataList(10, STRING_PREFIX)); } @@ -253,7 +252,6 @@ private void writeWithCommonCsv(File csvFile, CSVFormat csvFormat, List Appendable out = new PrintWriter(new OutputStreamWriter(Files.newOutputStream(csvFile.toPath()))); CSVPrinter printer = csvFormat.print(out); for (CsvData data : dataList) { - // format date printer.printRecord( data.getString(), DateUtils.format(data.getDate(), DateUtils.DATE_FORMAT_19), diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/dataformat/DateFormatData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/DateFormatData.java similarity index 96% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/dataformat/DateFormatData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/format/DateFormatData.java index fa4a21cb0..348ce0e08 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/dataformat/DateFormatData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/DateFormatData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.dataformat; +package org.apache.fesod.sheet.format; import lombok.EqualsAndHashCode; import lombok.Getter; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/DateFormatTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/DateFormatTest.java new file mode 100644 index 000000000..daa8721b9 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/format/DateFormatTest.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.format; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.util.TestFileUtil; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * + */ +public class DateFormatTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("binaryFormats") + void readCn(ExcelFormat format) { + File file = TestFileUtil.readFile("dataformat" + File.separator + "dataformat" + format.getExtension()); + List list = FesodSheet.read(file, DateFormatData.class, null) + .locale(Locale.CHINA) + .sheet() + .doReadSync(); + for (DateFormatData data : list) { + assertTrue(Objects.equals(data.getDateStringCn(), data.getDate()) + || Objects.equals(data.getDateStringCn2(), data.getDate())); + assertEquals(data.getNumberStringCn(), data.getNumber()); + } + } + + @ParameterizedTest + @MethodSource("binaryFormats") + void readUs(ExcelFormat format) { + File file = TestFileUtil.readFile("dataformat" + File.separator + "dataformat" + format.getExtension()); + List list = FesodSheet.read(file, DateFormatData.class, null) + .locale(Locale.US) + .sheet() + .doReadSync(); + for (DateFormatData data : list) { + assertEquals(data.getDateStringUs(), data.getDate()); + assertEquals(data.getNumberStringUs(), data.getNumber()); + } + } + + @Test + void readV2() { + File file07V2 = TestFileUtil.readFile("dataformat" + File.separator + "dataformatv2.xlsx"); + List> dataMap = + FesodSheet.read(file07V2).headRowNumber(0).doReadAllSync(); + assertEquals("15:00", dataMap.get(0).get(0)); + assertEquals("2023-1-01 00:00:00", dataMap.get(1).get(0)); + assertEquals("2023-1-01 00:00:00", dataMap.get(2).get(0)); + assertEquals("2023-1-01 00:00:01", dataMap.get(3).get(0)); + assertEquals("2023-1-01 00:00:00", dataMap.get(4).get(0)); + assertEquals("2023-1-01 00:00:00", dataMap.get(5).get(0)); + assertEquals("2023-1-01 00:00:01", dataMap.get(6).get(0)); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/handler/WriteHandlerData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/handler/WriteHandlerData.java deleted file mode 100644 index 562d5b672..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/handler/WriteHandlerData.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.handler; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -public class WriteHandlerData { - @ExcelProperty("姓名") - private String name; -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/handler/WriteHandlerTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/handler/WriteHandlerTest.java index 475c55669..e65cfc14b 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/handler/WriteHandlerTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/handler/WriteHandlerTest.java @@ -26,115 +26,60 @@ package org.apache.fesod.sheet.handler; import java.io.File; -import java.util.ArrayList; -import java.util.List; +import java.util.Collections; import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class WriteHandlerTest { +public class WriteHandlerTest extends AbstractExcelTest { - private static File file07; - private static File file03; - private static File fileCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("writeHandler07.xlsx"); - file03 = TestFileUtil.createNewFile("writeHandler03.xls"); - fileCsv = TestFileUtil.createNewFile("writeHandlerCsv.csv"); - } - - @Test - public void t01WorkbookWrite07() throws Exception { - workbookWrite(file07); - } - - @Test - public void t02WorkbookWrite03() throws Exception { - workbookWrite(file03); - } - - @Test - public void t03WorkbookWriteCsv() throws Exception { - workbookWrite(fileCsv); - } - - @Test - public void t11SheetWrite07() throws Exception { - sheetWrite(file07); - } - - @Test - public void t12SheetWrite03() throws Exception { - sheetWrite(file03); - } - - @Test - public void t13SheetWriteCsv() throws Exception { - sheetWrite(fileCsv); - } - - @Test - public void t21TableWrite07() throws Exception { - tableWrite(file07); - } - - @Test - public void t22TableWrite03() throws Exception { - tableWrite(file03); - } - - @Test - public void t23TableWriteCsv() throws Exception { - tableWrite(fileCsv); - } - - private void workbookWrite(File file) { + @ParameterizedTest + @MethodSource("allFormats") + void workbookWrite(ExcelFormat format) throws Exception { + File file = createTempFile(format); WriteHandler writeHandler = new WriteHandler(); FesodSheet.write(file) - .head(WriteHandlerData.class) + .head(SimpleData.class) + .includeColumnFieldNames(Collections.singletonList("name")) .registerWriteHandler(writeHandler) .sheet() - .doWrite(data()); + .doWrite(TestDataBuilder.simpleData(1)); writeHandler.afterAll(); } - private void sheetWrite(File file) { + @ParameterizedTest + @MethodSource("allFormats") + void sheetWrite(ExcelFormat format) throws Exception { + File file = createTempFile(format); WriteHandler writeHandler = new WriteHandler(); FesodSheet.write(file) - .head(WriteHandlerData.class) + .head(SimpleData.class) + .includeColumnFieldNames(Collections.singletonList("name")) .sheet() .registerWriteHandler(writeHandler) - .doWrite(data()); + .doWrite(TestDataBuilder.simpleData(1)); writeHandler.afterAll(); } - private void tableWrite(File file) { + @ParameterizedTest + @MethodSource("allFormats") + void tableWrite(ExcelFormat format) throws Exception { + File file = createTempFile(format); WriteHandler writeHandler = new WriteHandler(); FesodSheet.write(file) - .head(WriteHandlerData.class) + .head(SimpleData.class) + .includeColumnFieldNames(Collections.singletonList("name")) .sheet() .table(0) .registerWriteHandler(writeHandler) - .doWrite(data()); + .doWrite(TestDataBuilder.simpleData(1)); writeHandler.afterAll(); } - - private List data() { - List list = new ArrayList(); - for (int i = 0; i < 1; i++) { - WriteHandlerData data = new WriteHandlerData(); - data.setName("姓名" + i); - list.add(data); - } - return list; - } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ComplexDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ComplexDataListener.java deleted file mode 100644 index 193628faa..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ComplexDataListener.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.head; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class ComplexDataListener extends AnalysisEventListener { - - List list = new ArrayList(); - - @Override - public void invoke(ComplexHeadData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(1, list.size()); - ComplexHeadData data = list.get(0); - Assertions.assertEquals("字符串4", data.getString4()); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ComplexHeadData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ComplexHeadData.java index 8846192c9..73cf38e7d 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ComplexHeadData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ComplexHeadData.java @@ -37,18 +37,18 @@ @Setter @EqualsAndHashCode public class ComplexHeadData { - @ExcelProperty({"顶格", "顶格", "两格"}) + @ExcelProperty({"Region", "Region", "Merged"}) private String string0; - @ExcelProperty({"顶格", "顶格", "两格"}) + @ExcelProperty({"Region", "Region", "Merged"}) private String string1; - @ExcelProperty({"顶格", "四联", "四联"}) + @ExcelProperty({"Region", "Group", "Group"}) private String string2; - @ExcelProperty({"顶格", "四联", "四联"}) + @ExcelProperty({"Region", "Group", "Group"}) private String string3; - @ExcelProperty({"顶格"}) + @ExcelProperty({"Region"}) private String string4; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ComplexHeadDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ComplexHeadDataTest.java index a4ae735ec..0b8332572 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ComplexHeadDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ComplexHeadDataTest.java @@ -25,96 +25,46 @@ package org.apache.fesod.sheet.head; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; -import java.util.ArrayList; import java.util.List; import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** - * + * Test complex head write/read for all Excel formats using parameterized tests. */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class ComplexHeadDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - private static File file07AutomaticMergeHead; - private static File file03AutomaticMergeHead; - private static File fileCsvAutomaticMergeHead; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("complexHead07.xlsx"); - file03 = TestFileUtil.createNewFile("complexHead03.xls"); - fileCsv = TestFileUtil.createNewFile("complexHeadCsv.csv"); - file07AutomaticMergeHead = TestFileUtil.createNewFile("complexHeadAutomaticMergeHead07.xlsx"); - file03AutomaticMergeHead = TestFileUtil.createNewFile("complexHeadAutomaticMergeHead03.xls"); - fileCsvAutomaticMergeHead = TestFileUtil.createNewFile("complexHeadAutomaticMergeHeadCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() { - readAndWrite(fileCsv); - } +public class ComplexHeadDataTest extends AbstractExcelTest { - private void readAndWrite(File file) { - FesodSheet.write(file, ComplexHeadData.class).sheet().doWrite(data()); - FesodSheet.read(file, ComplexHeadData.class, new ComplexDataListener()) + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile("complexHead", format); + FesodSheet.write(file, ComplexHeadData.class).sheet().doWrite(TestDataBuilder.complexHeadData(1)); + List result = FesodSheet.read(file) + .head(ComplexHeadData.class) .xlsxSAXParserFactoryName("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl") .sheet() - .doRead(); + .doReadSync(); + assertEquals(1, result.size()); + assertEquals("String4", result.get(0).getString4()); } - @Test - public void t11ReadAndWriteAutomaticMergeHead07() { - readAndWriteAutomaticMergeHead(file07AutomaticMergeHead); - } - - @Test - public void t12ReadAndWriteAutomaticMergeHead03() { - readAndWriteAutomaticMergeHead(file03AutomaticMergeHead); - } - - @Test - public void t13ReadAndWriteAutomaticMergeHeadCsv() { - readAndWriteAutomaticMergeHead(fileCsvAutomaticMergeHead); - } - - private void readAndWriteAutomaticMergeHead(File file) { + @ParameterizedTest + @MethodSource("allFormats") + void readAndWriteAutomaticMergeHead(ExcelFormat format) throws Exception { + File file = createTempFile("complexHeadAutoMerge", format); FesodSheet.write(file, ComplexHeadData.class) .automaticMergeHead(Boolean.FALSE) .sheet() - .doWrite(data()); - FesodSheet.read(file, ComplexHeadData.class, new ComplexDataListener()) - .sheet() - .doRead(); - } - - private List data() { - List list = new ArrayList(); - ComplexHeadData data = new ComplexHeadData(); - data.setString0("字符串0"); - data.setString1("字符串1"); - data.setString2("字符串2"); - data.setString3("字符串3"); - data.setString4("字符串4"); - list.add(data); - return list; + .doWrite(TestDataBuilder.complexHeadData(1)); + List result = + FesodSheet.read(file).head(ComplexHeadData.class).sheet().doReadSync(); + assertEquals(1, result.size()); + assertEquals("String4", result.get(0).getString4()); } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/HeaderMergeStrategyTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/HeaderMergeStrategyTest.java index 2c1db0fa0..5521ed402 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/HeaderMergeStrategyTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/HeaderMergeStrategyTest.java @@ -25,49 +25,31 @@ import java.util.List; import org.apache.fesod.sheet.FesodSheet; import org.apache.fesod.sheet.enums.HeaderMergeStrategy; -import org.apache.fesod.sheet.util.TestFileUtil; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; /** * Test for header merge strategy * */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class HeaderMergeStrategyTest { - - private static File fileNone; - private static File fileHorizontalOnly; - private static File fileVerticalOnly; - private static File fileFullRectangle; - private static File fileAuto; - - @BeforeAll - public static void init() { - fileNone = TestFileUtil.createNewFile("headerMergeStrategyNone.xlsx"); - fileHorizontalOnly = TestFileUtil.createNewFile("headerMergeStrategyHorizontalOnly.xlsx"); - fileVerticalOnly = TestFileUtil.createNewFile("headerMergeStrategyVerticalOnly.xlsx"); - fileFullRectangle = TestFileUtil.createNewFile("headerMergeStrategyFullRectangle.xlsx"); - fileAuto = TestFileUtil.createNewFile("headerMergeStrategyAuto.xlsx"); - } +public class HeaderMergeStrategyTest extends AbstractExcelTest { @Test - public void testNoneStrategy() { + public void testNoneStrategy() throws Exception { + File file = createTempFile("headerMergeNone", ExcelFormat.XLSX); List> head = createTestHead(); - FesodSheet.write(fileNone) + FesodSheet.write(file) .head(head) .headerMergeStrategy(HeaderMergeStrategy.NONE) .sheet() .doWrite(createTestData()); // Verify no merged regions - try (org.apache.poi.ss.usermodel.Workbook workbook = - org.apache.poi.ss.usermodel.WorkbookFactory.create(fileNone)) { + try (org.apache.poi.ss.usermodel.Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { Sheet sheet = workbook.getSheetAt(0); Assertions.assertEquals( 0, sheet.getNumMergedRegions(), "NONE strategy should not create any merged regions"); @@ -77,17 +59,17 @@ public void testNoneStrategy() { } @Test - public void testHorizontalOnlyStrategy() { + public void testHorizontalOnlyStrategy() throws Exception { + File file = createTempFile("headerMergeHoriz", ExcelFormat.XLSX); List> head = createTestHead(); - FesodSheet.write(fileHorizontalOnly) + FesodSheet.write(file) .head(head) .headerMergeStrategy(HeaderMergeStrategy.HORIZONTAL_ONLY) .sheet() .doWrite(createTestData()); // Verify only horizontal merges exist - try (org.apache.poi.ss.usermodel.Workbook workbook = - org.apache.poi.ss.usermodel.WorkbookFactory.create(fileHorizontalOnly)) { + try (org.apache.poi.ss.usermodel.Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { Sheet sheet = workbook.getSheetAt(0); int mergedRegionCount = sheet.getNumMergedRegions(); @@ -105,17 +87,17 @@ public void testHorizontalOnlyStrategy() { } @Test - public void testVerticalOnlyStrategy() { + public void testVerticalOnlyStrategy() throws Exception { + File file = createTempFile("headerMergeVert", ExcelFormat.XLSX); List> head = createTestHead(); - FesodSheet.write(fileVerticalOnly) + FesodSheet.write(file) .head(head) .headerMergeStrategy(HeaderMergeStrategy.VERTICAL_ONLY) .sheet() .doWrite(createTestData()); // Verify only vertical merges exist - try (org.apache.poi.ss.usermodel.Workbook workbook = - org.apache.poi.ss.usermodel.WorkbookFactory.create(fileVerticalOnly)) { + try (org.apache.poi.ss.usermodel.Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { Sheet sheet = workbook.getSheetAt(0); int mergedRegionCount = sheet.getNumMergedRegions(); @@ -133,17 +115,17 @@ public void testVerticalOnlyStrategy() { } @Test - public void testFullRectangleStrategy() { + public void testFullRectangleStrategy() throws Exception { + File file = createTempFile("headerMergeRect", ExcelFormat.XLSX); List> head = createTestHead(); - FesodSheet.write(fileFullRectangle) + FesodSheet.write(file) .head(head) .headerMergeStrategy(HeaderMergeStrategy.FULL_RECTANGLE) .sheet() .doWrite(createTestData()); // Verify all merged regions form valid rectangles - try (org.apache.poi.ss.usermodel.Workbook workbook = - org.apache.poi.ss.usermodel.WorkbookFactory.create(fileFullRectangle)) { + try (org.apache.poi.ss.usermodel.Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { Sheet sheet = workbook.getSheetAt(0); int mergedRegionCount = sheet.getNumMergedRegions(); @@ -162,17 +144,17 @@ public void testFullRectangleStrategy() { } @Test - public void testAutoStrategy() { + public void testAutoStrategy() throws Exception { + File file = createTempFile("headerMergeAuto", ExcelFormat.XLSX); List> head = createTestHead(); - FesodSheet.write(fileAuto) + FesodSheet.write(file) .head(head) .headerMergeStrategy(HeaderMergeStrategy.AUTO) .sheet() .doWrite(createTestData()); // AUTO strategy should work similar to the old behavior - try (org.apache.poi.ss.usermodel.Workbook workbook = - org.apache.poi.ss.usermodel.WorkbookFactory.create(fileAuto)) { + try (org.apache.poi.ss.usermodel.Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { Sheet sheet = workbook.getSheetAt(0); // Just verify that the file was created successfully Assertions.assertNotNull(sheet, "Sheet should be created"); diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ImmutableListHeadDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ImmutableListHeadDataListener.java deleted file mode 100644 index e8c341e60..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ImmutableListHeadDataListener.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.fesod.sheet.head; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.metadata.data.ReadCellData; -import org.apache.fesod.sheet.read.listener.ReadListener; -import org.junit.jupiter.api.Assertions; - -public class ImmutableListHeadDataListener implements ReadListener> { - - private List> list = new ArrayList>(); - - @Override - public void invokeHead(Map> headMap, AnalysisContext context) { - Assertions.assertNotNull(context.readRowHolder().getRowIndex()); - headMap.forEach((key, value) -> { - Assertions.assertEquals(value.getRowIndex(), context.readRowHolder().getRowIndex()); - Assertions.assertEquals(value.getColumnIndex(), key); - }); - } - - @Override - public void invoke(Map data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - List> head = context.readSheetHolder().getHead(); - - Assertions.assertInstanceOf(ArrayList.class, head); - for (List item : head) { - Assertions.assertInstanceOf(ArrayList.class, item); - } - - Assertions.assertEquals(1, list.size()); - Map data = list.get(0); - Assertions.assertEquals("stringData", data.get(0)); - Assertions.assertEquals("1", data.get(1)); - Assertions.assertEquals("2025-10-31 01:01:01", data.get(2)); - Assertions.assertEquals("extraData", data.get(3)); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ImmutableListHeadDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ImmutableListHeadDataTest.java index e97741aa2..292c2954c 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ImmutableListHeadDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ImmutableListHeadDataTest.java @@ -19,61 +19,44 @@ package org.apache.fesod.sheet.head; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.apache.fesod.sheet.FastExcel; +import java.util.Map; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; import org.apache.fesod.sheet.util.DateUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@TestMethodOrder(MethodOrderer.MethodName.class) -public class ImmutableListHeadDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("listHead07.xlsx"); - file03 = TestFileUtil.createNewFile("listHead03.xls"); - fileCsv = TestFileUtil.createNewFile("listHeadCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() throws Exception { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() throws Exception { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() throws Exception { - readAndWrite(fileCsv); - } +/** + * Test immutable list head write/read for all Excel formats using parameterized tests. + */ +public class ImmutableListHeadDataTest extends AbstractExcelTest { - private void readAndWrite(File file) throws Exception { - FastExcel.write(file) + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile("listHead", format); + FesodSheet.write(file) .head(head()) .registerWriteHandler(new ImmutableListHeadDataWriteHandler()) .sheet() .doWrite(data()); - FastExcel.read(file) - .head(head()) - .registerReadListener(new ImmutableListHeadDataListener()) - .sheet() - .doRead(); + List> list = + FesodSheet.read(file).head(head()).sheet().doReadSync(); + assertEquals(1, list.size()); + Map row = list.get(0); + assertEquals("stringData", row.get(0)); + assertEquals("1", row.get(1)); + assertEquals("2025-10-31 01:01:01", row.get(2)); + assertEquals("extraData", row.get(3)); } private List> head() { diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ListHeadDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ListHeadDataListener.java deleted file mode 100644 index cf736261d..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ListHeadDataListener.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.head; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.metadata.data.ReadCellData; -import org.apache.fesod.sheet.read.listener.ReadListener; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class ListHeadDataListener implements ReadListener> { - - List> list = new ArrayList>(); - - @Override - public void invokeHead(Map> headMap, AnalysisContext context) { - Assertions.assertNotNull(context.readRowHolder().getRowIndex()); - headMap.forEach((key, value) -> { - Assertions.assertEquals(value.getRowIndex(), context.readRowHolder().getRowIndex()); - Assertions.assertEquals(value.getColumnIndex(), key); - }); - } - - @Override - public void invoke(Map data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(1, list.size()); - Map data = list.get(0); - Assertions.assertEquals("字符串0", data.get(0)); - Assertions.assertEquals("1", data.get(1)); - Assertions.assertEquals("2020-01-01 01:01:01", data.get(2)); - Assertions.assertEquals("额外数据", data.get(3)); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ListHeadDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ListHeadDataTest.java index a4119c37c..5d6a07d1e 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ListHeadDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/ListHeadDataTest.java @@ -25,66 +25,46 @@ package org.apache.fesod.sheet.head; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.text.ParseException; import java.util.ArrayList; import java.util.List; +import java.util.Map; import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; import org.apache.fesod.sheet.util.DateUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** - * + * Test list-based head write/read for all Excel formats using parameterized tests. */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class ListHeadDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("listHead07.xlsx"); - file03 = TestFileUtil.createNewFile("listHead03.xls"); - fileCsv = TestFileUtil.createNewFile("listHeadCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() throws Exception { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() throws Exception { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() throws Exception { - readAndWrite(fileCsv); - } +public class ListHeadDataTest extends AbstractExcelTest { - private void readAndWrite(File file) throws Exception { + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile("listHead", format); FesodSheet.write(file).head(head()).sheet().doWrite(data()); - FesodSheet.read(file) - .registerReadListener(new ListHeadDataListener()) - .sheet() - .doRead(); + List> list = FesodSheet.read(file).sheet().doReadSync(); + assertEquals(1, list.size()); + Map row = list.get(0); + assertEquals("String0", row.get(0)); + assertEquals("1", row.get(1)); + assertEquals("2020-01-01 01:01:01", row.get(2)); + assertEquals("ExtraData", row.get(3)); } private List> head() { List> list = new ArrayList>(); List head0 = new ArrayList(); - head0.add("字符串"); + head0.add("String"); List head1 = new ArrayList(); - head1.add("数字"); + head1.add("Number"); List head2 = new ArrayList(); - head2.add("日期"); + head2.add("Date"); list.add(head0); list.add(head1); list.add(head2); @@ -94,10 +74,10 @@ private List> head() { private List> data() throws ParseException { List> list = new ArrayList>(); List data0 = new ArrayList(); - data0.add("字符串0"); + data0.add("String0"); data0.add(1); data0.add(DateUtils.parseDate("2020-01-01 01:01:01")); - data0.add("额外数据"); + data0.add("ExtraData"); list.add(data0); return list; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/MaxHeadReadListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/MaxHeadReadListener.java index d769b8e11..e55f9d3c6 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/MaxHeadReadListener.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/MaxHeadReadListener.java @@ -21,9 +21,6 @@ import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.fesod.sheet.context.AnalysisContext; @@ -32,18 +29,11 @@ @Slf4j public class MaxHeadReadListener extends AnalysisEventListener> { - List> list = new ArrayList>(); - private List> headList = new ArrayList<>(); - private Map headTitleMap = new HashMap<>(); - private int headSize; - - public MaxHeadReadListener(int headSize) { - this.headSize = headSize; - } + private Map headTitleMap; @Override public void invoke(Map data, AnalysisContext context) { - list.add(data); + // Data validation stays in the test; this listener only captures head metadata. } @Override @@ -55,6 +45,5 @@ public void doAfterAllAnalysed(AnalysisContext context) { @Override public void invokeHeadMap(Map headMap, AnalysisContext context) { headTitleMap = headMap; - headList.add(headMap); } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/MaxHeadSizeTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/MaxHeadSizeTest.java index f893286fd..971b49e33 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/MaxHeadSizeTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/MaxHeadSizeTest.java @@ -27,50 +27,38 @@ import lombok.extern.slf4j.Slf4j; import org.apache.fesod.sheet.FesodSheet; import org.apache.fesod.sheet.support.ExcelTypeEnum; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; import org.apache.fesod.sheet.util.TestFileUtil; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; -@TestMethodOrder(MethodOrderer.MethodName.class) @Slf4j -public class MaxHeadSizeTest { - - private static String headFile01; - private static String headFile02; - private static String headFile03; - - @BeforeAll - public static void init() { - headFile01 = TestFileUtil.getPath() + "temp/issue220" + File.separator + "test01.xlsx"; - headFile02 = TestFileUtil.getPath() + "temp/issue220" + File.separator + "test02.xlsx"; - headFile03 = TestFileUtil.getPath() + "temp/issue220" + File.separator + "test03.xlsx"; - } +public class MaxHeadSizeTest extends AbstractExcelTest { @Test - public void t01ReadTest() throws Exception { - // issue example + public void readIssueExample() { + File headFile01 = headFile("test01.xlsx"); readFileWithMap(headFile01, 6); readFileWithPOJO(headFile01); } @Test - public void t02ReadTest() throws Exception { - // 表头有空列 + public void readWithEmptyHeadColumns() { + File headFile02 = headFile("test02.xlsx"); + // The header row contains empty columns. readFileWithMap(headFile02, 8); readFileWithPOJO(headFile02); } @Test - public void t03ReadTest() throws Exception { - // 表头列数比实际数据行的列少 + public void readWithFewerHeadColumns() { + File headFile03 = headFile("test03.xlsx"); + // The header row has fewer columns than the actual data rows. readFileWithMap(headFile03, 4); readFileWithPOJO(headFile03); } - private void readFileWithMap(String file, int expectHeadSize) { + private void readFileWithMap(File file, int expectHeadSize) { List> dataList; // default dataList = FesodSheet.read(file).excelType(ExcelTypeEnum.XLSX).sheet().doReadSync(); @@ -80,7 +68,7 @@ private void readFileWithMap(String file, int expectHeadSize) { }); // custom listener - dataList = FesodSheet.read(file, new MaxHeadReadListener(expectHeadSize)) + dataList = FesodSheet.read(file, new MaxHeadReadListener()) .excelType(ExcelTypeEnum.XLSX) .sheet() .doReadSync(); @@ -90,7 +78,7 @@ private void readFileWithMap(String file, int expectHeadSize) { }); } - private void readFileWithPOJO(String file) { + private void readFileWithPOJO(File file) { List dataList = FesodSheet.read(file) .head(MaxHeadSizeData.class) .excelType(ExcelTypeEnum.XLSX) @@ -100,4 +88,8 @@ private void readFileWithPOJO(String file) { log.info(JSON.toJSONString(d, JSONWriter.Feature.WriteMapNullValue)); }); } + + private File headFile(String fileName) { + return TestFileUtil.readFile("temp/issue220" + File.separator + fileName); + } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/NoHeadData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/NoHeadData.java index d06fe777d..96a587822 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/NoHeadData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/NoHeadData.java @@ -37,6 +37,6 @@ @Setter @EqualsAndHashCode public class NoHeadData { - @ExcelProperty("字符串") + @ExcelProperty("String") private String string; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/NoHeadDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/NoHeadDataTest.java index 2f93dcbb0..f3e27cff8 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/NoHeadDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/NoHeadDataTest.java @@ -25,61 +25,32 @@ package org.apache.fesod.sheet.head; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; -import java.util.ArrayList; import java.util.List; import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** - * + * Test no-head write/read for all Excel formats using parameterized tests. */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class NoHeadDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("noHead07.xlsx"); - file03 = TestFileUtil.createNewFile("noHead03.xls"); - fileCsv = TestFileUtil.createNewFile("noHeadCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() { - readAndWrite(fileCsv); - } - - private void readAndWrite(File file) { - FesodSheet.write(file, NoHeadData.class).needHead(Boolean.FALSE).sheet().doWrite(data()); - FesodSheet.read(file, NoHeadData.class, new NoHeadDataListener()) +public class NoHeadDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile("noHead", format); + FesodSheet.write(file, NoHeadData.class).needHead(Boolean.FALSE).sheet().doWrite(TestDataBuilder.noHeadData(1)); + List result = FesodSheet.read(file) + .head(NoHeadData.class) .headRowNumber(0) .sheet() - .doRead(); - } - - private List data() { - List list = new ArrayList(); - NoHeadData data = new NoHeadData(); - data.setString("字符串0"); - list.add(data); - return list; + .doReadSync(); + assertEquals(1, result.size()); + assertEquals("String0", result.get(0).getString()); } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/hiddensheets/HiddenSheetsListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/hiddensheets/HiddenSheetsListener.java deleted file mode 100644 index d942cbb04..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/hiddensheets/HiddenSheetsListener.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.fesod.sheet.hiddensheets; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -@Slf4j -public class HiddenSheetsListener extends AnalysisEventListener { - List list = new ArrayList<>(); - - @Override - public void invoke(HiddenSheetsData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - log.info("A form is read finished."); - Assertions.assertEquals("data01", list.get(0).getTitle()); - log.info("All row:{}", JSON.toJSONString(list)); - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/hiddensheets/HiddenSheetsTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/hiddensheets/HiddenSheetsTest.java deleted file mode 100644 index cedcb94ef..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/hiddensheets/HiddenSheetsTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.fesod.sheet.hiddensheets; - -import java.io.File; -import java.util.List; -import org.apache.fesod.sheet.ExcelReader; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.read.metadata.ReadSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -@TestMethodOrder(MethodOrderer.MethodName.class) -public class HiddenSheetsTest { - - private static File file07; - private static File file03; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.readFile("hiddensheets" + File.separator + "hiddensheets.xlsx"); - file03 = TestFileUtil.readFile("hiddensheets" + File.separator + "hiddensheets.xls"); - } - - @Test - public void t01Read07() { - read(file07, null); - read(file07, Boolean.FALSE); - read(file07, Boolean.TRUE); - } - - @Test - public void t02Read03() { - read(file03, null); - read(file03, Boolean.FALSE); - read(file03, Boolean.TRUE); - } - - @Test - public void t03Read07All() { - readAll(file07, null); - readAll(file07, Boolean.FALSE); - readAll(file07, Boolean.TRUE); - } - - @Test - public void t04Read03All() { - readAll(file03, null); - readAll(file03, Boolean.FALSE); - readAll(file03, Boolean.TRUE); - } - - @Test - public void t05ReadHiddenList() { - readHiddenList(file03); - readHiddenList(file07); - } - - private void readHiddenList(File file) { - try (ExcelReader excelReader = FesodSheet.read(file, HiddenSheetsData.class, new HiddenSheetsListener()) - .build()) { - List allSheetList = excelReader.excelExecutor().sheetList(); - Assertions.assertEquals( - 2, allSheetList.stream().filter(ReadSheet::isHidden).count()); - Assertions.assertEquals( - 1, allSheetList.stream().filter(ReadSheet::isVeryHidden).count()); - Assertions.assertEquals( - "Sheet5", - allSheetList.stream() - .filter(ReadSheet::isVeryHidden) - .findFirst() - .get() - .getSheetName()); - } - } - - private void read(File file, Boolean ignoreHidden) { - try (ExcelReader excelReader = FesodSheet.read(file, HiddenSheetsData.class, new HiddenSheetsListener()) - .ignoreHiddenSheet(ignoreHidden) - .build()) { - List sheets = excelReader.excelExecutor().sheetList(); - if (Boolean.TRUE.equals(ignoreHidden)) { - Assertions.assertEquals(3, sheets.size()); - } else { - Assertions.assertEquals(6, sheets.size()); - } - } - } - - private void readAll(File file, Boolean ignoreHidden) { - List dataList = FesodSheet.read(file, HiddenSheetsData.class, new HiddenSheetsListener()) - .ignoreHiddenSheet(ignoreHidden) - .doReadAllSync(); - if (Boolean.TRUE.equals(ignoreHidden)) { - Assertions.assertEquals(3, dataList.size()); - } else { - Assertions.assertEquals(6, dataList.size()); - } - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/multiplesheets/MultipleSheetsListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/multiplesheets/MultipleSheetsListener.java deleted file mode 100644 index 93ab408c9..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/multiplesheets/MultipleSheetsListener.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.multiplesheets; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class MultipleSheetsListener extends AnalysisEventListener { - - List list = new ArrayList(); - - @Override - public void invoke(MultipleSheetsData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - log.debug("A form is read finished."); - Assertions.assertEquals("表1数据", list.get(0).getTitle()); - log.debug("All row:{}", JSON.toJSONString(list)); - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/nomodel/NoModelDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/nomodel/NoModelDataTest.java deleted file mode 100644 index f0d6f9c60..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/nomodel/NoModelDataTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.nomodel; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.enums.ReadDefaultReturnEnum; -import org.apache.fesod.sheet.metadata.data.ReadCellData; -import org.apache.fesod.sheet.util.DateUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -@Slf4j -public class NoModelDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - private static File fileRepeat07; - private static File fileRepeat03; - private static File fileRepeatCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("noModel07.xlsx"); - file03 = TestFileUtil.createNewFile("noModel03.xls"); - fileCsv = TestFileUtil.createNewFile("noModelCsv.csv"); - fileRepeat07 = TestFileUtil.createNewFile("noModelRepeat07.xlsx"); - fileRepeat03 = TestFileUtil.createNewFile("noModelRepeat03.xls"); - fileRepeatCsv = TestFileUtil.createNewFile("noModelRepeatCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() throws Exception { - readAndWrite(file07, fileRepeat07, false); - } - - @Test - public void t02ReadAndWrite03() throws Exception { - readAndWrite(file03, fileRepeat03, false); - } - - @Test - public void t03ReadAndWriteCsv() throws Exception { - readAndWrite(fileCsv, fileRepeatCsv, true); - } - - private void readAndWrite(File file, File fileRepeat, boolean isCsv) throws Exception { - FesodSheet.write(file).sheet().doWrite(data()); - List> result = - FesodSheet.read(file).headRowNumber(0).sheet().doReadSync(); - Assertions.assertEquals(10, result.size()); - Map data10 = result.get(9); - Assertions.assertEquals("string19", data10.get(0)); - Assertions.assertEquals("109", data10.get(1)); - Assertions.assertEquals("2020-01-01 01:01:01", data10.get(2)); - - List> actualDataList = FesodSheet.read(file) - .headRowNumber(0) - .readDefaultReturn(ReadDefaultReturnEnum.ACTUAL_DATA) - .sheet() - .doReadSync(); - log.info("actualDataList:{}", JSON.toJSONString(actualDataList)); - Assertions.assertEquals(10, actualDataList.size()); - Map actualData10 = actualDataList.get(9); - Assertions.assertEquals("string19", actualData10.get(0)); - if (isCsv) { - // CSV only string type - Assertions.assertEquals("109", actualData10.get(1)); - Assertions.assertEquals("2020-01-01 01:01:01", actualData10.get(2)); - } else { - Assertions.assertEquals(0, new BigDecimal("109").compareTo((BigDecimal) actualData10.get(1))); - Assertions.assertEquals(LocalDateTime.of(2020, 1, 1, 1, 1, 1), actualData10.get(2)); - } - - List>> readCellDataList = FesodSheet.read(file) - .headRowNumber(0) - .readDefaultReturn(ReadDefaultReturnEnum.READ_CELL_DATA) - .sheet() - .doReadSync(); - log.info("readCellDataList:{}", JSON.toJSONString(readCellDataList)); - Assertions.assertEquals(10, readCellDataList.size()); - Map> readCellData10 = readCellDataList.get(9); - Assertions.assertEquals("string19", readCellData10.get(0).getData()); - if (isCsv) { - // CSV only string type - Assertions.assertEquals("109", readCellData10.get(1).getData()); - Assertions.assertEquals("2020-01-01 01:01:01", readCellData10.get(2).getData()); - } else { - Assertions.assertEquals(0, new BigDecimal("109").compareTo((BigDecimal) - readCellData10.get(1).getData())); - Assertions.assertEquals( - LocalDateTime.of(2020, 1, 1, 1, 1, 1), readCellData10.get(2).getData()); - } - - FesodSheet.write(fileRepeat).sheet().doWrite(result); - result = FesodSheet.read(fileRepeat).headRowNumber(0).sheet().doReadSync(); - Assertions.assertEquals(10, result.size()); - data10 = result.get(9); - Assertions.assertEquals("string19", data10.get(0)); - Assertions.assertEquals("109", data10.get(1)); - Assertions.assertEquals("2020-01-01 01:01:01", data10.get(2)); - } - - private List> data() throws Exception { - List> list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - List data = new ArrayList<>(); - data.add("string1" + i); - data.add(100 + i); - data.add(DateUtils.parseDate("2020-01-01 01:01:01")); - list.add(data); - } - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/noncamel/UnCamelDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/noncamel/UnCamelDataListener.java deleted file mode 100644 index f51fc4255..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/noncamel/UnCamelDataListener.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.noncamel; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class UnCamelDataListener extends AnalysisEventListener { - List list = new ArrayList<>(); - - @Override - public void invokeHeadMap(Map headMap, AnalysisContext context) { - log.debug("Head is:{}", JSON.toJSONString(headMap)); - Assertions.assertEquals("string1", headMap.get(0)); - Assertions.assertEquals("string2", headMap.get(1)); - Assertions.assertEquals("STring3", headMap.get(2)); - Assertions.assertEquals("STring4", headMap.get(3)); - Assertions.assertEquals("STRING5", headMap.get(4)); - Assertions.assertEquals("STRing6", headMap.get(5)); - } - - @Override - public void invoke(UnCamelData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(10, list.size()); - UnCamelData unCamelData = list.get(0); - Assertions.assertEquals("string1", unCamelData.getString1()); - Assertions.assertEquals("string2", unCamelData.getString2()); - Assertions.assertEquals("string3", unCamelData.getSTring3()); - Assertions.assertEquals("string4", unCamelData.getSTring4()); - Assertions.assertEquals("string5", unCamelData.getSTRING5()); - Assertions.assertEquals("string6", unCamelData.getSTRing6()); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/noncamel/UnCamelDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/noncamel/UnCamelDataTest.java deleted file mode 100644 index d2e479c6d..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/noncamel/UnCamelDataTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.noncamel; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class UnCamelDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("unCame07.xlsx"); - file03 = TestFileUtil.createNewFile("unCame03.xls"); - fileCsv = TestFileUtil.createNewFile("unCameCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() { - readAndWrite(fileCsv); - } - - private void readAndWrite(File file) { - FesodSheet.write(file, UnCamelData.class).sheet().doWrite(data()); - FesodSheet.read(file, UnCamelData.class, new UnCamelDataListener()) - .sheet() - .doRead(); - } - - private List data() { - List list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - UnCamelData unCamelData = new UnCamelData(); - unCamelData.setString1("string1"); - unCamelData.setString2("string2"); - unCamelData.setSTring3("string3"); - unCamelData.setSTring4("string4"); - unCamelData.setSTRING5("string5"); - unCamelData.setSTRing6("string6"); - list.add(unCamelData); - } - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/AutoStripParameterTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/AutoStripParameterTest.java deleted file mode 100644 index 307cdd779..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/AutoStripParameterTest.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.fesod.sheet.parameter; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.common.util.StringUtils; -import org.apache.fesod.sheet.ExcelReader; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.read.metadata.ReadSheet; -import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.apache.fesod.sheet.util.ParameterUtil; -import org.apache.fesod.sheet.util.SheetUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -@Slf4j -public class AutoStripParameterTest { - - private static File testFile; - private static final String FW_SPACES = " "; - private static final String SPACES = " "; - - @Test - public void test03() { - testAutoStripSheetNameInternal(ExcelTypeEnum.XLS, null, null); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLS, null, false); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLS, null, true); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLS, false, null); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLS, false, false); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLS, false, true); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLS, true, null); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLS, true, false); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLS, true, true); - - testAutoStripContentInternal(ExcelTypeEnum.XLS, null, null); - testAutoStripContentInternal(ExcelTypeEnum.XLS, null, false); - testAutoStripContentInternal(ExcelTypeEnum.XLS, null, true); - testAutoStripContentInternal(ExcelTypeEnum.XLS, false, null); - testAutoStripContentInternal(ExcelTypeEnum.XLS, false, false); - testAutoStripContentInternal(ExcelTypeEnum.XLS, false, true); - testAutoStripContentInternal(ExcelTypeEnum.XLS, true, null); - testAutoStripContentInternal(ExcelTypeEnum.XLS, true, false); - testAutoStripContentInternal(ExcelTypeEnum.XLS, true, true); - } - - @Test - public void test07() { - testAutoStripSheetNameInternal(ExcelTypeEnum.XLSX, null, null); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLSX, null, false); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLSX, null, true); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLSX, false, null); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLSX, false, false); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLSX, false, true); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLSX, true, null); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLSX, true, false); - testAutoStripSheetNameInternal(ExcelTypeEnum.XLSX, true, true); - - testAutoStripContentInternal(ExcelTypeEnum.XLSX, null, null); - testAutoStripContentInternal(ExcelTypeEnum.XLSX, null, false); - testAutoStripContentInternal(ExcelTypeEnum.XLSX, null, true); - testAutoStripContentInternal(ExcelTypeEnum.XLSX, false, null); - testAutoStripContentInternal(ExcelTypeEnum.XLSX, false, false); - testAutoStripContentInternal(ExcelTypeEnum.XLSX, false, true); - testAutoStripContentInternal(ExcelTypeEnum.XLSX, true, null); - testAutoStripContentInternal(ExcelTypeEnum.XLSX, true, false); - testAutoStripContentInternal(ExcelTypeEnum.XLSX, true, true); - } - - @Test - public void testCSV() { - testAutoStripContentInternal(ExcelTypeEnum.CSV, null, null); - testAutoStripContentInternal(ExcelTypeEnum.CSV, null, false); - testAutoStripContentInternal(ExcelTypeEnum.CSV, null, true); - testAutoStripContentInternal(ExcelTypeEnum.CSV, false, null); - testAutoStripContentInternal(ExcelTypeEnum.CSV, false, false); - testAutoStripContentInternal(ExcelTypeEnum.CSV, false, true); - testAutoStripContentInternal(ExcelTypeEnum.CSV, true, null); - testAutoStripContentInternal(ExcelTypeEnum.CSV, true, false); - testAutoStripContentInternal(ExcelTypeEnum.CSV, true, true); - } - - private void testAutoStripSheetNameInternal( - final ExcelTypeEnum excelType, final Boolean autoTrim, final Boolean autoStrip) { - testFile = TestFileUtil.createNewFile("auto-strip-sheet-name" + excelType.getValue()); - - final String sheetNameSpaces = SPACES + "Sheet1" + SPACES; - final String sheetNameFullWidthSpaces = FW_SPACES + "Sheet2" + FW_SPACES; - - List demoList = new ArrayList<>(); - ParameterData simpleData = new ParameterData(); - simpleData.setName("string"); - demoList.add(simpleData); - - try (ExcelWriter excelWriter = FesodSheet.write(testFile, ParameterData.class) - .excelType(excelType) - .autoTrim(autoTrim) - .autoStrip(autoStrip) - .build()) { - WriteSheet writeSheet = FesodSheet.writerSheet(sheetNameSpaces).build(); - excelWriter.write(demoList, writeSheet); - writeSheet = FesodSheet.writerSheet(sheetNameFullWidthSpaces).build(); - excelWriter.write(demoList, writeSheet); - } - - try (ExcelReader excelReader = FesodSheet.read(testFile) - .excelType(excelType) - .head(ParameterData.class) - .registerReadListenerIfNotNull(new AnalysisEventListener() { - @Override - public void invoke(ParameterData data, AnalysisContext context) { - log.info("Read one record: {}", JSON.toJSONString(data)); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - // global configuration match - Assertions.assertEquals( - autoTrim == null ? Boolean.TRUE : autoTrim, - ParameterUtil.getAutoTrimFlag( - context.readSheetHolder().getReadSheet(), context)); - Assertions.assertEquals( - autoStrip == null ? Boolean.FALSE : autoStrip, - ParameterUtil.getAutoStripFlag( - context.readSheetHolder().getReadSheet(), context)); - - // sheet name match - ReadSheet readSheet = context.readSheetHolder().getReadSheet(); - Assertions.assertEquals(readSheet, SheetUtils.match(readSheet, context)); - } - }) - .autoTrim(autoTrim) - .autoStrip(autoStrip) - .build()) { - - // set sheet name - excelReader.read( - FesodSheet.readSheet(sheetNameSpaces).build(), - FesodSheet.readSheet(sheetNameFullWidthSpaces).build()); - } - } - - private void testAutoStripContentInternal( - final ExcelTypeEnum excelType, final Boolean autoTrim, final Boolean autoStrip) { - testFile = TestFileUtil.createNewFile("auto-strip-content" + excelType.getValue()); - - final String testContentSpaces = SPACES + "String Data1" + SPACES; - final String testContentFullWidthSpaces = FW_SPACES + "String Data2" + FW_SPACES; - - List demoList = new ArrayList<>(); - ParameterData simpleData = new ParameterData(); - // normal spaces - simpleData.setName(testContentSpaces); - demoList.add(simpleData); - - simpleData = new ParameterData(); - // full-width spaces - simpleData.setName(testContentFullWidthSpaces); - demoList.add(simpleData); - - FesodSheet.write(testFile, ParameterData.class) - .excelType(excelType) - .autoTrim(autoTrim) - .autoStrip(autoStrip) - .sheet() - .doWrite(demoList); - - List dataList = FesodSheet.read(testFile) - .excelType(excelType) - .head(ParameterData.class) - .autoTrim(autoTrim) - .autoStrip(autoStrip) - .sheet() - .doReadSync(); - - log.info("Read records: {}", JSON.toJSONString(dataList)); - Assertions.assertEquals(2, dataList.size()); - if (Boolean.TRUE.equals(autoStrip)) { - Assertions.assertEquals( - StringUtils.strip(testContentSpaces), dataList.get(0).getName()); - Assertions.assertEquals( - StringUtils.strip(testContentFullWidthSpaces), - dataList.get(1).getName()); - } else if (autoTrim == null || autoTrim) { - Assertions.assertEquals(testContentSpaces.trim(), dataList.get(0).getName()); - Assertions.assertEquals( - testContentFullWidthSpaces.trim(), dataList.get(1).getName()); - } else { - Assertions.assertEquals(testContentSpaces, dataList.get(0).getName()); - Assertions.assertEquals(testContentFullWidthSpaces, dataList.get(1).getName()); - } - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/DateWindowingListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/DateWindowingListener.java deleted file mode 100644 index 3d9dbb2f3..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/DateWindowingListener.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.fesod.sheet.parameter; - -import com.alibaba.fastjson2.JSON; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -@Slf4j -public class DateWindowingListener extends AnalysisEventListener { - - private Boolean expectFlag = Boolean.FALSE; - - private DateWindowingListener() {} - - public DateWindowingListener(Boolean expectFlag) { - this.expectFlag = expectFlag == null ? Boolean.FALSE : expectFlag; - } - - @Override - public void invoke(ParameterData data, AnalysisContext context) { - log.info("row data:{}", JSON.toJSONString(data)); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - boolean isUse1904windowing = - context.readWorkbookHolder().globalConfiguration().getUse1904windowing(); - log.info( - "excel type:{},isUse1904windowing: {}", - context.readWorkbookHolder().getExcelType(), - isUse1904windowing); - Assertions.assertEquals(isUse1904windowing, this.expectFlag); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/DateWindowingTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/DateWindowingTest.java deleted file mode 100644 index 6d790bb9a..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/DateWindowingTest.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.fesod.sheet.parameter; - -import java.io.File; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.exception.ExcelAnalysisException; -import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -@TestMethodOrder(MethodOrderer.MethodName.class) -public class DateWindowingTest { - - private static File file03DateWindowing1900; - private static File file03DateWindowing1900Exists; - private static File file03DateWindowing1904; - private static File file03DateWindowing1904Exists; - private static File file07DateWindowing1900; - private static File file07DateWindowing1904; - private static File fileCsvDateWindowing1900; - private static File fileCsvDateWindowing1904; - - @BeforeAll - public static void init() { - file03DateWindowing1900 = TestFileUtil.createNewFile("datewindowing1900.xls"); - file03DateWindowing1900Exists = TestFileUtil.readFile("datewindowing/1900DateWindowing.xls"); - file03DateWindowing1904 = TestFileUtil.createNewFile("datewindowing1904.xls"); - file03DateWindowing1904Exists = TestFileUtil.readFile("datewindowing/1904DateWindowing.xls"); - file07DateWindowing1900 = TestFileUtil.createNewFile("datewindowing1900.xlsx"); - file07DateWindowing1904 = TestFileUtil.createNewFile("datewindowing1904.xlsx"); - fileCsvDateWindowing1900 = TestFileUtil.createNewFile("datewindowing1900.csv"); - fileCsvDateWindowing1904 = TestFileUtil.createNewFile("datewindowing1904.csv"); - } - - @Test - void test03WriteAndRead() { - // writing a file - FesodSheet.write(file03DateWindowing1900, ParameterData.class) - .excelType(ExcelTypeEnum.XLS) - .use1904windowing(Boolean.FALSE) - .sheet() - .doWrite(data()); - - // not support setting actual file to true. - FesodSheet.write(file03DateWindowing1904, ParameterData.class) - .excelType(ExcelTypeEnum.XLS) - .use1904windowing(Boolean.TRUE) - .sheet() - .doWrite(data()); - - // reading a file - Assertions.assertThrows(ExcelAnalysisException.class, () -> { - FesodSheet.read(file03DateWindowing1904, new DateWindowingListener(Boolean.TRUE)) - .excelType(ExcelTypeEnum.XLS) - .head(ParameterData.class) - .doReadAllSync(); - }); - FesodSheet.read(file03DateWindowing1900, new DateWindowingListener(Boolean.FALSE)) - .excelType(ExcelTypeEnum.XLS) - .use1904windowing(Boolean.FALSE) - .head(ParameterData.class) - .doReadAllSync(); - FesodSheet.read(file03DateWindowing1904, new DateWindowingListener(Boolean.TRUE)) - .excelType(ExcelTypeEnum.XLS) - .use1904windowing(Boolean.TRUE) - .head(ParameterData.class) - .doReadAllSync(); - FesodSheet.read(file03DateWindowing1900Exists, new DateWindowingListener(Boolean.FALSE)) - .excelType(ExcelTypeEnum.XLS) - .head(ParameterData.class) - .doReadAllSync(); - FesodSheet.read(file03DateWindowing1904Exists, new DateWindowingListener(Boolean.TRUE)) - .excelType(ExcelTypeEnum.XLS) - .head(ParameterData.class) - .doReadAllSync(); - } - - @Test - void test07WriteAndRead() { - // writing a file - FesodSheet.write(file07DateWindowing1900, ParameterData.class) - .excelType(ExcelTypeEnum.XLSX) - .use1904windowing(Boolean.FALSE) - .sheet() - .doWrite(data()); - FesodSheet.write(file07DateWindowing1904, ParameterData.class) - .excelType(ExcelTypeEnum.XLSX) - .use1904windowing(Boolean.TRUE) - .sheet() - .doWrite(data()); - - // reading a file - FesodSheet.read(file07DateWindowing1900, new DateWindowingListener(Boolean.FALSE)) - .excelType(ExcelTypeEnum.XLSX) - .head(ParameterData.class) - .doReadAllSync(); - FesodSheet.read(file07DateWindowing1904, new DateWindowingListener(Boolean.TRUE)) - .excelType(ExcelTypeEnum.XLSX) - .head(ParameterData.class) - .doReadAllSync(); - } - - @Test - void testCsvWriteAndRead() { - // writing a file - FesodSheet.write(fileCsvDateWindowing1900, ParameterData.class) - .excelType(ExcelTypeEnum.CSV) - .use1904windowing(Boolean.FALSE) - .sheet() - .doWrite(data()); - FesodSheet.write(fileCsvDateWindowing1904, ParameterData.class) - .excelType(ExcelTypeEnum.CSV) - .use1904windowing(Boolean.TRUE) - .sheet() - .doWrite(data()); - - // reading a file - FesodSheet.read(fileCsvDateWindowing1900, new DateWindowingListener(Boolean.FALSE)) - .excelType(ExcelTypeEnum.CSV) - .use1904windowing(Boolean.FALSE) - .head(ParameterData.class) - .doReadAllSync(); - Assertions.assertThrows(ExcelAnalysisException.class, () -> { - FesodSheet.read(fileCsvDateWindowing1904, new DateWindowingListener(Boolean.TRUE)) - .excelType(ExcelTypeEnum.CSV) - .head(ParameterData.class) - .doReadAllSync(); - }); - FesodSheet.read(fileCsvDateWindowing1904, new DateWindowingListener(Boolean.TRUE)) - .excelType(ExcelTypeEnum.CSV) - .use1904windowing(Boolean.TRUE) - .head(ParameterData.class) - .doReadAllSync(); - FesodSheet.read(fileCsvDateWindowing1904, new DateWindowingListener(Boolean.FALSE)) - .excelType(ExcelTypeEnum.CSV) - .head(ParameterData.class) - .doReadAllSync(); - } - - private List data() { - List list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - ParameterData simpleData = new ParameterData(); - simpleData.setName("姓名" + i); - simpleData.setDate(new Date()); - list.add(simpleData); - } - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/ParameterData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/ParameterData.java deleted file mode 100644 index 8807a5a2c..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/ParameterData.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.parameter; - -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -@Getter -@Setter -@EqualsAndHashCode -public class ParameterData { - @ExcelProperty("姓名") - private String name; - - @ExcelProperty("日期") - private Date date; -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/ParameterDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/ParameterDataListener.java deleted file mode 100644 index f923c08eb..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/ParameterDataListener.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.parameter; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class ParameterDataListener extends AnalysisEventListener { - - List list = new ArrayList(); - - @Override - public void invoke(ParameterData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(10, list.size()); - Assertions.assertEquals("姓名0", list.get(0).getName()); - Assertions.assertEquals(0, (int) (context.readSheetHolder().getSheetNo())); - Assertions.assertEquals( - "姓名", - context.readSheetHolder() - .getExcelReadHeadProperty() - .getHeadMap() - .get(0) - .getHeadNameList() - .get(0)); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/AutoStripParameterTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/AutoStripParameterTest.java new file mode 100644 index 000000000..0863967f2 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/AutoStripParameterTest.java @@ -0,0 +1,189 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.readwrite; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import com.alibaba.fastjson2.JSON; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.common.util.StringUtils; +import org.apache.fesod.sheet.ExcelReader; +import org.apache.fesod.sheet.ExcelWriter; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.context.AnalysisContext; +import org.apache.fesod.sheet.event.AnalysisEventListener; +import org.apache.fesod.sheet.read.metadata.ReadSheet; +import org.apache.fesod.sheet.support.ExcelTypeEnum; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.apache.fesod.sheet.util.ParameterUtil; +import org.apache.fesod.sheet.util.SheetUtils; +import org.apache.fesod.sheet.write.metadata.WriteSheet; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@Slf4j +public class AutoStripParameterTest extends AbstractExcelTest { + + private static final String FW_SPACES = " "; + private static final String SPACES = " "; + + @ParameterizedTest + @MethodSource("binaryFormats") + void testAutoStripSheetName(ExcelFormat format) { + ExcelTypeEnum excelType = format.toExcelTypeEnum(); + testAutoStripSheetNameInternal(excelType, null, null); + testAutoStripSheetNameInternal(excelType, null, false); + testAutoStripSheetNameInternal(excelType, null, true); + testAutoStripSheetNameInternal(excelType, false, null); + testAutoStripSheetNameInternal(excelType, false, false); + testAutoStripSheetNameInternal(excelType, false, true); + testAutoStripSheetNameInternal(excelType, true, null); + testAutoStripSheetNameInternal(excelType, true, false); + testAutoStripSheetNameInternal(excelType, true, true); + } + + @ParameterizedTest + @MethodSource("allFormats") + void testAutoStripContent(ExcelFormat format) { + ExcelTypeEnum excelType = format.toExcelTypeEnum(); + testAutoStripContentInternal(excelType, null, null); + testAutoStripContentInternal(excelType, null, false); + testAutoStripContentInternal(excelType, null, true); + testAutoStripContentInternal(excelType, false, null); + testAutoStripContentInternal(excelType, false, false); + testAutoStripContentInternal(excelType, false, true); + testAutoStripContentInternal(excelType, true, null); + testAutoStripContentInternal(excelType, true, false); + testAutoStripContentInternal(excelType, true, true); + } + + private void testAutoStripSheetNameInternal( + final ExcelTypeEnum excelType, final Boolean autoTrim, final Boolean autoStrip) { + File testFile = new File(tempDir, "auto-strip-sheet-name" + excelType.getValue()); + + final String sheetNameSpaces = SPACES + "Sheet1" + SPACES; + final String sheetNameFullWidthSpaces = FW_SPACES + "Sheet2" + FW_SPACES; + + List demoList = new ArrayList<>(); + SimpleData simpleData = new SimpleData(); + simpleData.setName("string"); + demoList.add(simpleData); + + try (ExcelWriter excelWriter = FesodSheet.write(testFile, SimpleData.class) + .excelType(excelType) + .autoTrim(autoTrim) + .autoStrip(autoStrip) + .build()) { + WriteSheet writeSheet = FesodSheet.writerSheet(sheetNameSpaces).build(); + excelWriter.write(demoList, writeSheet); + writeSheet = FesodSheet.writerSheet(sheetNameFullWidthSpaces).build(); + excelWriter.write(demoList, writeSheet); + } + + try (ExcelReader excelReader = FesodSheet.read(testFile) + .excelType(excelType) + .head(SimpleData.class) + .registerReadListenerIfNotNull(new AnalysisEventListener() { + @Override + public void invoke(SimpleData data, AnalysisContext context) { + log.info("Read one record: {}", JSON.toJSONString(data)); + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + // global configuration match + assertEquals( + autoTrim == null ? Boolean.TRUE : autoTrim, + ParameterUtil.getAutoTrimFlag( + context.readSheetHolder().getReadSheet(), context)); + assertEquals( + autoStrip == null ? Boolean.FALSE : autoStrip, + ParameterUtil.getAutoStripFlag( + context.readSheetHolder().getReadSheet(), context)); + + // sheet name match + ReadSheet readSheet = context.readSheetHolder().getReadSheet(); + assertEquals(readSheet, SheetUtils.match(readSheet, context)); + } + }) + .autoTrim(autoTrim) + .autoStrip(autoStrip) + .build()) { + + // set sheet name + excelReader.read( + FesodSheet.readSheet(sheetNameSpaces).build(), + FesodSheet.readSheet(sheetNameFullWidthSpaces).build()); + } + } + + private void testAutoStripContentInternal( + final ExcelTypeEnum excelType, final Boolean autoTrim, final Boolean autoStrip) { + File testFile = new File(tempDir, "auto-strip-content" + excelType.getValue()); + + final String testContentSpaces = SPACES + "String Data1" + SPACES; + final String testContentFullWidthSpaces = FW_SPACES + "String Data2" + FW_SPACES; + + List demoList = new ArrayList<>(); + SimpleData simpleData = new SimpleData(); + // normal spaces + simpleData.setName(testContentSpaces); + demoList.add(simpleData); + + simpleData = new SimpleData(); + // full-width spaces + simpleData.setName(testContentFullWidthSpaces); + demoList.add(simpleData); + + FesodSheet.write(testFile, SimpleData.class) + .excelType(excelType) + .autoTrim(autoTrim) + .autoStrip(autoStrip) + .sheet() + .doWrite(demoList); + + List dataList = FesodSheet.read(testFile) + .excelType(excelType) + .head(SimpleData.class) + .autoTrim(autoTrim) + .autoStrip(autoStrip) + .sheet() + .doReadSync(); + + log.info("Read records: {}", JSON.toJSONString(dataList)); + assertEquals(2, dataList.size()); + if (Boolean.TRUE.equals(autoStrip)) { + assertEquals(StringUtils.strip(testContentSpaces), dataList.get(0).getName()); + assertEquals( + StringUtils.strip(testContentFullWidthSpaces), + dataList.get(1).getName()); + } else if (autoTrim == null || autoTrim) { + assertEquals(testContentSpaces.trim(), dataList.get(0).getName()); + assertEquals(testContentFullWidthSpaces.trim(), dataList.get(1).getName()); + } else { + assertEquals(testContentSpaces, dataList.get(0).getName()); + assertEquals(testContentFullWidthSpaces, dataList.get(1).getName()); + } + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/CacheData.java similarity index 92% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/CacheData.java index a1fa2ed94..284ff08e8 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/cache/CacheData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/CacheData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.cache; +package org.apache.fesod.sheet.readwrite; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -37,9 +37,9 @@ @Setter @EqualsAndHashCode public class CacheData { - @ExcelProperty("姓名") + @ExcelProperty("Name") private String name; - @ExcelProperty("年龄") + @ExcelProperty("Age") private Long age; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/CacheDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/CacheDataTest.java new file mode 100644 index 000000000..d019573ee --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/CacheDataTest.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.readwrite; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.util.Map; +import lombok.Getter; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.annotation.ExcelProperty; +import org.apache.fesod.sheet.context.AnalysisContext; +import org.apache.fesod.sheet.enums.CacheLocationEnum; +import org.apache.fesod.sheet.event.AnalysisEventListener; +import org.apache.fesod.sheet.metadata.FieldCache; +import org.apache.fesod.sheet.read.listener.PageReadListener; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.util.ClassUtils; +import org.apache.fesod.sheet.util.FieldUtils; +import org.junit.jupiter.api.Test; + +/** + * + */ +public class CacheDataTest extends AbstractExcelTest { + + @Test + void clearsThreadLocalFieldCacheAfterRead() throws Exception { + File file07 = createTempFile("cache", ExcelFormat.XLSX); + Field field = FieldUtils.getField(ClassUtils.class, "FIELD_THREAD_LOCAL", true); + ThreadLocal, FieldCache>> fieldThreadLocal = + (ThreadLocal, FieldCache>>) field.get(ClassUtils.class.newInstance()); + assertNull(fieldThreadLocal.get()); + FesodSheet.write(file07, CacheData.class).sheet().doWrite(TestDataBuilder.cacheData(10)); + FesodSheet.read(file07, CacheData.class, new PageReadListener(dataList -> { + assertNotNull(fieldThreadLocal.get()); + })) + .sheet() + .doRead(); + assertNull(fieldThreadLocal.get()); + } + + @Test + void usesUpdatedHeaderWithInvocationCache() throws Exception { + setNameHeader("Name"); + File fileCacheInvoke = createTempFile("fileCacheInvoke", ExcelFormat.XLSX); + File fileCacheInvoke2 = createTempFile("fileCacheInvoke2", ExcelFormat.XLSX); + FesodSheet.write(fileCacheInvoke, CacheData.class).sheet().doWrite(TestDataBuilder.cacheData(10)); + assertHeadMap(fileCacheInvoke, "Name", null); + + setNameHeader("Name2"); + + FesodSheet.write(fileCacheInvoke2, CacheData.class).sheet().doWrite(TestDataBuilder.cacheData(10)); + assertHeadMap(fileCacheInvoke2, "Name2", null); + } + + @Test + void reusesOriginalHeaderWithMemoryCache() throws Exception { + setNameHeader("Name"); + + File fileCacheInvokeMemory = createTempFile("fileCacheInvokeMemory", ExcelFormat.XLSX); + File fileCacheInvokeMemory2 = createTempFile("fileCacheInvokeMemory2", ExcelFormat.XLSX); + FesodSheet.write(fileCacheInvokeMemory, CacheData.class) + .filedCacheLocation(CacheLocationEnum.MEMORY) + .sheet() + .doWrite(TestDataBuilder.cacheData(10)); + assertHeadMap(fileCacheInvokeMemory, "Name", CacheLocationEnum.MEMORY); + + setNameHeader("Name2"); + + FesodSheet.write(fileCacheInvokeMemory2, CacheData.class) + .filedCacheLocation(CacheLocationEnum.MEMORY) + .sheet() + .doWrite(TestDataBuilder.cacheData(10)); + assertHeadMap(fileCacheInvokeMemory2, "Name", CacheLocationEnum.MEMORY); + } + + private void assertHeadMap(File file, String expectedFirstHead, CacheLocationEnum cacheLocation) { + HeadCapturingListener listener = new HeadCapturingListener(); + + if (cacheLocation == null) { + FesodSheet.read(file, CacheData.class, listener).sheet().doRead(); + } else { + FesodSheet.read(file, CacheData.class, listener) + .filedCacheLocation(cacheLocation) + .sheet() + .doRead(); + } + + Map headMap = listener.getHeadMap(); + assertNotNull(headMap); + assertEquals(2, headMap.size()); + assertEquals(expectedFirstHead, headMap.get(0)); + assertEquals("Age", headMap.get(1)); + } + + private void setNameHeader(String nameHeader) throws Exception { + Field name = FieldUtils.getField(CacheData.class, "name", true); + ExcelProperty annotation = name.getAnnotation(ExcelProperty.class); + InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation); + Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues"); + memberValues.setAccessible(true); + Map map = (Map) memberValues.get(invocationHandler); + map.put("value", new String[] {nameHeader}); + } + + @Getter + private static class HeadCapturingListener extends AnalysisEventListener { + private Map headMap; + + @Override + public void invokeHeadMap(Map headMap, AnalysisContext context) { + this.headMap = headMap; + } + + @Override + public void invoke(CacheData data, AnalysisContext context) {} + + @Override + public void doAfterAllAnalysed(AnalysisContext context) {} + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/NoHeadDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/DateWindowingListener.java similarity index 64% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/head/NoHeadDataListener.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/DateWindowingListener.java index 41d6c6025..541f91158 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/head/NoHeadDataListener.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/DateWindowingListener.java @@ -23,34 +23,29 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.head; +package org.apache.fesod.sheet.readwrite; -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; +import lombok.AllArgsConstructor; +import lombok.Getter; import org.apache.fesod.sheet.context.AnalysisContext; import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; +import org.apache.fesod.sheet.testkit.models.SimpleData; /** - * + * Listener that captures the actual use1904windowing setting from the read context. */ -@Slf4j -public class NoHeadDataListener extends AnalysisEventListener { +@AllArgsConstructor +public class DateWindowingListener extends AnalysisEventListener { - List list = new ArrayList(); + @Getter + private Boolean actualUse1904windowing; @Override - public void invoke(NoHeadData data, AnalysisContext context) { - list.add(data); - } + public void invoke(SimpleData data, AnalysisContext context) {} @Override public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(1, list.size()); - NoHeadData data = list.get(0); - Assertions.assertEquals("字符串0", data.getString()); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); + actualUse1904windowing = + context.readWorkbookHolder().getGlobalConfiguration().getUse1904windowing(); } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/DateWindowingTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/DateWindowingTest.java new file mode 100644 index 000000000..3fd4dfced --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/DateWindowingTest.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.readwrite; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.support.ExcelTypeEnum; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.apache.fesod.sheet.util.TestFileUtil; +import org.junit.jupiter.api.Test; + +public class DateWindowingTest extends AbstractExcelTest { + + @Test + void readsXlsWindowingFlagsFromGeneratedAndFixtureFiles() throws Exception { + File file1900 = createTempFile("datewindowing1900", ExcelFormat.XLS); + File file1904 = createTempFile("datewindowing1904", ExcelFormat.XLS); + writeDateWindowingFile(file1900, ExcelTypeEnum.XLS, Boolean.FALSE); + writeDateWindowingFile(file1904, ExcelTypeEnum.XLS, Boolean.TRUE); + + assertActualWindowing(file1904, ExcelTypeEnum.XLS, null, Boolean.FALSE); + assertActualWindowing(file1900, ExcelTypeEnum.XLS, Boolean.FALSE, Boolean.FALSE); + assertActualWindowing(file1904, ExcelTypeEnum.XLS, Boolean.TRUE, Boolean.TRUE); + assertActualWindowing(fixtureFile("1900DateWindowing.xls"), ExcelTypeEnum.XLS, null, Boolean.FALSE); + assertActualWindowing(fixtureFile("1904DateWindowing.xls"), ExcelTypeEnum.XLS, null, Boolean.TRUE); + } + + @Test + void readsXlsxWindowingFlagsFromGeneratedFiles() throws Exception { + File file1900 = createTempFile("datewindowing1900", ExcelFormat.XLSX); + File file1904 = createTempFile("datewindowing1904", ExcelFormat.XLSX); + writeDateWindowingFile(file1900, ExcelTypeEnum.XLSX, Boolean.FALSE); + writeDateWindowingFile(file1904, ExcelTypeEnum.XLSX, Boolean.TRUE); + + assertActualWindowing(file1900, ExcelTypeEnum.XLSX, null, Boolean.FALSE); + assertActualWindowing(file1904, ExcelTypeEnum.XLSX, null, Boolean.TRUE); + } + + @Test + void readsCsvWindowingFlagsFromReadConfiguration() throws Exception { + File file1900 = createTempFile("datewindowing1900", ExcelFormat.CSV); + File file1904 = createTempFile("datewindowing1904", ExcelFormat.CSV); + writeDateWindowingFile(file1900, ExcelTypeEnum.CSV, Boolean.FALSE); + writeDateWindowingFile(file1904, ExcelTypeEnum.CSV, Boolean.TRUE); + + assertActualWindowing(file1900, ExcelTypeEnum.CSV, Boolean.FALSE, Boolean.FALSE); + assertActualWindowing(file1904, ExcelTypeEnum.CSV, null, Boolean.FALSE); + assertActualWindowing(file1904, ExcelTypeEnum.CSV, Boolean.TRUE, Boolean.TRUE); + assertActualWindowing(file1904, ExcelTypeEnum.CSV, null, Boolean.FALSE); + } + + private void writeDateWindowingFile(File file, ExcelTypeEnum excelType, Boolean use1904windowing) { + FesodSheet.write(file, SimpleData.class) + .excelType(excelType) + .use1904windowing(use1904windowing) + .sheet() + .doWrite(TestDataBuilder.simpleDataWithDate(10)); + } + + private void assertActualWindowing( + File file, + ExcelTypeEnum excelType, + Boolean configuredUse1904windowing, + Boolean expectedActualUse1904windowing) { + DateWindowingListener listener = new DateWindowingListener(Boolean.FALSE); + if (configuredUse1904windowing == null) { + FesodSheet.read(file, listener) + .excelType(excelType) + .head(SimpleData.class) + .doReadAllSync(); + } else { + FesodSheet.read(file, listener) + .excelType(excelType) + .use1904windowing(configuredUse1904windowing) + .head(SimpleData.class) + .doReadAllSync(); + } + assertEquals(expectedActualUse1904windowing, listener.getActualUse1904windowing()); + } + + private File fixtureFile(String fileName) { + return TestFileUtil.readFile("datewindowing/" + fileName); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/data/DemoData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/DemoData.java similarity index 91% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/data/DemoData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/DemoData.java index a9f96d524..734578ae4 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/data/DemoData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/DemoData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.data; +package org.apache.fesod.sheet.readwrite; import java.util.Date; import lombok.EqualsAndHashCode; @@ -31,7 +31,7 @@ import lombok.Setter; /** - * 基础数据类.这里的排序和excel里面的排序一致 + * Basic data model. Field order matches the corresponding Excel column order. * * **/ diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/EncryptDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/EncryptDataTest.java new file mode 100644 index 000000000..829836341 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/EncryptDataTest.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.readwrite; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.io.File; +import java.nio.file.Files; +import java.util.List; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.read.builder.ExcelReaderBuilder; +import org.apache.fesod.sheet.support.ExcelTypeEnum; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.listeners.CollectingReadListener; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.apache.fesod.sheet.write.builder.ExcelWriterBuilder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Test encrypt read/write for all Excel formats using parameterized tests. + */ +public class EncryptDataTest extends AbstractExcelTest { + private static final String PASSWORD = "123456"; + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWriteAllCombinations(ExcelFormat format) throws Exception { + ExcelTypeEnum excelType = format.toExcelTypeEnum(); + + // File-based: no explicit type, no password + readAndWrite(createTempFile("enc-f-np", format), null, false, false, excelType); + // File-based: no explicit type, with password + readAndWrite(createTempFile("enc-f-wp", format), null, true, false, excelType); + // File-based: explicit type, no password + readAndWrite(createTempFile("enc-f-tp", format), excelType, false, false, excelType); + // File-based: explicit type, with password + readAndWrite(createTempFile("enc-f-twp", format), excelType, true, false, excelType); + + // Stream-based: no explicit type, no password + readAndWrite(createTempFile("enc-s-np", format), null, false, true, excelType); + // Stream-based: no explicit type, with password + readAndWrite(createTempFile("enc-s-wp", format), null, true, true, excelType); + // Stream-based: explicit type, no password + readAndWrite(createTempFile("enc-s-tp", format), excelType, false, true, excelType); + // Stream-based: explicit type, with password + readAndWrite(createTempFile("enc-s-twp", format), excelType, true, true, excelType); + } + + private void readAndWrite( + File file, ExcelTypeEnum excelType, boolean hasPassword, boolean isStream, ExcelTypeEnum streamType) + throws Exception { + ExcelWriterBuilder excelWriterBuilder = isStream + ? FesodSheet.write(Files.newOutputStream(file.toPath()), SimpleData.class) + : FesodSheet.write(file, SimpleData.class); + + ExcelReaderBuilder readerBuilder = isStream + ? FesodSheet.read( + Files.newInputStream(file.toPath()), SimpleData.class, new CollectingReadListener()) + : FesodSheet.read(file, SimpleData.class, new CollectingReadListener()); + if (excelType != null) { + excelWriterBuilder.excelType(excelType); + readerBuilder.excelType(excelType); + } + if (isStream && excelType == null) { + // Stream API needs type hint when not explicitly set + excelWriterBuilder.excelType(streamType); + readerBuilder.excelType(streamType); + } + if (hasPassword) { + excelWriterBuilder.password(PASSWORD); + readerBuilder.password(PASSWORD); + } + + excelWriterBuilder.sheet().doWrite(TestDataBuilder.simpleData(10)); + List dataList = readerBuilder.sheet().doReadSync(); + assertEquals(10, dataList.size()); + assertNotNull(dataList.get(0).getName()); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExcelAnalysisStopSheetExceptionDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExcelAnalysisStopSheetExceptionDataListener.java similarity index 79% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExcelAnalysisStopSheetExceptionDataListener.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExcelAnalysisStopSheetExceptionDataListener.java index 90edce01a..558c1e25d 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExcelAnalysisStopSheetExceptionDataListener.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExcelAnalysisStopSheetExceptionDataListener.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.exception; +package org.apache.fesod.sheet.readwrite; import java.util.List; import java.util.Map; @@ -33,19 +33,20 @@ import org.apache.fesod.common.util.MapUtils; import org.apache.fesod.sheet.context.AnalysisContext; import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; +import org.apache.fesod.sheet.exception.ExcelAnalysisStopSheetException; +import org.apache.fesod.sheet.testkit.models.SimpleData; /** * */ @Getter @Slf4j -public class ExcelAnalysisStopSheetExceptionDataListener extends AnalysisEventListener { +public class ExcelAnalysisStopSheetExceptionDataListener extends AnalysisEventListener { private Map> dataMap = MapUtils.newHashMap(); @Override - public void invoke(ExceptionData data, AnalysisContext context) { + public void invoke(SimpleData data, AnalysisContext context) { List sheetDataList = dataMap.computeIfAbsent(context.readSheetHolder().getSheetNo(), key -> ListUtils.newArrayList()); sheetDataList.add(data.getName()); @@ -55,9 +56,5 @@ public void invoke(ExceptionData data, AnalysisContext context) { } @Override - public void doAfterAllAnalysed(AnalysisContext context) { - List sheetDataList = dataMap.get(context.readSheetHolder().getSheetNo()); - Assertions.assertNotNull(sheetDataList); - Assertions.assertEquals(5, sheetDataList.size()); - } + public void doAfterAllAnalysed(AnalysisContext context) {} } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExceptionDataListener.java similarity index 65% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionDataListener.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExceptionDataListener.java index 5b7183871..28693a700 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionDataListener.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExceptionDataListener.java @@ -23,26 +23,30 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.exception; +package org.apache.fesod.sheet.readwrite; import com.alibaba.fastjson2.JSON; import java.util.ArrayList; import java.util.List; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.fesod.sheet.context.AnalysisContext; import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; +import org.apache.fesod.sheet.testkit.models.SimpleData; /** * */ +@Getter @Slf4j -public class ExceptionDataListener extends AnalysisEventListener { - List list = new ArrayList(); +public class ExceptionDataListener extends AnalysisEventListener { + private List list = new ArrayList(); + private Integer sheetNo; + private String headName; @Override public void onException(Exception exception, AnalysisContext context) { - log.info("抛出异常,忽略:{}", exception.getMessage(), exception); + log.info("Ignored exception while reading: {}", exception.getMessage(), exception); } @Override @@ -51,26 +55,23 @@ public boolean hasNext(AnalysisContext context) { } @Override - public void invoke(ExceptionData data, AnalysisContext context) { + public void invoke(SimpleData data, AnalysisContext context) { + sheetNo = context.readSheetHolder().getSheetNo(); list.add(data); if (list.size() == 5) { int i = 5 / 0; } } + @Override + public void invokeHeadMap(java.util.Map headMap, AnalysisContext context) { + headName = headMap.get(0); + } + @Override public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(8, list.size()); - Assertions.assertEquals("姓名0", list.get(0).getName()); - Assertions.assertEquals(0, (int) (context.readSheetHolder().getSheetNo())); - Assertions.assertEquals( - "姓名", - context.readSheetHolder() - .getExcelReadHeadProperty() - .getHeadMap() - .get(0) - .getHeadNameList() - .get(0)); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); + if (!list.isEmpty()) { + log.debug("First row:{}", JSON.toJSONString(list.get(0))); + } } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExceptionDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExceptionDataTest.java new file mode 100644 index 000000000..0374d671f --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExceptionDataTest.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.readwrite; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.util.List; +import java.util.Map; +import org.apache.fesod.sheet.ExcelWriter; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.apache.fesod.sheet.write.metadata.WriteSheet; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * + */ +public class ExceptionDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile(format); + FesodSheet.write(file, SimpleData.class).sheet().doWrite(TestDataBuilder.simpleData(10)); + ExceptionDataListener listener = new ExceptionDataListener(); + FesodSheet.read(file, SimpleData.class, listener).sheet().doRead(); + assertEquals(8, listener.getList().size()); + assertEquals("Name0", listener.getList().get(0).getName()); + assertEquals(0, (int) listener.getSheetNo()); + assertEquals("Name", listener.getHeadName()); + } + + @ParameterizedTest + @MethodSource("binaryFormats") + void readAndWriteException(ExcelFormat format) throws Exception { + File file = createTempFile(format); + FesodSheet.write(file, SimpleData.class).sheet().doWrite(TestDataBuilder.simpleData(10)); + ArithmeticException exception = assertThrows(ArithmeticException.class, () -> FesodSheet.read( + file, SimpleData.class, new ExceptionThrowDataListener()) + .sheet() + .doRead()); + assertEquals("/ by zero", exception.getMessage()); + } + + @ParameterizedTest + @MethodSource("binaryFormats") + void readAndWriteExcelAnalysisStopSheetException(ExcelFormat format) throws Exception { + File file = createTempFile(format); + try (ExcelWriter excelWriter = FesodSheet.write(file, SimpleData.class).build()) { + for (int i = 0; i < 5; i++) { + String sheetName = "sheet" + i; + WriteSheet writeSheet = FesodSheet.writerSheet(i, sheetName).build(); + List data = TestDataBuilder.simpleData(10, sheetName + "-"); + excelWriter.write(data, writeSheet); + } + } + + ExcelAnalysisStopSheetExceptionDataListener listener = new ExcelAnalysisStopSheetExceptionDataListener(); + FesodSheet.read(file, SimpleData.class, listener).doReadAll(); + Map> dataMap = listener.getDataMap(); + assertEquals(5, dataMap.size()); + for (int i = 0; i < 5; i++) { + List sheetDataList = dataMap.get(i); + assertNotNull(sheetDataList); + assertEquals(5, sheetDataList.size()); + String sheetName = "sheet" + i; + for (String sheetData : sheetDataList) { + assertTrue(sheetData.startsWith(sheetName)); + } + } + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionThrowDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExceptionThrowDataListener.java similarity index 83% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionThrowDataListener.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExceptionThrowDataListener.java index fa622df3e..02296cc51 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/ExceptionThrowDataListener.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ExceptionThrowDataListener.java @@ -23,24 +23,27 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.exception; +package org.apache.fesod.sheet.readwrite; import java.util.ArrayList; import java.util.List; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.fesod.sheet.context.AnalysisContext; import org.apache.fesod.sheet.read.listener.ReadListener; +import org.apache.fesod.sheet.testkit.models.SimpleData; /** * */ +@Getter @Slf4j -public class ExceptionThrowDataListener implements ReadListener { +public class ExceptionThrowDataListener implements ReadListener { - List list = new ArrayList(); + private final List list = new ArrayList(); @Override - public void invoke(ExceptionData data, AnalysisContext context) { + public void invoke(SimpleData data, AnalysisContext context) { list.add(data); if (list.size() == 5) { int i = 5 / 0; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/large/LargeData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/LargeData.java similarity index 97% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/large/LargeData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/LargeData.java index da20368db..7329e699c 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/large/LargeData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/LargeData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.large; +package org.apache.fesod.sheet.readwrite; import lombok.EqualsAndHashCode; import lombok.Getter; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/large/LargeDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/LargeDataListener.java similarity index 83% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/large/LargeDataListener.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/LargeDataListener.java index e198865b3..da0d32cb7 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/large/LargeDataListener.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/LargeDataListener.java @@ -23,18 +23,18 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.large; +package org.apache.fesod.sheet.readwrite; import com.alibaba.fastjson2.JSON; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.fesod.sheet.context.AnalysisContext; import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.junit.jupiter.api.Assertions; /** * */ +@Getter @Slf4j public class LargeDataListener extends AnalysisEventListener { private int count = 0; @@ -53,10 +53,5 @@ public void invoke(LargeData data, AnalysisContext context) { @Override public void doAfterAllAnalysed(AnalysisContext context) { log.info("Large row count:{}", count); - if (context.readWorkbookHolder().getExcelType() != ExcelTypeEnum.CSV) { - Assertions.assertEquals(464509, count); - } else { - Assertions.assertEquals(499999, count); - } } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/large/LargeDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/LargeDataTest.java similarity index 79% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/large/LargeDataTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/LargeDataTest.java index 6e0b2e25a..e1e3e1af1 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/large/LargeDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/LargeDataTest.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.large; +package org.apache.fesod.sheet.readwrite; import java.io.File; import java.io.FileOutputStream; @@ -32,6 +32,7 @@ import lombok.extern.slf4j.Slf4j; import org.apache.fesod.sheet.ExcelWriter; import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; import org.apache.fesod.sheet.util.TestFileUtil; import org.apache.fesod.sheet.write.metadata.WriteSheet; import org.apache.poi.xssf.streaming.SXSSFCell; @@ -39,52 +40,32 @@ import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; /** * */ -@TestMethodOrder(MethodOrderer.MethodName.class) @Slf4j -public class LargeDataTest { - - private static File fileFill07; - private static File template07; - private static File fileCsv; - private static File fileWrite07; - private static File fileWriteTemp07; - private static File fileWritePoi07; +public class LargeDataTest extends AbstractExcelTest { private int i = 0; - @BeforeAll - public static void init() { - fileFill07 = TestFileUtil.createNewFile("largefill07.xlsx"); - fileWrite07 = TestFileUtil.createNewFile("large" + File.separator + "fileWrite07.xlsx"); - fileWriteTemp07 = TestFileUtil.createNewFile("large" + File.separator + "fileWriteTemp07.xlsx"); - fileWritePoi07 = TestFileUtil.createNewFile("large" + File.separator + "fileWritePoi07.xlsx"); - template07 = TestFileUtil.readFile("large" + File.separator + "fill.xlsx"); - fileCsv = TestFileUtil.createNewFile("largefileCsv.csv"); - } - @Test - public void t01Read() throws Exception { + public void read() { long start = System.currentTimeMillis(); - FesodSheet.read( - TestFileUtil.getPath() + "large" + File.separator + "large07.xlsx", - LargeData.class, - new LargeDataListener()) + LargeDataListener listener = new LargeDataListener(); + FesodSheet.read(TestFileUtil.getPath() + "large" + File.separator + "large07.xlsx", LargeData.class, listener) .headRowNumber(2) .sheet() .doRead(); log.info("Large data total time spent:{}", System.currentTimeMillis() - start); + Assertions.assertEquals(464509, listener.getCount()); } @Test - public void t02Fill() { + public void fill() { + File fileFill07 = new File(tempDir, "largefill07.xlsx"); + File template07 = TestFileUtil.readFile("large" + File.separator + "fill.xlsx"); try (ExcelWriter excelWriter = FesodSheet.write(fileFill07).withTemplate(template07).build()) { WriteSheet writeSheet = FesodSheet.writerSheet().build(); @@ -96,7 +77,8 @@ public void t02Fill() { } @Test - public void t03ReadAndWriteCsv() { + public void readAndWriteCsv() { + File fileCsv = new File(tempDir, "largefileCsv.csv"); // write long start = System.currentTimeMillis(); try (ExcelWriter excelWriter = FesodSheet.write(fileCsv).build()) { @@ -110,14 +92,17 @@ public void t03ReadAndWriteCsv() { // read start = System.currentTimeMillis(); - FesodSheet.read(fileCsv, LargeData.class, new LargeDataListener()) - .sheet() - .doRead(); + LargeDataListener csvListener = new LargeDataListener(); + FesodSheet.read(fileCsv, LargeData.class, csvListener).sheet().doRead(); log.info("CSV large data total time spent:{}", System.currentTimeMillis() - start); + Assertions.assertEquals(499999, csvListener.getCount()); } @Test - public void t04Write() throws Exception { + public void write() throws Exception { + File fileWriteTemp07 = new File(tempDir, "fileWriteTemp07.xlsx"); + File fileWrite07 = new File(tempDir, "fileWrite07.xlsx"); + File fileWritePoi07 = new File(tempDir, "fileWritePoi07.xlsx"); ExcelWriter excelWriter = FesodSheet.write(fileWriteTemp07, LargeData.class).build(); WriteSheet writeSheet = FesodSheet.writerSheet().build(); diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/ParameterDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ParameterDataTest.java similarity index 56% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/ParameterDataTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ParameterDataTest.java index 80fec1b7a..b95e14a93 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/parameter/ParameterDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/ParameterDataTest.java @@ -23,11 +23,11 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.parameter; +package org.apache.fesod.sheet.readwrite; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.FileOutputStream; -import java.util.ArrayList; import java.util.List; import org.apache.fesod.sheet.ExcelReader; import org.apache.fesod.sheet.ExcelWriter; @@ -36,95 +36,76 @@ import org.apache.fesod.sheet.converters.string.StringStringConverter; import org.apache.fesod.sheet.read.metadata.ReadSheet; import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.apache.fesod.sheet.util.TestFileUtil; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.listeners.CollectingReadListener; +import org.apache.fesod.sheet.testkit.models.SimpleData; import org.apache.fesod.sheet.write.metadata.WriteSheet; import org.apache.fesod.sheet.write.metadata.WriteTable; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class ParameterDataTest { - - private static File file07; - private static File fileCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("parameter07.xlsx"); - fileCsv = TestFileUtil.createNewFile("parameterCsv.csv"); - } - - @Test - public void t01ReadAndWrite() throws Exception { - readAndWrite1(file07, ExcelTypeEnum.XLSX); - readAndWrite2(file07, ExcelTypeEnum.XLSX); - readAndWrite3(file07, ExcelTypeEnum.XLSX); - readAndWrite4(file07, ExcelTypeEnum.XLSX); - readAndWrite5(file07, ExcelTypeEnum.XLSX); - readAndWrite6(file07, ExcelTypeEnum.XLSX); - readAndWrite7(file07, ExcelTypeEnum.XLSX); - } - - @Test - public void t02ReadAndWrite() throws Exception { - readAndWrite1(fileCsv, ExcelTypeEnum.CSV); - readAndWrite2(fileCsv, ExcelTypeEnum.CSV); - readAndWrite3(fileCsv, ExcelTypeEnum.CSV); - readAndWrite4(fileCsv, ExcelTypeEnum.CSV); - readAndWrite5(fileCsv, ExcelTypeEnum.CSV); - readAndWrite6(fileCsv, ExcelTypeEnum.CSV); - readAndWrite7(fileCsv, ExcelTypeEnum.CSV); +public class ParameterDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile("parameter", format); + ExcelTypeEnum type = format.toExcelTypeEnum(); + readAndWrite1(file, type); + readAndWrite2(file, type); + readAndWrite3(file, type); + readAndWrite4(file, type); + readAndWrite5(file, type); + readAndWrite6(file, type); + readAndWrite7(file, type); } private void readAndWrite1(File file, ExcelTypeEnum type) { - FesodSheet.write(file.getPath()).head(ParameterData.class).sheet().doWrite(data()); - FesodSheet.read(file.getPath()) - .head(ParameterData.class) - .registerReadListener(new ParameterDataListener()) - .sheet() - .doRead(); + FesodSheet.write(file.getPath()).head(SimpleData.class).sheet().doWrite(TestDataBuilder.simpleData(10)); + List dataList = + FesodSheet.read(file.getPath()).head(SimpleData.class).sheet().doReadSync(); + assertParameterData(dataList); } private void readAndWrite2(File file, ExcelTypeEnum type) { - FesodSheet.write(file.getPath(), ParameterData.class).sheet().doWrite(data()); - FesodSheet.read(file.getPath(), ParameterData.class, new ParameterDataListener()) + FesodSheet.write(file.getPath(), SimpleData.class).sheet().doWrite(TestDataBuilder.simpleData(10)); + List dataList = FesodSheet.read( + file.getPath(), SimpleData.class, new CollectingReadListener()) .sheet() - .doRead(); + .doReadSync(); + assertParameterData(dataList); } private void readAndWrite3(File file, ExcelTypeEnum type) throws Exception { FesodSheet.write(new FileOutputStream(file)) .excelType(type) - .head(ParameterData.class) + .head(SimpleData.class) .sheet() - .doWrite(data()); - FesodSheet.read(file.getPath()) - .head(ParameterData.class) - .registerReadListener(new ParameterDataListener()) - .sheet() - .doRead(); + .doWrite(TestDataBuilder.simpleData(10)); + List dataList = + FesodSheet.read(file.getPath()).head(SimpleData.class).sheet().doReadSync(); + assertParameterData(dataList); } private void readAndWrite4(File file, ExcelTypeEnum type) throws Exception { - FesodSheet.write(new FileOutputStream(file), ParameterData.class) + FesodSheet.write(new FileOutputStream(file), SimpleData.class) .excelType(type) .sheet() - .doWrite(data()); - FesodSheet.read(file.getPath(), new ParameterDataListener()) - .head(ParameterData.class) - .sheet() - .doRead(); + .doWrite(TestDataBuilder.simpleData(10)); + List dataList = + FesodSheet.read(file.getPath()).head(SimpleData.class).sheet().doReadSync(); + assertParameterData(dataList); } private void readAndWrite5(File file, ExcelTypeEnum type) throws Exception { ExcelWriter excelWriter = FesodSheet.write(new FileOutputStream(file)) .excelType(type) - .head(ParameterData.class) + .head(SimpleData.class) .relativeHeadRowIndex(0) .build(); WriteSheet writeSheet = FesodSheet.writerSheet(0) @@ -135,17 +116,18 @@ private void readAndWrite5(File file, ExcelTypeEnum type) throws Exception { .relativeHeadRowIndex(0) .needHead(Boolean.TRUE) .build(); - excelWriter.write(data(), writeSheet, writeTable); + excelWriter.write(TestDataBuilder.simpleData(10), writeSheet, writeTable); excelWriter.finish(); - ExcelReader excelReader = FesodSheet.read(file.getPath(), new ParameterDataListener()) - .head(ParameterData.class) + CollectingReadListener listener1 = new CollectingReadListener(); + ExcelReader excelReader = FesodSheet.read(file.getPath(), listener1) + .head(SimpleData.class) .mandatoryUseInputStream(Boolean.FALSE) .autoCloseStream(Boolean.TRUE) .readCache(new MapCache()) .build(); ReadSheet readSheet = FesodSheet.readSheet() - .head(ParameterData.class) + .head(SimpleData.class) .use1904windowing(Boolean.FALSE) .headRowNumber(1) .sheetNo(0) @@ -153,21 +135,24 @@ private void readAndWrite5(File file, ExcelTypeEnum type) throws Exception { .build(); excelReader.read(readSheet); excelReader.finish(); + assertParameterData(listener1.getRows()); - excelReader = FesodSheet.read(file.getPath(), new ParameterDataListener()) - .head(ParameterData.class) + CollectingReadListener listener2 = new CollectingReadListener(); + excelReader = FesodSheet.read(file.getPath(), listener2) + .head(SimpleData.class) .mandatoryUseInputStream(Boolean.FALSE) .autoCloseStream(Boolean.TRUE) .readCache(new MapCache()) .build(); - excelReader.read(); + excelReader.readAll(); excelReader.finish(); + assertParameterData(listener2.getRows()); } private void readAndWrite6(File file, ExcelTypeEnum type) throws Exception { ExcelWriter excelWriter = FesodSheet.write(new FileOutputStream(file)) .excelType(type) - .head(ParameterData.class) + .head(SimpleData.class) .relativeHeadRowIndex(0) .build(); WriteSheet writeSheet = FesodSheet.writerSheet(0) @@ -179,58 +164,57 @@ private void readAndWrite6(File file, ExcelTypeEnum type) throws Exception { .relativeHeadRowIndex(0) .needHead(Boolean.TRUE) .build(); - excelWriter.write(data(), writeSheet, writeTable); + excelWriter.write(TestDataBuilder.simpleData(10), writeSheet, writeTable); excelWriter.finish(); - ExcelReader excelReader = FesodSheet.read(file.getPath(), new ParameterDataListener()) - .head(ParameterData.class) + CollectingReadListener listener1 = new CollectingReadListener(); + ExcelReader excelReader = FesodSheet.read(file.getPath(), listener1) + .head(SimpleData.class) .mandatoryUseInputStream(Boolean.FALSE) .autoCloseStream(Boolean.TRUE) .readCache(new MapCache()) .build(); ReadSheet readSheet = FesodSheet.readSheet("0") - .head(ParameterData.class) + .head(SimpleData.class) .use1904windowing(Boolean.FALSE) .headRowNumber(1) .sheetNo(0) .build(); excelReader.read(readSheet); excelReader.finish(); + assertParameterData(listener1.getRows()); - excelReader = FesodSheet.read(file.getPath(), new ParameterDataListener()) - .head(ParameterData.class) + CollectingReadListener listener2 = new CollectingReadListener(); + excelReader = FesodSheet.read(file.getPath(), listener2) + .head(SimpleData.class) .mandatoryUseInputStream(Boolean.FALSE) .autoCloseStream(Boolean.TRUE) .readCache(new MapCache()) .build(); - excelReader.read(); + excelReader.readAll(); excelReader.finish(); + assertParameterData(listener2.getRows()); } private void readAndWrite7(File file, ExcelTypeEnum type) { - FesodSheet.write(file, ParameterData.class) + FesodSheet.write(file, SimpleData.class) .registerConverter(new StringStringConverter()) .sheet() .registerConverter(new StringStringConverter()) .needHead(Boolean.FALSE) .table(0) .needHead(Boolean.TRUE) - .doWrite(data()); - FesodSheet.read(file.getPath()) - .head(ParameterData.class) - .registerReadListener(new ParameterDataListener()) + .doWrite(TestDataBuilder.simpleData(10)); + List dataList = FesodSheet.read(file.getPath()) + .head(SimpleData.class) .sheet() .registerConverter(new StringStringConverter()) - .doRead(); + .doReadSync(); + assertParameterData(dataList); } - private List data() { - List list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - ParameterData simpleData = new ParameterData(); - simpleData.setName("姓名" + i); - list.add(simpleData); - } - return list; + private void assertParameterData(List dataList) { + assertEquals(10, dataList.size()); + assertEquals("Name0", dataList.get(0).getName()); } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/XlsxSaxAnalyserReadOpcPackageTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/XlsxSaxAnalyserReadOpcPackageTest.java similarity index 95% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/XlsxSaxAnalyserReadOpcPackageTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/XlsxSaxAnalyserReadOpcPackageTest.java index d04f04c40..8c09788a5 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/exception/XlsxSaxAnalyserReadOpcPackageTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/readwrite/XlsxSaxAnalyserReadOpcPackageTest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.exception; +package org.apache.fesod.sheet.readwrite; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -30,8 +30,10 @@ import org.apache.fesod.sheet.analysis.v07.XlsxSaxAnalyser; import org.apache.fesod.sheet.context.xlsx.DefaultXlsxReadContext; import org.apache.fesod.sheet.context.xlsx.XlsxReadContext; +import org.apache.fesod.sheet.exception.ExcelCommonException; import org.apache.fesod.sheet.read.metadata.ReadWorkbook; import org.apache.fesod.sheet.support.ExcelTypeEnum; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; import org.junit.jupiter.api.Test; /** @@ -39,7 +41,7 @@ * POI's NotOfficeXmlFileException/InvalidFormatException into ExcelCommonException * with a message containing "Invalid OOXML/zip format". */ -public class XlsxSaxAnalyserReadOpcPackageTest { +public class XlsxSaxAnalyserReadOpcPackageTest extends AbstractExcelTest { @Test void invalidInputStream_mandatoryUseInputStream_throwsExcelCommonException() { diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/repetition/RepetitionDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/repetition/RepetitionDataListener.java deleted file mode 100644 index 382dc449e..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/repetition/RepetitionDataListener.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.repetition; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class RepetitionDataListener extends AnalysisEventListener { - - List list = new ArrayList(); - - @Override - public void invoke(RepetitionData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(2, list.size()); - Assertions.assertEquals("字符串0", list.get(0).getString()); - Assertions.assertEquals("字符串0", list.get(1).getString()); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/repetition/RepetitionDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/repetition/RepetitionDataTest.java deleted file mode 100644 index ca4c755f1..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/repetition/RepetitionDataTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.repetition; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import org.apache.fesod.sheet.ExcelReader; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.read.metadata.ReadSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.apache.fesod.sheet.write.metadata.WriteTable; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class RepetitionDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - private static File fileTable07; - private static File fileTable03; - private static File fileTableCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("repetition07.xlsx"); - file03 = TestFileUtil.createNewFile("repetition03.xls"); - fileCsv = TestFileUtil.createNewFile("repetitionCsv.csv"); - fileTable07 = TestFileUtil.createNewFile("repetitionTable07.xlsx"); - fileTable03 = TestFileUtil.createNewFile("repetitionTable03.xls"); - fileTableCsv = TestFileUtil.createNewFile("repetitionTableCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() { - readAndWrite(fileCsv); - } - - private void readAndWrite(File file) { - try (ExcelWriter excelWriter = - FesodSheet.write(file, RepetitionData.class).build()) { - WriteSheet writeSheet = FesodSheet.writerSheet(0).build(); - excelWriter.write(data(), writeSheet).write(data(), writeSheet); - } - try (ExcelReader excelReader = FesodSheet.read(file, RepetitionData.class, new RepetitionDataListener()) - .build()) { - ReadSheet readSheet = FesodSheet.readSheet(0).build(); - excelReader.read(readSheet); - } - } - - @Test - public void t11ReadAndWriteTable07() { - readAndWriteTable(fileTable07); - } - - @Test - public void t12ReadAndWriteTable03() { - readAndWriteTable(fileTable03); - } - - @Test - public void t13ReadAndWriteTableCsv() { - readAndWriteTable(fileTableCsv); - } - - private void readAndWriteTable(File file) { - try (ExcelWriter excelWriter = - FesodSheet.write(file, RepetitionData.class).build()) { - WriteSheet writeSheet = FesodSheet.writerSheet(0).build(); - WriteTable writeTable = - FesodSheet.writerTable(0).relativeHeadRowIndex(0).build(); - excelWriter.write(data(), writeSheet, writeTable).write(data(), writeSheet, writeTable); - } - try (ExcelReader excelReader = FesodSheet.read(file, RepetitionData.class, new RepetitionDataListener()) - .build()) { - ReadSheet readSheet = FesodSheet.readSheet(0).headRowNumber(2).build(); - excelReader.read(readSheet); - } - } - - private List data() { - List list = new ArrayList(); - RepetitionData data = new RepetitionData(); - data.setString("字符串0"); - list.add(data); - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/HiddenSheetsTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/HiddenSheetsTest.java new file mode 100644 index 000000000..53b972163 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/HiddenSheetsTest.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.sheet; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import java.util.List; +import org.apache.fesod.sheet.ExcelReader; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.read.metadata.ReadSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.listeners.CollectingReadListener; +import org.apache.fesod.sheet.testkit.models.TitleData; +import org.apache.fesod.sheet.util.TestFileUtil; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +public class HiddenSheetsTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("binaryFormats") + void read(ExcelFormat format) { + File file = TestFileUtil.readFile("hiddensheets" + File.separator + "hiddensheets" + format.getExtension()); + read(file, null); + read(file, Boolean.FALSE); + read(file, Boolean.TRUE); + } + + @ParameterizedTest + @MethodSource("binaryFormats") + void readAll(ExcelFormat format) { + File file = TestFileUtil.readFile("hiddensheets" + File.separator + "hiddensheets" + format.getExtension()); + readAll(file, null); + readAll(file, Boolean.FALSE); + readAll(file, Boolean.TRUE); + } + + @ParameterizedTest + @MethodSource("binaryFormats") + void readHiddenList(ExcelFormat format) { + File file = TestFileUtil.readFile("hiddensheets" + File.separator + "hiddensheets" + format.getExtension()); + try (ExcelReader excelReader = FesodSheet.read(file, TitleData.class, new CollectingReadListener()) + .build()) { + List allSheetList = excelReader.excelExecutor().sheetList(); + assertEquals(2, allSheetList.stream().filter(ReadSheet::isHidden).count()); + assertEquals( + 1, allSheetList.stream().filter(ReadSheet::isVeryHidden).count()); + assertEquals( + "Sheet5", + allSheetList.stream() + .filter(ReadSheet::isVeryHidden) + .findFirst() + .get() + .getSheetName()); + } + } + + private void read(File file, Boolean ignoreHidden) { + try (ExcelReader excelReader = FesodSheet.read(file, TitleData.class, new CollectingReadListener()) + .ignoreHiddenSheet(ignoreHidden) + .build()) { + List sheets = excelReader.excelExecutor().sheetList(); + if (Boolean.TRUE.equals(ignoreHidden)) { + assertEquals(3, sheets.size()); + } else { + assertEquals(6, sheets.size()); + } + } + } + + private void readAll(File file, Boolean ignoreHidden) { + List dataList = FesodSheet.read(file, TitleData.class, new CollectingReadListener()) + .ignoreHiddenSheet(ignoreHidden) + .doReadAllSync(); + if (Boolean.TRUE.equals(ignoreHidden)) { + assertEquals(3, dataList.size()); + } else { + assertEquals(6, dataList.size()); + } + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/multiplesheets/MultipleSheetsDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/MultipleSheetsDataTest.java similarity index 51% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/multiplesheets/MultipleSheetsDataTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/MultipleSheetsDataTest.java index 6364636be..cbbb56fce 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/multiplesheets/MultipleSheetsDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/MultipleSheetsDataTest.java @@ -23,71 +23,49 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.multiplesheets; +package org.apache.fesod.sheet.sheet; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.util.List; import org.apache.fesod.sheet.ExcelReader; import org.apache.fesod.sheet.FesodSheet; import org.apache.fesod.sheet.read.metadata.ReadSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.listeners.CollectingReadListener; +import org.apache.fesod.sheet.testkit.models.TitleData; import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class MultipleSheetsDataTest { +public class MultipleSheetsDataTest extends AbstractExcelTest { - private static File file07; - private static File file03; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.readFile("multiplesheets" + File.separator + "multiplesheets.xlsx"); - file03 = TestFileUtil.readFile("multiplesheets" + File.separator + "multiplesheets.xls"); - } - - @Test - public void t01Read07() { - read(file07); - } - - @Test - public void t02Read03() { - read(file03); - } - - @Test - public void t03Read07All() { - readAll(file07); - } - - @Test - public void t04Read03All() { - readAll(file03); - } - - private void read(File file) { - MultipleSheetsListener multipleSheetsListener = new MultipleSheetsListener(); - try (ExcelReader excelReader = FesodSheet.read(file, MultipleSheetsData.class, multipleSheetsListener) - .build()) { + @ParameterizedTest + @MethodSource("binaryFormats") + void read(ExcelFormat format) { + File file = TestFileUtil.readFile("multiplesheets" + File.separator + "multiplesheets" + format.getExtension()); + CollectingReadListener listener = new CollectingReadListener<>(); + try (ExcelReader excelReader = + FesodSheet.read(file, TitleData.class, listener).build()) { List sheets = excelReader.excelExecutor().sheetList(); int count = 1; for (ReadSheet readSheet : sheets) { excelReader.read(readSheet); - Assertions.assertEquals(multipleSheetsListener.getList().size(), count); + assertEquals(count, listener.getRowCount()); count++; } } } - private void readAll(File file) { - FesodSheet.read(file, MultipleSheetsData.class, new MultipleSheetsListener()) + @ParameterizedTest + @MethodSource("binaryFormats") + void readAll(ExcelFormat format) { + File file = TestFileUtil.readFile("multiplesheets" + File.separator + "multiplesheets" + format.getExtension()); + FesodSheet.read(file, TitleData.class, new CollectingReadListener()) .doReadAll(); } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/writesheet/WriteSheetData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/WriteSheetData.java similarity index 80% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/writesheet/WriteSheetData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/WriteSheetData.java index 3156ec85c..fb64e7a0a 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/writesheet/WriteSheetData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/WriteSheetData.java @@ -17,17 +17,27 @@ * under the License. */ -package org.apache.fesod.sheet.writesheet; +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.sheet; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.fesod.sheet.annotation.ExcelProperty; +/** + * + */ @Getter @Setter @EqualsAndHashCode public class WriteSheetData { - @ExcelProperty("字符串标题") + + @ExcelProperty("String") private String string; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/WriteSheetTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/WriteSheetTest.java new file mode 100644 index 000000000..462b0d039 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/sheet/WriteSheetTest.java @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.sheet; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.fesod.sheet.ExcelWriter; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.write.metadata.WriteSheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.junit.jupiter.api.Test; + +public class WriteSheetTest extends AbstractExcelTest { + + @Test + public void testSheetOrderXls() throws Exception { + testSheetOrderInternal(ExcelFormat.XLS, Arrays.asList(0)); + testSheetOrderInternal(ExcelFormat.XLS, Arrays.asList(0, 1, 2)); + testSheetOrderInternal(ExcelFormat.XLS, Arrays.asList(2)); + testSheetOrderInternal(ExcelFormat.XLS, Arrays.asList(10, 6, 8)); + testSheetOrderInternal(ExcelFormat.XLS, Arrays.asList(-1)); + testSheetOrderInternal(ExcelFormat.XLS, Arrays.asList(-8, -10, -6)); + testSheetOrderInternal(ExcelFormat.XLS, Arrays.asList(-8, 6)); + testSheetOrderWithSheetName(ExcelFormat.XLS); + } + + @Test + public void testSheetOrderXlsx() throws Exception { + testSheetOrderInternal(ExcelFormat.XLSX, Arrays.asList(0)); + testSheetOrderInternal(ExcelFormat.XLSX, Arrays.asList(0, 1, 2)); + testSheetOrderInternal(ExcelFormat.XLSX, Arrays.asList(2)); + testSheetOrderInternal(ExcelFormat.XLSX, Arrays.asList(10, 6, 8)); + testSheetOrderInternal(ExcelFormat.XLSX, Arrays.asList(-1)); + testSheetOrderInternal(ExcelFormat.XLSX, Arrays.asList(-8, -10, -6)); + testSheetOrderInternal(ExcelFormat.XLSX, Arrays.asList(-8, 6)); + testSheetOrderWithSheetName(ExcelFormat.XLSX); + } + + private void testSheetOrderInternal(ExcelFormat format, List sheetNoList) throws Exception { + Map dataMap = initSheetDataSizeList(sheetNoList); + + File testFile = createTempFile(format); + try (ExcelWriter excelWriter = FesodSheet.write(testFile, WriteSheetData.class) + .excelType(format.toExcelTypeEnum()) + .build()) { + for (Integer sheetNo : sheetNoList) { + excelWriter.write( + TestDataBuilder.writeSheetData(dataMap.get(sheetNo)), + FesodSheet.writerSheet(sheetNo).build()); + } + } + + for (int i = 0; i < sheetNoList.size(); i++) { + List sheetDataList = FesodSheet.read(testFile) + .excelType(format.toExcelTypeEnum()) + .head(WriteSheetData.class) + .sheet(i) + .doReadSync(); + assertEquals(dataMap.get(sheetNoList.get(i)), sheetDataList.size()); + } + } + + private Map initSheetDataSizeList(List sheetNoList) { + Collections.sort(sheetNoList); + Map dataMap = new HashMap<>(); + for (int i = 0; i < sheetNoList.size(); i++) { + dataMap.put(sheetNoList.get(i), i + 1); + } + return dataMap; + } + + private void testSheetOrderWithSheetName(ExcelFormat format) throws Exception { + List sheetNameList = Arrays.asList("Sheet1", "Sheet2", "Sheet3", "Sheet111112222233333444445555566666"); + List sheetNoList = Arrays.asList(0, 1, 2, 3); + + Map dataMap = initSheetDataSizeList(sheetNoList); + File testFile = createTempFile("sheet-order-name", format); + + try (ExcelWriter excelWriter = FesodSheet.write(testFile, WriteSheetData.class) + .excelType(format.toExcelTypeEnum()) + .build()) { + + int sheetNo = 0; + WriteSheet writeSheet = FesodSheet.writerSheet(sheetNo).build(); + excelWriter.write(TestDataBuilder.writeSheetData(dataMap.get(sheetNo)), writeSheet); + assertEquals(sheetNo, excelWriter.writeContext().writeSheetHolder().getSheetNo()); + + sheetNo = 1; + writeSheet = FesodSheet.writerSheet(sheetNameList.get(sheetNo)).build(); + excelWriter.write(TestDataBuilder.writeSheetData(dataMap.get(sheetNo)), writeSheet); + assertEquals(sheetNo, excelWriter.writeContext().writeSheetHolder().getSheetNo()); + + sheetNo = 2; + writeSheet = + FesodSheet.writerSheet(sheetNo, sheetNameList.get(sheetNo)).build(); + excelWriter.write(TestDataBuilder.writeSheetData(dataMap.get(sheetNo)), writeSheet); + assertEquals(sheetNo, excelWriter.writeContext().writeSheetHolder().getSheetNo()); + + sheetNo = 3; + writeSheet = + FesodSheet.writerSheet(sheetNo, sheetNameList.get(sheetNo)).build(); + excelWriter.write(TestDataBuilder.writeSheetData(dataMap.get(sheetNo)), writeSheet); + assertEquals( + sheetNameList.get(sheetNo).substring(0, Workbook.MAX_SENSITIVE_SHEET_NAME_LEN), + excelWriter.writeContext().writeSheetHolder().getSheetName()); + assertEquals(sheetNo, excelWriter.writeContext().writeSheetHolder().getSheetNo()); + } + + for (int i = 0; i < sheetNoList.size(); i++) { + List sheetDataList = FesodSheet.read(testFile) + .excelType(format.toExcelTypeEnum()) + .head(WriteSheetData.class) + .sheet(i) + .doReadSync(); + assertEquals(dataMap.get(sheetNoList.get(i)), sheetDataList.size()); + } + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleDataListener.java deleted file mode 100644 index 9c30cd147..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleDataListener.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.simple; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.event.SyncReadListener; -import org.junit.jupiter.api.Assertions; - -/** - * Define an AnalysisEventListener to handler the Analysis event - * - * - */ -@Slf4j -public class SimpleDataListener extends AnalysisEventListener { - - List list = new ArrayList(); - - /** - * handle header of the file data - * - * @param headMap head map - * @param context context - */ - @Override - public void invokeHeadMap(Map headMap, AnalysisContext context) { - log.debug("Head is:{}", JSON.toJSONString(headMap)); - Assertions.assertEquals("姓名", headMap.get(0)); - } - - /** - * handle data row in the file - *

- * this is the same way of implement as {@link SyncReadListener#invoke} - * all the data are stored synchronously - *

- * - * @param data data - * @param context context - */ - @Override - public void invoke(SimpleData data, AnalysisContext context) { - list.add(data); - } - - /** - * do after all analyse process - * - * @param context context - */ - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - // check the results - Assertions.assertEquals(10, list.size()); - Assertions.assertEquals("姓名0", list.get(0).getName()); - Assertions.assertEquals(0, (int) (context.readSheetHolder().getSheetNo())); - Assertions.assertEquals( - "姓名", - context.readSheetHolder() - .getExcelReadHeadProperty() - .getHeadMap() - .get(0) - .getHeadNameList() - .get(0)); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleDataTest.java deleted file mode 100644 index 001b70465..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleDataTest.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.simple; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.read.listener.PageReadListener; -import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * Test simple read/write for Excel formats: - *
  • Excel 2007 format (.xlsx)
  • - *
  • Excel 2003 format (.xls)
  • - *
  • CSV format (.csv)
  • - * Test methods are grouped by prefixes: - *
  • t0x: Basic read/write tests
  • - *
  • t1x: Synchronous reading tests
  • - *
  • t2x: Specific feature tests (sheet name reading, pagination, etc.)
  • - * - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -@Slf4j -public class SimpleDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("simple07.xlsx"); - file03 = TestFileUtil.createNewFile("simple03.xls"); - fileCsv = TestFileUtil.createNewFile("simpleCsv.csv"); - } - - @Test - public void t01ReadAndWrite07() { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() { - readAndWrite(fileCsv); - } - - /** - * Test simple read/write with file - * - * @param file file - */ - private void readAndWrite(File file) { - FesodSheet.write(file, SimpleData.class).sheet().doWrite(data()); - // use a SimpleDataListener object to handle and check result - FesodSheet.read(file, SimpleData.class, new SimpleDataListener()) - .sheet() - .doRead(); - } - - @Test - public void t04ReadAndWrite07() throws Exception { - readAndWriteInputStream(file07, ExcelTypeEnum.XLSX); - } - - @Test - public void t05ReadAndWrite03() throws Exception { - readAndWriteInputStream(file03, ExcelTypeEnum.XLS); - } - - @Test - public void t06ReadAndWriteCsv() throws Exception { - readAndWriteInputStream(fileCsv, ExcelTypeEnum.CSV); - } - - /** - * Test simple read/write with InputStream/OutputStream - * - * @param file file used to generate InputStream/OutputStream - * @param excelTypeEnum excel type enum - * @throws Exception exception - */ - private void readAndWriteInputStream(File file, ExcelTypeEnum excelTypeEnum) throws Exception { - FesodSheet.write(new FileOutputStream(file), SimpleData.class) - .excelType(excelTypeEnum) - .sheet() - .doWrite(data()); - // use a SimpleDataListener object to handle and check result - FesodSheet.read(new FileInputStream(file), SimpleData.class, new SimpleDataListener()) - .sheet() - .doRead(); - } - - /** - * Test synchronous reading of Excel 2007 format - */ - @Test - public void t11SynchronousRead07() { - synchronousRead(file07); - } - - /** - * Test synchronous reading of Excel 2003 format - */ - @Test - public void t12SynchronousRead03() { - synchronousRead(file03); - } - - /** - * Test synchronous reading of CSV format - */ - @Test - public void t13SynchronousReadCsv() { - synchronousRead(fileCsv); - } - - /** - * test read sheet in an Excel file with specified sheetName - */ - @Test - public void t21SheetNameRead07() { - List> list = FesodSheet.read( - TestFileUtil.readFile("simple" + File.separator + "simple07.xlsx")) - // set the sheet name to read - .sheet("simple") - .doReadSync(); - Assertions.assertEquals(1, list.size()); - } - - /** - * test read sheet in an Excel file with specified sheetNo - */ - @Test - public void t22SheetNoRead07() { - List> list = FesodSheet.read( - TestFileUtil.readFile("simple" + File.separator + "simple07.xlsx")) - // sheetNo begin with 0 - .sheet(1) - .doReadSync(); - Assertions.assertEquals(1, list.size()); - } - - /** - * Test page reading with PageReadListener - *

    - * PageReadListener processes Excel data in batches, triggering callbacks when reaching - * specified batch size. {@link PageReadListener#invoke} - * Useful for large files to prevent memory overflow - *

    - */ - @Test - public void t23PageReadListener07() { - // Read the first 5 rows of an Excel file - FesodSheet.read( - file07, - SimpleData.class, - new PageReadListener( - dataList -> { - Assertions.assertEquals(5, dataList.size()); - }, - 5)) - .sheet() - .doRead(); - } - - /** - * Synchronous reading of Excel files - *

    - * Unlike asynchronous reading with listeners, synchronous reading loads all data into memory - * and returns a complete data list. It may cause memory issues when processing large files. - *

    - * - * @param file file - */ - private void synchronousRead(File file) { - // Synchronous read file - List list = FesodSheet.read(file).head(SimpleData.class).sheet().doReadSync(); - Assertions.assertEquals(10, list.size()); - Assertions.assertInstanceOf(SimpleData.class, list.get(0)); - Assertions.assertEquals("姓名0", ((SimpleData) list.get(0)).getName()); - } - - /** - * mock data - * - * @return {@link List }<{@link SimpleData }> - */ - private List data() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - SimpleData simpleData = new SimpleData(); - simpleData.setName("姓名" + i); - list.add(simpleData); - } - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/skip/SkipData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/skip/SkipData.java deleted file mode 100644 index c5370948a..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/skip/SkipData.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.skip; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -public class SkipData { - - @ExcelProperty("姓名") - private String name; -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/sort/SortDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/sort/SortDataListener.java deleted file mode 100644 index d0b895f46..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/sort/SortDataListener.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.sort; - -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class SortDataListener extends AnalysisEventListener { - - List list = new ArrayList(); - - @Override - public void invoke(SortData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(1, list.size()); - SortData sortData = list.get(0); - Assertions.assertEquals("column1", sortData.getColumn1()); - Assertions.assertEquals("column2", sortData.getColumn2()); - Assertions.assertEquals("column3", sortData.getColumn3()); - Assertions.assertEquals("column4", sortData.getColumn4()); - Assertions.assertEquals("column5", sortData.getColumn5()); - Assertions.assertEquals("column6", sortData.getColumn6()); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/sort/SortDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/sort/SortDataTest.java deleted file mode 100644 index 6e8890d3a..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/sort/SortDataTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.sort; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -/** - * - */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class SortDataTest { - - private static File file07; - private static File file03; - private static File fileCsv; - private static File sortNoHead07; - private static File sortNoHead03; - private static File sortNoHeadCsv; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("sort.xlsx"); - file03 = TestFileUtil.createNewFile("sort.xls"); - fileCsv = TestFileUtil.createNewFile("sort.csv"); - sortNoHead07 = TestFileUtil.createNewFile("sortNoHead.xlsx"); - sortNoHead03 = TestFileUtil.createNewFile("sortNoHead.xls"); - sortNoHeadCsv = TestFileUtil.createNewFile("sortNoHead.csv"); - } - - @Test - public void t01ReadAndWrite07() { - readAndWrite(file07); - } - - @Test - public void t02ReadAndWrite03() { - readAndWrite(file03); - } - - @Test - public void t03ReadAndWriteCsv() { - readAndWrite(fileCsv); - } - - @Test - public void t11ReadAndWriteNoHead07() { - readAndWriteNoHead(sortNoHead07); - } - - @Test - public void t12ReadAndWriteNoHead03() { - readAndWriteNoHead(sortNoHead03); - } - - @Test - public void t13ReadAndWriteNoHeadCsv() { - readAndWriteNoHead(sortNoHeadCsv); - } - - private void readAndWrite(File file) { - FesodSheet.write(file, SortData.class).sheet().doWrite(data()); - List> dataMap = FesodSheet.read(file).sheet().doReadSync(); - Assertions.assertEquals(1, dataMap.size()); - Map record = dataMap.get(0); - Assertions.assertEquals("column1", record.get(0)); - Assertions.assertEquals("column2", record.get(1)); - Assertions.assertEquals("column3", record.get(2)); - Assertions.assertEquals("column4", record.get(3)); - Assertions.assertEquals("column5", record.get(4)); - Assertions.assertEquals("column6", record.get(5)); - - FesodSheet.read(file, SortData.class, new SortDataListener()).sheet().doRead(); - } - - private void readAndWriteNoHead(File file) { - FesodSheet.write(file).head(head()).sheet().doWrite(data()); - List> dataMap = FesodSheet.read(file).sheet().doReadSync(); - Assertions.assertEquals(1, dataMap.size()); - Map record = dataMap.get(0); - Assertions.assertEquals("column1", record.get(0)); - Assertions.assertEquals("column2", record.get(1)); - Assertions.assertEquals("column3", record.get(2)); - Assertions.assertEquals("column4", record.get(3)); - Assertions.assertEquals("column5", record.get(4)); - Assertions.assertEquals("column6", record.get(5)); - FesodSheet.read(file, SortData.class, new SortDataListener()).sheet().doRead(); - } - - private List> head() { - List> head = new ArrayList>(); - head.add(Collections.singletonList("column1")); - head.add(Collections.singletonList("column2")); - head.add(Collections.singletonList("column3")); - head.add(Collections.singletonList("column4")); - head.add(Collections.singletonList("column5")); - head.add(Collections.singletonList("column6")); - return head; - } - - private List data() { - List list = new ArrayList(); - SortData sortData = new SortData(); - sortData.setColumn1("column1"); - sortData.setColumn2("column2"); - sortData.setColumn3("column3"); - sortData.setColumn4("column4"); - sortData.setColumn5("column5"); - sortData.setColumn6("column6"); - list.add(sortData); - return list; - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationData.java similarity index 89% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationData.java index 4357f028b..f27fd18bd 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationData.java @@ -23,12 +23,14 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.annotation; +package org.apache.fesod.sheet.style; import java.util.Date; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; +import org.apache.fesod.sheet.annotation.ExcelIgnore; +import org.apache.fesod.sheet.annotation.ExcelProperty; import org.apache.fesod.sheet.annotation.format.DateTimeFormat; import org.apache.fesod.sheet.annotation.format.NumberFormat; import org.apache.fesod.sheet.annotation.write.style.ColumnWidth; @@ -45,11 +47,11 @@ @HeadRowHeight(50) @ContentRowHeight(100) public class AnnotationData { - @ExcelProperty("日期") + @ExcelProperty("Date") @DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒") private Date date; - @ExcelProperty(value = "数字") + @ExcelProperty(value = "Number") @NumberFormat("#.##%") private Double number; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationDataTest.java new file mode 100644 index 000000000..ac859d5cc --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationDataTest.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.style; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.assertions.ExcelAssertions; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Test annotation write/read for all formats using parameterized tests. + */ +public class AnnotationDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile("annotation", format); + FesodSheet.write().file(file).head(AnnotationData.class).sheet().doWrite(dataStyle()); + + if (format != ExcelFormat.CSV) { + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + ea.sheet(0) + .hasColumnWidth(0, 50 * 256) + .row(0) + .hasHeight((short) 1000) + .and() + .row(1) + .hasHeight((short) 2000); + } + } + } + + @ParameterizedTest + @MethodSource("binaryFormats") + void writeStyle(ExcelFormat format) throws Exception { + Assumptions.assumeTrue(format.supportsStyles()); + File file = createTempFile("annotationStyle", format); + FesodSheet.write().file(file).head(AnnotationStyleData.class).sheet().doWrite(dataStyle()); + + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + ea.sheet(0) + .row(0) + .cell(0) + .hasFillColor(new byte[] {-1, 0, -1}) + .hasFontColor(new byte[] {-1, -52, 0}) + .hasFontSize((short) 40) + .and() + .cell(1) + .hasFillColor(new byte[] {-1, 0, 0}) + .hasFontColor(new byte[] {0, -1, -1}) + .hasFontSize((short) 20) + .and() + .and() + .row(1) + .cell(0) + .hasFillColor(new byte[] {0, -52, -1}) + .hasFontColor(new byte[] {0, 0, -1}) + .hasFontSize((short) 50) + .and() + .cell(1) + .hasFillColor(new byte[] {0, -128, 0}) + .hasFontColor(new byte[] {-64, -64, -64}) + .hasFontSize((short) 30); + } + } + + private List dataStyle() { + List list = new ArrayList<>(); + AnnotationStyleData data = new AnnotationStyleData(); + data.setString("string"); + data.setString1("string1"); + list.add(data); + return list; + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationIndexAndNameData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationIndexAndNameData.java similarity index 84% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationIndexAndNameData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationIndexAndNameData.java index 70bcaff9a..0fa9df4e9 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationIndexAndNameData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationIndexAndNameData.java @@ -23,11 +23,12 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.annotation; +package org.apache.fesod.sheet.style; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; +import org.apache.fesod.sheet.annotation.ExcelProperty; /** * @@ -36,15 +37,15 @@ @Setter @EqualsAndHashCode public class AnnotationIndexAndNameData { - @ExcelProperty(value = "第四个", index = 4) + @ExcelProperty(value = "FourthCol", index = 4) private String index4; - @ExcelProperty(value = "第二个") + @ExcelProperty(value = "SecondCol") private String index2; @ExcelProperty(index = 0) private String index0; - @ExcelProperty(value = "第一个", index = 1) + @ExcelProperty(value = "FirstCol", index = 1) private String index1; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationIndexAndNameDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationIndexAndNameDataTest.java new file mode 100644 index 000000000..256c6ca96 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationIndexAndNameDataTest.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.style; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import java.util.List; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Annotation index and name data test using parameterized tests. + */ +public class AnnotationIndexAndNameDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile("annotationIndexAndName", format); + FesodSheet.write(file, AnnotationIndexAndNameData.class) + .sheet() + .doWrite(TestDataBuilder.annotationIndexAndNameData(1)); + List result = FesodSheet.read(file) + .head(AnnotationIndexAndNameData.class) + .sheet() + .doReadSync(); + assertEquals(1, result.size()); + assertEquals("Item0", result.get(0).getIndex0()); + assertEquals("Item1", result.get(0).getIndex1()); + assertEquals("Item2", result.get(0).getIndex2()); + assertEquals("Item4", result.get(0).getIndex4()); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationStyleData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationStyleData.java similarity index 93% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationStyleData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationStyleData.java index 7d04932ea..e8918ec35 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/AnnotationStyleData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/AnnotationStyleData.java @@ -23,11 +23,12 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.annotation; +package org.apache.fesod.sheet.style; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; +import org.apache.fesod.sheet.annotation.ExcelProperty; import org.apache.fesod.sheet.annotation.write.style.ContentFontStyle; import org.apache.fesod.sheet.annotation.write.style.ContentStyle; import org.apache.fesod.sheet.annotation.write.style.HeadFontStyle; @@ -45,13 +46,13 @@ @ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 17) @ContentFontStyle(fontHeightInPoints = 30, color = 22) public class AnnotationStyleData { - @ExcelProperty("字符串") + @ExcelProperty("String") @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 14) @HeadFontStyle(fontHeightInPoints = 40, color = 51) @ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40) @ContentFontStyle(fontHeightInPoints = 50, color = 12) private String string; - @ExcelProperty("字符串1") + @ExcelProperty("String1") private String string1; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/ExcelPropertyFormatTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/ExcelPropertyFormatTest.java similarity index 98% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/ExcelPropertyFormatTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/style/ExcelPropertyFormatTest.java index 95a80b316..ca049d3eb 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/annotation/ExcelPropertyFormatTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/ExcelPropertyFormatTest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.annotation; +package org.apache.fesod.sheet.style; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -35,6 +35,7 @@ import lombok.Data; import org.apache.fesod.common.util.StringUtils; import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.annotation.ExcelProperty; import org.apache.fesod.sheet.annotation.format.DateTimeFormat; import org.apache.fesod.sheet.context.AnalysisContext; import org.apache.fesod.sheet.read.listener.ReadListener; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/annotation/FillAnnotationData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillAnnotationData.java similarity index 97% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/annotation/FillAnnotationData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillAnnotationData.java index c7e4d9c39..68d106ed0 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/annotation/FillAnnotationData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillAnnotationData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.fill.annotation; +package org.apache.fesod.sheet.style; import java.util.Date; import lombok.EqualsAndHashCode; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/annotation/FillAnnotationDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillAnnotationDataTest.java similarity index 71% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/annotation/FillAnnotationDataTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillAnnotationDataTest.java index a9dd6f9ae..c035f0c27 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/annotation/FillAnnotationDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillAnnotationDataTest.java @@ -23,13 +23,15 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.fill.annotation; +package org.apache.fesod.sheet.style; import java.io.File; -import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; import org.apache.fesod.sheet.util.DateUtils; import org.apache.fesod.sheet.util.TestFileUtil; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; @@ -46,48 +48,31 @@ import org.apache.poi.xssf.usermodel.XSSFShape; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; /** * */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class FillAnnotationDataTest { +public class FillAnnotationDataTest extends AbstractExcelTest { - private static File file07; - private static File file03; - private static File fileTemplate07; - private static File fileTemplate03; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("fillAnnotation07.xlsx"); - file03 = TestFileUtil.createNewFile("fillAnnotation03.xls"); - fileTemplate07 = TestFileUtil.readFile("fill" + File.separator + "annotation.xlsx"); - fileTemplate03 = TestFileUtil.readFile("fill" + File.separator + "annotation.xls"); - } - - @Test - public void t01ReadAndWrite07() throws Exception { - readAndWrite(file07, fileTemplate07); + @ParameterizedTest + @MethodSource("binaryFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile("fillAnnotation", format); + File fileTemplate = TestFileUtil.readFile("fill" + File.separator + "annotation" + format.getExtension()); + readAndWriteImpl(file, fileTemplate); } - @Test - public void t02ReadAndWrite03() throws Exception { - readAndWrite(file03, fileTemplate03); - } - - private void readAndWrite(File file, File fileTemplate) throws Exception { + private void readAndWriteImpl(File file, File fileTemplate) throws Exception { FesodSheet.write() .file(file) .head(FillAnnotationData.class) .withTemplate(fileTemplate) .sheet() - .doFill(data()); + .doFill(TestDataBuilder.fillAnnotationData( + 5, TestFileUtil.getPath() + "converter" + File.separator + "img.jpg")); try (Workbook workbook = WorkbookFactory.create(file)) { Sheet sheet = workbook.getSheetAt(0); @@ -133,20 +118,4 @@ private void readAndWrite(File file, File fileTemplate) throws Exception { } } } - - private List data() throws Exception { - List list = new ArrayList<>(); - FillAnnotationData data = new FillAnnotationData(); - data.setDate(DateUtils.parseDate("2020-01-01 01:01:01")); - data.setNumber(99.99); - data.setString1("string1"); - data.setString2("string2"); - data.setImage(TestFileUtil.getPath() + "converter" + File.separator + "img.jpg"); - list.add(data); - list.add(data); - list.add(data); - list.add(data); - list.add(data); - return list; - } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/FillData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillData.java similarity index 97% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/FillData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillData.java index 90fd6a101..1ca1bddea 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/FillData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.fill; +package org.apache.fesod.sheet.style; import lombok.EqualsAndHashCode; import lombok.Getter; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillDataTest.java new file mode 100644 index 000000000..537c94536 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillDataTest.java @@ -0,0 +1,201 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.style; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.fesod.sheet.ExcelWriter; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.enums.WriteDirectionEnum; +import org.apache.fesod.sheet.exception.ExcelGenerateException; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.util.TestFileUtil; +import org.apache.fesod.sheet.write.merge.LoopMergeStrategy; +import org.apache.fesod.sheet.write.metadata.WriteSheet; +import org.apache.fesod.sheet.write.metadata.fill.FillConfig; +import org.apache.fesod.sheet.write.metadata.fill.FillWrapper; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Test fill operations for all Excel formats using parameterized tests. + */ +public class FillDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("allFormats") + void simpleFill(ExcelFormat format) throws Exception { + File file = createTempFile("fill", format); + File template = TestFileUtil.readFile("fill" + File.separator + "simple" + format.getExtension()); + if (format == ExcelFormat.CSV) { + ExcelGenerateException ex = assertThrows(ExcelGenerateException.class, () -> fill(file, template)); + assertEquals("csv cannot use template.", ex.getMessage()); + } else { + fill(file, template); + } + } + + @ParameterizedTest + @MethodSource("binaryFormats") + void complexFill(ExcelFormat format) throws Exception { + Assumptions.assumeTrue(format.supportsTemplates()); + File file = createTempFile("fillComplex", format); + File template = TestFileUtil.readFile("fill" + File.separator + "complex" + format.getExtension()); + complexFillImpl(file, template); + } + + @ParameterizedTest + @MethodSource("binaryFormats") + void horizontalFill(ExcelFormat format) throws Exception { + Assumptions.assumeTrue(format.supportsTemplates()); + File file = createTempFile("fillHorizontal", format); + File template = TestFileUtil.readFile("fill" + File.separator + "horizontal" + format.getExtension()); + horizontalFillImpl(file, template); + } + + @ParameterizedTest + @MethodSource("binaryFormats") + void byNameFill(ExcelFormat format) throws Exception { + Assumptions.assumeTrue(format.supportsTemplates()); + File file = createTempFile("byName", format); + File template = TestFileUtil.readFile("fill" + File.separator + "byName" + format.getExtension()); + byNameFillImpl(file, template); + } + + @ParameterizedTest + @MethodSource("binaryFormats") + void compositeFill(ExcelFormat format) throws Exception { + Assumptions.assumeTrue(format.supportsTemplates()); + File file = createTempFile("composite", format); + File template = TestFileUtil.readFile("fill" + File.separator + "composite" + format.getExtension()); + compositeFillImpl(file, template); + } + + private void byNameFillImpl(File file, File template) { + FillData fillData = new FillData(); + fillData.setName("Zhang San"); + fillData.setNumber(5.2); + FesodSheet.write(file, FillData.class) + .withTemplate(template) + .sheet("Sheet2") + .doFill(fillData); + } + + @SuppressWarnings("unchecked") + private void compositeFillImpl(File file, File template) { + try (ExcelWriter excelWriter = + FesodSheet.write(file).withTemplate(template).build()) { + WriteSheet writeSheet = FesodSheet.writerSheet().build(); + + FillConfig fillConfig = FillConfig.builder() + .direction(WriteDirectionEnum.HORIZONTAL) + .build(); + excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); + excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); + excelWriter.fill(new FillWrapper("data2", data()), writeSheet); + excelWriter.fill(new FillWrapper("data2", data()), writeSheet); + excelWriter.fill(new FillWrapper("data3", data()), writeSheet); + excelWriter.fill(new FillWrapper("data3", data()), writeSheet); + Map map = new HashMap(); + map.put("date", "2019-10-09 13:28:28"); + excelWriter.fill(map, writeSheet); + } + + List list = FesodSheet.read(file) + .ignoreEmptyRow(false) + .sheet() + .headRowNumber(0) + .doReadSync(); + Map map0 = (Map) list.get(0); + assertEquals("Zhang San", map0.get(21)); + Map map27 = (Map) list.get(27); + assertEquals("Zhang San", map27.get(0)); + Map map29 = (Map) list.get(29); + assertEquals("Zhang San", map29.get(3)); + } + + @SuppressWarnings("unchecked") + private void horizontalFillImpl(File file, File template) { + try (ExcelWriter excelWriter = + FesodSheet.write(file).withTemplate(template).build()) { + WriteSheet writeSheet = FesodSheet.writerSheet().build(); + FillConfig fillConfig = FillConfig.builder() + .direction(WriteDirectionEnum.HORIZONTAL) + .build(); + excelWriter.fill(data(), fillConfig, writeSheet); + excelWriter.fill(data(), fillConfig, writeSheet); + Map map = new HashMap(); + map.put("date", "2019-10-09 13:28:28"); + excelWriter.fill(map, writeSheet); + excelWriter.finish(); + } + + List list = FesodSheet.read(file).sheet().headRowNumber(0).doReadSync(); + assertEquals(5L, list.size()); + Map map0 = (Map) list.get(0); + assertEquals("Zhang San", map0.get(2)); + } + + @SuppressWarnings("unchecked") + private void complexFillImpl(File file, File template) { + try (ExcelWriter excelWriter = + FesodSheet.write(file).withTemplate(template).build()) { + WriteSheet writeSheet = FesodSheet.writerSheet() + .registerWriteHandler(new LoopMergeStrategy(2, 0)) + .build(); + FillConfig fillConfig = + FillConfig.builder().forceNewRow(Boolean.TRUE).build(); + excelWriter.fill(data(), fillConfig, writeSheet); + excelWriter.fill(data(), fillConfig, writeSheet); + Map map = new HashMap(); + map.put("date", "2019-10-09 13:28:28"); + map.put("total", 1000); + excelWriter.fill(map, writeSheet); + } + List list = FesodSheet.read(file).sheet().headRowNumber(3).doReadSync(); + assertEquals(21L, list.size()); + Map map19 = (Map) list.get(19); + assertEquals("Zhang San", map19.get(0)); + } + + private void fill(File file, File template) { + FillData fillData = new FillData(); + fillData.setName("Zhang San"); + fillData.setNumber(5.2); + FesodSheet.write(file, FillData.class).withTemplate(template).sheet().doFill(fillData); + } + + private List data() { + return TestDataBuilder.fillData(10); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleAnnotatedData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleAnnotatedData.java similarity index 98% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleAnnotatedData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleAnnotatedData.java index 1358bdda1..2eef1ac58 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleAnnotatedData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleAnnotatedData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.fill.style; +package org.apache.fesod.sheet.style; import java.util.Date; import lombok.EqualsAndHashCode; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleAnnotatedTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleAnnotatedTest.java similarity index 87% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleAnnotatedTest.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleAnnotatedTest.java index 7643c3565..eef77ac31 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleAnnotatedTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleAnnotatedTest.java @@ -23,15 +23,15 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.fill.style; +package org.apache.fesod.sheet.style; import java.io.File; import java.io.FileInputStream; -import java.util.List; -import org.apache.fesod.common.util.ListUtils; import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.fill.FillData; import org.apache.fesod.sheet.metadata.Head; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; import org.apache.fesod.sheet.util.DateUtils; import org.apache.fesod.sheet.util.TestFileUtil; import org.apache.fesod.sheet.write.handler.context.CellWriteHandlerContext; @@ -49,40 +49,36 @@ import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class FillStyleAnnotatedTest { - - private static File FillStyleAnnotated07; - private static File FillStyleAnnotated03; - private static File fileStyleTemplate07; - private static File fileStyleTemplate03; - - @BeforeAll - public static void init() { - FillStyleAnnotated07 = TestFileUtil.createNewFile("FillStyleAnnotated07.xlsx"); - FillStyleAnnotated03 = TestFileUtil.createNewFile("FillStyleAnnotated03.xls"); - fileStyleTemplate07 = TestFileUtil.readFile("fill" + File.separator + "style.xlsx"); - fileStyleTemplate03 = TestFileUtil.readFile("fill" + File.separator + "style.xls"); - } - - @Test - public void t01Fill07() throws Exception { - fill(FillStyleAnnotated07, fileStyleTemplate07); - XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(FillStyleAnnotated07)); - XSSFSheet sheet = workbook.getSheetAt(0); - t01Fill07check(sheet.getRow(1)); - t01Fill07check(sheet.getRow(2)); +public class FillStyleAnnotatedTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("binaryFormats") + void fill(ExcelFormat format) throws Exception { + File file = createTempFile("FillStyleAnnotated", format); + File template = TestFileUtil.readFile("fill" + File.separator + "style" + format.getExtension()); + fill(file, template); + if (format == ExcelFormat.XLSX) { + try (XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file))) { + XSSFSheet sheet = workbook.getSheetAt(0); + fillXlsxCheck(sheet.getRow(1)); + fillXlsxCheck(sheet.getRow(2)); + } + } else { + try (HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file))) { + HSSFSheet sheet = workbook.getSheetAt(0); + fillXlsCheck(workbook, sheet.getRow(1)); + fillXlsCheck(workbook, sheet.getRow(2)); + } + } } - private void t01Fill07check(XSSFRow row) { + private void fillXlsxCheck(XSSFRow row) { XSSFCell cell0 = row.getCell(0); Assertions.assertEquals("Zhang San", cell0.getStringCellValue()); Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat()); @@ -139,16 +135,7 @@ private void t01Fill07check(XSSFRow row) { Assertions.assertFalse(cell5.getCellStyle().getFont().getBold()); } - @Test - public void t02Fill03() throws Exception { - fill(FillStyleAnnotated03, fileStyleTemplate03); - HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(FillStyleAnnotated03)); - HSSFSheet sheet = workbook.getSheetAt(0); - t02Fill03check(workbook, sheet.getRow(1)); - t02Fill03check(workbook, sheet.getRow(2)); - } - - private void t02Fill03check(HSSFWorkbook workbook, HSSFRow row) { + private void fillXlsCheck(HSSFWorkbook workbook, HSSFRow row) { HSSFCell cell0 = row.getCell(0); Assertions.assertEquals("Zhang San", cell0.getStringCellValue()); Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat()); @@ -218,10 +205,10 @@ private void fill(File file, File template) throws Exception { FesodSheet.write(file, FillStyleAnnotatedData.class) .withTemplate(template) .sheet() - .doFill(data()); + .doFill(TestDataBuilder.fillStyleAnnotatedData(10)); } - private void t11FillStyleHandler07check(XSSFRow row) { + private void fillStyleHandlerXlsxCheck(XSSFRow row) { XSSFCell cell0 = row.getCell(0); Assertions.assertEquals("Zhang San", cell0.getStringCellValue()); Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat()); @@ -278,7 +265,7 @@ private void t11FillStyleHandler07check(XSSFRow row) { Assertions.assertTrue(cell5.getCellStyle().getFont().getBold()); } - private void t12FillStyleHandler03check(HSSFWorkbook workbook, HSSFRow row) { + private void fillStyleHandlerXlsCheck(HSSFWorkbook workbook, HSSFRow row) { HSSFCell cell0 = row.getCell(0); Assertions.assertEquals("Zhang San", cell0.getStringCellValue()); Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat()); @@ -389,21 +376,6 @@ protected WriteCellStyle headCellStyle(Head head) { return null; } }) - .doFill(data()); - } - - private List data() throws Exception { - List list = ListUtils.newArrayList(); - for (int i = 0; i < 10; i++) { - FillStyleAnnotatedData fillData = new FillStyleAnnotatedData(); - list.add(fillData); - fillData.setName("Zhang San"); - fillData.setNumber(5.2); - fillData.setDate(DateUtils.parseDate("2020-01-01 01:01:01")); - if (i == 5) { - fillData.setName(null); - } - } - return list; + .doFill(TestDataBuilder.fillStyleAnnotatedData(10)); } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleData.java similarity index 96% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleData.java index 26de0de24..09d31c1d6 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/fill/style/FillStyleData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleData.java @@ -23,7 +23,7 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.fill.style; +package org.apache.fesod.sheet.style; import java.util.Date; import lombok.EqualsAndHashCode; diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleDataTest.java new file mode 100644 index 000000000..371720bf0 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/FillStyleDataTest.java @@ -0,0 +1,486 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. + * + * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. + */ + +package org.apache.fesod.sheet.style; + +import java.io.File; +import java.io.FileInputStream; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.metadata.Head; +import org.apache.fesod.sheet.testkit.assertions.ExcelAssertions; +import org.apache.fesod.sheet.testkit.assertions.RowAssert; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.util.DateUtils; +import org.apache.fesod.sheet.util.TestFileUtil; +import org.apache.fesod.sheet.write.handler.context.CellWriteHandlerContext; +import org.apache.fesod.sheet.write.metadata.style.WriteCellStyle; +import org.apache.fesod.sheet.write.metadata.style.WriteFont; +import org.apache.fesod.sheet.write.style.AbstractVerticalCellStyleStrategy; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.FillPatternType; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * + */ +public class FillStyleDataTest extends AbstractExcelTest { + + @ParameterizedTest + @MethodSource("binaryFormats") + void fill(ExcelFormat format) throws Exception { + File file = createTempFile("fileStyle", format); + File template = TestFileUtil.readFile("fill" + File.separator + "style" + format.getExtension()); + fill(file, template); + try (ExcelAssertions workbook = ExcelAssertions.assertThat(file)) { + if (format == ExcelFormat.XLSX) { + fillXlsxCheck(workbook.sheet(0).row(1)); + fillXlsxCheck(workbook.sheet(0).row(2)); + } else { + fillXlsCheck(workbook.sheet(0).row(1)); + fillXlsCheck(workbook.sheet(0).row(2)); + } + } + } + + private void fillXlsxCheck(RowAssert row) { + row.cell(0) + .hasStringValue("Zhang San") + .hasDataFormat(49) + .hasBoldFont(true) + .satisfies(cell -> { + XSSFCell xssfCell = (XSSFCell) cell; + Assertions.assertEquals( + "FF00B050", + xssfCell.getCellStyle() + .getFillForegroundColorColor() + .getARGBHex()); + Assertions.assertEquals( + "FF7030A0", + xssfCell.getCellStyle().getFont().getXSSFColor().getARGBHex()); + }); + + row.cell(1) + .satisfies(cell -> Assertions.assertEquals(5.2, cell.getNumericCellValue(), 1)) + .hasDataFormat(0) + .hasBoldFont(false) + .satisfies(cell -> { + XSSFCell xssfCell = (XSSFCell) cell; + Assertions.assertEquals( + "FF92D050", + xssfCell.getCellStyle() + .getFillForegroundColorColor() + .getARGBHex()); + Assertions.assertEquals( + "FF4BACC6", + xssfCell.getCellStyle().getFont().getXSSFColor().getARGBHex()); + }); + + row.cell(2) + .satisfies(cell -> Assertions.assertEquals( + "2020-01-01 01:01:01", DateUtils.format(cell.getDateCellValue(), "yyyy-MM-dd HH:mm:ss"))) + .hasDataFormatString("yyyy-MM-dd HH:mm:ss") + .hasBoldFont(true) + .satisfies(cell -> { + XSSFCell xssfCell = (XSSFCell) cell; + Assertions.assertEquals( + "FFFFC000", + xssfCell.getCellStyle() + .getFillForegroundColorColor() + .getARGBHex()); + Assertions.assertEquals( + "FFC0504D", + xssfCell.getCellStyle().getFont().getXSSFColor().getARGBHex()); + }); + + row.cell(3) + .hasStringValue("Zhang San is 5.2 years old this year") + .hasDataFormat(0) + .hasBoldFont(true) + .satisfies(cell -> { + XSSFCell xssfCell = (XSSFCell) cell; + Assertions.assertEquals( + "FFFF0000", + xssfCell.getCellStyle() + .getFillForegroundColorColor() + .getARGBHex()); + Assertions.assertEquals( + "FFEEECE1", + xssfCell.getCellStyle().getFont().getXSSFColor().getARGBHex()); + }); + + row.cell(4) + .hasStringValue("{.name} ignored,Zhang San") + .hasDataFormat(0) + .hasBoldFont(false) + .satisfies(cell -> { + XSSFCell xssfCell = (XSSFCell) cell; + Assertions.assertEquals( + "FFC00000", + xssfCell.getCellStyle() + .getFillForegroundColorColor() + .getARGBHex()); + Assertions.assertEquals( + "FF000000", + xssfCell.getCellStyle().getFont().getXSSFColor().getARGBHex()); + }); + + row.cell(5).hasStringValue("Empty").hasDataFormat(0).hasBoldFont(false).satisfies(cell -> { + XSSFCell xssfCell = (XSSFCell) cell; + Assertions.assertEquals( + "FFF79646", + xssfCell.getCellStyle().getFillForegroundColorColor().getARGBHex()); + Assertions.assertEquals( + "FF8064A2", xssfCell.getCellStyle().getFont().getXSSFColor().getARGBHex()); + }); + } + + private void fillXlsCheck(RowAssert row) { + row.cell(0) + .hasStringValue("Zhang San") + .hasDataFormat(49) + .hasBoldFont(true) + .satisfies(cell -> { + HSSFCell hssfCell = (HSSFCell) cell; + HSSFWorkbook workbook = (HSSFWorkbook) hssfCell.getSheet().getWorkbook(); + Assertions.assertEquals( + "0:8080:0", + hssfCell.getCellStyle() + .getFillForegroundColorColor() + .getHexString()); + Assertions.assertEquals( + "8080:0:8080", + hssfCell.getCellStyle() + .getFont(workbook) + .getHSSFColor(workbook) + .getHexString()); + }); + + row.cell(1) + .satisfies(cell -> Assertions.assertEquals(5.2, cell.getNumericCellValue(), 1)) + .hasDataFormat(0) + .hasBoldFont(false) + .satisfies(cell -> { + HSSFCell hssfCell = (HSSFCell) cell; + HSSFWorkbook workbook = (HSSFWorkbook) hssfCell.getSheet().getWorkbook(); + Assertions.assertEquals( + "9999:CCCC:0", + hssfCell.getCellStyle() + .getFillForegroundColorColor() + .getHexString()); + Assertions.assertEquals( + "0:8080:8080", + hssfCell.getCellStyle() + .getFont(workbook) + .getHSSFColor(workbook) + .getHexString()); + }); + + row.cell(2) + .satisfies(cell -> Assertions.assertEquals( + "2020-01-01 01:01:01", DateUtils.format(cell.getDateCellValue(), "yyyy-MM-dd HH:mm:ss"))) + .hasDataFormatString("yyyy-MM-dd HH:mm:ss") + .hasBoldFont(true) + .satisfies(cell -> { + HSSFCell hssfCell = (HSSFCell) cell; + HSSFWorkbook workbook = (HSSFWorkbook) hssfCell.getSheet().getWorkbook(); + Assertions.assertEquals( + "FFFF:CCCC:0", + hssfCell.getCellStyle() + .getFillForegroundColorColor() + .getHexString()); + Assertions.assertEquals( + "8080:0:0", + hssfCell.getCellStyle() + .getFont(workbook) + .getHSSFColor(workbook) + .getHexString()); + }); + + row.cell(3) + .hasStringValue("Zhang San is 5.2 years old this year") + .hasDataFormat(0) + .hasBoldFont(true) + .satisfies(cell -> { + HSSFCell hssfCell = (HSSFCell) cell; + HSSFWorkbook workbook = (HSSFWorkbook) hssfCell.getSheet().getWorkbook(); + Assertions.assertEquals( + "FFFF:0:0", + hssfCell.getCellStyle() + .getFillForegroundColorColor() + .getHexString()); + Assertions.assertEquals( + "FFFF:FFFF:9999", + hssfCell.getCellStyle() + .getFont(workbook) + .getHSSFColor(workbook) + .getHexString()); + }); + + row.cell(4) + .hasStringValue("{.name} ignored,Zhang San") + .hasDataFormat(0) + .hasBoldFont(false) + .satisfies(cell -> { + HSSFCell hssfCell = (HSSFCell) cell; + HSSFWorkbook workbook = (HSSFWorkbook) hssfCell.getSheet().getWorkbook(); + Assertions.assertEquals( + "9999:3333:0", + hssfCell.getCellStyle() + .getFillForegroundColorColor() + .getHexString()); + Assertions.assertEquals( + "3333:3333:3333", + hssfCell.getCellStyle() + .getFont(workbook) + .getHSSFColor(workbook) + .getHexString()); + }); + + row.cell(5).hasStringValue("Empty").hasDataFormat(0).hasBoldFont(false).satisfies(cell -> { + HSSFCell hssfCell = (HSSFCell) cell; + HSSFWorkbook workbook = (HSSFWorkbook) hssfCell.getSheet().getWorkbook(); + Assertions.assertEquals( + "9999:3333:0", + hssfCell.getCellStyle().getFillForegroundColorColor().getHexString()); + Assertions.assertEquals( + "CCCC:9999:FFFF", + hssfCell.getCellStyle() + .getFont(workbook) + .getHSSFColor(workbook) + .getHexString()); + }); + } + + private void fill(File file, File template) throws Exception { + FesodSheet.write(file, FillStyleData.class) + .withTemplate(template) + .sheet() + .doFill(TestDataBuilder.fillStyleData(10)); + } + + @ParameterizedTest + @MethodSource("binaryFormats") + void fillStyleHandler(ExcelFormat format) throws Exception { + File file = createTempFile("fileStyleHandler", format); + File template = TestFileUtil.readFile("fill" + File.separator + "style" + format.getExtension()); + fillStyleHandler(file, template); + if (format == ExcelFormat.XLSX) { + try (XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file))) { + XSSFSheet sheet = workbook.getSheetAt(0); + fillStyleHandlerXlsxCheck(sheet.getRow(1)); + fillStyleHandlerXlsxCheck(sheet.getRow(2)); + } + } else { + try (HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file))) { + HSSFSheet sheet = workbook.getSheetAt(0); + fillStyleHandlerXlsCheck(workbook, sheet.getRow(1)); + fillStyleHandlerXlsCheck(workbook, sheet.getRow(2)); + } + } + } + + private void fillStyleHandlerXlsxCheck(XSSFRow row) { + XSSFCell cell0 = row.getCell(0); + Assertions.assertEquals("Zhang San", cell0.getStringCellValue()); + Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat()); + Assertions.assertEquals( + "FFFFFF00", cell0.getCellStyle().getFillForegroundColorColor().getARGBHex()); + Assertions.assertEquals( + "FF808000", cell0.getCellStyle().getFont().getXSSFColor().getARGBHex()); + Assertions.assertTrue(cell0.getCellStyle().getFont().getBold()); + + XSSFCell cell1 = row.getCell(1); + Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1); + Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat()); + Assertions.assertEquals( + "FFFF0000", cell1.getCellStyle().getFillForegroundColorColor().getARGBHex()); + Assertions.assertEquals( + "FF800000", cell1.getCellStyle().getFont().getXSSFColor().getARGBHex()); + Assertions.assertTrue(cell1.getCellStyle().getFont().getBold()); + + XSSFCell cell2 = row.getCell(2); + Assertions.assertEquals( + "2020-01-01 01:01:01", DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss")); + Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString()); + Assertions.assertEquals( + "FF008000", cell2.getCellStyle().getFillForegroundColorColor().getARGBHex()); + Assertions.assertEquals( + "FF003300", cell2.getCellStyle().getFont().getXSSFColor().getARGBHex()); + Assertions.assertTrue(cell2.getCellStyle().getFont().getBold()); + + XSSFCell cell3 = row.getCell(3); + Assertions.assertEquals("Zhang San is 5.2 years old this year", cell3.getStringCellValue()); + Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat()); + Assertions.assertEquals( + "FFFF0000", cell3.getCellStyle().getFillForegroundColorColor().getARGBHex()); + Assertions.assertEquals( + "FFEEECE1", cell3.getCellStyle().getFont().getXSSFColor().getARGBHex()); + Assertions.assertTrue(cell3.getCellStyle().getFont().getBold()); + + XSSFCell cell4 = row.getCell(4); + Assertions.assertEquals("{.name} ignored,Zhang San", cell4.getStringCellValue()); + Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat()); + Assertions.assertEquals( + "FFC00000", cell4.getCellStyle().getFillForegroundColorColor().getARGBHex()); + Assertions.assertEquals( + "FF000000", cell4.getCellStyle().getFont().getXSSFColor().getARGBHex()); + Assertions.assertFalse(cell4.getCellStyle().getFont().getBold()); + + XSSFCell cell5 = row.getCell(5); + Assertions.assertEquals("Empty", cell5.getStringCellValue()); + Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat()); + Assertions.assertEquals( + "FFF79646", cell5.getCellStyle().getFillForegroundColorColor().getARGBHex()); + Assertions.assertEquals( + "FF8064A2", cell5.getCellStyle().getFont().getXSSFColor().getARGBHex()); + Assertions.assertFalse(cell5.getCellStyle().getFont().getBold()); + } + + private void fillStyleHandlerXlsCheck(HSSFWorkbook workbook, HSSFRow row) { + HSSFCell cell0 = row.getCell(0); + Assertions.assertEquals("Zhang San", cell0.getStringCellValue()); + Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat()); + Assertions.assertEquals( + "FFFF:FFFF:0", + cell0.getCellStyle().getFillForegroundColorColor().getHexString()); + Assertions.assertEquals( + "8080:8080:0", + cell0.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); + Assertions.assertTrue(cell0.getCellStyle().getFont(workbook).getBold()); + + HSSFCell cell1 = row.getCell(1); + Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1); + Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat()); + Assertions.assertEquals( + "FFFF:0:0", cell1.getCellStyle().getFillForegroundColorColor().getHexString()); + Assertions.assertEquals( + "8080:0:0", + cell1.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); + Assertions.assertTrue(cell1.getCellStyle().getFont(workbook).getBold()); + + HSSFCell cell2 = row.getCell(2); + Assertions.assertEquals( + "2020-01-01 01:01:01", DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss")); + Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString()); + Assertions.assertEquals( + "0:8080:0", cell2.getCellStyle().getFillForegroundColorColor().getHexString()); + Assertions.assertEquals( + "0:3333:0", + cell2.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); + Assertions.assertTrue(cell2.getCellStyle().getFont(workbook).getBold()); + + HSSFCell cell3 = row.getCell(3); + Assertions.assertEquals("Zhang San is 5.2 years old this year", cell3.getStringCellValue()); + Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat()); + Assertions.assertEquals( + "FFFF:0:0", cell3.getCellStyle().getFillForegroundColorColor().getHexString()); + Assertions.assertEquals( + "FFFF:FFFF:9999", + cell3.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); + Assertions.assertTrue(cell3.getCellStyle().getFont(workbook).getBold()); + + HSSFCell cell4 = row.getCell(4); + Assertions.assertEquals("{.name} ignored,Zhang San", cell4.getStringCellValue()); + Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat()); + Assertions.assertEquals( + "9999:3333:0", + cell4.getCellStyle().getFillForegroundColorColor().getHexString()); + Assertions.assertEquals( + "3333:3333:3333", + cell4.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); + Assertions.assertFalse(cell4.getCellStyle().getFont(workbook).getBold()); + + HSSFCell cell5 = row.getCell(5); + Assertions.assertEquals("Empty", cell5.getStringCellValue()); + Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat()); + Assertions.assertEquals( + "9999:3333:0", + cell5.getCellStyle().getFillForegroundColorColor().getHexString()); + Assertions.assertEquals( + "CCCC:9999:FFFF", + cell5.getCellStyle().getFont(workbook).getHSSFColor(workbook).getHexString()); + Assertions.assertFalse(cell5.getCellStyle().getFont(workbook).getBold()); + } + + private void fillStyleHandler(File file, File template) throws Exception { + FesodSheet.write(file, FillStyleData.class) + .withTemplate(template) + .sheet() + .registerWriteHandler(new AbstractVerticalCellStyleStrategy() { + + @Override + protected WriteCellStyle contentCellStyle(CellWriteHandlerContext context) { + WriteCellStyle writeCellStyle = new WriteCellStyle(); + WriteFont writeFont = new WriteFont(); + writeCellStyle.setWriteFont(writeFont); + writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); + writeFont.setBold(true); + if (context.getColumnIndex() == 0) { + writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); + writeFont.setColor(IndexedColors.DARK_YELLOW.getIndex()); + } + if (context.getColumnIndex() == 1) { + writeCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); + writeFont.setColor(IndexedColors.DARK_RED.getIndex()); + } + if (context.getColumnIndex() == 2) { + writeCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); + writeFont.setColor(IndexedColors.DARK_GREEN.getIndex()); + } + if (context.getColumnIndex() == 3) { + writeCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex()); + writeFont.setColor(IndexedColors.DARK_BLUE.getIndex()); + } + if (context.getColumnIndex() == 4) { + writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); + writeFont.setColor(IndexedColors.DARK_YELLOW.getIndex()); + } + if (context.getColumnIndex() == 5) { + writeCellStyle.setFillForegroundColor(IndexedColors.TEAL.getIndex()); + writeFont.setColor(IndexedColors.DARK_TEAL.getIndex()); + } + return writeCellStyle; + } + + @Override + protected WriteCellStyle headCellStyle(Head head) { + return null; + } + }) + .doFill(TestDataBuilder.fillStyleData(10)); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/StyleData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/StyleData.java index 95c57da09..74798cc05 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/StyleData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/StyleData.java @@ -41,9 +41,9 @@ @HeadStyle @HeadFontStyle public class StyleData { - @ExcelProperty("字符串") + @ExcelProperty("String") private String string; - @ExcelProperty("字符串1") + @ExcelProperty("String1") private String string1; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/StyleDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/StyleDataListener.java deleted file mode 100644 index 68b08d670..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/StyleDataListener.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.style; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class StyleDataListener extends AnalysisEventListener { - List list = new ArrayList(); - - @Override - public void invoke(StyleData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(2, list.size()); - Assertions.assertEquals("字符串0", list.get(0).getString()); - Assertions.assertEquals("字符串1", list.get(1).getString()); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/StyleDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/StyleDataTest.java index e972677fc..3d8fbc422 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/StyleDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/style/StyleDataTest.java @@ -25,8 +25,8 @@ package org.apache.fesod.sheet.style; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; -import java.util.ArrayList; import java.util.List; import org.apache.fesod.sheet.FesodSheet; import org.apache.fesod.sheet.annotation.write.style.HeadFontStyle; @@ -35,8 +35,10 @@ import org.apache.fesod.sheet.metadata.data.DataFormatData; import org.apache.fesod.sheet.metadata.property.FontProperty; import org.apache.fesod.sheet.metadata.property.StyleProperty; -import org.apache.fesod.sheet.util.StyleTestUtils; -import org.apache.fesod.sheet.util.TestFileUtil; +import org.apache.fesod.sheet.testkit.assertions.ExcelAssertions; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; import org.apache.fesod.sheet.write.merge.LoopMergeStrategy; import org.apache.fesod.sheet.write.merge.OnceAbsoluteMergeStrategy; import org.apache.fesod.sheet.write.metadata.style.WriteCellStyle; @@ -46,55 +48,30 @@ import org.apache.fesod.sheet.write.style.column.SimpleColumnWidthStyleStrategy; import org.apache.fesod.sheet.write.style.row.SimpleRowHeightStyleStrategy; import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** - * + * Test style write/read for binary Excel formats using parameterized tests. */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class StyleDataTest { - - private static File file07; - private static File file03; - private static File fileVerticalCellStyleStrategy07; - private static File fileVerticalCellStyleStrategy207; - private static File fileLoopMergeStrategy; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("style07.xlsx"); - file03 = TestFileUtil.createNewFile("style03.xls"); - fileVerticalCellStyleStrategy07 = TestFileUtil.createNewFile("verticalCellStyle.xlsx"); - fileVerticalCellStyleStrategy207 = TestFileUtil.createNewFile("verticalCellStyle2.xlsx"); - fileLoopMergeStrategy = TestFileUtil.createNewFile("loopMergeStrategy.xlsx"); - } - - @Test - public void t01ReadAndWrite07() throws Exception { - readAndWrite(file07); - } +public class StyleDataTest extends AbstractExcelTest { - @Test - public void t02ReadAndWrite03() throws Exception { - readAndWrite(file03); + @ParameterizedTest + @MethodSource("binaryFormats") + void readAndWrite(ExcelFormat format) throws Exception { + File file = createTempFile("style", format); + readAndWriteImpl(file); } @Test - public void t03AbstractVerticalCellStyleStrategy() { + void abstractVerticalCellStyleStrategy() throws Exception { + File file = createTempFile("verticalCellStyle", ExcelFormat.XLSX); AbstractVerticalCellStyleStrategy verticalCellStyleStrategy = new AbstractVerticalCellStyleStrategy() { @Override protected WriteCellStyle headCellStyle(Head head) { @@ -149,14 +126,15 @@ protected WriteCellStyle contentCellStyle(Head head) { return writeCellStyle; } }; - FesodSheet.write(fileVerticalCellStyleStrategy07, StyleData.class) + FesodSheet.write(file, StyleData.class) .registerWriteHandler(verticalCellStyleStrategy) .sheet() - .doWrite(data()); + .doWrite(TestDataBuilder.styleData(2)); } @Test - public void t04AbstractVerticalCellStyleStrategy02() { + void abstractVerticalCellStyleStrategy02() throws Exception { + File file = createTempFile("verticalCellStyle2", ExcelFormat.XLSX); final StyleProperty styleProperty = StyleProperty.build(StyleData.class.getAnnotation(HeadStyle.class)); final FontProperty fontProperty = FontProperty.build(StyleData.class.getAnnotation(HeadFontStyle.class)); AbstractVerticalCellStyleStrategy verticalCellStyleStrategy = new AbstractVerticalCellStyleStrategy() { @@ -191,21 +169,22 @@ protected WriteCellStyle contentCellStyle(Head head) { return writeCellStyle; } }; - FesodSheet.write(fileVerticalCellStyleStrategy207, StyleData.class) + FesodSheet.write(file, StyleData.class) .registerWriteHandler(verticalCellStyleStrategy) .sheet() - .doWrite(data()); + .doWrite(TestDataBuilder.styleData(2)); } @Test - public void t05LoopMergeStrategy() { - FesodSheet.write(fileLoopMergeStrategy, StyleData.class) + void loopMergeStrategy() throws Exception { + File file = createTempFile("loopMergeStrategy", ExcelFormat.XLSX); + FesodSheet.write(file, StyleData.class) .sheet() .registerWriteHandler(new LoopMergeStrategy(2, 1)) - .doWrite(data10()); + .doWrite(TestDataBuilder.styleData(10)); } - private void readAndWrite(File file) throws Exception { + private void readAndWriteImpl(File file) { SimpleColumnWidthStyleStrategy simpleColumnWidthStyleStrategy = new SimpleColumnWidthStyleStrategy(50); SimpleRowHeightStyleStrategy simpleRowHeightStyleStrategy = new SimpleRowHeightStyleStrategy((short) 40, (short) 50); @@ -233,58 +212,41 @@ private void readAndWrite(File file) throws Exception { .registerWriteHandler(horizontalCellStyleStrategy) .registerWriteHandler(onceAbsoluteMergeStrategy) .sheet() - .doWrite(data()); - FesodSheet.read(file, StyleData.class, new StyleDataListener()).sheet().doRead(); - - Workbook workbook = WorkbookFactory.create(file); - Sheet sheet = workbook.getSheetAt(0); - Assertions.assertEquals(50 * 256, sheet.getColumnWidth(0), 0); - - Row row0 = sheet.getRow(0); - Assertions.assertEquals(800, row0.getHeight(), 0); - Cell cell00 = row0.getCell(0); - Assertions.assertArrayEquals(new byte[] {-1, -1, 0}, StyleTestUtils.getFillForegroundColor(cell00)); - Assertions.assertArrayEquals(new byte[] {-128, -128, 0}, StyleTestUtils.getFontColor(cell00, workbook)); - Assertions.assertEquals(20, StyleTestUtils.getFontHeightInPoints(cell00, workbook)); - - Cell cell01 = row0.getCell(1); - Assertions.assertArrayEquals(new byte[] {-1, -1, 0}, StyleTestUtils.getFillForegroundColor(cell01)); - Assertions.assertArrayEquals(new byte[] {-128, -128, 0}, StyleTestUtils.getFontColor(cell01, workbook)); - Assertions.assertEquals(20, StyleTestUtils.getFontHeightInPoints(cell01, workbook)); - - Row row1 = sheet.getRow(1); - Assertions.assertEquals(1000, row1.getHeight(), 0); - Cell cell10 = row1.getCell(0); - Assertions.assertArrayEquals(new byte[] {0, -128, -128}, StyleTestUtils.getFillForegroundColor(cell10)); - Assertions.assertArrayEquals(new byte[] {0, 51, 102}, StyleTestUtils.getFontColor(cell10, workbook)); - Assertions.assertEquals(30, StyleTestUtils.getFontHeightInPoints(cell10, workbook)); - Cell cell11 = row1.getCell(1); - Assertions.assertArrayEquals(new byte[] {0, -128, -128}, StyleTestUtils.getFillForegroundColor(cell11)); - Assertions.assertArrayEquals(new byte[] {0, 51, 102}, StyleTestUtils.getFontColor(cell11, workbook)); - Assertions.assertEquals(30, StyleTestUtils.getFontHeightInPoints(cell11, workbook)); - } - - private List data() { - List list = new ArrayList(); - StyleData data = new StyleData(); - data.setString("字符串0"); - data.setString1("字符串01"); - StyleData data1 = new StyleData(); - data1.setString("字符串1"); - data1.setString1("字符串11"); - list.add(data); - list.add(data1); - return list; - } - - private List data10() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - StyleData data = new StyleData(); - data.setString("字符串0"); - data.setString1("字符串01"); - list.add(data); + .doWrite(TestDataBuilder.styleData(2)); + + List result = + FesodSheet.read(file).head(StyleData.class).sheet().doReadSync(); + assertEquals(2, result.size()); + assertEquals("String0", result.get(0).getString()); + assertEquals("String1", result.get(1).getString()); + + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + ea.sheet(0) + .hasColumnWidth(0, 50 * 256) + .row(0) + .hasHeight((short) 800) + .cell(0) + .hasFillColor(new byte[] {-1, -1, 0}) + .hasFontColor(new byte[] {-128, -128, 0}) + .hasFontSize((short) 20) + .and() + .cell(1) + .hasFillColor(new byte[] {-1, -1, 0}) + .hasFontColor(new byte[] {-128, -128, 0}) + .hasFontSize((short) 20) + .and() + .and() + .row(1) + .hasHeight((short) 1000) + .cell(0) + .hasFillColor(new byte[] {0, -128, -128}) + .hasFontColor(new byte[] {0, 51, 102}) + .hasFontSize((short) 30) + .and() + .cell(1) + .hasFillColor(new byte[] {0, -128, -128}) + .hasFontColor(new byte[] {0, 51, 102}) + .hasFontSize((short) 30); } - return list; } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/template/TemplateData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/template/TemplateData.java index 1e0d948a4..097034dde 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/template/TemplateData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/template/TemplateData.java @@ -37,9 +37,9 @@ @Setter @EqualsAndHashCode public class TemplateData { - @ExcelProperty("字符串0") + @ExcelProperty("String0") private String string0; - @ExcelProperty("字符串1") + @ExcelProperty("String1") private String string1; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/template/TemplateDataListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/template/TemplateDataListener.java deleted file mode 100644 index f7f6a0d1c..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/template/TemplateDataListener.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * This file is part of the Apache Fesod (Incubating) project, which was derived from Alibaba EasyExcel. - * - * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. - */ - -package org.apache.fesod.sheet.template; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.junit.jupiter.api.Assertions; - -/** - * - */ -@Slf4j -public class TemplateDataListener extends AnalysisEventListener { - - List list = new ArrayList(); - - @Override - public void invoke(TemplateData data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assertions.assertEquals(2, list.size()); - Assertions.assertEquals("字符串0", list.get(0).getString0()); - Assertions.assertEquals("字符串1", list.get(1).getString0()); - log.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/template/TemplateDataTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/template/TemplateDataTest.java index e2575cfbf..41fd41ad1 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/template/TemplateDataTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/template/TemplateDataTest.java @@ -25,73 +25,42 @@ package org.apache.fesod.sheet.template; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; -import java.util.ArrayList; import java.util.List; import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.base.AbstractExcelTest; +import org.apache.fesod.sheet.testkit.builders.TestDataBuilder; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** - * + * Test template write/read for binary Excel formats using parameterized tests. */ -@TestMethodOrder(MethodOrderer.MethodName.class) -public class TemplateDataTest { - - private static File file07; - private static File file03; - - @BeforeAll - public static void init() { - file07 = TestFileUtil.createNewFile("template07.xlsx"); - file03 = TestFileUtil.createNewFile("template03.xls"); - } - - @Test - public void t01ReadAndWrite07() { - readAndWrite07(file07); - } - - @Test - public void t02ReadAndWrite03() { - readAndWrite03(file03); - } +public class TemplateDataTest extends AbstractExcelTest { - private void readAndWrite07(File file) { + @ParameterizedTest + @MethodSource("binaryFormats") + void readAndWrite(ExcelFormat format) throws Exception { + Assumptions.assumeTrue(format.supportsTemplates()); + File file = createTempFile("template", format); + String templateName = "template" + File.separator + "template" + (format == ExcelFormat.XLSX ? "07" : "03") + + format.getExtension(); + File template = TestFileUtil.readFile(templateName); FesodSheet.write(file, TemplateData.class) - .withTemplate(TestFileUtil.readFile("template" + File.separator + "template07.xlsx")) + .withTemplate(template) .sheet() - .doWrite(data()); - FesodSheet.read(file, TemplateData.class, new TemplateDataListener()) + .doWrite(TestDataBuilder.templateData(2)); + List result = FesodSheet.read(file) + .head(TemplateData.class) .headRowNumber(3) .sheet() - .doRead(); - } - - private void readAndWrite03(File file) { - FesodSheet.write(file, TemplateData.class) - .withTemplate(TestFileUtil.readFile("template" + File.separator + "template03.xls")) - .sheet() - .doWrite(data()); - FesodSheet.read(file, TemplateData.class, new TemplateDataListener()) - .headRowNumber(3) - .sheet() - .doRead(); - } - - private List data() { - List list = new ArrayList(); - TemplateData data = new TemplateData(); - data.setString0("字符串0"); - data.setString1("字符串01"); - TemplateData data1 = new TemplateData(); - data1.setString0("字符串1"); - data1.setString1("字符串11"); - list.add(data); - list.add(data1); - return list; + .doReadSync(); + assertEquals(2, result.size()); + assertEquals("String0", result.get(0).getString0()); + assertEquals("String1", result.get(1).getString0()); } } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/CellAssert.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/CellAssert.java new file mode 100644 index 000000000..bb8c5a304 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/CellAssert.java @@ -0,0 +1,201 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.assertions; + +import java.util.Arrays; +import java.util.function.Consumer; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFCell; + +/** + * Fluent assertions for a {@link Cell}, including style assertions that absorb + * the logic from {@code StyleTestUtils}. + */ +public class CellAssert { + + private final Cell cell; + private final Workbook workbook; + private final RowAssert parent; + + CellAssert(Cell cell, Workbook workbook, RowAssert parent) { + this.cell = cell; + this.workbook = workbook; + this.parent = parent; + } + + /** + * Asserts the cell has the expected string value. + */ + public CellAssert hasStringValue(String expected) { + String actual = cell.getStringCellValue(); + if (!expected.equals(actual)) { + throw new AssertionError("Expected string value \"" + expected + "\" but was \"" + actual + "\""); + } + return this; + } + + /** + * Asserts the cell has the expected numeric value. + */ + public CellAssert hasNumericValue(double expected) { + double actual = cell.getNumericCellValue(); + if (Double.compare(expected, actual) != 0) { + throw new AssertionError("Expected numeric value " + expected + " but was " + actual); + } + return this; + } + + /** + * Asserts the cell has the expected data format index. + */ + public CellAssert hasDataFormat(int expected) { + int actual = cell.getCellStyle().getDataFormat(); + if (actual != expected) { + throw new AssertionError("Expected data format " + expected + " but was " + actual); + } + return this; + } + + /** + * Asserts the cell has the expected data format string. + */ + public CellAssert hasDataFormatString(String expected) { + String actual = cell.getCellStyle().getDataFormatString(); + if (!expected.equals(actual)) { + throw new AssertionError("Expected data format string \"" + expected + "\" but was \"" + actual + "\""); + } + return this; + } + + /** + * Asserts the cell has the expected boolean value. + */ + public CellAssert hasBooleanValue(boolean expected) { + boolean actual = cell.getBooleanCellValue(); + if (expected != actual) { + throw new AssertionError("Expected boolean value " + expected + " but was " + actual); + } + return this; + } + + /** + * Asserts the cell's fill foreground color matches the expected RGB bytes. + * Dispatches on XSSF vs HSSF cell types. + */ + public CellAssert hasFillColor(byte[] expectedRgb) { + byte[] actual; + if (cell instanceof XSSFCell) { + actual = ((XSSFCell) cell) + .getCellStyle() + .getFillForegroundColorColor() + .getRGB(); + } else { + actual = short2byte(((HSSFCell) cell) + .getCellStyle() + .getFillForegroundColorColor() + .getTriplet()); + } + if (!Arrays.equals(expectedRgb, actual)) { + throw new AssertionError( + "Expected fill color " + Arrays.toString(expectedRgb) + " but was " + Arrays.toString(actual)); + } + return this; + } + + /** + * Asserts the cell's font color matches the expected RGB bytes. + * Dispatches on XSSF vs HSSF cell types. + */ + public CellAssert hasFontColor(byte[] expectedRgb) { + byte[] actual; + if (cell instanceof XSSFCell) { + actual = ((XSSFCell) cell).getCellStyle().getFont().getXSSFColor().getRGB(); + } else { + actual = short2byte(((HSSFCell) cell) + .getCellStyle() + .getFont(workbook) + .getHSSFColor((HSSFWorkbook) workbook) + .getTriplet()); + } + if (!Arrays.equals(expectedRgb, actual)) { + throw new AssertionError( + "Expected font color " + Arrays.toString(expectedRgb) + " but was " + Arrays.toString(actual)); + } + return this; + } + + /** + * Asserts the cell's font size matches the expected points. + */ + public CellAssert hasFontSize(short expectedPoints) { + short actual; + if (cell instanceof XSSFCell) { + actual = ((XSSFCell) cell).getCellStyle().getFont().getFontHeightInPoints(); + } else { + actual = ((HSSFCell) cell).getCellStyle().getFont(workbook).getFontHeightInPoints(); + } + if (actual != expectedPoints) { + throw new AssertionError("Expected font size " + expectedPoints + " but was " + actual); + } + return this; + } + + /** + * Asserts whether the cell font is bold. + */ + public CellAssert hasBoldFont(boolean expected) { + boolean actual; + if (cell instanceof XSSFCell) { + actual = ((XSSFCell) cell).getCellStyle().getFont().getBold(); + } else { + actual = ((HSSFCell) cell).getCellStyle().getFont(workbook).getBold(); + } + if (actual != expected) { + throw new AssertionError("Expected bold font " + expected + " but was " + actual); + } + return this; + } + + /** + * Escape hatch for custom POI assertions on the underlying cell. + */ + public CellAssert satisfies(Consumer assertion) { + assertion.accept(cell); + return this; + } + + /** + * Returns to the parent assertion chain. + */ + public RowAssert and() { + return parent; + } + + private static byte[] short2byte(short[] shorts) { + byte[] bytes = new byte[shorts.length]; + for (int i = 0; i < shorts.length; i++) { + bytes[i] = (byte) shorts[i]; + } + return bytes; + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/ExcelAssertions.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/ExcelAssertions.java new file mode 100644 index 000000000..36122a2bb --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/ExcelAssertions.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.assertions; + +import java.io.File; +import java.io.IOException; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; + +/** + * Entry point for the fluent Excel assertion API. + * + *

    Opens a workbook from a file and provides chainable assertions on its contents. + * Implements {@link AutoCloseable} to ensure the workbook is closed after assertions. + * + *

    Usage: + *

    {@code
    + * try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) {
    + *     ea.sheet(0).row(0).cell(0).hasStringValue("Name");
    + * }
    + * }
    + */ +public final class ExcelAssertions implements AutoCloseable { + + private final Workbook workbook; + private final File file; + + private ExcelAssertions(Workbook workbook, File file) { + this.workbook = workbook; + this.file = file; + } + + /** + * Opens the given Excel file and returns a fluent assertion entry point. + * + * @param file the Excel file to assert against + * @return a new {@code ExcelAssertions} instance + * @throws AssertionError if the file does not exist or cannot be opened as a workbook + */ + public static ExcelAssertions assertThat(File file) { + if (!file.exists()) { + throw new AssertionError("File does not exist: " + file.getAbsolutePath()); + } + try { + Workbook wb = WorkbookFactory.create(file); + return new ExcelAssertions(wb, file); + } catch (IOException e) { + throw new AssertionError("Failed to open workbook: " + file.getAbsolutePath(), e); + } + } + + /** + * Returns a {@link WorkbookAssert} for the underlying workbook. + */ + public WorkbookAssert workbook() { + return new WorkbookAssert(workbook, this); + } + + /** + * Shortcut to assert on a specific sheet by index. + */ + public SheetAssert sheet(int index) { + return workbook().sheet(index); + } + + Workbook getWorkbook() { + return workbook; + } + + File getFile() { + return file; + } + + @Override + public void close() { + try { + workbook.close(); + } catch (IOException e) { + // best effort + } + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/ExcelAssertionsTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/ExcelAssertionsTest.java new file mode 100644 index 000000000..54e892995 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/ExcelAssertionsTest.java @@ -0,0 +1,166 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.assertions; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class ExcelAssertionsTest { + + @TempDir + File tempDir; + + private File writeSimpleFile(String name) { + File file = new File(tempDir, name); + List data = new ArrayList(); + for (int i = 0; i < 3; i++) { + SimpleData d = new SimpleData(); + d.setName("Name" + i); + data.add(d); + } + FesodSheet.write(file, SimpleData.class).sheet().doWrite(data); + return file; + } + + @Test + void assertThatOpensFile() { + File file = writeSimpleFile("test.xlsx"); + ExcelAssertions ea = ExcelAssertions.assertThat(file); + ea.close(); + } + + @Test + void assertThatThrowsForMissingFile() { + File missing = new File(tempDir, "nonexistent.xlsx"); + assertThrows(AssertionError.class, () -> ExcelAssertions.assertThat(missing)); + } + + @Test + void sheetCountAssertion() { + File file = writeSimpleFile("test.xlsx"); + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + ea.workbook().hasSheetCount(1); + } + } + + @Test + void sheetCountMismatchThrows() { + File file = writeSimpleFile("test.xlsx"); + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + assertThrows(AssertionError.class, () -> ea.workbook().hasSheetCount(5)); + } + } + + @Test + void sheetIndexOutOfBoundsThrows() { + File file = writeSimpleFile("test.xlsx"); + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + assertThrows(AssertionError.class, () -> ea.sheet(99)); + } + } + + @Test + void rowCountAssertion() { + File file = writeSimpleFile("test.xlsx"); + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + // 1 header row + 3 data rows = 4 + ea.sheet(0).hasRowCount(4); + } + } + + @Test + void nullRowThrows() { + File file = writeSimpleFile("test.xlsx"); + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + assertThrows(AssertionError.class, () -> ea.sheet(0).row(999)); + } + } + + @Test + void nullCellThrows() { + File file = writeSimpleFile("test.xlsx"); + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + assertThrows(AssertionError.class, () -> ea.sheet(0).row(0).cell(999)); + } + } + + @Test + void stringValueCorrectPasses() { + File file = writeSimpleFile("test.xlsx"); + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + // Row 0 is header "Name", row 1 is "Name0" + ea.sheet(0).row(0).cell(0).hasStringValue("Name"); + ea.sheet(0).row(1).cell(0).hasStringValue("Name0"); + ea.sheet(0).row(2).cell(0).hasStringValue("Name1"); + ea.sheet(0).row(3).cell(0).hasStringValue("Name2"); + } + } + + @Test + void stringValueIncorrectThrows() { + File file = writeSimpleFile("test.xlsx"); + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + assertThrows(AssertionError.class, () -> ea.sheet(0).row(1).cell(0).hasStringValue("wrong")); + } + } + + @Test + void autoCloseableWorks() { + File file = writeSimpleFile("test.xlsx"); + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + ea.sheet(0).row(0).cell(0).hasStringValue("Name"); + } + // Should not throw — workbook is closed + } + + @Test + void satisfiesEscapeHatch() { + File file = writeSimpleFile("test.xlsx"); + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + ea.sheet(0) + .row(1) + .cell(0) + .satisfies(cell -> assertTrue(cell.getStringCellValue().startsWith("Name"))); + } + } + + @Test + void chainedNavigationAndBack() { + File file = writeSimpleFile("test.xlsx"); + try (ExcelAssertions ea = ExcelAssertions.assertThat(file)) { + ea.sheet(0) + .row(1) + .cell(0) + .hasStringValue("Name0") + .and() // back to RowAssert + .and() // back to SheetAssert + .row(2) + .cell(0) + .hasStringValue("Name1"); + } + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/RowAssert.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/RowAssert.java new file mode 100644 index 000000000..943cc61fd --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/RowAssert.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.assertions; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Workbook; + +/** + * Fluent assertions for a {@link Row}. + */ +public class RowAssert { + + private final Row row; + private final Workbook workbook; + private final SheetAssert parent; + + RowAssert(Row row, Workbook workbook, SheetAssert parent) { + this.row = row; + this.workbook = workbook; + this.parent = parent; + } + + /** + * Asserts the row has the expected height in twips. + */ + public RowAssert hasHeight(short expectedHeight) { + short actual = row.getHeight(); + if (actual != expectedHeight) { + throw new AssertionError("Expected row height " + expectedHeight + " but was " + actual); + } + return this; + } + + /** + * Navigates to a cell by index for further assertions. + * + * @throws AssertionError if the cell is null + */ + public CellAssert cell(int index) { + Cell cell = row.getCell(index); + if (cell == null) { + throw new AssertionError("Cell " + index + " is null in row " + row.getRowNum()); + } + return new CellAssert(cell, workbook, this); + } + + /** + * Returns to the parent assertion chain. + */ + public SheetAssert and() { + return parent; + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/SheetAssert.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/SheetAssert.java new file mode 100644 index 000000000..1bf177505 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/SheetAssert.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.assertions; + +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; + +/** + * Fluent assertions for a {@link Sheet}. + */ +public class SheetAssert { + + private final Sheet sheet; + private final Workbook workbook; + private final WorkbookAssert parent; + + SheetAssert(Sheet sheet, Workbook workbook, WorkbookAssert parent) { + this.sheet = sheet; + this.workbook = workbook; + this.parent = parent; + } + + /** + * Asserts the sheet has the expected number of physical rows. + */ + public SheetAssert hasRowCount(int expected) { + int actual = sheet.getPhysicalNumberOfRows(); + if (actual != expected) { + throw new AssertionError( + "Expected " + expected + " rows but sheet '" + sheet.getSheetName() + "' has " + actual); + } + return this; + } + + /** + * Asserts a column has the expected width (in 1/256th of a character width units). + */ + public SheetAssert hasColumnWidth(int columnIndex, int expectedWidth) { + int actual = sheet.getColumnWidth(columnIndex); + if (actual != expectedWidth) { + throw new AssertionError( + "Expected column " + columnIndex + " width " + expectedWidth + " but was " + actual); + } + return this; + } + + /** + * Navigates to a row by index for further assertions. + * + * @throws AssertionError if the row is null + */ + public RowAssert row(int index) { + Row row = sheet.getRow(index); + if (row == null) { + throw new AssertionError("Row " + index + " is null in sheet '" + sheet.getSheetName() + "'"); + } + return new RowAssert(row, workbook, this); + } + + /** + * Returns to the parent assertion chain. + */ + public WorkbookAssert and() { + return parent; + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/WorkbookAssert.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/WorkbookAssert.java new file mode 100644 index 000000000..39019d1a0 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/assertions/WorkbookAssert.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.assertions; + +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; + +/** + * Fluent assertions for a {@link Workbook}. + */ +public class WorkbookAssert { + + private final Workbook workbook; + private final ExcelAssertions parent; + + WorkbookAssert(Workbook workbook, ExcelAssertions parent) { + this.workbook = workbook; + this.parent = parent; + } + + /** + * Asserts the workbook has the expected number of sheets. + */ + public WorkbookAssert hasSheetCount(int expected) { + int actual = workbook.getNumberOfSheets(); + if (actual != expected) { + throw new AssertionError("Expected " + expected + " sheets but was " + actual); + } + return this; + } + + /** + * Navigates to a sheet by index for further assertions. + * + * @throws AssertionError if the index is out of bounds + */ + public SheetAssert sheet(int index) { + int count = workbook.getNumberOfSheets(); + if (index < 0 || index >= count) { + throw new AssertionError("Sheet index " + index + " out of bounds, workbook has " + count + " sheet(s)"); + } + Sheet sheet = workbook.getSheetAt(index); + return new SheetAssert(sheet, workbook, this); + } + + /** + * Returns to the parent assertion chain. + */ + public ExcelAssertions and() { + return parent; + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/base/AbstractExcelTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/base/AbstractExcelTest.java new file mode 100644 index 000000000..efd42bab7 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/base/AbstractExcelTest.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.base; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.stream.Stream; +import org.apache.fesod.sheet.testkit.enums.ApiMode; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.helpers.RoundTripHelper; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.provider.Arguments; + +/** + * Base class for modernized test classes. Provides: + *
      + *
    • A JUnit 5 {@code @TempDir} for isolated temp files
    • + *
    • Static method sources for parameterized tests
    • + *
    • Convenience helpers delegating to {@link RoundTripHelper}
    • + *
    + */ +public abstract class AbstractExcelTest { + + @TempDir + protected File tempDir; + + // --- Format Providers (static, for @MethodSource) --- + + protected static Stream allFormats() { + return Stream.of(ExcelFormat.values()); + } + + protected static Stream binaryFormats() { + return Stream.of(ExcelFormat.XLSX, ExcelFormat.XLS); + } + + protected static Stream allFormatsWithApiMode() { + Stream.Builder builder = Stream.builder(); + for (ExcelFormat format : ExcelFormat.values()) { + for (ApiMode mode : ApiMode.values()) { + builder.add(Arguments.of(format, mode)); + } + } + return builder.build(); + } + + // --- Temp File Management --- + + protected File createTempFile(ExcelFormat format) throws IOException { + return format.createTempFile("test", tempDir); + } + + protected File createTempFile(String prefix, ExcelFormat format) throws IOException { + return format.createTempFile(prefix, tempDir); + } + + // --- Convenience Helpers (delegate to RoundTripHelper) --- + + protected void writeData(File file, Class clazz, List data) { + RoundTripHelper.write(file, clazz, data); + } + + protected List readData(File file, Class clazz) { + return RoundTripHelper.read(file, clazz); + } + + protected List writeAndRead(ExcelFormat format, Class clazz, List data) throws IOException { + File file = createTempFile(format); + return RoundTripHelper.writeAndRead(file, clazz, data); + } + + protected List writeAndRead(ExcelFormat format, Class writeClazz, List data, Class readClazz) + throws IOException { + File file = createTempFile(format); + return RoundTripHelper.writeAndRead(file, writeClazz, data, readClazz); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/builders/TestDataBuilder.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/builders/TestDataBuilder.java new file mode 100644 index 000000000..8f83376a7 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/builders/TestDataBuilder.java @@ -0,0 +1,401 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.builders; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import org.apache.fesod.sheet.converter.ConverterWriteData; +import org.apache.fesod.sheet.converter.ExcludeOrIncludeData; +import org.apache.fesod.sheet.converter.SortData; +import org.apache.fesod.sheet.core.RepetitionData; +import org.apache.fesod.sheet.core.UnCamelData; +import org.apache.fesod.sheet.head.ComplexHeadData; +import org.apache.fesod.sheet.head.NoHeadData; +import org.apache.fesod.sheet.metadata.data.WriteCellData; +import org.apache.fesod.sheet.readwrite.CacheData; +import org.apache.fesod.sheet.sheet.WriteSheetData; +import org.apache.fesod.sheet.style.AnnotationData; +import org.apache.fesod.sheet.style.AnnotationIndexAndNameData; +import org.apache.fesod.sheet.style.FillAnnotationData; +import org.apache.fesod.sheet.style.FillData; +import org.apache.fesod.sheet.style.FillStyleAnnotatedData; +import org.apache.fesod.sheet.style.FillStyleData; +import org.apache.fesod.sheet.style.StyleData; +import org.apache.fesod.sheet.template.TemplateData; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.apache.fesod.sheet.testkit.models.TitleData; +import org.apache.fesod.sheet.util.DateUtils; +import org.apache.fesod.sheet.util.TestUtil; + +/** + * Shared test data factory methods, replacing per-class {@code data()} methods. + */ +public final class TestDataBuilder { + + private TestDataBuilder() {} + + /** + * Creates a list of {@link SimpleData} with names "Name0" through "Name{count-1}". + */ + public static List simpleData(int count) { + List list = new ArrayList(); + for (int i = 0; i < count; i++) { + SimpleData d = new SimpleData(); + d.setName("Name" + i); + list.add(d); + } + return list; + } + + /** + * Creates a single-element list of {@link ConverterWriteData} with all 14 fields populated. + */ + public static List converterWriteData() { + List list = new ArrayList(); + ConverterWriteData data = new ConverterWriteData(); + data.setDate(TestUtil.TEST_DATE); + data.setLocalDate(TestUtil.TEST_LOCAL_DATE); + data.setLocalDateTime(TestUtil.TEST_LOCAL_DATE_TIME); + data.setBooleanData(Boolean.TRUE); + data.setBigDecimal(BigDecimal.ONE); + data.setBigInteger(BigInteger.ONE); + data.setLongData(1L); + data.setIntegerData(1); + data.setShortData((short) 1); + data.setByteData((byte) 1); + data.setDoubleData(1.0); + data.setFloatData((float) 1.0); + data.setString("test"); + data.setCellData(new WriteCellData<>("custom")); + list.add(data); + return list; + } + + /** + * Creates a list of {@link SimpleData} with prefixed names like "{prefix}Name0". + */ + public static List simpleData(int count, String prefix) { + List list = new ArrayList(); + for (int i = 0; i < count; i++) { + SimpleData d = new SimpleData(); + d.setName(prefix + "Name" + i); + list.add(d); + } + return list; + } + + /** + * Creates a list of {@link SimpleData} with name and age fields populated. + */ + public static List simpleDataWithAge(int count) { + List list = new ArrayList(); + for (int i = 0; i < count; i++) { + SimpleData d = new SimpleData(); + d.setName("Name" + i); + d.setAge(i); + list.add(d); + } + return list; + } + + /** + * Creates a list of {@link SimpleData} with name and date fields populated. + */ + public static List simpleDataWithDate(int count) { + List list = new ArrayList(); + for (int i = 0; i < count; i++) { + SimpleData d = new SimpleData(); + d.setName("Name" + i); + d.setDate(new java.util.Date()); + list.add(d); + } + return list; + } + + /** + * Creates a list of {@link CacheData} with name ("Name") and age (Long, "Age") fields. + */ + public static List cacheData(int count) { + List list = new ArrayList(); + for (int i = 0; i < count; i++) { + CacheData d = new CacheData(); + d.setName("Name" + i); + d.setAge((long) i); + list.add(d); + } + return list; + } + + /** + * Creates a list of {@link TitleData} with titles like "{prefix}0". + */ + public static List titleData(int count, String prefix) { + List list = new ArrayList(); + for (int i = 0; i < count; i++) { + TitleData d = new TitleData(); + d.setTitle(prefix + i); + list.add(d); + } + return list; + } + + public static List unCamelData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + UnCamelData d = new UnCamelData(); + d.setString1("string1"); + d.setString2("string2"); + d.setSTring3("string3"); + d.setSTring4("string4"); + d.setSTRING5("string5"); + d.setSTRing6("string6"); + list.add(d); + } + return list; + } + + public static List repetitionData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + RepetitionData d = new RepetitionData(); + d.setString("String0"); + list.add(d); + } + return list; + } + + public static List writeSheetData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + WriteSheetData d = new WriteSheetData(); + d.setString("String" + i); + list.add(d); + } + return list; + } + + public static List complexHeadData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + ComplexHeadData d = new ComplexHeadData(); + d.setString0("String0"); + d.setString1("String1"); + d.setString2("String2"); + d.setString3("String3"); + d.setString4("String4"); + list.add(d); + } + return list; + } + + public static List noHeadData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + NoHeadData d = new NoHeadData(); + d.setString("String0"); + list.add(d); + } + return list; + } + + public static List excludeOrIncludeData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + ExcludeOrIncludeData d = new ExcludeOrIncludeData(); + d.setColumn1("column1"); + d.setColumn2("column2"); + d.setColumn3("column3"); + d.setColumn4("column4"); + list.add(d); + } + return list; + } + + public static List sortData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + SortData d = new SortData(); + d.setColumn1("column1"); + d.setColumn2("column2"); + d.setColumn3("column3"); + d.setColumn4("column4"); + d.setColumn5("column5"); + d.setColumn6("column6"); + list.add(d); + } + return list; + } + + public static List styleData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + StyleData d = new StyleData(); + d.setString("String" + i); + d.setString1("String" + i + "1"); + list.add(d); + } + return list; + } + + public static List annotationData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + AnnotationData d = new AnnotationData(); + try { + d.setDate(DateUtils.parseDate("2020-01-01 01:01:01")); + } catch (Exception e) { + throw new RuntimeException(e); + } + d.setNumber(99.99); + d.setIgnore("ignore"); + d.setTransientString("ignore"); + list.add(d); + } + return list; + } + + public static List annotationIndexAndNameData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + AnnotationIndexAndNameData d = new AnnotationIndexAndNameData(); + d.setIndex0("Item0"); + d.setIndex1("Item1"); + d.setIndex2("Item2"); + d.setIndex4("Item4"); + list.add(d); + } + return list; + } + + public static List fillData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + FillData d = new FillData(); + if (i == 5) { + d.setName(null); + } else { + d.setName("Zhang San"); + } + d.setNumber(5.2); + list.add(d); + } + return list; + } + + public static List fillStyleData(int count) throws Exception { + List list = new ArrayList(); + Date date = DateUtils.parseDate("2020-01-01 01:01:01"); + for (int i = 0; i < count; i++) { + FillStyleData d = new FillStyleData(); + d.setName(i == 5 ? null : "Zhang San"); + d.setNumber(5.2); + d.setDate(date); + list.add(d); + } + return list; + } + + public static List fillStyleAnnotatedData(int count) throws Exception { + List list = new ArrayList(); + Date date = DateUtils.parseDate("2020-01-01 01:01:01"); + for (int i = 0; i < count; i++) { + FillStyleAnnotatedData d = new FillStyleAnnotatedData(); + d.setName(i == 5 ? null : "Zhang San"); + d.setNumber(5.2); + d.setDate(date); + list.add(d); + } + return list; + } + + public static List fillAnnotationData(int count, String imagePath) throws Exception { + List list = new ArrayList(); + Date date = DateUtils.parseDate("2020-01-01 01:01:01"); + for (int i = 0; i < count; i++) { + FillAnnotationData d = new FillAnnotationData(); + d.setDate(date); + d.setNumber(99.99); + d.setString1("string1"); + d.setString2("string2"); + d.setImage(imagePath); + list.add(d); + } + return list; + } + + public static List templateData(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + TemplateData d = new TemplateData(); + d.setString0("String" + i); + d.setString1("String" + i + "1"); + list.add(d); + } + return list; + } + + public static List> noModelData(int count) throws Exception { + List> list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + List data = new ArrayList<>(); + data.add("string1" + i); + data.add(100 + i); + data.add(org.apache.fesod.sheet.util.DateUtils.parseDate("2020-01-01 01:01:01")); + list.add(data); + } + return list; + } + + public static List cellDataWriteData() throws Exception { + List list = new ArrayList<>(); + org.apache.fesod.sheet.converter.CellDataWriteData cellDataData = + new org.apache.fesod.sheet.converter.CellDataWriteData(); + cellDataData.setDate(new org.apache.fesod.sheet.metadata.data.WriteCellData<>( + org.apache.fesod.sheet.util.DateUtils.parseDate("2020-01-01 01:01:01"))); + org.apache.fesod.sheet.metadata.data.WriteCellData integer1 = + new org.apache.fesod.sheet.metadata.data.WriteCellData<>(); + integer1.setType(org.apache.fesod.sheet.enums.CellDataTypeEnum.NUMBER); + integer1.setNumberValue(java.math.BigDecimal.valueOf(2L)); + cellDataData.setInteger1(integer1); + cellDataData.setInteger2(2); + org.apache.fesod.sheet.metadata.data.WriteCellData formulaValue = + new org.apache.fesod.sheet.metadata.data.WriteCellData<>(); + org.apache.fesod.sheet.metadata.data.FormulaData formulaData = + new org.apache.fesod.sheet.metadata.data.FormulaData(); + formulaValue.setFormulaData(formulaData); + formulaData.setFormulaValue("B2+C2"); + cellDataData.setFormulaValue(formulaValue); + list.add(cellDataData); + return list; + } + + public static List customConverterWriteData() { + List list = new ArrayList<>(); + org.apache.fesod.sheet.converter.CustomConverterWriteData writeData = + new org.apache.fesod.sheet.converter.CustomConverterWriteData(); + writeData.setTimestampStringData(java.sql.Timestamp.valueOf("2020-01-01 01:00:00")); + writeData.setTimestampNumberData(java.sql.Timestamp.valueOf("2020-12-01 12:12:12")); + list.add(writeData); + return list; + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/builders/TestDataBuilderTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/builders/TestDataBuilderTest.java new file mode 100644 index 000000000..f2bdd43b6 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/builders/TestDataBuilderTest.java @@ -0,0 +1,122 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.builders; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.util.List; +import org.apache.fesod.sheet.converter.ConverterWriteData; +import org.apache.fesod.sheet.style.FillAnnotationData; +import org.apache.fesod.sheet.style.FillStyleAnnotatedData; +import org.apache.fesod.sheet.style.FillStyleData; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.apache.fesod.sheet.util.DateUtils; +import org.apache.fesod.sheet.util.TestUtil; +import org.junit.jupiter.api.Test; + +class TestDataBuilderTest { + + @Test + void simpleDataCountAccuracy() { + List data = TestDataBuilder.simpleData(10); + assertEquals(10, data.size()); + for (SimpleData d : data) { + assertNotNull(d); + assertNotNull(d.getName()); + } + } + + @Test + void simpleDataFieldValues() { + List data = TestDataBuilder.simpleData(3); + assertEquals("Name0", data.get(0).getName()); + assertEquals("Name1", data.get(1).getName()); + assertEquals("Name2", data.get(2).getName()); + } + + @Test + void simpleDataSingleElement() { + List data = TestDataBuilder.simpleData(1); + assertEquals(1, data.size()); + assertEquals("Name0", data.get(0).getName()); + } + + @Test + void converterWriteDataNotEmpty() { + List data = TestDataBuilder.converterWriteData(); + assertFalse(data.isEmpty()); + assertEquals(1, data.size()); + } + + @Test + void converterWriteDataFieldValues() { + ConverterWriteData data = TestDataBuilder.converterWriteData().get(0); + assertEquals(TestUtil.TEST_DATE, data.getDate()); + assertEquals(TestUtil.TEST_LOCAL_DATE, data.getLocalDate()); + assertEquals(TestUtil.TEST_LOCAL_DATE_TIME, data.getLocalDateTime()); + assertEquals(Boolean.TRUE, data.getBooleanData()); + assertEquals(1, data.getBigDecimal().intValue()); + assertEquals(1, data.getBigInteger().intValue()); + assertEquals(1L, data.getLongData()); + assertEquals(1, (int) data.getIntegerData()); + assertEquals((short) 1, (short) data.getShortData()); + assertEquals((byte) 1, (byte) data.getByteData()); + assertEquals(1.0, data.getDoubleData(), 0.0); + assertEquals((float) 1.0, data.getFloatData(), 0.0); + assertEquals("test", data.getString()); + assertEquals("custom", data.getCellData().getStringValue()); + } + + @Test + void fillStyleDataMatchesLegacyFixtures() throws Exception { + List data = TestDataBuilder.fillStyleData(10); + assertEquals(10, data.size()); + assertEquals("Zhang San", data.get(0).getName()); + assertEquals(5.2, data.get(0).getNumber(), 0.0); + assertEquals("2020-01-01 01:01:01", DateUtils.format(data.get(0).getDate(), "yyyy-MM-dd HH:mm:ss")); + assertEquals(null, data.get(5).getName()); + } + + @Test + void fillStyleAnnotatedDataMatchesLegacyFixtures() throws Exception { + List data = TestDataBuilder.fillStyleAnnotatedData(10); + assertEquals(10, data.size()); + assertEquals("Zhang San", data.get(0).getName()); + assertEquals(5.2, data.get(0).getNumber(), 0.0); + assertEquals(null, data.get(5).getName()); + } + + @Test + void fillAnnotationDataMatchesLegacyFixtures() throws Exception { + List data = TestDataBuilder.fillAnnotationData(5, "image-path"); + assertEquals(5, data.size()); + assertEquals(99.99, data.get(0).getNumber(), 0.0); + assertEquals("string1", data.get(0).getString1()); + assertEquals("string2", data.get(0).getString2()); + assertEquals("image-path", data.get(0).getImage()); + } + + @Test + void titleDataMatchesExpectedPrefixPattern() { + assertEquals("sheet-0", TestDataBuilder.titleData(2, "sheet-").get(0).getTitle()); + assertEquals("sheet-1", TestDataBuilder.titleData(2, "sheet-").get(1).getTitle()); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/hiddensheets/HiddenSheetsData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/enums/ApiMode.java similarity index 78% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/hiddensheets/HiddenSheetsData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/enums/ApiMode.java index ca5cd2eb2..f96e84aac 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/hiddensheets/HiddenSheetsData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/enums/ApiMode.java @@ -17,15 +17,12 @@ * under the License. */ -package org.apache.fesod.sheet.hiddensheets; +package org.apache.fesod.sheet.testkit.enums; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -@Getter -@Setter -@EqualsAndHashCode -public class HiddenSheetsData { - private String title; +/** + * Distinguishes between File-based and Stream-based FesodSheet API usage in parameterized tests. + */ +public enum ApiMode { + FILE, + STREAM } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/enums/ExcelFormat.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/enums/ExcelFormat.java new file mode 100644 index 000000000..4c8b9e795 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/enums/ExcelFormat.java @@ -0,0 +1,121 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.enums; + +import java.io.File; +import java.io.IOException; +import lombok.Getter; +import org.apache.fesod.sheet.support.ExcelTypeEnum; + +/** + * Test-only enum bridging to the production {@link ExcelTypeEnum} with format capability metadata. + * + *

    Each constant carries flags indicating which features (templates, images, encryption, styles) + * are supported by that format, enabling parameterized tests to skip unsupported combinations + * via {@code Assumptions.assumeTrue(format.supportsXxx())}. + */ +public enum ExcelFormat { + XLSX(".xlsx", ExcelTypeEnum.XLSX, true, true, true, true), + XLS(".xls", ExcelTypeEnum.XLS, true, true, false, true), + CSV(".csv", ExcelTypeEnum.CSV, false, false, false, false); + + @Getter + private final String extension; + + private final ExcelTypeEnum excelTypeEnum; + private final boolean supportsTemplates; + private final boolean supportsImages; + private final boolean supportsEncryption; + private final boolean supportsStyles; + + ExcelFormat( + String extension, + ExcelTypeEnum excelTypeEnum, + boolean supportsTemplates, + boolean supportsImages, + boolean supportsEncryption, + boolean supportsStyles) { + this.extension = extension; + this.excelTypeEnum = excelTypeEnum; + this.supportsTemplates = supportsTemplates; + this.supportsImages = supportsImages; + this.supportsEncryption = supportsEncryption; + this.supportsStyles = supportsStyles; + } + + public ExcelTypeEnum toExcelTypeEnum() { + return excelTypeEnum; + } + + public boolean supportsTemplates() { + return supportsTemplates; + } + + public boolean supportsImages() { + return supportsImages; + } + + public boolean supportsEncryption() { + return supportsEncryption; + } + + public boolean supportsStyles() { + return supportsStyles; + } + + /** + * Creates a temp file with the correct extension in the given directory. + * + * @param prefix filename prefix (at least 3 characters) + * @param directory the directory in which the file is to be created + * @return a newly created temp file with the format's extension + * @throws IOException if the file cannot be created + */ + public File createTempFile(String prefix, File directory) throws IOException { + return File.createTempFile(prefix, extension, directory); + } + + /** + * Creates a temp file with the correct extension in the system temp directory. + * + * @param prefix filename prefix (at least 3 characters) + * @return a newly created temp file with the format's extension + * @throws IOException if the file cannot be created + */ + public File createTempFile(String prefix) throws IOException { + return File.createTempFile(prefix, extension); + } + + /** + * Looks up the {@code ExcelFormat} corresponding to the given production {@link ExcelTypeEnum}. + * + * @param type the production enum value + * @return the matching {@code ExcelFormat} + * @throws IllegalArgumentException if no match is found + */ + public static ExcelFormat fromExcelTypeEnum(ExcelTypeEnum type) { + for (ExcelFormat format : values()) { + if (format.excelTypeEnum == type) { + return format; + } + } + throw new IllegalArgumentException("No ExcelFormat for ExcelTypeEnum: " + type); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/enums/ExcelFormatTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/enums/ExcelFormatTest.java new file mode 100644 index 000000000..57759d8fa --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/enums/ExcelFormatTest.java @@ -0,0 +1,123 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.enums; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.io.IOException; +import org.apache.fesod.sheet.support.ExcelTypeEnum; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +class ExcelFormatTest { + + @TempDir + File tempDir; + + // --- Capability flag tests --- + + @Test + void xlsxCapabilities() { + assertTrue(ExcelFormat.XLSX.supportsTemplates()); + assertTrue(ExcelFormat.XLSX.supportsImages()); + assertTrue(ExcelFormat.XLSX.supportsEncryption()); + assertTrue(ExcelFormat.XLSX.supportsStyles()); + } + + @Test + void xlsCapabilities() { + assertTrue(ExcelFormat.XLS.supportsTemplates()); + assertTrue(ExcelFormat.XLS.supportsImages()); + assertFalse(ExcelFormat.XLS.supportsEncryption()); + assertTrue(ExcelFormat.XLS.supportsStyles()); + } + + @Test + void csvCapabilities() { + assertFalse(ExcelFormat.CSV.supportsTemplates()); + assertFalse(ExcelFormat.CSV.supportsImages()); + assertFalse(ExcelFormat.CSV.supportsEncryption()); + assertFalse(ExcelFormat.CSV.supportsStyles()); + } + + // --- Extension tests --- + + @Test + void extensions() { + assertEquals(".xlsx", ExcelFormat.XLSX.getExtension()); + assertEquals(".xls", ExcelFormat.XLS.getExtension()); + assertEquals(".csv", ExcelFormat.CSV.getExtension()); + } + + // --- Enum round-trip: toExcelTypeEnum / fromExcelTypeEnum --- + + @ParameterizedTest + @EnumSource(ExcelFormat.class) + void enumRoundTrip(ExcelFormat format) { + ExcelTypeEnum type = format.toExcelTypeEnum(); + ExcelFormat roundTripped = ExcelFormat.fromExcelTypeEnum(type); + assertEquals(format, roundTripped); + } + + @Test + void toExcelTypeEnumMapping() { + assertEquals(ExcelTypeEnum.XLSX, ExcelFormat.XLSX.toExcelTypeEnum()); + assertEquals(ExcelTypeEnum.XLS, ExcelFormat.XLS.toExcelTypeEnum()); + assertEquals(ExcelTypeEnum.CSV, ExcelFormat.CSV.toExcelTypeEnum()); + } + + // --- Temp file tests --- + + @ParameterizedTest + @EnumSource(ExcelFormat.class) + void createTempFileHasCorrectExtension(ExcelFormat format) throws IOException { + File file = format.createTempFile("test", tempDir); + assertTrue( + file.getName().endsWith(format.getExtension()), + "Expected file name to end with " + format.getExtension() + ", got: " + file.getName()); + assertEquals(tempDir, file.getParentFile()); + } + + @ParameterizedTest + @EnumSource(ExcelFormat.class) + void createTempFileInSystemTempDir(ExcelFormat format) throws IOException { + File file = format.createTempFile("test"); + try { + assertTrue( + file.getName().endsWith(format.getExtension()), + "Expected file name to end with " + format.getExtension() + ", got: " + file.getName()); + assertTrue(file.exists()); + } finally { + file.delete(); + } + } + + // --- Edge cases --- + + @Test + void fromExcelTypeEnumWithNull() { + assertThrows(IllegalArgumentException.class, () -> ExcelFormat.fromExcelTypeEnum(null)); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/helpers/RoundTripHelper.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/helpers/RoundTripHelper.java new file mode 100644 index 000000000..45dfccc54 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/helpers/RoundTripHelper.java @@ -0,0 +1,168 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.helpers; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.testkit.enums.ApiMode; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.listeners.CollectingReadListener; + +/** + * Encapsulates write-then-read boilerplate for round-trip tests. + * + *

    Provides File-based, Stream-based, and sync read helpers that eliminate + * the repetitive write/read code found in every existing test class. + */ +public final class RoundTripHelper { + + private RoundTripHelper() {} + + // ---- Same model for write and read ---- + + /** + * Writes data to file, then reads it back using the same model class. + */ + public static List writeAndRead(File file, Class clazz, List data) { + write(file, clazz, data); + return read(file, clazz); + } + + // ---- Different write/read models ---- + + /** + * Writes data using {@code writeClazz}, then reads it back using {@code readClazz}. + * Supports asymmetric models (e.g., WriteCellData vs ReadCellData). + */ + public static List writeAndRead(File file, Class writeClazz, List data, Class readClazz) { + write(file, writeClazz, data); + return read(file, readClazz); + } + + // ---- Stream-based round trip ---- + + /** + * Writes data via OutputStream, then reads via InputStream. + * Requires explicit {@code ExcelFormat} because the stream API needs the type hint. + */ + public static List writeAndReadViaStream( + File file, ExcelFormat format, Class clazz, List data) throws Exception { + try (OutputStream os = new FileOutputStream(file)) { + FesodSheet.write(os, clazz) + .excelType(format.toExcelTypeEnum()) + .sheet() + .doWrite(data); + } + try (InputStream is = new FileInputStream(file)) { + CollectingReadListener listener = new CollectingReadListener(); + FesodSheet.read(is, clazz, listener) + .excelType(format.toExcelTypeEnum()) + .sheet() + .doRead(); + return listener.getRows(); + } + } + + /** + * Writes data via OutputStream, then reads using a different model via InputStream. + */ + public static List writeAndReadViaStream( + File file, ExcelFormat format, Class writeClazz, List data, Class readClazz) throws Exception { + try (OutputStream os = new FileOutputStream(file)) { + FesodSheet.write(os, writeClazz) + .excelType(format.toExcelTypeEnum()) + .sheet() + .doWrite(data); + } + try (InputStream is = new FileInputStream(file)) { + CollectingReadListener listener = new CollectingReadListener(); + FesodSheet.read(is, readClazz, listener) + .excelType(format.toExcelTypeEnum()) + .sheet() + .doRead(); + return listener.getRows(); + } + } + + // ---- Sync read round trip ---- + + /** + * Writes data to file, then reads synchronously via {@code doReadSync()}. + */ + @SuppressWarnings("unchecked") + public static List writeAndReadSync(File file, Class clazz, List data) { + write(file, clazz, data); + List raw = FesodSheet.read(file).head(clazz).sheet().doReadSync(); + List result = new ArrayList(raw.size()); + for (Object obj : raw) { + result.add((T) obj); + } + return result; + } + + // ---- API-mode-aware round trip ---- + + /** + * Dispatches to File-based or Stream-based round-trip based on {@code mode}. + */ + public static List writeAndRead( + File file, ExcelFormat format, ApiMode mode, Class clazz, List data) throws Exception { + if (mode == ApiMode.STREAM) { + return writeAndReadViaStream(file, format, clazz, data); + } + return writeAndRead(file, clazz, data); + } + + /** + * Dispatches to File-based or Stream-based round-trip with asymmetric models. + */ + public static List writeAndRead( + File file, ExcelFormat format, ApiMode mode, Class writeClazz, List data, Class readClazz) + throws Exception { + if (mode == ApiMode.STREAM) { + return writeAndReadViaStream(file, format, writeClazz, data, readClazz); + } + return writeAndRead(file, writeClazz, data, readClazz); + } + + // ---- Primitives ---- + + /** + * Writes data to a file using the File-based API. + */ + public static void write(File file, Class clazz, List data) { + FesodSheet.write(file, clazz).sheet().doWrite(data); + } + + /** + * Reads data from a file using the File-based API with a {@link CollectingReadListener}. + */ + public static List read(File file, Class clazz) { + CollectingReadListener listener = new CollectingReadListener(); + FesodSheet.read(file, clazz, listener).sheet().doRead(); + return listener.getRows(); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/helpers/RoundTripHelperTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/helpers/RoundTripHelperTest.java new file mode 100644 index 000000000..aeff87ee5 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/helpers/RoundTripHelperTest.java @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.helpers; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.apache.fesod.sheet.testkit.enums.ApiMode; +import org.apache.fesod.sheet.testkit.enums.ExcelFormat; +import org.apache.fesod.sheet.testkit.models.SimpleData; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +class RoundTripHelperTest { + + @TempDir + File tempDir; + + private static List simpleData(int count) { + List list = new ArrayList(); + for (int i = 0; i < count; i++) { + SimpleData d = new SimpleData(); + d.setName("Name" + i); + list.add(d); + } + return list; + } + + @ParameterizedTest + @EnumSource(ExcelFormat.class) + void writeAndReadPreservesRowCount(ExcelFormat format) throws IOException { + File file = format.createTempFile("rth-test", tempDir); + List data = simpleData(10); + + List result = RoundTripHelper.writeAndRead(file, SimpleData.class, data); + + assertEquals(10, result.size()); + assertEquals("Name0", result.get(0).getName()); + assertEquals("Name9", result.get(9).getName()); + } + + @ParameterizedTest + @EnumSource(ExcelFormat.class) + void writeAndReadViaStream(ExcelFormat format) throws Exception { + File file = format.createTempFile("rth-stream", tempDir); + List data = simpleData(5); + + List result = RoundTripHelper.writeAndReadViaStream(file, format, SimpleData.class, data); + + assertEquals(5, result.size()); + assertEquals("Name0", result.get(0).getName()); + assertEquals("Name4", result.get(4).getName()); + } + + @ParameterizedTest + @EnumSource(ExcelFormat.class) + void writeAndReadSync(ExcelFormat format) throws IOException { + File file = format.createTempFile("rth-sync", tempDir); + List data = simpleData(3); + + List result = RoundTripHelper.writeAndReadSync(file, SimpleData.class, data); + + assertEquals(3, result.size()); + assertEquals("Name0", result.get(0).getName()); + } + + @ParameterizedTest + @EnumSource(ExcelFormat.class) + void apiModeFileMatchesDirect(ExcelFormat format) throws Exception { + File file = format.createTempFile("rth-mode", tempDir); + List data = simpleData(7); + + List result = RoundTripHelper.writeAndRead(file, format, ApiMode.FILE, SimpleData.class, data); + + assertEquals(7, result.size()); + assertEquals("Name0", result.get(0).getName()); + } + + @ParameterizedTest + @EnumSource(ExcelFormat.class) + void apiModeStreamMatchesDirect(ExcelFormat format) throws Exception { + File file = format.createTempFile("rth-smode", tempDir); + List data = simpleData(7); + + List result = RoundTripHelper.writeAndRead(file, format, ApiMode.STREAM, SimpleData.class, data); + + assertEquals(7, result.size()); + assertEquals("Name0", result.get(0).getName()); + } + + @ParameterizedTest + @EnumSource(ExcelFormat.class) + void fileAndStreamApiProduceSameResults(ExcelFormat format) throws Exception { + List data = simpleData(5); + + File fileA = format.createTempFile("rth-fa", tempDir); + List fileResult = RoundTripHelper.writeAndRead(fileA, SimpleData.class, data); + + File fileB = format.createTempFile("rth-fb", tempDir); + List streamResult = RoundTripHelper.writeAndReadViaStream(fileB, format, SimpleData.class, data); + + assertEquals(fileResult.size(), streamResult.size()); + for (int i = 0; i < fileResult.size(); i++) { + assertEquals(fileResult.get(i).getName(), streamResult.get(i).getName()); + } + } + + @ParameterizedTest + @EnumSource(ExcelFormat.class) + void writePrimitiveThenReadPrimitive(ExcelFormat format) throws IOException { + File file = format.createTempFile("rth-prim", tempDir); + List data = simpleData(4); + + RoundTripHelper.write(file, SimpleData.class, data); + List result = RoundTripHelper.read(file, SimpleData.class); + + assertNotNull(result); + assertFalse(result.isEmpty()); + assertEquals(4, result.size()); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/listeners/CollectingReadListener.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/listeners/CollectingReadListener.java new file mode 100644 index 000000000..38c8e5cc0 --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/listeners/CollectingReadListener.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.listeners; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.apache.fesod.sheet.context.AnalysisContext; +import org.apache.fesod.sheet.event.AnalysisEventListener; + +/** + * A generic, reusable {@link AnalysisEventListener} that simply collects every row into a list. + * + *

    Unlike the legacy per-test listeners, this class contains no assertions and + * no logging. Assertions belong in the test method; data collection belongs here. + * + * @param the row model type + */ +public class CollectingReadListener extends AnalysisEventListener { + + private final List rows = new ArrayList(); + + @Override + public void invoke(T data, AnalysisContext context) { + rows.add(data); + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + // intentionally empty — no assertions, no logging + } + + /** + * Returns an unmodifiable view of all collected rows. + */ + public List getRows() { + return Collections.unmodifiableList(rows); + } + + /** + * Returns the number of collected rows. + */ + public int getRowCount() { + return rows.size(); + } + + /** + * Returns the first collected row. + * + * @throws AssertionError if no rows have been collected + */ + public T getFirstRow() { + if (rows.isEmpty()) { + throw new AssertionError("Expected at least one row, but CollectingReadListener collected none"); + } + return rows.get(0); + } + + /** + * Clears all collected rows, allowing reuse of the same listener instance. + */ + public void clear() { + rows.clear(); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/listeners/CollectingReadListenerTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/listeners/CollectingReadListenerTest.java new file mode 100644 index 000000000..e72725b3d --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/listeners/CollectingReadListenerTest.java @@ -0,0 +1,106 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.listeners; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.List; +import org.junit.jupiter.api.Test; + +class CollectingReadListenerTest { + + @Test + void collectionInvariantWithMultipleInvocations() { + CollectingReadListener listener = new CollectingReadListener(); + + listener.invoke("row0", null); + listener.invoke("row1", null); + listener.invoke("row2", null); + + assertEquals(3, listener.getRowCount()); + List rows = listener.getRows(); + assertEquals(3, rows.size()); + assertEquals("row0", rows.get(0)); + assertEquals("row1", rows.get(1)); + assertEquals("row2", rows.get(2)); + } + + @Test + void getRowsReturnsUnmodifiableView() { + CollectingReadListener listener = new CollectingReadListener(); + listener.invoke("data", null); + + List rows = listener.getRows(); + assertThrows(UnsupportedOperationException.class, () -> rows.add("illegal")); + assertThrows(UnsupportedOperationException.class, () -> rows.remove(0)); + assertThrows(UnsupportedOperationException.class, () -> rows.clear()); + } + + @Test + void clearResetsState() { + CollectingReadListener listener = new CollectingReadListener(); + listener.invoke("row0", null); + listener.invoke("row1", null); + assertEquals(2, listener.getRowCount()); + + listener.clear(); + + assertEquals(0, listener.getRowCount()); + assertTrue(listener.getRows().isEmpty()); + } + + @Test + void getFirstRowReturnsFirstElement() { + CollectingReadListener listener = new CollectingReadListener(); + listener.invoke("first", null); + listener.invoke("second", null); + + assertEquals("first", listener.getFirstRow()); + } + + @Test + void getFirstRowOnEmptyThrowsAssertionError() { + CollectingReadListener listener = new CollectingReadListener(); + + AssertionError error = assertThrows(AssertionError.class, () -> listener.getFirstRow()); + assertTrue(error.getMessage().contains("at least one row")); + } + + @Test + void doAfterAllAnalysedDoesNothing() { + CollectingReadListener listener = new CollectingReadListener(); + listener.invoke("data", null); + + // should not throw or modify state + listener.doAfterAllAnalysed(null); + + assertEquals(1, listener.getRowCount()); + assertEquals("data", listener.getFirstRow()); + } + + @Test + void emptyListenerHasZeroRows() { + CollectingReadListener listener = new CollectingReadListener(); + + assertEquals(0, listener.getRowCount()); + assertTrue(listener.getRows().isEmpty()); + } +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/models/ConverterBaseData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/models/ConverterBaseData.java new file mode 100644 index 000000000..853d8097b --- /dev/null +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/models/ConverterBaseData.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fesod.sheet.testkit.models; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Date; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import org.apache.fesod.sheet.annotation.ExcelProperty; + +/** + * Abstract base class extracting the 13 common fields shared by + * {@code ConverterReadData} and {@code ConverterWriteData}. + */ +@Getter +@Setter +@EqualsAndHashCode +public abstract class ConverterBaseData { + @ExcelProperty("Date") + private Date date; + + @ExcelProperty("Local Date") + private LocalDate localDate; + + @ExcelProperty("Local Date Time") + private LocalDateTime localDateTime; + + @ExcelProperty("Boolean") + private Boolean booleanData; + + @ExcelProperty("Big Decimal") + private BigDecimal bigDecimal; + + @ExcelProperty("Big Integer") + private BigInteger bigInteger; + + @ExcelProperty("Long") + private long longData; + + @ExcelProperty("Integer") + private Integer integerData; + + @ExcelProperty("Short") + private Short shortData; + + @ExcelProperty("Byte") + private Byte byteData; + + @ExcelProperty("Double") + private double doubleData; + + @ExcelProperty("Float") + private Float floatData; + + @ExcelProperty("String") + private String string; +} diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/models/SimpleData.java similarity index 82% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/models/SimpleData.java index 27ff2c349..a988e90f2 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/simple/SimpleData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/models/SimpleData.java @@ -23,25 +23,27 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.simple; +package org.apache.fesod.sheet.testkit.models; +import java.util.Date; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.fesod.sheet.annotation.ExcelProperty; /** - * mock data format for simple read/write - *

    - * Use ExcelProperty {@link ExcelProperty} to mark headers - *

    - * - * + * Three-field simple data model for read/write tests. */ @Getter @Setter @EqualsAndHashCode public class SimpleData { - @ExcelProperty("姓名") + @ExcelProperty("Name") private String name; + + @ExcelProperty("Age") + private Integer age; + + @ExcelProperty("Date") + private Date date; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/multiplesheets/MultipleSheetsData.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/models/TitleData.java similarity index 88% rename from fesod-sheet/src/test/java/org/apache/fesod/sheet/multiplesheets/MultipleSheetsData.java rename to fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/models/TitleData.java index f02d503a5..40f76cc07 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/multiplesheets/MultipleSheetsData.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/testkit/models/TitleData.java @@ -23,18 +23,18 @@ * Copyright (C) 2018-2024 Alibaba Group Holding Ltd. */ -package org.apache.fesod.sheet.multiplesheets; +package org.apache.fesod.sheet.testkit.models; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** - * + * Simple title data model for multiple-sheet and hidden-sheet tests. */ @Getter @Setter @EqualsAndHashCode -public class MultipleSheetsData { +public class TitleData { private String title; } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/BeanMapUtilsTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/BeanMapUtilsTest.java index 19eb919a9..582befa49 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/BeanMapUtilsTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/BeanMapUtilsTest.java @@ -19,6 +19,8 @@ package org.apache.fesod.sheet.util; +import lombok.Getter; +import lombok.Setter; import org.apache.fesod.shaded.cglib.beans.BeanMap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -28,25 +30,11 @@ */ class BeanMapUtilsTest { + @Setter + @Getter public static class TestUser { private String name; private int age; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } } @Test diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/ClassUtilsTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/ClassUtilsTest.java index da41bae8d..c48f231a1 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/ClassUtilsTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/ClassUtilsTest.java @@ -125,7 +125,7 @@ void test_declaredFields_cache_memory() { } @Test - void test_declaredFields_cache_ThreadLocal() throws NoSuchFieldException, IllegalAccessException { + void test_declaredFields_cache_ThreadLocal() { Mockito.when(globalConfiguration.getFiledCacheLocation()).thenReturn(CacheLocationEnum.THREAD_LOCAL); FieldCache cache1 = ClassUtils.declaredFields(SimpleEntity.class, writeHolder); diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/ConverterUtilsTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/ConverterUtilsTest.java index 8f8e69cd5..31c907515 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/ConverterUtilsTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/ConverterUtilsTest.java @@ -202,7 +202,7 @@ void test_ReadCellData_raw_defaultString() throws Exception, NoSuchFieldExceptio Object result = ConverterUtils.convertToJavaObject( cellData, field, ReadCellData.class, null, null, converterMap, context, 1, 0); - Assertions.assertTrue(result instanceof ReadCellData); + Assertions.assertInstanceOf(ReadCellData.class, result); Mockito.verify(stringConverter).convertToJavaData(Mockito.any()); } diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/DateUtilsTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/DateUtilsTest.java index 43460cfc2..7b3aaa109 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/DateUtilsTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/DateUtilsTest.java @@ -210,7 +210,7 @@ void test_format_BigDecimal() { "61.0, 1900-03-01 00:00:00", "43831.5, 2020-01-01 12:00:00" }) - void test_getJavaDate_1900(double excelValue, String expectedStr) throws ParseException { + void test_getJavaDate_1900(double excelValue, String expectedStr) { Date date = DateUtils.getJavaDate(excelValue, false); SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_19); diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/FileTypeUtilsTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/FileTypeUtilsTest.java index fcd84924b..6e404068c 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/FileTypeUtilsTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/FileTypeUtilsTest.java @@ -47,7 +47,7 @@ void setup() throws Exception { } private byte[] loadImage(String filename) throws IOException { - try (InputStream is = getClass().getClassLoader().getResourceAsStream("images" + File.separator + filename); ) { + try (InputStream is = getClass().getClassLoader().getResourceAsStream("images" + File.separator + filename)) { Assertions.assertNotNull(is); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/StyleUtilTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/StyleUtilTest.java index fefd57973..438769c85 100644 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/StyleUtilTest.java +++ b/fesod-sheet/src/test/java/org/apache/fesod/sheet/util/StyleUtilTest.java @@ -123,7 +123,7 @@ void testBuildCellStyle_withAllPropertiesSet_shouldApplyAllProperties() { void testBuildCellStyle_withPartialPropertiesSet_shouldOnlyApplyNonNullProperties() { Workbook workbook = new HSSFWorkbook(); CellStyle originStyle = workbook.createCellStyle(); - originStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 原始值 + originStyle.setVerticalAlignment(VerticalAlignment.CENTER); // original value WriteCellStyle writeCellStyle = new WriteCellStyle(); writeCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT); diff --git a/fesod-sheet/src/test/java/org/apache/fesod/sheet/writesheet/WriteSheetTest.java b/fesod-sheet/src/test/java/org/apache/fesod/sheet/writesheet/WriteSheetTest.java deleted file mode 100644 index a6099467a..000000000 --- a/fesod-sheet/src/test/java/org/apache/fesod/sheet/writesheet/WriteSheetTest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.fesod.sheet.writesheet; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class WriteSheetTest { - - @Test - public void testSheetOrder03() { - // normal - testSheetOrderInternal(ExcelTypeEnum.XLS, Arrays.asList(0)); - testSheetOrderInternal(ExcelTypeEnum.XLS, Arrays.asList(0, 1, 2)); - // sheetNo is bigger than the size of workbook sheet num - testSheetOrderInternal(ExcelTypeEnum.XLS, Arrays.asList(2)); - testSheetOrderInternal(ExcelTypeEnum.XLS, Arrays.asList(10, 6, 8)); - // negative numbers - testSheetOrderInternal(ExcelTypeEnum.XLS, Arrays.asList(-1)); - testSheetOrderInternal(ExcelTypeEnum.XLS, Arrays.asList(-8, -10, -6)); - testSheetOrderInternal(ExcelTypeEnum.XLS, Arrays.asList(-8, 6)); - // build a WriteSheet using the sheet name - testSheetOrderWithSheetName(ExcelTypeEnum.XLS); - } - - @Test - public void testSheetOrder07() { - // normal - testSheetOrderInternal(ExcelTypeEnum.XLSX, Arrays.asList(0)); - testSheetOrderInternal(ExcelTypeEnum.XLSX, Arrays.asList(0, 1, 2)); - // sheetNo is bigger than the size of workbook sheet num - testSheetOrderInternal(ExcelTypeEnum.XLSX, Arrays.asList(2)); - testSheetOrderInternal(ExcelTypeEnum.XLSX, Arrays.asList(10, 6, 8)); - // negative numbers - testSheetOrderInternal(ExcelTypeEnum.XLSX, Arrays.asList(-1)); - testSheetOrderInternal(ExcelTypeEnum.XLSX, Arrays.asList(-8, -10, -6)); - testSheetOrderInternal(ExcelTypeEnum.XLSX, Arrays.asList(-8, 6)); - // build a WriteSheet using the sheet name - testSheetOrderWithSheetName(ExcelTypeEnum.XLSX); - } - - private void testSheetOrderInternal(ExcelTypeEnum excelTypeEnum, List sheetNoList) { - Map dataMap = initSheetDataSizeList(sheetNoList); - - File testFile = TestFileUtil.createNewFile("writesheet/write-sheet-order" + excelTypeEnum.getValue()); - // write a file in the order of sheetNoList. - try (ExcelWriter excelWriter = FesodSheet.write(testFile, WriteSheetData.class) - .excelType(excelTypeEnum) - .build()) { - for (Integer sheetNo : sheetNoList) { - excelWriter.write( - dataList(dataMap.get(sheetNo)), - FesodSheet.writerSheet(sheetNo).build()); - } - } - - for (int i = 0; i < sheetNoList.size(); i++) { - List sheetDataList = FesodSheet.read(testFile) - .excelType(excelTypeEnum) - .head(WriteSheetData.class) - .sheet(i) - .doReadSync(); - Assertions.assertEquals(dataMap.get(sheetNoList.get(i)), sheetDataList.size()); - } - } - - private Map initSheetDataSizeList(List sheetNoList) { - // sort by sheetNo - Collections.sort(sheetNoList); - // key: sheetNo - // value: data size - Map dataMap = new HashMap<>(); - for (int i = 0; i < sheetNoList.size(); i++) { - dataMap.put(sheetNoList.get(i), i + 1); - } - return dataMap; - } - - private void testSheetOrderWithSheetName(ExcelTypeEnum excelTypeEnum) { - List sheetNameList = Arrays.asList("Sheet1", "Sheet2", "Sheet3", "Sheet111112222233333444445555566666"); - List sheetNoList = Arrays.asList(0, 1, 2, 3); - - Map dataMap = initSheetDataSizeList(sheetNoList); - File testFile = TestFileUtil.createNewFile("writesheet/write-sheet-order-name" + excelTypeEnum.getValue()); - - try (ExcelWriter excelWriter = FesodSheet.write(testFile, WriteSheetData.class) - .excelType(excelTypeEnum) - .build()) { - - // sheetName is empty - int sheetNo = 0; - WriteSheet writeSheet = FesodSheet.writerSheet(sheetNo).build(); - excelWriter.write(dataList(dataMap.get(sheetNo)), writeSheet); - Assertions.assertEquals( - sheetNo, excelWriter.writeContext().writeSheetHolder().getSheetNo()); - - // sheetNo is empty - sheetNo = 1; - writeSheet = FesodSheet.writerSheet(sheetNameList.get(sheetNo)).build(); - excelWriter.write(dataList(dataMap.get(sheetNo)), writeSheet); - Assertions.assertEquals( - sheetNo, excelWriter.writeContext().writeSheetHolder().getSheetNo()); - - sheetNo = 2; - writeSheet = - FesodSheet.writerSheet(sheetNo, sheetNameList.get(sheetNo)).build(); - excelWriter.write(dataList(dataMap.get(sheetNo)), writeSheet); - Assertions.assertEquals( - sheetNo, excelWriter.writeContext().writeSheetHolder().getSheetNo()); - - sheetNo = 3; - writeSheet = - FesodSheet.writerSheet(sheetNo, sheetNameList.get(sheetNo)).build(); - excelWriter.write(dataList(dataMap.get(sheetNo)), writeSheet); - Assertions.assertEquals( - sheetNameList.get(sheetNo).substring(0, Workbook.MAX_SENSITIVE_SHEET_NAME_LEN), - excelWriter.writeContext().writeSheetHolder().getSheetName()); - Assertions.assertEquals( - sheetNo, excelWriter.writeContext().writeSheetHolder().getSheetNo()); - } - - for (int i = 0; i < sheetNoList.size(); i++) { - List sheetDataList = FesodSheet.read(testFile) - .excelType(excelTypeEnum) - .head(WriteSheetData.class) - .sheet(i) - .doReadSync(); - Assertions.assertEquals(dataMap.get(sheetNoList.get(i)), sheetDataList.size()); - } - } - - private static List dataList(int size) { - List dataList = new ArrayList<>(); - for (int i = 0; i < size; i++) { - WriteSheetData data = new WriteSheetData(); - data.setString("String" + i); - dataList.add(data); - } - return dataList; - } -} diff --git a/fesod-sheet/src/test/resources/bom/no_bom.csv b/fesod-sheet/src/test/resources/bom/no_bom.csv index 461c1eb00..376236535 100644 --- a/fesod-sheet/src/test/resources/bom/no_bom.csv +++ b/fesod-sheet/src/test/resources/bom/no_bom.csv @@ -1,4 +1,4 @@ -姓名,年纪 +Name,Age 姓名0,20 姓名1,20 姓名2,20 diff --git a/fesod-sheet/src/test/resources/bom/office_bom.csv b/fesod-sheet/src/test/resources/bom/office_bom.csv index b6a80992d..93b8aa428 100644 --- a/fesod-sheet/src/test/resources/bom/office_bom.csv +++ b/fesod-sheet/src/test/resources/bom/office_bom.csv @@ -1,4 +1,4 @@ -姓名,年纪 +Name,Age 姓名0,20 姓名1,20 姓名2,20 diff --git a/fesod-sheet/src/test/resources/converter/converterCsv.csv b/fesod-sheet/src/test/resources/converter/convertercsv.csv similarity index 100% rename from fesod-sheet/src/test/resources/converter/converterCsv.csv rename to fesod-sheet/src/test/resources/converter/convertercsv.csv diff --git a/fesod-sheet/src/test/resources/csv/simple-quote.csv b/fesod-sheet/src/test/resources/csv/simple-quote.csv index 0af30b141..445c0b33f 100644 --- a/fesod-sheet/src/test/resources/csv/simple-quote.csv +++ b/fesod-sheet/src/test/resources/csv/simple-quote.csv @@ -1,4 +1,4 @@ -"字符串标题","日期标题","数字标题" +"String","Date","Number" "String0,""quote""","2020-01-01 01:01:00",1 "String1","2020-01-02 01:01:00",2 "String2","2020-01-03 01:01:00",3 diff --git a/fesod-sheet/src/test/resources/csv/simple.csv b/fesod-sheet/src/test/resources/csv/simple.csv index 31bbc9161..22da9570d 100644 --- a/fesod-sheet/src/test/resources/csv/simple.csv +++ b/fesod-sheet/src/test/resources/csv/simple.csv @@ -1,4 +1,4 @@ -字符串标题,日期标题,数字标题 +String,Date,Number String0,2020-01-01 01:01:00,1 String1,2020-01-02 01:01:00,2 String2,2020-01-03 01:01:00,3