You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestMultiSheetFormulaEvaluatorOnXSSF.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.xssf.usermodel;
  16. import static org.apache.logging.log4j.util.Unbox.box;
  17. import static org.apache.poi.xssf.usermodel.TestMultiSheetFormulaEvaluatorOnXSSF.SS.COLUMN_INDEX_FUNCTION_NAME;
  18. import static org.apache.poi.xssf.usermodel.TestMultiSheetFormulaEvaluatorOnXSSF.SS.COLUMN_INDEX_TEST_NAME;
  19. import static org.junit.jupiter.api.Assertions.assertEquals;
  20. import static org.junit.jupiter.api.Assertions.assertNotNull;
  21. import static org.junit.jupiter.api.Assertions.assertTrue;
  22. import static org.junit.jupiter.api.Assertions.fail;
  23. import static org.junit.jupiter.api.Assumptions.assumeTrue;
  24. import java.util.ArrayList;
  25. import java.util.List;
  26. import java.util.Locale;
  27. import java.util.stream.Stream;
  28. import org.apache.logging.log4j.LogManager;
  29. import org.apache.logging.log4j.Logger;
  30. import org.apache.poi.hssf.HSSFTestDataSamples;
  31. import org.apache.poi.openxml4j.opc.OPCPackage;
  32. import org.apache.poi.openxml4j.opc.PackageAccess;
  33. import org.apache.poi.ss.formula.functions.BaseTestNumeric;
  34. import org.apache.poi.ss.usermodel.Cell;
  35. import org.apache.poi.ss.usermodel.CellType;
  36. import org.apache.poi.ss.usermodel.CellValue;
  37. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  38. import org.apache.poi.ss.usermodel.Row;
  39. import org.apache.poi.ss.usermodel.Sheet;
  40. import org.junit.jupiter.api.AfterAll;
  41. import org.junit.jupiter.params.ParameterizedTest;
  42. import org.junit.jupiter.params.provider.Arguments;
  43. import org.junit.jupiter.params.provider.MethodSource;
  44. /**
  45. * Tests formulas for multi sheet reference (i.e. SUM(Sheet1:Sheet5!A1))
  46. */
  47. public final class TestMultiSheetFormulaEvaluatorOnXSSF {
  48. private static final Logger LOG = LogManager.getLogger(TestMultiSheetFormulaEvaluatorOnXSSF.class);
  49. private static XSSFWorkbook workbook;
  50. private static Sheet sheet;
  51. private static FormulaEvaluator evaluator;
  52. /**
  53. * This class defines constants for navigating around the test data spreadsheet used for these tests.
  54. */
  55. interface SS {
  56. /**
  57. * Name of the test spreadsheet (found in the standard test data folder)
  58. */
  59. String FILENAME = "FormulaSheetRange.xlsx";
  60. /**
  61. * Row (zero-based) in the test spreadsheet where the function examples start.
  62. */
  63. int START_FUNCTIONS_ROW_INDEX = 10; // Row '11'
  64. /**
  65. * Index of the column that contains the function names
  66. */
  67. int COLUMN_INDEX_FUNCTION_NAME = 0; // Column 'A'
  68. /**
  69. * Index of the column that contains the test names
  70. */
  71. int COLUMN_INDEX_TEST_NAME = 1; // Column 'B'
  72. /**
  73. * Used to indicate when there are no more functions left
  74. */
  75. String FUNCTION_NAMES_END_SENTINEL = "<END>";
  76. /**
  77. * Index of the column where the test expected value is present
  78. */
  79. short COLUMN_INDEX_EXPECTED_VALUE = 2; // Column 'C'
  80. /**
  81. * Index of the column where the test actual value is present
  82. */
  83. short COLUMN_INDEX_ACTUAL_VALUE = 3; // Column 'D'
  84. /**
  85. * Test sheet name (sheet with all test formulae)
  86. */
  87. String TEST_SHEET_NAME = "test";
  88. }
  89. @AfterAll
  90. public static void closeResource() throws Exception {
  91. workbook.close();
  92. }
  93. public static Stream<Arguments> data() throws Exception {
  94. workbook = new XSSFWorkbook( OPCPackage.open(HSSFTestDataSamples.getSampleFile(SS.FILENAME), PackageAccess.READ) );
  95. sheet = workbook.getSheet( SS.TEST_SHEET_NAME );
  96. evaluator = new XSSFFormulaEvaluator(workbook);
  97. List<Arguments> data = new ArrayList<>();
  98. processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, null);
  99. return data.stream();
  100. }
  101. /**
  102. * @param startRowIndex row index in the spreadsheet where the first function/operator is found
  103. * @param testFocusFunctionName name of a single function/operator to test alone.
  104. * Typically pass <code>null</code> to test all functions
  105. */
  106. private static void processFunctionGroup(List<Arguments> data, int startRowIndex, String testFocusFunctionName) {
  107. for (int rowIndex = startRowIndex; true; rowIndex++) {
  108. Row r = sheet.getRow(rowIndex);
  109. // only evaluate non empty row
  110. if(r == null) continue;
  111. String targetFunctionName = getTargetFunctionName(r);
  112. assertNotNull(targetFunctionName,
  113. "Test spreadsheet cell empty on row ("
  114. + (rowIndex+1) + "). Expected function name or '"
  115. + SS.FUNCTION_NAMES_END_SENTINEL + "'");
  116. if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) {
  117. // found end of functions list
  118. break;
  119. }
  120. String targetTestName = getTargetTestName(r);
  121. if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) {
  122. // expected results are on the row below
  123. Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE);
  124. assertNotNull(expectedValueCell,
  125. "Missing expected values cell for function '"
  126. + targetFunctionName + ", test" + targetTestName + " (row " +
  127. rowIndex + 1 + ")");
  128. data.add(Arguments.of(targetTestName, targetFunctionName, rowIndex));
  129. }
  130. }
  131. }
  132. @ParameterizedTest
  133. @MethodSource("data")
  134. void processFunctionRow(String targetTestName, String targetFunctionName, int formulasRowIdx) {
  135. Row r = sheet.getRow(formulasRowIdx);
  136. Cell expValue = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE);
  137. assertNotNull(expValue,
  138. "Missing expected values cell for function '"
  139. + targetFunctionName + ", test" + targetTestName + " (row " +
  140. formulasRowIdx + 1 + ")");
  141. Cell c = r.getCell(SS.COLUMN_INDEX_ACTUAL_VALUE);
  142. assumeTrue(c != null);
  143. assumeTrue(c.getCellType() == CellType.FORMULA);
  144. CellValue actValue = evaluator.evaluate(c);
  145. String msg = String.format(Locale.ROOT, "Function '%s': Test: '%s': Formula: %s @ %d:%d",
  146. targetFunctionName, targetTestName, c.getCellFormula(), formulasRowIdx, SS.COLUMN_INDEX_ACTUAL_VALUE);
  147. assertNotNull(actValue, msg + " - actual value was null");
  148. final CellType expectedCellType = expValue.getCellType();
  149. switch (expectedCellType) {
  150. case BLANK:
  151. assertEquals(CellType.BLANK, actValue.getCellType(), msg);
  152. break;
  153. case BOOLEAN:
  154. assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg);
  155. assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg);
  156. break;
  157. case ERROR:
  158. assertEquals(CellType.ERROR, actValue.getCellType(), msg);
  159. // if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values
  160. // assertEquals(msg, expected.getErrorCellValue(), actual.getErrorValue());
  161. // }
  162. break;
  163. case FORMULA: // will never be used, since we will call method after formula evaluation
  164. fail("Cannot expect formula as result of formula evaluation: " + msg);
  165. case NUMERIC:
  166. assertEquals(CellType.NUMERIC, actValue.getCellType(), msg);
  167. BaseTestNumeric.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR);
  168. // double delta = Math.abs(expected.getNumericCellValue()-actual.getNumberValue());
  169. // double pctExpected = Math.abs(0.00001*expected.getNumericCellValue());
  170. // assertTrue(msg, delta <= pctExpected);
  171. break;
  172. case STRING:
  173. assertEquals(CellType.STRING, actValue.getCellType(), msg);
  174. assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg);
  175. break;
  176. default:
  177. fail("Unexpected cell type: " + expectedCellType);
  178. }
  179. }
  180. /**
  181. * @return <code>null</code> if cell is missing, empty or blank
  182. */
  183. private static String getTargetFunctionName(Row r) {
  184. if(r == null) {
  185. LOG.atWarn().log("Given null row, can't figure out function name");
  186. return null;
  187. }
  188. Cell cell = r.getCell(COLUMN_INDEX_FUNCTION_NAME);
  189. if(cell == null) {
  190. LOG.atWarn().log("Row {} has no cell " + COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name", box(r.getRowNum()));
  191. return null;
  192. }
  193. CellType ct = cell.getCellType();
  194. assertTrue(ct == CellType.BLANK || ct == CellType.STRING,
  195. "Bad cell type for 'function name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")");
  196. return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null;
  197. }
  198. /**
  199. * @return <code>null</code> if cell is missing, empty or blank
  200. */
  201. private static String getTargetTestName(Row r) {
  202. if(r == null) {
  203. LOG.atWarn().log("Given null row, can't figure out test name");
  204. return null;
  205. }
  206. Cell cell = r.getCell(COLUMN_INDEX_TEST_NAME);
  207. if(cell == null) {
  208. LOG.atWarn().log("Row {} has no cell " + COLUMN_INDEX_TEST_NAME + ", can't figure out test name", box(r.getRowNum()));
  209. return null;
  210. }
  211. CellType ct = cell.getCellType();
  212. assertTrue(ct == CellType.BLANK || ct == CellType.STRING,
  213. "Bad cell type for 'test name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")");
  214. return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null;
  215. }
  216. }