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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 java.io.InputStream;
  17. import java.io.PrintStream;
  18. import java.util.Collection;
  19. import junit.framework.Assert;
  20. import junit.framework.AssertionFailedError;
  21. import junit.framework.TestCase;
  22. import org.apache.poi.hssf.HSSFTestDataSamples;
  23. import org.apache.poi.ss.formula.eval.TestFormulasFromSpreadsheet;
  24. import org.apache.poi.ss.formula.functions.TestMathX;
  25. import org.apache.poi.ss.usermodel.Cell;
  26. import org.apache.poi.ss.usermodel.CellValue;
  27. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  28. import org.apache.poi.ss.usermodel.Row;
  29. import org.apache.poi.ss.usermodel.Sheet;
  30. import org.apache.poi.openxml4j.opc.OPCPackage;
  31. import org.apache.poi.util.POILogFactory;
  32. import org.apache.poi.util.POILogger;
  33. /**
  34. * Tests formulas for multi sheet reference (i.e. SUM(Sheet1:Sheet5!A1))
  35. */
  36. public final class TestMultiSheetFormulaEvaluatorOnXSSF extends TestCase {
  37. private static final POILogger logger = POILogFactory.getLogger(TestFormulasFromSpreadsheet.class);
  38. private static final class Result {
  39. public static final int SOME_EVALUATIONS_FAILED = -1;
  40. public static final int ALL_EVALUATIONS_SUCCEEDED = +1;
  41. public static final int NO_EVALUATIONS_FOUND = 0;
  42. }
  43. /**
  44. * This class defines constants for navigating around the test data spreadsheet used for these tests.
  45. */
  46. private static final class SS {
  47. /**
  48. * Name of the test spreadsheet (found in the standard test data folder)
  49. */
  50. public final static String FILENAME = "FormulaSheetRange.xlsx";
  51. /**
  52. * Row (zero-based) in the test spreadsheet where the function examples start.
  53. */
  54. public static final int START_FUNCTIONS_ROW_INDEX = 10; // Row '11'
  55. /**
  56. * Index of the column that contains the function names
  57. */
  58. public static final int COLUMN_INDEX_FUNCTION_NAME = 0; // Column 'A'
  59. /**
  60. * Index of the column that contains the test names
  61. */
  62. public static final int COLUMN_INDEX_TEST_NAME = 1; // Column 'B'
  63. /**
  64. * Used to indicate when there are no more functions left
  65. */
  66. public static final String FUNCTION_NAMES_END_SENTINEL = "<END>";
  67. /**
  68. * Index of the column where the test expected value is present
  69. */
  70. public static final short COLUMN_INDEX_EXPECTED_VALUE = 2; // Column 'C'
  71. /**
  72. * Index of the column where the test actual value is present
  73. */
  74. public static final short COLUMN_INDEX_ACTUAL_VALUE = 3; // Column 'D'
  75. /**
  76. * Test sheet name (sheet with all test formulae)
  77. */
  78. public static final String TEST_SHEET_NAME = "test";
  79. }
  80. private XSSFWorkbook workbook;
  81. private Sheet sheet;
  82. // Note - multiple failures are aggregated before ending.
  83. // If one or more functions fail, a single AssertionFailedError is thrown at the end
  84. private int _functionFailureCount;
  85. private int _functionSuccessCount;
  86. private int _evaluationFailureCount;
  87. private int _evaluationSuccessCount;
  88. private static void confirmExpectedResult(String msg, Cell expected, CellValue actual) {
  89. if (expected == null) {
  90. throw new AssertionFailedError(msg + " - Bad setup data expected value is null");
  91. }
  92. if(actual == null) {
  93. throw new AssertionFailedError(msg + " - actual value was null");
  94. }
  95. switch (expected.getCellType()) {
  96. case Cell.CELL_TYPE_BLANK:
  97. assertEquals(msg, Cell.CELL_TYPE_BLANK, actual.getCellType());
  98. break;
  99. case Cell.CELL_TYPE_BOOLEAN:
  100. assertEquals(msg, Cell.CELL_TYPE_BOOLEAN, actual.getCellType());
  101. assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue());
  102. break;
  103. case Cell.CELL_TYPE_ERROR:
  104. assertEquals(msg, Cell.CELL_TYPE_ERROR, actual.getCellType());
  105. if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values
  106. assertEquals(msg, expected.getErrorCellValue(), actual.getErrorValue());
  107. }
  108. break;
  109. case Cell.CELL_TYPE_FORMULA: // will never be used, since we will call method after formula evaluation
  110. throw new AssertionFailedError("Cannot expect formula as result of formula evaluation: " + msg);
  111. case Cell.CELL_TYPE_NUMERIC:
  112. assertEquals(msg, Cell.CELL_TYPE_NUMERIC, actual.getCellType());
  113. TestMathX.assertEquals(msg, expected.getNumericCellValue(), actual.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR);
  114. // double delta = Math.abs(expected.getNumericCellValue()-actual.getNumberValue());
  115. // double pctExpected = Math.abs(0.00001*expected.getNumericCellValue());
  116. // assertTrue(msg, delta <= pctExpected);
  117. break;
  118. case Cell.CELL_TYPE_STRING:
  119. assertEquals(msg, Cell.CELL_TYPE_STRING, actual.getCellType());
  120. assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getStringValue());
  121. break;
  122. }
  123. }
  124. protected void setUp() throws Exception {
  125. if (workbook == null) {
  126. InputStream is = HSSFTestDataSamples.openSampleFileStream(SS.FILENAME);
  127. OPCPackage pkg = OPCPackage.open(is);
  128. workbook = new XSSFWorkbook( pkg );
  129. sheet = workbook.getSheet( SS.TEST_SHEET_NAME );
  130. }
  131. _functionFailureCount = 0;
  132. _functionSuccessCount = 0;
  133. _evaluationFailureCount = 0;
  134. _evaluationSuccessCount = 0;
  135. }
  136. public void testFunctionsFromTestSpreadsheet() {
  137. processFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, null);
  138. // confirm results
  139. String successMsg = "There were "
  140. + _evaluationSuccessCount + " successful evaluation(s) and "
  141. + _functionSuccessCount + " function(s) without error";
  142. if(_functionFailureCount > 0) {
  143. String msg = _functionFailureCount + " function(s) failed in "
  144. + _evaluationFailureCount + " evaluation(s). " + successMsg;
  145. throw new AssertionFailedError(msg);
  146. }
  147. logger.log(POILogger.INFO, getClass().getName() + ": " + successMsg);
  148. }
  149. /**
  150. * @param startRowIndex row index in the spreadsheet where the first function/operator is found
  151. * @param testFocusFunctionName name of a single function/operator to test alone.
  152. * Typically pass <code>null</code> to test all functions
  153. */
  154. private void processFunctionGroup(int startRowIndex, String testFocusFunctionName) {
  155. FormulaEvaluator evaluator = new XSSFFormulaEvaluator(workbook);
  156. int rowIndex = startRowIndex;
  157. while (true) {
  158. Row r = sheet.getRow(rowIndex);
  159. // only evaluate non empty row
  160. if( r != null )
  161. {
  162. String targetFunctionName = getTargetFunctionName(r);
  163. String targetTestName = getTargetTestName(r);
  164. if(targetFunctionName == null) {
  165. throw new AssertionFailedError("Test spreadsheet cell empty on row ("
  166. + (rowIndex+1) + "). Expected function name or '"
  167. + SS.FUNCTION_NAMES_END_SENTINEL + "'");
  168. }
  169. if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) {
  170. // found end of functions list
  171. break;
  172. }
  173. if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) {
  174. // expected results are on the row below
  175. Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE);
  176. if(expectedValueCell == null) {
  177. int missingRowNum = rowIndex + 1;
  178. throw new AssertionFailedError("Missing expected values cell for function '"
  179. + targetFunctionName + ", test" + targetTestName + " (row " +
  180. missingRowNum + ")");
  181. }
  182. switch(processFunctionRow(evaluator, targetFunctionName, targetTestName, r, expectedValueCell)) {
  183. case Result.ALL_EVALUATIONS_SUCCEEDED: _functionSuccessCount++; break;
  184. case Result.SOME_EVALUATIONS_FAILED: _functionFailureCount++; break;
  185. default:
  186. throw new RuntimeException("unexpected result");
  187. case Result.NO_EVALUATIONS_FOUND: // do nothing
  188. break;
  189. }
  190. }
  191. }
  192. rowIndex ++;
  193. }
  194. }
  195. /**
  196. *
  197. * @return a constant from the local Result class denoting whether there were any evaluation
  198. * cases, and whether they all succeeded.
  199. */
  200. private int processFunctionRow(FormulaEvaluator evaluator, String targetFunctionName,
  201. String targetTestName, Row formulasRow, Cell expectedValueCell) {
  202. int result = Result.NO_EVALUATIONS_FOUND; // so far
  203. Cell c = formulasRow.getCell(SS.COLUMN_INDEX_ACTUAL_VALUE);
  204. if (c == null || c.getCellType() != Cell.CELL_TYPE_FORMULA) {
  205. return result;
  206. }
  207. CellValue actualValue = evaluator.evaluate(c);
  208. try {
  209. confirmExpectedResult("Function '" + targetFunctionName + "': Test: '" + targetTestName + "' Formula: " + c.getCellFormula()
  210. + " @ " + formulasRow.getRowNum() + ":" + SS.COLUMN_INDEX_ACTUAL_VALUE,
  211. expectedValueCell, actualValue);
  212. _evaluationSuccessCount ++;
  213. if(result != Result.SOME_EVALUATIONS_FAILED) {
  214. result = Result.ALL_EVALUATIONS_SUCCEEDED;
  215. }
  216. } catch (AssertionFailedError e) {
  217. _evaluationFailureCount ++;
  218. printShortStackTrace(System.err, e);
  219. result = Result.SOME_EVALUATIONS_FAILED;
  220. }
  221. return result;
  222. }
  223. /**
  224. * Useful to keep output concise when expecting many failures to be reported by this test case
  225. */
  226. private static void printShortStackTrace(PrintStream ps, AssertionFailedError e) {
  227. StackTraceElement[] stes = e.getStackTrace();
  228. int startIx = 0;
  229. // skip any top frames inside junit.framework.Assert
  230. while(startIx<stes.length) {
  231. if(!stes[startIx].getClassName().equals(Assert.class.getName())) {
  232. break;
  233. }
  234. startIx++;
  235. }
  236. // skip bottom frames (part of junit framework)
  237. int endIx = startIx+1;
  238. while(endIx < stes.length) {
  239. if(stes[endIx].getClassName().equals(TestCase.class.getName())) {
  240. break;
  241. }
  242. endIx++;
  243. }
  244. if(startIx >= endIx) {
  245. // something went wrong. just print the whole stack trace
  246. e.printStackTrace(ps);
  247. }
  248. endIx -= 4; // skip 4 frames of reflection invocation
  249. ps.println(e.toString());
  250. for(int i=startIx; i<endIx; i++) {
  251. ps.println("\tat " + stes[i].toString());
  252. }
  253. }
  254. /**
  255. * @return <code>null</code> if cell is missing, empty or blank
  256. */
  257. private static String getTargetFunctionName(Row r) {
  258. if(r == null) {
  259. System.err.println("Warning - given null row, can't figure out function name");
  260. return null;
  261. }
  262. Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME);
  263. if(cell == null) {
  264. System.err.println("Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name");
  265. return null;
  266. }
  267. if(cell.getCellType() == Cell.CELL_TYPE_BLANK) {
  268. return null;
  269. }
  270. if(cell.getCellType() == Cell.CELL_TYPE_STRING) {
  271. return cell.getRichStringCellValue().getString();
  272. }
  273. throw new AssertionFailedError("Bad cell type for 'function name' column: ("
  274. + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")");
  275. }
  276. /**
  277. * @return <code>null</code> if cell is missing, empty or blank
  278. */
  279. private static String getTargetTestName(Row r) {
  280. if(r == null) {
  281. System.err.println("Warning - given null row, can't figure out test name");
  282. return null;
  283. }
  284. Cell cell = r.getCell(SS.COLUMN_INDEX_TEST_NAME);
  285. if(cell == null) {
  286. System.err.println("Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_TEST_NAME + ", can't figure out test name");
  287. return null;
  288. }
  289. if(cell.getCellType() == Cell.CELL_TYPE_BLANK) {
  290. return null;
  291. }
  292. if(cell.getCellType() == Cell.CELL_TYPE_STRING) {
  293. return cell.getRichStringCellValue().getString();
  294. }
  295. throw new AssertionFailedError("Bad cell type for 'test name' column: ("
  296. + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")");
  297. }
  298. }