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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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.junit.Assert.assertEquals;
  17. import static org.junit.Assert.assertNotNull;
  18. import static org.junit.Assert.fail;
  19. import static org.junit.Assume.assumeNotNull;
  20. import static org.junit.Assume.assumeTrue;
  21. import java.util.ArrayList;
  22. import java.util.Collection;
  23. import java.util.List;
  24. import java.util.Locale;
  25. import org.apache.poi.hssf.HSSFTestDataSamples;
  26. import org.apache.poi.openxml4j.opc.OPCPackage;
  27. import org.apache.poi.openxml4j.opc.PackageAccess;
  28. import org.apache.poi.ss.formula.eval.TestFormulasFromSpreadsheet;
  29. import org.apache.poi.ss.formula.functions.TestMathX;
  30. import org.apache.poi.ss.usermodel.Cell;
  31. import org.apache.poi.ss.usermodel.CellType;
  32. import org.apache.poi.ss.usermodel.CellValue;
  33. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  34. import org.apache.poi.ss.usermodel.Row;
  35. import org.apache.poi.ss.usermodel.Sheet;
  36. import org.apache.poi.util.POILogFactory;
  37. import org.apache.poi.util.POILogger;
  38. import org.junit.AfterClass;
  39. import org.junit.Test;
  40. import org.junit.runner.RunWith;
  41. import org.junit.runners.Parameterized;
  42. import org.junit.runners.Parameterized.Parameter;
  43. import org.junit.runners.Parameterized.Parameters;
  44. /**
  45. * Tests formulas for multi sheet reference (i.e. SUM(Sheet1:Sheet5!A1))
  46. */
  47. @RunWith(Parameterized.class)
  48. public final class TestMultiSheetFormulaEvaluatorOnXSSF {
  49. private static final POILogger logger = POILogFactory.getLogger(TestFormulasFromSpreadsheet.class);
  50. private static XSSFWorkbook workbook;
  51. private static Sheet sheet;
  52. private static FormulaEvaluator evaluator;
  53. /**
  54. * This class defines constants for navigating around the test data spreadsheet used for these tests.
  55. */
  56. interface SS {
  57. /**
  58. * Name of the test spreadsheet (found in the standard test data folder)
  59. */
  60. String FILENAME = "FormulaSheetRange.xlsx";
  61. /**
  62. * Row (zero-based) in the test spreadsheet where the function examples start.
  63. */
  64. int START_FUNCTIONS_ROW_INDEX = 10; // Row '11'
  65. /**
  66. * Index of the column that contains the function names
  67. */
  68. int COLUMN_INDEX_FUNCTION_NAME = 0; // Column 'A'
  69. /**
  70. * Index of the column that contains the test names
  71. */
  72. int COLUMN_INDEX_TEST_NAME = 1; // Column 'B'
  73. /**
  74. * Used to indicate when there are no more functions left
  75. */
  76. String FUNCTION_NAMES_END_SENTINEL = "<END>";
  77. /**
  78. * Index of the column where the test expected value is present
  79. */
  80. short COLUMN_INDEX_EXPECTED_VALUE = 2; // Column 'C'
  81. /**
  82. * Index of the column where the test actual value is present
  83. */
  84. short COLUMN_INDEX_ACTUAL_VALUE = 3; // Column 'D'
  85. /**
  86. * Test sheet name (sheet with all test formulae)
  87. */
  88. String TEST_SHEET_NAME = "test";
  89. }
  90. @Parameter(value = 0)
  91. public String targetTestName;
  92. @Parameter(value = 1)
  93. public String targetFunctionName;
  94. @Parameter(value = 2)
  95. public int formulasRowIdx;
  96. @AfterClass
  97. public static void closeResource() throws Exception {
  98. workbook.close();
  99. }
  100. @Parameters(name="{0}")
  101. public static Collection<Object[]> data() throws Exception {
  102. workbook = new XSSFWorkbook( OPCPackage.open(HSSFTestDataSamples.getSampleFile(SS.FILENAME), PackageAccess.READ) );
  103. sheet = workbook.getSheet( SS.TEST_SHEET_NAME );
  104. evaluator = new XSSFFormulaEvaluator(workbook);
  105. List<Object[]> data = new ArrayList<Object[]>();
  106. processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, null);
  107. return data;
  108. }
  109. /**
  110. * @param startRowIndex row index in the spreadsheet where the first function/operator is found
  111. * @param testFocusFunctionName name of a single function/operator to test alone.
  112. * Typically pass <code>null</code> to test all functions
  113. */
  114. private static void processFunctionGroup(List<Object[]> data, int startRowIndex, String testFocusFunctionName) {
  115. for (int rowIndex = startRowIndex; true; rowIndex++) {
  116. Row r = sheet.getRow(rowIndex);
  117. // only evaluate non empty row
  118. if(r == null) continue;
  119. String targetFunctionName = getTargetFunctionName(r);
  120. assertNotNull("Test spreadsheet cell empty on row ("
  121. + (rowIndex+1) + "). Expected function name or '"
  122. + SS.FUNCTION_NAMES_END_SENTINEL + "'", targetFunctionName);
  123. if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) {
  124. // found end of functions list
  125. break;
  126. }
  127. String targetTestName = getTargetTestName(r);
  128. if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) {
  129. // expected results are on the row below
  130. Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE);
  131. assertNotNull("Missing expected values cell for function '"
  132. + targetFunctionName + ", test" + targetTestName + " (row " +
  133. rowIndex + 1 + ")", expectedValueCell);
  134. data.add(new Object[]{targetTestName, targetFunctionName, rowIndex});
  135. }
  136. }
  137. }
  138. /**
  139. *
  140. * @return a constant from the local Result class denoting whether there were any evaluation
  141. * cases, and whether they all succeeded.
  142. */
  143. @Test
  144. public void processFunctionRow() {
  145. Row r = sheet.getRow(formulasRowIdx);
  146. Cell expValue = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE);
  147. assertNotNull("Missing expected values cell for function '"
  148. + targetFunctionName + ", test" + targetTestName + " (row " +
  149. formulasRowIdx + 1 + ")", expValue);
  150. Cell c = r.getCell(SS.COLUMN_INDEX_ACTUAL_VALUE);
  151. assumeNotNull(c);
  152. assumeTrue(c.getCellTypeEnum() == CellType.FORMULA);
  153. CellValue actValue = evaluator.evaluate(c);
  154. String msg = String.format(Locale.ROOT, "Function '%s': Test: '%s': Formula: %s @ %d:%d",
  155. targetFunctionName, targetTestName, c.getCellFormula(), formulasRowIdx, SS.COLUMN_INDEX_ACTUAL_VALUE);
  156. assertNotNull(msg + " - actual value was null", actValue);
  157. final CellType expectedCellType = expValue.getCellTypeEnum();
  158. switch (expectedCellType) {
  159. case BLANK:
  160. assertEquals(msg, CellType.BLANK, actValue.getCellTypeEnum());
  161. break;
  162. case BOOLEAN:
  163. assertEquals(msg, CellType.BOOLEAN, actValue.getCellTypeEnum());
  164. assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue());
  165. break;
  166. case ERROR:
  167. assertEquals(msg, CellType.ERROR, actValue.getCellTypeEnum());
  168. // if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values
  169. // assertEquals(msg, expected.getErrorCellValue(), actual.getErrorValue());
  170. // }
  171. break;
  172. case FORMULA: // will never be used, since we will call method after formula evaluation
  173. fail("Cannot expect formula as result of formula evaluation: " + msg);
  174. case NUMERIC:
  175. assertEquals(msg, CellType.NUMERIC, actValue.getCellTypeEnum());
  176. TestMathX.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR);
  177. // double delta = Math.abs(expected.getNumericCellValue()-actual.getNumberValue());
  178. // double pctExpected = Math.abs(0.00001*expected.getNumericCellValue());
  179. // assertTrue(msg, delta <= pctExpected);
  180. break;
  181. case STRING:
  182. assertEquals(msg, CellType.STRING, actValue.getCellTypeEnum());
  183. assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue());
  184. break;
  185. default:
  186. fail("Unexpected cell type: " + expectedCellType);
  187. }
  188. }
  189. /**
  190. * @return <code>null</code> if cell is missing, empty or blank
  191. */
  192. private static String getTargetFunctionName(Row r) {
  193. if(r == null) {
  194. logger.log(POILogger.WARN, "Warning - given null row, can't figure out function name");
  195. return null;
  196. }
  197. Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME);
  198. if(cell == null) {
  199. logger.log(POILogger.WARN, "Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name");
  200. return null;
  201. }
  202. if(cell.getCellTypeEnum() == CellType.BLANK) {
  203. return null;
  204. }
  205. if(cell.getCellTypeEnum() == CellType.STRING) {
  206. return cell.getRichStringCellValue().getString();
  207. }
  208. fail("Bad cell type for 'function name' column: ("
  209. + cell.getCellTypeEnum() + ") row (" + (r.getRowNum() +1) + ")");
  210. return "";
  211. }
  212. /**
  213. * @return <code>null</code> if cell is missing, empty or blank
  214. */
  215. private static String getTargetTestName(Row r) {
  216. if(r == null) {
  217. logger.log(POILogger.WARN, "Warning - given null row, can't figure out test name");
  218. return null;
  219. }
  220. Cell cell = r.getCell(SS.COLUMN_INDEX_TEST_NAME);
  221. if(cell == null) {
  222. logger.log(POILogger.WARN, "Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_TEST_NAME + ", can't figure out test name");
  223. return null;
  224. }
  225. if(cell.getCellTypeEnum() == CellType.BLANK) {
  226. return null;
  227. }
  228. if(cell.getCellTypeEnum() == CellType.STRING) {
  229. return cell.getRichStringCellValue().getString();
  230. }
  231. fail("Bad cell type for 'test name' column: ("
  232. + cell.getCellTypeEnum() + ") row (" + (r.getRowNum() +1) + ")");
  233. return "";
  234. }
  235. }