Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

TestMultiSheetEval.java 12KB

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