poi-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From u..@apache.org
Subject svn commit: r634936 [7/8] - in /poi/branches/ooxml: ./ legal/ src/contrib/src/org/apache/poi/hssf/contrib/view/ src/documentation/content/xdocs/ src/documentation/content/xdocs/getinvolved/ src/documentation/content/xdocs/hslf/ src/java/org/apache/poi/...
Date Sat, 08 Mar 2008 11:49:17 GMT
Modified: poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/model/TestFormulaParserSP.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/model/TestFormulaParserSP.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/model/TestFormulaParserSP.java (original)
+++ poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/model/TestFormulaParserSP.java Sat Mar  8 03:49:00 2008
@@ -1,4 +1,3 @@
-
 /* ====================================================================
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
@@ -15,30 +14,30 @@
    See the License for the specific language governing permissions and
    limitations under the License.
 ==================================================================== */
-        
+
 package org.apache.poi.hssf.model;
 
 import junit.framework.TestCase;
 
+import org.apache.poi.hssf.model.FormulaParser.FormulaParseException;
 import org.apache.poi.hssf.record.formula.FuncVarPtg;
 import org.apache.poi.hssf.record.formula.NamePtg;
 import org.apache.poi.hssf.record.formula.Ptg;
+import org.apache.poi.hssf.usermodel.HSSFCell;
 import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
 import org.apache.poi.hssf.usermodel.HSSFName;
+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.hssf.usermodel.HSSFFormulaEvaluator.CellValue;
 
 /**
  * Test the low level formula parser functionality,
  *  but using parts which need to use the
  *  HSSFFormulaEvaluator, which is in scratchpad 
  */
-public class TestFormulaParserSP extends TestCase {
+public final class TestFormulaParserSP extends TestCase {
 
-    public TestFormulaParserSP(String name) {
-        super(name);
-    }
-	
 	public void testWithNamedRange() throws Exception {
 		HSSFWorkbook workbook = new HSSFWorkbook();
 		FormulaParser fp;
@@ -80,4 +79,32 @@
 		assertEquals(FuncVarPtg.class, ptgs[1].getClass());
 	}
 
+	public void testEvaluateFormulaWithRowBeyond32768_Bug44539() {
+		
+		HSSFWorkbook wb = new HSSFWorkbook();
+		HSSFSheet sheet = wb.createSheet();
+		wb.setSheetName(0, "Sheet1");
+		
+		HSSFRow row = sheet.createRow(0);
+		HSSFCell cell = row.createCell((short)0);
+		cell.setCellFormula("SUM(A32769:A32770)");
+
+		// put some values in the cells to make the evaluation more interesting
+		sheet.createRow(32768).createCell((short)0).setCellValue(31);
+		sheet.createRow(32769).createCell((short)0).setCellValue(11);
+		
+		HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(sheet, wb);
+		fe.setCurrentRow(row);
+		CellValue result;
+		try {
+			result = fe.evaluate(cell);
+		} catch (FormulaParseException e) {
+			if(e.getMessage().equals("Found reference to named range \"A\", but that named range wasn't defined!")) {
+				fail("Identifed bug 44539");
+			}
+			throw new RuntimeException(e);
+		}
+		assertEquals(HSSFCell.CELL_TYPE_NUMERIC, result.getCellType());
+		assertEquals(42.0, result.getNumberValue(), 0.0);
+	}
 }

Modified: poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/AllIndividualFunctionEvaluationTests.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/AllIndividualFunctionEvaluationTests.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/AllIndividualFunctionEvaluationTests.java (original)
+++ poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/AllIndividualFunctionEvaluationTests.java Sat Mar  8 03:49:00 2008
@@ -31,13 +31,23 @@
 	// TODO - have this suite incorporated into a higher level one
 	public static Test suite() {
 		TestSuite result = new TestSuite("Tests for org.apache.poi.hssf.record.formula.functions");
+		result.addTestSuite(TestAverage.class);
 		result.addTestSuite(TestCountFuncs.class);
 		result.addTestSuite(TestDate.class);
 		result.addTestSuite(TestFinanceLib.class);
 		result.addTestSuite(TestIndex.class);
+		result.addTestSuite(TestIsBlank.class);
+		result.addTestSuite(TestLen.class);
+		result.addTestSuite(TestMid.class);
 		result.addTestSuite(TestMathX.class);
+		result.addTestSuite(TestMatch.class);
+		result.addTestSuite(TestOffset.class);
 		result.addTestSuite(TestRowCol.class);
+		result.addTestSuite(TestSumproduct.class);
 		result.addTestSuite(TestStatsLib.class);
+		result.addTestSuite(TestTFunc.class);
+		result.addTestSuite(TestTrim.class);
+		result.addTestSuite(TestXYNumericFunction.class);
 		return result;
 	}
 

Modified: poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/EvalFactory.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/EvalFactory.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/EvalFactory.java (original)
+++ poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/EvalFactory.java Sat Mar  8 03:49:00 2008
@@ -58,6 +58,6 @@
 	 * Creates a single RefEval (with value zero)
 	 */
 	public static RefEval createRefEval(String refStr) {
-		return new Ref2DEval(new ReferencePtg(refStr), ZERO, true);
+		return new Ref2DEval(new ReferencePtg(refStr), ZERO);
 	}
 }

Modified: poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/NumericFunctionInvoker.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/NumericFunctionInvoker.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/NumericFunctionInvoker.java (original)
+++ poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/NumericFunctionInvoker.java Sat Mar  8 03:49:00 2008
@@ -23,13 +23,14 @@
 import org.apache.poi.hssf.record.formula.eval.ErrorEval;
 import org.apache.poi.hssf.record.formula.eval.Eval;
 import org.apache.poi.hssf.record.formula.eval.NumericValueEval;
+import org.apache.poi.hssf.record.formula.eval.OperationEval;
 
 /**
  * Test helper class for invoking functions with numeric results.
  * 
  * @author Josh Micich
  */
-final class NumericFunctionInvoker {
+public final class NumericFunctionInvoker {
 
 	private NumericFunctionInvoker() {
 		// no instances of this class
@@ -61,11 +62,35 @@
 		
 	}
 	/**
+	 * Invokes the specified operator with the arguments.
+	 * <p/>
+	 * This method cannot be used for confirming error return codes.  Any non-numeric evaluation
+	 * result causes the current junit test to fail.
+	 */
+	public static double invoke(OperationEval f, Eval[] args, int srcCellRow, int srcCellCol) {
+		try {
+			return invokeInternal(f, args, srcCellRow, srcCellCol);
+		} catch (NumericEvalEx e) {
+			throw new AssertionFailedError("Evaluation of function (" + f.getClass().getName() 
+					+ ") failed: " + e.getMessage());
+		}
+		
+	}
+	/**
 	 * Formats nicer error messages for the junit output
 	 */
-	private static double invokeInternal(Function f, Eval[] args, int srcCellRow, int srcCellCol)
+	private static double invokeInternal(Object target, Eval[] args, int srcCellRow, int srcCellCol)
 				throws NumericEvalEx {
-		Eval evalResult = f.evaluate(args, srcCellRow, (short)srcCellCol);
+		Eval evalResult;
+		// TODO - make OperationEval extend Function
+		if (target instanceof Function) {
+			Function ff = (Function) target;
+			evalResult = ff.evaluate(args, srcCellRow, (short)srcCellCol);
+		} else {
+			OperationEval ff = (OperationEval) target;
+			evalResult = ff.evaluate(args, srcCellRow, (short)srcCellCol);
+		}
+		
 		if(evalResult == null) {
 			throw new NumericEvalEx("Result object was null");
 		}
@@ -86,8 +111,8 @@
 		if(errorCodesAreEqual(ee, ErrorEval.FUNCTION_NOT_IMPLEMENTED)) {
 			return "Function not implemented";
 		}
-		if(errorCodesAreEqual(ee, ErrorEval.UNKNOWN_ERROR)) {
-			return "Unknown error";
+		if(errorCodesAreEqual(ee, ErrorEval.VALUE_INVALID)) {
+			return "Error code: #VALUE! (invalid value)";
 		}
 		return "Error code=" + ee.getErrorCode();
 	}

Modified: poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/TestCountFuncs.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/TestCountFuncs.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/TestCountFuncs.java (original)
+++ poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/record/formula/functions/TestCountFuncs.java Sat Mar  8 03:49:00 2008
@@ -125,7 +125,7 @@
 		};
 		Area2DEval arg0 = new Area2DEval(new AreaPtg("C1:C6"), values);
 		
-		Ref2DEval criteriaArg = new Ref2DEval(new ReferencePtg("A1"), new NumberEval(25), true);
+		Ref2DEval criteriaArg = new Ref2DEval(new ReferencePtg("A1"), new NumberEval(25));
 		Eval[] args=  { arg0, criteriaArg, };
 		
 		double actual = NumericFunctionInvoker.invoke(new Countif(), args);

Modified: poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java (original)
+++ poi/branches/ooxml/src/scratchpad/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java Sat Mar  8 03:49:00 2008
@@ -21,14 +21,14 @@
 import java.util.Iterator;
 import java.util.List;
 
+import junit.framework.TestCase;
+
 import org.apache.poi.hssf.record.FormulaRecord;
 import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
-import org.apache.poi.hssf.record.formula.ExpPtg;
+import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.CellValue;
 import org.apache.poi.hssf.util.CellReference;
 
-import junit.framework.TestCase;
-
-public class TestBug42464 extends TestCase {
+public final class TestBug42464 extends TestCase {
 	String dirname;
 
 	protected void setUp() throws Exception {
@@ -68,26 +68,27 @@
 		Iterator it = row.cellIterator();
 		while(it.hasNext()) {
 			HSSFCell cell = (HSSFCell)it.next();
-			if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
-				FormulaRecordAggregate record = (FormulaRecordAggregate)
-					cell.getCellValueRecord();
-				FormulaRecord r = record.getFormulaRecord();
-				List ptgs = r.getParsedExpression();
-				
-				String cellRef = (new CellReference(row.getRowNum(), cell.getCellNum())).toString();
-				if(cellRef.equals("BP24")) {
-					System.out.print(cellRef);
-					System.out.println(" - has " + r.getNumberOfExpressionTokens() + " ptgs over " + r.getExpressionLength()  + " tokens:");
-					for(int i=0; i<ptgs.size(); i++) {
-						String c = ptgs.get(i).getClass().toString();
-						System.out.println("\t" + c.substring(c.lastIndexOf('.')+1) );
-					}
-					System.out.println("-> " + cell.getCellFormula());
+			if(cell.getCellType() != HSSFCell.CELL_TYPE_FORMULA) {
+			    continue;
+			}
+			FormulaRecordAggregate record = (FormulaRecordAggregate) cell.getCellValueRecord();
+			FormulaRecord r = record.getFormulaRecord();
+			List ptgs = r.getParsedExpression();
+			
+			String cellRef = new CellReference(row.getRowNum(), cell.getCellNum(), false, false).formatAsString();
+			if(false && cellRef.equals("BP24")) { // TODO - replace System.out.println()s with asserts
+				System.out.print(cellRef);
+				System.out.println(" - has " + r.getNumberOfExpressionTokens() 
+				        + " ptgs over " + r.getExpressionLength()  + " tokens:");
+				for(int i=0; i<ptgs.size(); i++) {
+					String c = ptgs.get(i).getClass().toString();
+					System.out.println("\t" + c.substring(c.lastIndexOf('.')+1) );
 				}
-				
-				eval.evaluate(cell);
-				
+				System.out.println("-> " + cell.getCellFormula());
 			}
+			
+			CellValue evalResult = eval.evaluate(cell);
+			assertNotNull(evalResult);
 		}
 	}
 }

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/TestPOIDocumentMain.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/TestPOIDocumentMain.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/TestPOIDocumentMain.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/TestPOIDocumentMain.java Sat Mar  8 03:49:00 2008
@@ -85,7 +85,8 @@
     public void testWriteProperties() throws Exception {
     	// Just check we can write them back out into a filesystem
     	POIFSFileSystem outFS = new POIFSFileSystem();
-    	doc.writeProperties(outFS);
+    	doc.readProperties();
+        doc.writeProperties(outFS);
     	
     	// Should now hold them
     	assertNotNull(
@@ -101,7 +102,8 @@
 		
     	// Write them out
     	POIFSFileSystem outFS = new POIFSFileSystem();
-    	doc.writeProperties(outFS);
+    	doc.readProperties();
+        doc.writeProperties(outFS);
     	outFS.writeFilesystem(baos);
     	
     	// Create a new version

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/HSSFTests.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/HSSFTests.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/HSSFTests.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/HSSFTests.java Sat Mar  8 03:49:00 2008
@@ -1,4 +1,3 @@
-
 /* ====================================================================
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
@@ -15,7 +14,7 @@
    See the License for the specific language governing permissions and
    limitations under the License.
 ==================================================================== */
-        
+
 package org.apache.poi.hssf;
 
 import junit.framework.Test;
@@ -26,80 +25,8 @@
 import org.apache.poi.hssf.model.TestDrawingManager;
 import org.apache.poi.hssf.model.TestFormulaParser;
 import org.apache.poi.hssf.model.TestSheet;
-import org.apache.poi.hssf.record.TestAreaFormatRecord;
-import org.apache.poi.hssf.record.TestAreaRecord;
-import org.apache.poi.hssf.record.TestAxisLineFormatRecord;
-import org.apache.poi.hssf.record.TestAxisOptionsRecord;
-import org.apache.poi.hssf.record.TestAxisParentRecord;
-import org.apache.poi.hssf.record.TestAxisRecord;
-import org.apache.poi.hssf.record.TestAxisUsedRecord;
-import org.apache.poi.hssf.record.TestBarRecord;
-import org.apache.poi.hssf.record.TestBoundSheetRecord;
-import org.apache.poi.hssf.record.TestCategorySeriesAxisRecord;
-import org.apache.poi.hssf.record.TestChartRecord;
-import org.apache.poi.hssf.record.TestDatRecord;
-import org.apache.poi.hssf.record.TestDataFormatRecord;
-import org.apache.poi.hssf.record.TestDefaultDataLabelTextPropertiesRecord;
-import org.apache.poi.hssf.record.TestFontBasisRecord;
-import org.apache.poi.hssf.record.TestFontIndexRecord;
-import org.apache.poi.hssf.record.TestFormulaRecord;
-import org.apache.poi.hssf.record.TestFrameRecord;
-import org.apache.poi.hssf.record.TestLegendRecord;
-import org.apache.poi.hssf.record.TestLineFormatRecord;
-import org.apache.poi.hssf.record.TestLinkedDataRecord;
-import org.apache.poi.hssf.record.TestNameRecord;
-import org.apache.poi.hssf.record.TestNumberFormatIndexRecord;
-import org.apache.poi.hssf.record.TestObjectLinkRecord;
-import org.apache.poi.hssf.record.TestPaletteRecord;
-import org.apache.poi.hssf.record.TestPlotAreaRecord;
-import org.apache.poi.hssf.record.TestPlotGrowthRecord;
-import org.apache.poi.hssf.record.TestRecordFactory;
-import org.apache.poi.hssf.record.TestSCLRecord;
-import org.apache.poi.hssf.record.TestSSTDeserializer;
-import org.apache.poi.hssf.record.TestSSTRecord;
-import org.apache.poi.hssf.record.TestSSTRecordSizeCalculator;
-import org.apache.poi.hssf.record.TestSeriesChartGroupIndexRecord;
-import org.apache.poi.hssf.record.TestSeriesIndexRecord;
-import org.apache.poi.hssf.record.TestSeriesLabelsRecord;
-import org.apache.poi.hssf.record.TestSeriesListRecord;
-import org.apache.poi.hssf.record.TestSeriesRecord;
-import org.apache.poi.hssf.record.TestSeriesTextRecord;
-import org.apache.poi.hssf.record.TestSeriesToChartGroupRecord;
-import org.apache.poi.hssf.record.TestSheetPropertiesRecord;
-import org.apache.poi.hssf.record.TestStringRecord;
-import org.apache.poi.hssf.record.TestSupBookRecord;
-import org.apache.poi.hssf.record.TestTextRecord;
-import org.apache.poi.hssf.record.TestTickRecord;
-import org.apache.poi.hssf.record.TestUnicodeString;
-import org.apache.poi.hssf.record.TestUnitsRecord;
-import org.apache.poi.hssf.record.TestValueRangeRecord;
-import org.apache.poi.hssf.record.aggregates.TestRowRecordsAggregate;
-import org.apache.poi.hssf.record.aggregates.TestValueRecordsAggregate;
-import org.apache.poi.hssf.record.formula.AllFormulaTests;
-import org.apache.poi.hssf.usermodel.TestBugs;
-import org.apache.poi.hssf.usermodel.TestCellStyle;
-import org.apache.poi.hssf.usermodel.TestCloneSheet;
-import org.apache.poi.hssf.usermodel.TestEscherGraphics;
-import org.apache.poi.hssf.usermodel.TestEscherGraphics2d;
-import org.apache.poi.hssf.usermodel.TestFontDetails;
-import org.apache.poi.hssf.usermodel.TestFormulas;
-import org.apache.poi.hssf.usermodel.TestHSSFCell;
-import org.apache.poi.hssf.usermodel.TestHSSFClientAnchor;
-import org.apache.poi.hssf.usermodel.TestHSSFComment;
-import org.apache.poi.hssf.usermodel.TestHSSFDateUtil;
-import org.apache.poi.hssf.usermodel.TestHSSFHeaderFooter;
-import org.apache.poi.hssf.usermodel.TestHSSFPalette;
-import org.apache.poi.hssf.usermodel.TestHSSFRichTextString;
-import org.apache.poi.hssf.usermodel.TestHSSFRow;
-import org.apache.poi.hssf.usermodel.TestHSSFSheet;
-import org.apache.poi.hssf.usermodel.TestHSSFSheetOrder;
-import org.apache.poi.hssf.usermodel.TestHSSFSheetSetOrder;
-import org.apache.poi.hssf.usermodel.TestHSSFWorkbook;
-import org.apache.poi.hssf.usermodel.TestNamedRange;
-import org.apache.poi.hssf.usermodel.TestReadWriteChart;
-import org.apache.poi.hssf.usermodel.TestSanityChecker;
-import org.apache.poi.hssf.usermodel.TestSheetShiftRows;
-import org.apache.poi.hssf.usermodel.TestWorkbook;
+import org.apache.poi.hssf.record.AllRecordTests;
+import org.apache.poi.hssf.usermodel.AllUserModelTests;
 import org.apache.poi.hssf.util.TestAreaReference;
 import org.apache.poi.hssf.util.TestCellReference;
 import org.apache.poi.hssf.util.TestRKUtil;
@@ -107,118 +34,36 @@
 import org.apache.poi.hssf.util.TestSheetReferences;
 
 /**
- * Test Suite for running just HSSF tests.  Mostly
- * this is for my convienience.
+ * Test Suite for all sub-packages of org.apache.poi.hssf<br/>
+ * 
+ * Mostly this is for my convenience.
  * 
  * @author Andrew C. Oliver acoliver@apache.org
  */
-public class HSSFTests
-{
+public final class HSSFTests {
 
-    public static void main(String[] args)
-    {
+    public static void main(String[] args) {
         junit.textui.TestRunner.run(suite());
     }
 
-    public static Test suite()
-    {
-        TestSuite suite =
-            new TestSuite("Test for org.apache.poi.hssf.usermodel");
-        //$JUnit-BEGIN$
-
-    suite.addTest(new TestSuite(TestBugs.class));
-    suite.addTest(new TestSuite(TestCloneSheet.class));
-    suite.addTest(new TestSuite(TestEscherGraphics.class));
-    suite.addTest(new TestSuite(TestEscherGraphics2d.class));
-    suite.addTest(new TestSuite(TestFontDetails.class));
-    suite.addTest(new TestSuite(TestHSSFClientAnchor.class));
-    suite.addTest(new TestSuite(TestHSSFHeaderFooter.class));
-    suite.addTest(new TestSuite(TestHSSFRichTextString.class));
-    suite.addTest(new TestSuite(TestHSSFSheetOrder.class));
-    suite.addTest(new TestSuite(TestHSSFSheetSetOrder.class));
-    suite.addTest(new TestSuite(TestHSSFWorkbook.class));
-    suite.addTest(new TestSuite(TestSanityChecker.class));
-    suite.addTest(new TestSuite(TestSheetShiftRows.class));
-
-        suite.addTest(new TestSuite(TestCellStyle.class));
-        suite.addTest(new TestSuite(TestFormulas.class));
-        suite.addTest(new TestSuite(TestHSSFCell.class));
-        suite.addTest(new TestSuite(TestHSSFDateUtil.class));
-        suite.addTest(new TestSuite(TestHSSFPalette.class));
-        suite.addTest(new TestSuite(TestHSSFRow.class));
-        suite.addTest(new TestSuite(TestHSSFSheet.class));
-        suite.addTest(new TestSuite(TestNamedRange.class));
-        suite.addTest(new TestSuite(TestReadWriteChart.class));
-        suite.addTest(new TestSuite(TestWorkbook.class));
-
+    public static Test suite() {
+        TestSuite suite = new TestSuite("Tests for org.apache.poi.hssf");
+        // $JUnit-BEGIN$
 
+        suite.addTest(AllUserModelTests.suite());
+        suite.addTest(AllRecordTests.suite());
 
         suite.addTest(new TestSuite(TestFormulaParser.class));
-        suite.addTest(new TestSuite(TestAreaFormatRecord.class));
-        suite.addTest(new TestSuite(TestAreaRecord.class));
-        suite.addTest(new TestSuite(TestAxisLineFormatRecord.class));
-        suite.addTest(new TestSuite(TestAxisOptionsRecord.class));
-        suite.addTest(new TestSuite(TestAxisParentRecord.class));
-        suite.addTest(new TestSuite(TestAxisRecord.class));
-        suite.addTest(new TestSuite(TestAxisUsedRecord.class));
-        suite.addTest(new TestSuite(TestBarRecord.class));
-        suite.addTest(new TestSuite(TestBoundSheetRecord.class));
-        suite.addTest(new TestSuite(TestCategorySeriesAxisRecord.class));
-        suite.addTest(new TestSuite(TestChartRecord.class));
-        suite.addTest(new TestSuite(TestDatRecord.class));
-        suite.addTest(new TestSuite(TestDataFormatRecord.class));
-        suite.addTest(
-            new TestSuite(TestDefaultDataLabelTextPropertiesRecord.class));
-        suite.addTest(new TestSuite(TestFontBasisRecord.class));
-        suite.addTest(new TestSuite(TestFontIndexRecord.class));
-        suite.addTest(new TestSuite(TestFormulaRecord.class));
-        suite.addTest(new TestSuite(TestFrameRecord.class));
-        suite.addTest(new TestSuite(TestLegendRecord.class));
-        suite.addTest(new TestSuite(TestLineFormatRecord.class));
-        suite.addTest(new TestSuite(TestLinkedDataRecord.class));
-        suite.addTest(new TestSuite(TestNumberFormatIndexRecord.class));
-        suite.addTest(new TestSuite(TestObjectLinkRecord.class));
-        suite.addTest(new TestSuite(TestPaletteRecord.class));
-        suite.addTest(new TestSuite(TestPlotAreaRecord.class));
-        suite.addTest(new TestSuite(TestPlotGrowthRecord.class));
-        suite.addTest(new TestSuite(TestRecordFactory.class));
-        suite.addTest(new TestSuite(TestSCLRecord.class));
-        suite.addTest(new TestSuite(TestSSTDeserializer.class));
-        suite.addTest(new TestSuite(TestSSTRecord.class));
-        suite.addTest(new TestSuite(TestSSTRecordSizeCalculator.class));
-        suite.addTest(new TestSuite(TestSeriesChartGroupIndexRecord.class));
-        suite.addTest(new TestSuite(TestSeriesIndexRecord.class));
-        suite.addTest(new TestSuite(TestSeriesLabelsRecord.class));
-        suite.addTest(new TestSuite(TestSeriesListRecord.class));
-        suite.addTest(new TestSuite(TestSeriesRecord.class));
-        suite.addTest(new TestSuite(TestSeriesTextRecord.class));
-        suite.addTest(new TestSuite(TestSeriesToChartGroupRecord.class));
-        suite.addTest(new TestSuite(TestSheetPropertiesRecord.class));
-        suite.addTest(new TestSuite(TestStringRecord.class));
-        suite.addTest(new TestSuite(TestSupBookRecord.class));
-        suite.addTest(new TestSuite(TestTextRecord.class));
-        suite.addTest(new TestSuite(TestTickRecord.class));
-        suite.addTest(new TestSuite(TestUnicodeString.class));
-        suite.addTest(new TestSuite(TestUnitsRecord.class));
-        suite.addTest(new TestSuite(TestValueRangeRecord.class));
-        suite.addTest(new TestSuite(TestRowRecordsAggregate.class));
         suite.addTest(new TestSuite(TestAreaReference.class));
         suite.addTest(new TestSuite(TestCellReference.class));
-		  suite.addTest(new TestSuite(TestRangeAddress.class));		
+        suite.addTest(new TestSuite(TestRangeAddress.class));
         suite.addTest(new TestSuite(TestRKUtil.class));
         suite.addTest(new TestSuite(TestSheetReferences.class));
-        
-        
-        suite.addTest(AllFormulaTests.suite());
-		  suite.addTest(new TestSuite(TestValueRecordsAggregate.class));
-		  suite.addTest(new TestSuite(TestNameRecord.class));
-                  suite.addTest(new TestSuite(TestEventRecordFactory.class));
-                  suite.addTest(new TestSuite(TestModelFactory.class));
-                  suite.addTest(new TestSuite(TestDrawingManager.class));
-                  suite.addTest(new TestSuite(TestSheet.class));
-
-        suite.addTest(new TestSuite(TestHSSFComment.class));
-        //$JUnit-END$
+        suite.addTest(new TestSuite(TestEventRecordFactory.class));
+        suite.addTest(new TestSuite(TestModelFactory.class));
+        suite.addTest(new TestSuite(TestDrawingManager.class));
+        suite.addTest(new TestSuite(TestSheet.class));
+        // $JUnit-END$
         return suite;
     }
 }

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java Sat Mar  8 03:49:00 2008
@@ -1,4 +1,3 @@
-
 /* ====================================================================
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
@@ -18,24 +17,35 @@
         
 package org.apache.poi.hssf.model;
 
+import junit.framework.AssertionFailedError;
 import junit.framework.TestCase;
 
+import org.apache.poi.hssf.model.FormulaParser.FormulaParseException;
 import org.apache.poi.hssf.record.formula.AbstractFunctionPtg;
 import org.apache.poi.hssf.record.formula.AddPtg;
+import org.apache.poi.hssf.record.formula.AreaPtg;
 import org.apache.poi.hssf.record.formula.AttrPtg;
 import org.apache.poi.hssf.record.formula.BoolPtg;
+import org.apache.poi.hssf.record.formula.ConcatPtg;
 import org.apache.poi.hssf.record.formula.DividePtg;
 import org.apache.poi.hssf.record.formula.EqualPtg;
+import org.apache.poi.hssf.record.formula.ErrPtg;
+import org.apache.poi.hssf.record.formula.FuncPtg;
 import org.apache.poi.hssf.record.formula.FuncVarPtg;
 import org.apache.poi.hssf.record.formula.IntPtg;
 import org.apache.poi.hssf.record.formula.LessEqualPtg;
 import org.apache.poi.hssf.record.formula.LessThanPtg;
+import org.apache.poi.hssf.record.formula.MissingArgPtg;
+import org.apache.poi.hssf.record.formula.MultiplyPtg;
 import org.apache.poi.hssf.record.formula.NamePtg;
 import org.apache.poi.hssf.record.formula.NotEqualPtg;
 import org.apache.poi.hssf.record.formula.NumberPtg;
+import org.apache.poi.hssf.record.formula.PercentPtg;
+import org.apache.poi.hssf.record.formula.PowerPtg;
 import org.apache.poi.hssf.record.formula.Ptg;
 import org.apache.poi.hssf.record.formula.ReferencePtg;
 import org.apache.poi.hssf.record.formula.StringPtg;
+import org.apache.poi.hssf.record.formula.SubtractPtg;
 import org.apache.poi.hssf.record.formula.UnaryMinusPtg;
 import org.apache.poi.hssf.record.formula.UnaryPlusPtg;
 import org.apache.poi.hssf.usermodel.HSSFCell;
@@ -49,27 +59,27 @@
  * Some tests are also done in scratchpad, if they need
  *  HSSFFormulaEvaluator, which is there
  */
-public class TestFormulaParser extends TestCase {
+public final class TestFormulaParser extends TestCase {
 
-    public TestFormulaParser(String name) {
-        super(name);
-    }
-    public void setUp(){
-        
-    }
-    
-    public void tearDown() {
-        
+    /**
+     * @return parsed token array already confirmed not <code>null</code>
+     */
+    private static Ptg[] parseFormula(String s) {
+        FormulaParser fp = new FormulaParser(s, null);
+        fp.parse();
+        Ptg[] result = fp.getRPNPtg();
+        assertNotNull("Ptg array should not be null", result);
+        return result;
     }
     
     public void testSimpleFormula() {
-        FormulaParser fp = new FormulaParser("2+2;",null);
+        FormulaParser fp = new FormulaParser("2+2",null);
         fp.parse();
         Ptg[] ptgs = fp.getRPNPtg();
         assertTrue("three tokens expected, got "+ptgs.length,ptgs.length == 3);
     }
     public void testFormulaWithSpace1() {
-        FormulaParser fp = new FormulaParser(" 2 + 2 ;",null);
+        FormulaParser fp = new FormulaParser(" 2 + 2 ",null);
         fp.parse();
         Ptg[] ptgs = fp.getRPNPtg();
         assertTrue("three tokens expected, got "+ptgs.length,ptgs.length == 3);
@@ -82,7 +92,7 @@
     public void testFormulaWithSpace2() {
         Ptg[] ptgs;
         FormulaParser fp;
-        fp = new FormulaParser("2+ sum( 3 , 4) ;",null);
+        fp = new FormulaParser("2+ sum( 3 , 4) ",null);
         fp.parse();
         ptgs = fp.getRPNPtg();
         assertTrue("five tokens expected, got "+ptgs.length,ptgs.length == 5);
@@ -91,7 +101,7 @@
      public void testFormulaWithSpaceNRef() {
         Ptg[] ptgs;
         FormulaParser fp;
-        fp = new FormulaParser("sum( A2:A3 );",null);
+        fp = new FormulaParser("sum( A2:A3 )",null);
         fp.parse();
         ptgs = fp.getRPNPtg();
         assertTrue("two tokens expected, got "+ptgs.length,ptgs.length == 2);
@@ -100,7 +110,7 @@
     public void testFormulaWithString() {
         Ptg[] ptgs;
         FormulaParser fp;
-        fp = new FormulaParser("\"hello\" & \"world\" ;",null);
+        fp = new FormulaParser("\"hello\" & \"world\" ",null);
         fp.parse();
         ptgs = fp.getRPNPtg();
         assertTrue("three token expected, got " + ptgs.length, ptgs.length == 3);
@@ -273,20 +283,21 @@
 	}
 	    
     public void testMacroFunction() {
-        Workbook w = new Workbook();
+        Workbook w = Workbook.createWorkbook();
         FormulaParser fp = new FormulaParser("FOO()", w);
         fp.parse();
         Ptg[] ptg = fp.getRPNPtg();
 
-        AbstractFunctionPtg tfunc = (AbstractFunctionPtg) ptg[0];
-        assertEquals("externalflag", tfunc.getName());
-
-        NamePtg tname = (NamePtg) ptg[1];
+        // the name gets encoded as the first arg
+        NamePtg tname = (NamePtg) ptg[0];
         assertEquals("FOO", tname.toFormulaString(w));
+        
+        AbstractFunctionPtg tfunc = (AbstractFunctionPtg) ptg[1];
+        assertEquals("externalflag", tfunc.getName());
     }
 
     public void testEmbeddedSlash() {
-        FormulaParser fp = new FormulaParser("HYPERLINK(\"http://www.jakarta.org\",\"Jakarta\");",null);
+        FormulaParser fp = new FormulaParser("HYPERLINK(\"http://www.jakarta.org\",\"Jakarta\")",null);
         fp.parse();
         Ptg[] ptg = fp.getRPNPtg();
         assertTrue("first ptg is string",ptg[0] instanceof StringPtg);
@@ -397,7 +408,7 @@
 	public void testUnderscore() {
 		HSSFWorkbook wb = new HSSFWorkbook();
     	
-    	wb.createSheet("Cash_Flow");;
+    	wb.createSheet("Cash_Flow");
     	
     	HSSFSheet sheet = wb.createSheet("Test");
     	HSSFRow row = sheet.createRow(0);
@@ -438,7 +449,7 @@
     public void testExponentialInSheet() throws Exception {
         HSSFWorkbook wb = new HSSFWorkbook();
 
-        wb.createSheet("Cash_Flow");;
+        wb.createSheet("Cash_Flow");
 
         HSSFSheet sheet = wb.createSheet("Test");
         HSSFRow row = sheet.createRow(0);
@@ -514,7 +525,7 @@
     public void testNumbers() {
         HSSFWorkbook wb = new HSSFWorkbook();
         
-        wb.createSheet("Cash_Flow");;
+        wb.createSheet("Cash_Flow");
         
         HSSFSheet sheet = wb.createSheet("Test");
         HSSFRow row = sheet.createRow(0);
@@ -553,7 +564,7 @@
     public void testRanges() {
         HSSFWorkbook wb = new HSSFWorkbook();
         
-        wb.createSheet("Cash_Flow");;
+        wb.createSheet("Cash_Flow");
         
         HSSFSheet sheet = wb.createSheet("Test");
         HSSFRow row = sheet.createRow(0);
@@ -571,5 +582,266 @@
         cell.setCellFormula("A1...A2");
         formula = cell.getCellFormula();
         assertEquals("A1:A2", formula);
-    }        
+    }
+    
+    /**
+     * Test for bug observable at svn revision 618865 (5-Feb-2008)<br/>
+     * a formula consisting of a single no-arg function got rendered without the function braces
+     */
+    public void testToFormulaStringZeroArgFunction() {
+        
+        Workbook book = Workbook.createWorkbook(); // not really used in this test
+        
+        Ptg[] ptgs = {
+                new FuncPtg(10, 0),
+        };
+        assertEquals("NA()", FormulaParser.toFormulaString(book, ptgs));
+    }
+
+    public void testPercent() {
+        Ptg[] ptgs;
+        ptgs = parseFormula("5%");
+        assertEquals(2, ptgs.length);
+        assertEquals(ptgs[0].getClass(), IntPtg.class);
+        assertEquals(ptgs[1].getClass(), PercentPtg.class);
+
+        // spaces OK
+        ptgs = parseFormula(" 250 % ");
+        assertEquals(2, ptgs.length);
+        assertEquals(ptgs[0].getClass(), IntPtg.class);
+        assertEquals(ptgs[1].getClass(), PercentPtg.class);
+        
+        
+        // double percent OK 
+        ptgs = parseFormula("12345.678%%");
+        assertEquals(3, ptgs.length);
+        assertEquals(ptgs[0].getClass(), NumberPtg.class);
+        assertEquals(ptgs[1].getClass(), PercentPtg.class);
+        assertEquals(ptgs[2].getClass(), PercentPtg.class);
+        
+        // percent of a bracketed expression
+        ptgs = parseFormula("(A1+35)%*B1%");
+        assertEquals(8, ptgs.length);
+        assertEquals(ptgs[4].getClass(), PercentPtg.class);
+        assertEquals(ptgs[6].getClass(), PercentPtg.class);
+        
+        // percent of a text quantity
+        ptgs = parseFormula("\"8.75\"%");
+        assertEquals(2, ptgs.length);
+        assertEquals(ptgs[0].getClass(), StringPtg.class);
+        assertEquals(ptgs[1].getClass(), PercentPtg.class);
+
+        // percent to the power of
+        ptgs = parseFormula("50%^3");
+        assertEquals(4, ptgs.length);
+        assertEquals(ptgs[0].getClass(), IntPtg.class);
+        assertEquals(ptgs[1].getClass(), PercentPtg.class);
+        assertEquals(ptgs[2].getClass(), IntPtg.class);
+        assertEquals(ptgs[3].getClass(), PowerPtg.class);
+
+        //
+        // things that parse OK but would *evaluate* to an error
+        
+        ptgs = parseFormula("\"abc\"%");
+        assertEquals(2, ptgs.length);
+        assertEquals(ptgs[0].getClass(), StringPtg.class);
+        assertEquals(ptgs[1].getClass(), PercentPtg.class);
+        
+        ptgs = parseFormula("#N/A%");
+        assertEquals(2, ptgs.length);
+        assertEquals(ptgs[0].getClass(), ErrPtg.class);
+        assertEquals(ptgs[1].getClass(), PercentPtg.class);
+    }
+    
+    /**
+     * Tests combinations of various operators in the absence of brackets
+     */
+    public void testPrecedenceAndAssociativity() {
+
+        Class[] expClss;
+        
+        // TRUE=TRUE=2=2  evaluates to FALSE
+        expClss = new Class[] { BoolPtg.class, BoolPtg.class, EqualPtg.class, 
+                IntPtg.class, EqualPtg.class, IntPtg.class, EqualPtg.class,  };
+        confirmTokenClasses("TRUE=TRUE=2=2", expClss);
+       
+
+        //  2^3^2    evaluates to 64 not 512
+        expClss = new Class[] { IntPtg.class, IntPtg.class, PowerPtg.class, 
+                IntPtg.class, PowerPtg.class, };
+        confirmTokenClasses("2^3^2", expClss);
+        
+        // "abc" & 2 + 3 & "def"   evaluates to "abc5def"
+        expClss = new Class[] { StringPtg.class, IntPtg.class, IntPtg.class, 
+                AddPtg.class, ConcatPtg.class, StringPtg.class, ConcatPtg.class, };
+        confirmTokenClasses("\"abc\"&2+3&\"def\"", expClss);
+        
+        
+        //  (1 / 2) - (3 * 4)
+        expClss = new Class[] { IntPtg.class, IntPtg.class, DividePtg.class, 
+                IntPtg.class, IntPtg.class, MultiplyPtg.class, SubtractPtg.class, };
+        confirmTokenClasses("1/2-3*4", expClss);
+        
+        // 2 * (2^2)
+        expClss = new Class[] { IntPtg.class, IntPtg.class, IntPtg.class, PowerPtg.class, MultiplyPtg.class, };
+        // NOT: (2 *2) ^ 2 -> int int multiply int power
+        confirmTokenClasses("2*2^2", expClss);
+        
+        //  2^200% -> 2 not 1.6E58
+        expClss = new Class[] { IntPtg.class, IntPtg.class, PercentPtg.class, PowerPtg.class, };
+        confirmTokenClasses("2^200%", expClss);
+    }
+    
+    private static void confirmTokenClasses(String formula, Class[] expectedClasses) {
+        Ptg[] ptgs = parseFormula(formula);
+        assertEquals(expectedClasses.length, ptgs.length);
+        for (int i = 0; i < expectedClasses.length; i++) {
+            if(expectedClasses[i] != ptgs[i].getClass()) {
+                fail("difference at token[" + i + "]: expected ("
+                    + expectedClasses[i].getName() + ") but got (" 
+                    + ptgs[i].getClass().getName() + ")");
+            }
+        }
+    }
+
+    public void testPower() {
+        confirmTokenClasses("2^5", new Class[] { IntPtg.class, IntPtg.class, PowerPtg.class, });
+    }
+
+    private static Ptg parseSingleToken(String formula, Class ptgClass) {
+        Ptg[] ptgs = parseFormula(formula);
+        assertEquals(1, ptgs.length);
+        Ptg result = ptgs[0];
+        assertEquals(ptgClass, result.getClass());
+        return result;
+    }
+
+    public void testParseNumber() {
+        IntPtg ip;
+        
+        // bug 33160
+        ip = (IntPtg) parseSingleToken("40", IntPtg.class);
+        assertEquals(40, ip.getValue());
+        ip = (IntPtg) parseSingleToken("40000", IntPtg.class);
+        assertEquals(40000, ip.getValue());
+        
+        // check the upper edge of the IntPtg range:
+        ip = (IntPtg) parseSingleToken("65535", IntPtg.class);
+        assertEquals(65535, ip.getValue());
+        NumberPtg np = (NumberPtg) parseSingleToken("65536", NumberPtg.class);
+        assertEquals(65536, np.getValue(), 0);
+        
+        np = (NumberPtg) parseSingleToken("65534.6", NumberPtg.class);
+        assertEquals(65534.6, np.getValue(), 0);
+    }
+    
+    public void testMissingArgs() {
+        
+        Class[] expClss;
+        
+        expClss = new Class[] { ReferencePtg.class, MissingArgPtg.class, ReferencePtg.class, 
+                FuncVarPtg.class, };
+        confirmTokenClasses("if(A1, ,C1)", expClss);
+        
+        expClss = new Class[] { MissingArgPtg.class, AreaPtg.class, MissingArgPtg.class,
+                FuncVarPtg.class, };
+        confirmTokenClasses("counta( , A1:B2, )", expClss);
+    }
+
+    public void testParseErrorLiterals() {
+        
+        confirmParseErrorLiteral(ErrPtg.NULL_INTERSECTION, "#NULL!");
+        confirmParseErrorLiteral(ErrPtg.DIV_ZERO, "#DIV/0!");
+        confirmParseErrorLiteral(ErrPtg.VALUE_INVALID, "#VALUE!");
+        confirmParseErrorLiteral(ErrPtg.REF_INVALID, "#REF!");
+        confirmParseErrorLiteral(ErrPtg.NAME_INVALID, "#NAME?");
+        confirmParseErrorLiteral(ErrPtg.NUM_ERROR, "#NUM!");
+        confirmParseErrorLiteral(ErrPtg.N_A, "#N/A");
+    }
+
+    private static void confirmParseErrorLiteral(ErrPtg expectedToken, String formula) {
+        assertEquals(expectedToken, parseSingleToken(formula, ErrPtg.class));
+    }
+    
+    /**
+     * To aid readability the parameters have been encoded with single quotes instead of double
+     * quotes.  This method converts single quotes to double quotes before performing the parse
+     * and result check.
+     */
+    private static void confirmStringParse(String singleQuotedValue) {
+        // formula: internal quotes become double double, surround with double quotes
+        String formula = '"' + singleQuotedValue.replaceAll("'", "\"\"") + '"';
+        String expectedValue = singleQuotedValue.replace('\'', '"');
+        
+        StringPtg sp = (StringPtg) parseSingleToken(formula, StringPtg.class);
+        assertEquals(expectedValue, sp.getValue());
+    }
+    
+    public void testPaseStringLiterals() {
+        confirmStringParse("goto considered harmful");
+        
+        confirmStringParse("goto 'considered' harmful");
+        
+        confirmStringParse("");
+        confirmStringParse("'");
+        confirmStringParse("''");
+        confirmStringParse("' '");
+        confirmStringParse(" ' ");
+    }
+    
+    public void testParseSumIfSum() {
+        String formulaString;
+        Ptg[] ptgs;
+        ptgs = parseFormula("sum(5, 2, if(3>2, sum(A1:A2), 6))");
+        formulaString = FormulaParser.toFormulaString(null, ptgs);
+        assertEquals("SUM(5,2,IF(3>2,SUM(A1:A2),6))", formulaString);
+
+        ptgs = parseFormula("if(1<2,sum(5, 2, if(3>2, sum(A1:A2), 6)),4)");
+        formulaString = FormulaParser.toFormulaString(null, ptgs);
+        assertEquals("IF(1<2,SUM(5,2,IF(3>2,SUM(A1:A2),6)),4)", formulaString);
+    }
+    public void testParserErrors() {
+        parseExpectedException("1 2");
+        parseExpectedException(" 12 . 345  ");
+        parseExpectedException("1 .23  ");
+
+        parseExpectedException("sum(#NAME)");
+        parseExpectedException("1 + #N / A * 2");
+        parseExpectedException("#value?");
+        parseExpectedException("#DIV/ 0+2");
+        
+        
+        if (false) { // TODO - add functionality to detect func arg count mismatch
+            parseExpectedException("IF(TRUE)");
+            parseExpectedException("countif(A1:B5, C1, D1)");
+        }
+    }
+    
+    private static void parseExpectedException(String formula) {
+        try {
+            parseFormula(formula);
+            throw new AssertionFailedError("expected parse exception");
+        } catch (FormulaParseException e) {
+            // expected during successful test
+            assertNotNull(e.getMessage());
+        } catch (RuntimeException e) {
+            e.printStackTrace();
+            fail("Wrong exception:" + e.getMessage());
+        }
+    }
+
+    public void testSetFormulaWithRowBeyond32768_Bug44539() {
+        
+        HSSFWorkbook wb = new HSSFWorkbook();
+        HSSFSheet sheet = wb.createSheet();
+        wb.setSheetName(0, "Sheet1");
+        
+        HSSFRow row = sheet.createRow(0);
+        HSSFCell cell = row.createCell((short)0);
+        cell.setCellFormula("SUM(A32769:A32770)");
+        if("SUM(A-32767:A-32766)".equals(cell.getCellFormula())) {
+            fail("Identified bug 44539");
+        }
+        assertEquals("SUM(A32769:A32770)", cell.getCellFormula());
+    }
 }

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java Sat Mar  8 03:49:00 2008
@@ -29,15 +29,25 @@
  *
  * @author Andrew C. Oliver (acoliver at apache dot org)
  */
-public class TestSupBookRecord
-        extends TestCase
-{
+public final class TestSupBookRecord extends TestCase {
     /**
      * This contains a fake data section of a SubBookRecord
      */
-    byte[] data = new byte[] {
-        (byte)0x04,(byte)0x00,(byte)0x01,(byte)0x04
+    byte[] dataIR = new byte[] {
+        (byte)0x04,(byte)0x00,(byte)0x01,(byte)0x04,
     };
+    byte[] dataAIF = new byte[] {
+        (byte)0x01,(byte)0x00,(byte)0x01,(byte)0x3A,
+    };
+    byte[] dataER = new byte[] {
+        (byte)0x02,(byte)0x00,
+        (byte)0x07,(byte)0x00,   (byte)0x00,   
+                (byte)'t', (byte)'e', (byte)'s', (byte)'t', (byte)'U', (byte)'R', (byte)'L',  
+        (byte)0x06,(byte)0x00,   (byte)0x00,   
+                (byte)'S', (byte)'h', (byte)'e', (byte)'e', (byte)'t', (byte)'1', 
+        (byte)0x06,(byte)0x00,   (byte)0x00,   
+                (byte)'S', (byte)'h', (byte)'e', (byte)'e', (byte)'t', (byte)'2', 
+   };
 
     public TestSupBookRecord(String name)
     {
@@ -47,36 +57,67 @@
     /**
      * tests that we can load the record
      */
-    public void testLoad()
-            throws Exception
-    {
+    public void testLoadIR() {
 
-        SupBookRecord record = new SupBookRecord(new TestcaseRecordInputStream((short)0x01AE, (short)data.length, data));      
-        assertEquals( 0x401, record.getFlag());             //expected flag
+        SupBookRecord record = new SupBookRecord(new TestcaseRecordInputStream((short)0x01AE, dataIR));      
+        assertTrue( record.isInternalReferences() );             //expected flag
         assertEquals( 0x4, record.getNumberOfSheets() );    //expected # of sheets
 
         assertEquals( 8, record.getRecordSize() );  //sid+size+data
 
         record.validateSid((short)0x01AE);
     }
-    
+    /**
+     * tests that we can load the record
+     */
+    public void testLoadER() {
+
+        SupBookRecord record = new SupBookRecord(new TestcaseRecordInputStream((short)0x01AE, dataER));      
+        assertTrue( record.isExternalReferences() );             //expected flag
+        assertEquals( 0x2, record.getNumberOfSheets() );    //expected # of sheets
+
+        assertEquals( 34, record.getRecordSize() );  //sid+size+data
+        
+        assertEquals("testURL", record.getURL().getString());
+        UnicodeString[] sheetNames = record.getSheetNames();
+        assertEquals(2, sheetNames.length);
+        assertEquals("Sheet1", sheetNames[0].getString());
+        assertEquals("Sheet2", sheetNames[1].getString());
+
+        record.validateSid((short)0x01AE);
+    }
     
     /**
+     * tests that we can load the record
+     */
+    public void testLoadAIF() {
+
+        SupBookRecord record = new SupBookRecord(new TestcaseRecordInputStream((short)0x01AE, dataAIF));      
+        assertTrue( record.isAddInFunctions() );             //expected flag
+        assertEquals( 0x1, record.getNumberOfSheets() );    //expected # of sheets
+        assertEquals( 8, record.getRecordSize() );  //sid+size+data
+        record.validateSid((short)0x01AE);
+    }
+   
+    /**
      * Tests that we can store the record
      *
      */
-    public void testStore()
-    {
-        SupBookRecord record = new SupBookRecord();
-        record.setFlag( (short) 0x401 );
-        record.setNumberOfSheets( (short)0x4 );
-        
+    public void testStoreIR() {
+        SupBookRecord record = SupBookRecord.createInternalReferences((short)4);
 
+        TestcaseRecordInputStream.confirmRecordEncoding(0x01AE, dataIR, record.serialize());
+    }   
+    
+    public void testStoreER() {
+        UnicodeString url = new UnicodeString("testURL");
+        UnicodeString[] sheetNames = {
+                new UnicodeString("Sheet1"),
+                new UnicodeString("Sheet2"),
+        };
+        SupBookRecord record = SupBookRecord.createExternalReferences(url, sheetNames);
 
-        byte [] recordBytes = record.serialize();
-        assertEquals(recordBytes.length - 4, data.length);
-        for (int i = 0; i < data.length; i++)
-            assertEquals("At offset " + i, data[i], recordBytes[i+4]);
+        TestcaseRecordInputStream.confirmRecordEncoding(0x01AE, dataER, record.serialize());
     }    
     
     public static void main(String [] args) {
@@ -84,6 +125,4 @@
         .println("Testing org.apache.poi.hssf.record.SupBookRecord");
         junit.textui.TestRunner.run(TestSupBookRecord.class);
     }
-    
-
 }

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java Sat Mar  8 03:49:00 2008
@@ -1,4 +1,3 @@
-
 /* ====================================================================
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
@@ -16,11 +15,12 @@
    limitations under the License.
 ==================================================================== */
 
-
-
 package org.apache.poi.hssf.record;
 
 import java.io.ByteArrayInputStream;
+
+import junit.framework.Assert;
+
 import org.apache.poi.util.LittleEndian;
 
 /**
@@ -33,6 +33,14 @@
 public class TestcaseRecordInputStream
         extends RecordInputStream
 {
+    /**
+     * Convenience constructor
+     */
+    public TestcaseRecordInputStream(int sid, byte[] data)
+    {
+      super(new ByteArrayInputStream(mergeDataAndSid((short)sid, (short)data.length, data)));
+      nextRecord();
+    }
     public TestcaseRecordInputStream(short sid, short length, byte[] data)
     {
       super(new ByteArrayInputStream(mergeDataAndSid(sid, length, data)));
@@ -45,5 +53,19 @@
       LittleEndian.putShort(result, 2, length);
       System.arraycopy(data, 0, result, 4, data.length);
       return result;
+    }
+    /**
+     * Confirms data sections are equal
+     * @param expectedData - just raw data (without sid or size short ints)
+     * @param actualRecordBytes this includes 4 prefix bytes (sid & size)
+     */
+    public static void confirmRecordEncoding(int expectedSid, byte[] expectedData, byte[] actualRecordBytes) {
+        int expectedDataSize = expectedData.length;
+        Assert.assertEquals(actualRecordBytes.length - 4, expectedDataSize);
+        Assert.assertEquals(expectedSid, LittleEndian.getShort(actualRecordBytes, 0));
+        Assert.assertEquals(expectedDataSize, LittleEndian.getShort(actualRecordBytes, 2));
+        for (int i = 0; i < expectedDataSize; i++)
+            Assert.assertEquals("At offset " + i, expectedData[i], actualRecordBytes[i+4]);
+        
     }
 }

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java Sat Mar  8 03:49:00 2008
@@ -17,15 +17,30 @@
 
 package org.apache.poi.hssf.record.aggregates;
 
-import junit.framework.TestCase;
-import org.apache.poi.hssf.record.*;
-
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
+import java.util.zip.CRC32;
+
+import junit.framework.AssertionFailedError;
+import junit.framework.TestCase;
+
+import org.apache.poi.hssf.record.BlankRecord;
+import org.apache.poi.hssf.record.FormulaRecord;
+import org.apache.poi.hssf.record.Record;
+import org.apache.poi.hssf.record.SharedFormulaRecord;
+import org.apache.poi.hssf.record.UnknownRecord;
+import org.apache.poi.hssf.record.WindowOneRecord;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 
 public class TestValueRecordsAggregate extends TestCase
 {
+    private static final String ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE = "AbnormalSharedFormulaFlag.xls";
     ValueRecordsAggregate valueRecord = new ValueRecordsAggregate();
 
     /**
@@ -201,6 +216,119 @@
         valueRecord.construct( 0, records );
         valueRecord = (ValueRecordsAggregate) valueRecord.clone();
         assertEquals( 36, valueRecord.getRecordSize() );
+    }
+
+    
+    /**
+     * Sometimes the 'shared formula' flag (<tt>FormulaRecord.isSharedFormula()</tt>) is set when 
+     * there is no corresponding SharedFormulaRecord available. SharedFormulaRecord definitions do
+     * not span multiple sheets.  They are are only defined within a sheet, and thus they do not 
+     * have a sheet index field (only row and column range fields).<br/>
+     * So it is important that the code which locates the SharedFormulaRecord for each 
+     * FormulaRecord does not allow matches across sheets.</br> 
+     * 
+     * Prior to bugzilla 44449 (Feb 2008), POI <tt>ValueRecordsAggregate.construct(int, List)</tt> 
+     * allowed <tt>SharedFormulaRecord</tt>s to be erroneously used across sheets.  That incorrect
+     * behaviour is shown by this test.<p/>
+     * 
+     * <b>Notes on how to produce the test spreadsheet</b>:</p>
+     * The setup for this test (AbnormalSharedFormulaFlag.xls) is rather fragile, insomuchas 
+     * re-saving the file (either with Excel or POI) clears the flag.<br/>
+     * <ol>
+     * <li>A new spreadsheet was created in Excel (File | New | Blank Workbook).</li>
+     * <li>Sheet3 was deleted.</li>
+     * <li>Sheet2!A1 formula was set to '="second formula"', and fill-dragged through A1:A8.</li>
+     * <li>Sheet1!A1 formula was set to '="first formula"', and also fill-dragged through A1:A8.</li>
+     * <li>Four rows on Sheet1 "5" through "8" were deleted ('delete rows' alt-E D, not 'clear' Del).</li>
+     * <li>The spreadsheet was saved as AbnormalSharedFormulaFlag.xls.</li>
+     * </ol>
+     * Prior to the row delete action the spreadsheet has two <tt>SharedFormulaRecord</tt>s. One 
+     * for each sheet. To expose the bug, the shared formulas have been made to overlap.<br/>
+     * The row delete action (as described here) seems to to delete the 
+     * <tt>SharedFormulaRecord</tt> from Sheet1 (but not clear the 'shared formula' flags.<br/>
+     * There are other variations on this theme to create the same effect.  
+     * 
+     */
+    public void testSpuriousSharedFormulaFlag() {
+        File dataDir = new File(System.getProperty("HSSF.testdata.path"));
+        File testFile = new File(dataDir, ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE);
+        
+        long actualCRC = getFileCRC(testFile);
+        long expectedCRC = 2277445406L;
+        if(actualCRC != expectedCRC) {
+            System.err.println("Expected crc " + expectedCRC  + " but got " + actualCRC);
+            throw failUnexpectedTestFileChange();
+        }
+        HSSFWorkbook wb;
+        try {
+            FileInputStream in = new FileInputStream(testFile);
+            wb = new HSSFWorkbook(in);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+        
+        HSSFSheet s = wb.getSheetAt(0); // Sheet1
+        
+        String cellFormula;
+        cellFormula = getFormulaFromFirstCell(s, 0); // row "1"
+        // the problem is not observable in the first row of the shared formula
+        if(!cellFormula.equals("\"first formula\"")) {
+            throw new RuntimeException("Something else wrong with this test case");
+        }
+        
+        // but the problem is observable in rows 2,3,4 
+        cellFormula = getFormulaFromFirstCell(s, 1); // row "2"
+        if(cellFormula.equals("\"second formula\"")) {
+            throw new AssertionFailedError("found bug 44449 (Wrong SharedFormulaRecord was used).");
+        }
+        if(!cellFormula.equals("\"first formula\"")) {
+            throw new RuntimeException("Something else wrong with this test case");
+        }
+    }
+    private static String getFormulaFromFirstCell(HSSFSheet s, int rowIx) {
+        return s.getRow(rowIx).getCell((short)0).getCellFormula();
+    }
+
+    /**
+     * If someone opened this particular test file in Excel and saved it, the peculiar condition
+     * which causes the target bug would probably disappear.  This test would then just succeed
+     * regardless of whether the fix was present.  So a CRC check is performed to make it less easy
+     * for that to occur.
+     */
+    private static RuntimeException failUnexpectedTestFileChange() {
+        String msg = "Test file '" + ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE + "' has changed.  "
+            + "This junit may not be properly testing for the target bug.  "
+            + "Either revert the test file or ensure that the new version "
+            + "has the right characteristics to test the target bug.";
+        // A breakpoint in ValueRecordsAggregate.handleMissingSharedFormulaRecord(FormulaRecord)
+        // should get hit during parsing of Sheet1.
+        // If the test spreadsheet is created as directed, this condition should occur.
+        // It is easy to upset the test spreadsheet (for example re-saving will destroy the 
+        // peculiar condition we are testing for). 
+        throw new RuntimeException(msg);
+    }
+
+    /**
+     * gets a CRC checksum for the content of a file
+     */
+    private static long getFileCRC(File f) {
+        CRC32 crc = new CRC32();
+        byte[] buf = new byte[2048];
+        try {
+            InputStream is = new FileInputStream(f);
+            while(true) {
+                int bytesRead = is.read(buf);
+                if(bytesRead < 1) {
+                    break;
+                }
+                crc.update(buf, 0, bytesRead);
+            }
+            is.close();
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+        
+        return crc.getValue();
     }
 
 }

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/AbstractPtgTestCase.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/AbstractPtgTestCase.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/AbstractPtgTestCase.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/AbstractPtgTestCase.java Sat Mar  8 03:49:00 2008
@@ -1,4 +1,3 @@
-        
 /* ====================================================================
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
@@ -28,6 +27,7 @@
 
 import org.apache.poi.hssf.model.Workbook;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 
 /**
  * Convenient abstract class to reduce the amount of boilerplate code needed
@@ -35,8 +35,7 @@
  *
  * @author Daniel Noll (daniel at nuix dot com dot au)
  */
-public abstract class AbstractPtgTestCase extends TestCase
-{
+public abstract class AbstractPtgTestCase extends TestCase {
     /** Directory containing the test data. */
     private static String dataDir = System.getProperty("HSSF.testdata.path");
 
@@ -51,16 +50,16 @@
             throws IOException {
         File file = new File(dataDir, filename);
         InputStream stream = new BufferedInputStream(new FileInputStream(file));
-        try
-        {
-            return new HSSFWorkbook(stream);
-        }
-        finally
-        {
+        // TODO - temp workaround to keep stdout quiet due to warning msg in POIFS 
+        // When that warning msg is disabled, remove this wrapper and the close() call, 
+        InputStream wrappedStream = POIFSFileSystem.createNonClosingInputStream(stream);
+        try {
+            return new HSSFWorkbook(wrappedStream);
+        } finally {
             stream.close();
         }
     }
-    
+
     /**
      * Creates a new Workbook and adds one sheet with the specified name
      */
@@ -73,5 +72,4 @@
 		book.setSheetName(0, sheetName); 
 		return book;
 	}
-    
 }

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/AllFormulaTests.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/AllFormulaTests.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/AllFormulaTests.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/AllFormulaTests.java Sat Mar  8 03:49:00 2008
@@ -14,7 +14,6 @@
    See the License for the specific language governing permissions and
    limitations under the License.
 ==================================================================== */
-        
 
 package org.apache.poi.hssf.record.formula;
 
@@ -33,7 +32,8 @@
 		result.addTestSuite(TestArea3DPtg.class);
 		result.addTestSuite(TestAreaErrPtg.class);
         result.addTestSuite(TestAreaPtg.class);
-		result.addTestSuite(TestErrPtg.class);
+        result.addTestSuite(TestErrPtg.class);
+        result.addTestSuite(TestExternalFunctionFormulas.class);
 		result.addTestSuite(TestFuncPtg.class);
 		result.addTestSuite(TestIntersectionPtg.class);
 		result.addTestSuite(TestPercentPtg.class);

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/TestAreaPtg.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/TestAreaPtg.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/TestAreaPtg.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/record/formula/TestAreaPtg.java Sat Mar  8 03:49:00 2008
@@ -27,15 +27,12 @@
  *
  * @author Dmitriy Kumshayev
  */
-public class TestAreaPtg extends TestCase
-{
+public final class TestAreaPtg extends TestCase {
 
 	AreaPtg relative;
 	AreaPtg absolute;
 	
-	protected void setUp() throws Exception
-	{
-		super.setUp();
+	protected void setUp() {
 		short firstRow=5;
 		short lastRow=13;
 		short firstCol=7;
@@ -64,10 +61,9 @@
 	}
 
 
-	public void resetColumns(AreaPtg aptg)
-	{
-		short fc = aptg.getFirstColumn();
-		short lc = aptg.getLastColumn();
+	private static void resetColumns(AreaPtg aptg) {
+		int fc = aptg.getFirstColumn();
+		int lc = aptg.getLastColumn();
 		aptg.setFirstColumn(fc);
 		aptg.setLastColumn(lc);
 		assertEquals(fc , aptg.getFirstColumn() );

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java Sat Mar  8 03:49:00 2008
@@ -1089,6 +1089,44 @@
         //  "EmptyStackException"
         //assertEquals("=CHOOSE(2,A2,A3,A4)", c2.getCellFormula());
     }
+    
+    /**
+     * Crystal reports generates files with short 
+     *  StyleRecords, which is against the spec
+     */
+    public void test44471() throws Exception {
+        FileInputStream in = new FileInputStream(new File(cwd, "OddStyleRecord.xls"));
+        
+        // Used to blow up with an ArrayIndexOutOfBounds
+        //  when creating a StyleRecord
+        HSSFWorkbook wb = new HSSFWorkbook(in);
+        in.close();
+        
+        assertEquals(1, wb.getNumberOfSheets());
+    }
+    
+    /**
+     * Files with "read only recommended" were giving
+     *  grief on the FileSharingRecord
+     */
+    public void test44536() throws Exception {
+        FileInputStream in = new FileInputStream(new File(cwd, "ReadOnlyRecommended.xls"));
+        
+        // Used to blow up with an IllegalArgumentException
+        //  when creating a FileSharingRecord
+        HSSFWorkbook wb = new HSSFWorkbook(in);
+        in.close();
+        
+        // Check read only advised
+        assertEquals(3, wb.getNumberOfSheets());
+        assertTrue(wb.isWriteProtected());
+        
+        // But also check that another wb isn't
+        in = new FileInputStream(new File(cwd, "SimpleWithChoose.xls"));
+        wb = new HSSFWorkbook(in);
+        in.close();
+        assertFalse(wb.isWriteProtected());
+    }
 }
 
 

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java Sat Mar  8 03:49:00 2008
@@ -51,7 +51,7 @@
   public void testDataValidation() throws Exception
   {
     System.out.println("\nTest no. 2 - Test Excel's Data validation mechanism");
-    String resultFile   = System.getProperty("HSSF.testdata.path")+"/TestDataValidation.xls";
+    String resultFile   = System.getProperty("java.io.tmpdir")+File.separator+"TestDataValidation.xls";
     HSSFWorkbook wb = new HSSFWorkbook();
 
     HSSFCellStyle style_1 = this.createStyle( wb, HSSFCellStyle.ALIGN_LEFT );

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java Sat Mar  8 03:49:00 2008
@@ -302,10 +302,10 @@
                 }
                 
                 c = r.getCell((short) y);
-                CellReference cr= new CellReference(refx1,refy1);
-                ref=cr.toString();
-                cr=new CellReference(refx2,refy2);
-                ref2=cr.toString();
+                CellReference cr= new CellReference(refx1,refy1, false, false);
+                ref=cr.formatAsString();
+                cr=new CellReference(refx2,refy2, false, false);
+                ref2=cr.formatAsString();
 
                 c = r.createCell((short) y);
                 c.setCellFormula("" + ref + operator + ref2);
@@ -379,10 +379,10 @@
                 }
 
                 c = r.getCell((short) y);
-                CellReference cr= new CellReference(refx1,refy1);
-                ref=cr.toString();
-                cr=new CellReference(refx2,refy2);
-                ref2=cr.toString();
+                CellReference cr= new CellReference(refx1, refy1, false, false);
+                ref=cr.formatAsString();
+                cr=new CellReference(refx2,refy2, false, false);
+                ref2=cr.formatAsString();
                 
                 
                 assertTrue("loop Formula is as expected "+ref+operator+ref2+"!="+c.getCellFormula(),(

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java Sat Mar  8 03:49:00 2008
@@ -160,6 +160,49 @@
         assertEquals("FFFF:0:FFFF", p.getColor((short)14).getHexString());
     }
     
+    public void testFindSimilar() throws Exception {
+    	HSSFWorkbook book = new HSSFWorkbook();
+    	HSSFPalette p = book.getCustomPalette();
+    	
+    	
+    	// Add a few edge colours in
+    	p.setColorAtIndex((short)8, (byte)-1, (byte)0, (byte)0);
+    	p.setColorAtIndex((short)9, (byte)0, (byte)-1, (byte)0);
+    	p.setColorAtIndex((short)10, (byte)0, (byte)0, (byte)-1);
+    	
+    	// And some near a few of them
+    	p.setColorAtIndex((short)11, (byte)-1, (byte)2, (byte)2);
+    	p.setColorAtIndex((short)12, (byte)-2, (byte)2, (byte)10);
+    	p.setColorAtIndex((short)13, (byte)-4, (byte)0, (byte)0);
+    	p.setColorAtIndex((short)14, (byte)-8, (byte)0, (byte)0);
+    	
+    	assertEquals(
+    			"FFFF:0:0", p.getColor((short)8).getHexString()
+    	);
+    	
+    	// Now check we get the right stuff back
+    	assertEquals(
+    			p.getColor((short)8).getHexString(), 
+    			p.findSimilarColor((byte)-1, (byte)0, (byte)0).getHexString()
+    	);
+    	assertEquals(
+    			p.getColor((short)8).getHexString(), 
+    			p.findSimilarColor((byte)-2, (byte)0, (byte)0).getHexString()
+    	);
+    	assertEquals(
+    			p.getColor((short)8).getHexString(), 
+    			p.findSimilarColor((byte)-1, (byte)1, (byte)0).getHexString()
+    	);
+    	assertEquals(
+    			p.getColor((short)11).getHexString(), 
+    			p.findSimilarColor((byte)-1, (byte)2, (byte)1).getHexString()
+    	);
+    	assertEquals(
+    			p.getColor((short)12).getHexString(), 
+    			p.findSimilarColor((byte)-1, (byte)2, (byte)10).getHexString()
+    	);
+    }
+    
     /**
      * Verifies that the generated gnumeric-format string values match the
      * hardcoded values in the HSSFColor default color palette

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java Sat Mar  8 03:49:00 2008
@@ -16,25 +16,28 @@
 */
 package org.apache.poi.hssf.usermodel;
 
-import junit.framework.TestCase;
-
-import java.io.IOException;
-import java.io.FileInputStream;
 import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import junit.framework.TestCase;
 
 /**
  * Test <code>HSSFPicture</code>.
  *
  * @author Yegor Kozlov (yegor at apache.org)
  */
-public class TestHSSFPicture extends TestCase{
+public final class TestHSSFPicture extends TestCase{
 
-    public void testResize() throws Exception {
+    public void testResize() {
         HSSFWorkbook wb = new HSSFWorkbook();
         HSSFSheet sh1 = wb.createSheet();
         HSSFPatriarch p1 = sh1.createDrawingPatriarch();
 
-        int idx1 = loadPicture( "src/resources/logos/logoKarmokar4.png", wb);
+        byte[] pictureData = getTestDataFileContent("logoKarmokar4.png");
+        int idx1 = wb.addPicture( pictureData, HSSFWorkbook.PICTURE_TYPE_PNG );
         HSSFPicture picture1 = p1.createPicture(new HSSFClientAnchor(), idx1);
         HSSFClientAnchor anchor1 = picture1.getPreferredSize();
 
@@ -52,28 +55,25 @@
     /**
      * Copied from org.apache.poi.hssf.usermodel.examples.OfficeDrawing
      */
-    private static int loadPicture( String path, HSSFWorkbook wb ) throws IOException
-    {
-        int pictureIndex;
-        FileInputStream fis = null;
-        ByteArrayOutputStream bos = null;
-        try
-        {
-            fis = new FileInputStream( path);
-            bos = new ByteArrayOutputStream( );
-            int c;
-            while ( (c = fis.read()) != -1)
-                bos.write( c );
-            pictureIndex = wb.addPicture( bos.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG );
-        }
-        finally
-        {
-            if (fis != null)
-                fis.close();
-            if (bos != null)
-                bos.close();
-        }
-        return pictureIndex;
-    }
+     private static byte[] getTestDataFileContent(String fileName) {
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
 
+        String readFilename = System.getProperty("HSSF.testdata.path");
+        try {
+            InputStream fis = new FileInputStream(readFilename+File.separator+fileName);
+
+            byte[] buf = new byte[512];
+            while(true) {
+                int bytesRead = fis.read(buf);
+                if(bytesRead < 1) {
+                    break;
+                }
+                bos.write(buf, 0, bytesRead);
+            }
+            fis.close();
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+        return bos.toByteArray();
+     }
 }

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java Sat Mar  8 03:49:00 2008
@@ -1,4 +1,3 @@
-
 /* ====================================================================
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
@@ -15,34 +14,22 @@
    See the License for the specific language governing permissions and
    limitations under the License.
 ==================================================================== */
-        
 
 package org.apache.poi.hssf.usermodel;
 
-import junit.framework.TestCase;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 
-import org.apache.poi.util.TempFile;
+import junit.framework.TestCase;
 
 /**
  * Test HSSFRow is okay.
  *
  * @author Glen Stampoultzis (glens at apache.org)
  */
-public class TestHSSFRow
-        extends TestCase
-{
-    public TestHSSFRow(String s)
-    {
-        super(s);
-    }
+public final class TestHSSFRow extends TestCase {
 
-    public void testLastAndFirstColumns()
-            throws Exception
-    {
+    public void testLastAndFirstColumns() {
         HSSFWorkbook workbook = new HSSFWorkbook();
         HSSFSheet sheet = workbook.createSheet();
         HSSFRow row = sheet.createRow((short) 0);
@@ -51,127 +38,146 @@
 
         row.createCell((short) 2);
         assertEquals(2, row.getFirstCellNum());
-        assertEquals(2, row.getLastCellNum());
+        assertEquals(3, row.getLastCellNum());
 
         row.createCell((short) 1);
         assertEquals(1, row.getFirstCellNum());
-        assertEquals(2, row.getLastCellNum());
-        
+        assertEquals(3, row.getLastCellNum());
+
         // check the exact case reported in 'bug' 43901 - notice that the cellNum is '0' based
         row.createCell((short) 3);
         assertEquals(1, row.getFirstCellNum());
-        assertEquals(3, row.getLastCellNum());
-
+        assertEquals(4, row.getLastCellNum());
     }
 
-    public void testRemoveCell()
-            throws Exception
-    {
+    public void testRemoveCell() throws Exception {
         HSSFWorkbook workbook = new HSSFWorkbook();
         HSSFSheet sheet = workbook.createSheet();
         HSSFRow row = sheet.createRow((short) 0);
         assertEquals(-1, row.getLastCellNum());
         assertEquals(-1, row.getFirstCellNum());
         row.createCell((short) 1);
-        assertEquals(1, row.getLastCellNum());
+        assertEquals(2, row.getLastCellNum());
         assertEquals(1, row.getFirstCellNum());
         row.createCell((short) 3);
-        assertEquals(3, row.getLastCellNum());
+        assertEquals(4, row.getLastCellNum());
         assertEquals(1, row.getFirstCellNum());
         row.removeCell(row.getCell((short) 3));
-        assertEquals(1, row.getLastCellNum());
+        assertEquals(2, row.getLastCellNum());
         assertEquals(1, row.getFirstCellNum());
         row.removeCell(row.getCell((short) 1));
         assertEquals(-1, row.getLastCellNum());
         assertEquals(-1, row.getFirstCellNum());
 
-        // check the row record actually writes it out as 0's
+        // all cells on this row have been removed
+        // so check the row record actually writes it out as 0's
         byte[] data = new byte[100];
         row.getRowRecord().serialize(0, data);
         assertEquals(0, data[6]);
         assertEquals(0, data[8]);
 
-        File file = TempFile.createTempFile("XXX", "XLS");
-        FileOutputStream stream = new FileOutputStream(file);
-        workbook.write(stream);
-        stream.close();
-        FileInputStream inputStream = new FileInputStream(file);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        workbook.write(baos);
+        baos.close();
+        ByteArrayInputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
         workbook = new HSSFWorkbook(inputStream);
         sheet = workbook.getSheetAt(0);
-        stream.close();
-        file.delete();
+        inputStream.close();
+
         assertEquals(-1, sheet.getRow((short) 0).getLastCellNum());
         assertEquals(-1, sheet.getRow((short) 0).getFirstCellNum());
     }
-    
-    public void testMoveCell() throws Exception {
+
+    public void testMoveCell() {
         HSSFWorkbook workbook = new HSSFWorkbook();
         HSSFSheet sheet = workbook.createSheet();
         HSSFRow row = sheet.createRow((short) 0);
         HSSFRow rowB = sheet.createRow((short) 1);
-        
+
         HSSFCell cellA2 = rowB.createCell((short)0);
         assertEquals(0, rowB.getFirstCellNum());
         assertEquals(0, rowB.getFirstCellNum());
-        
+
         assertEquals(-1, row.getLastCellNum());
         assertEquals(-1, row.getFirstCellNum());
         HSSFCell cellB2 = row.createCell((short) 1);
         HSSFCell cellB3 = row.createCell((short) 2);
         HSSFCell cellB4 = row.createCell((short) 3);
-    	
+
         assertEquals(1, row.getFirstCellNum());
-        assertEquals(3, row.getLastCellNum());
-        
+        assertEquals(4, row.getLastCellNum());
+
         // Try to move to somewhere else that's used
         try {
-        	row.moveCell(cellB2, (short)3);
-        	fail();
-        } catch(IllegalArgumentException e) {}
-        
+            row.moveCell(cellB2, (short)3);
+            fail("IllegalArgumentException should have been thrown");
+        } catch(IllegalArgumentException e) {
+            // expected during successful test
+        }
+
         // Try to move one off a different row
         try {
-        	row.moveCell(cellA2, (short)3);
-        	fail();
-        } catch(IllegalArgumentException e) {}
-        
+            row.moveCell(cellA2, (short)3);
+            fail("IllegalArgumentException should have been thrown");
+        } catch(IllegalArgumentException e) {
+            // expected during successful test
+        }
+
         // Move somewhere spare
         assertNotNull(row.getCell((short)1));
-    	row.moveCell(cellB2, (short)5);
+        row.moveCell(cellB2, (short)5);
         assertNull(row.getCell((short)1));
         assertNotNull(row.getCell((short)5));
-    	
-    	assertEquals(5, cellB2.getCellNum());
+
+        assertEquals(5, cellB2.getCellNum());
         assertEquals(2, row.getFirstCellNum());
-        assertEquals(5, row.getLastCellNum());
-        
+        assertEquals(6, row.getLastCellNum());
     }
-    
-    public void testRowBounds()
-            throws Exception
-    {
+
+    public void testRowBounds() {
       HSSFWorkbook workbook = new HSSFWorkbook();
       HSSFSheet sheet = workbook.createSheet();
       //Test low row bound
-      HSSFRow row = sheet.createRow( (short) 0);
-      //Test low row bound exception      
-      boolean caughtException = false;
+      sheet.createRow( (short) 0);
+      //Test low row bound exception
       try {
-        row = sheet.createRow(-1);        
+        sheet.createRow(-1);
+        fail("IndexOutOfBoundsException should have been thrown");
       } catch (IndexOutOfBoundsException ex) {
-        caughtException = true;
-      }      
-      assertTrue(caughtException);
-      //Test high row bound      
-      row = sheet.createRow(65535);     
-      //Test high row bound exception           
-      caughtException = false;
+        // expected during successful test
+      }
+
+      //Test high row bound
+      sheet.createRow(65535);
+      //Test high row bound exception
       try {
-        row = sheet.createRow(65536);        
+        sheet.createRow(65536);
+        fail("IndexOutOfBoundsException should have been thrown");
       } catch (IndexOutOfBoundsException ex) {
-        caughtException = true;
-      }      
-      assertTrue(caughtException);
+        // expected during successful test
+      }
+    }
+
+    /**
+     * Prior to patch 43901, POI was producing files with the wrong last-column
+     * number on the row
+     */
+    public void testLastCellNumIsCorrectAfterAddCell_bug43901(){
+        HSSFWorkbook book = new HSSFWorkbook();
+        HSSFSheet sheet = book.createSheet("test");
+        HSSFRow row = sheet.createRow(0);
+
+        // New row has last col -1
+        assertEquals(-1, row.getLastCellNum());
+        if(row.getLastCellNum() == 0) {
+            fail("Identified bug 43901");
+        }
+
+        // Create two cells, will return one higher
+        //  than that for the last number
+        row.createCell((short) 0);
+        assertEquals(1, row.getLastCellNum());
+        row.createCell((short) 255);
+        assertEquals(256, row.getLastCellNum());
     }
-    
 }

Modified: poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestNamedRange.java
URL: http://svn.apache.org/viewvc/poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestNamedRange.java?rev=634936&r1=634935&r2=634936&view=diff
==============================================================================
--- poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestNamedRange.java (original)
+++ poi/branches/ooxml/src/testcases/org/apache/poi/hssf/usermodel/TestNamedRange.java Sat Mar  8 03:49:00 2008
@@ -578,18 +578,16 @@
         
         // retrieve the cell at the named range and test its contents
         AreaReference aref = new AreaReference(aNamedCell.getReference());
-        CellReference[] crefs = aref.getCells();
-        assertNotNull(crefs);
-        assertEquals("Should be exactly 1 cell in the named cell :'" +cellName+"'", 1, crefs.length);
-        for (int i=0, iSize=crefs.length; i<iSize; i++) {
-            CellReference cref = crefs[i];
-            assertNotNull(cref);
-            HSSFSheet s = wb.getSheet(cref.getSheetName());
-            HSSFRow r = sheet.getRow(cref.getRow());
-            HSSFCell c = r.getCell(cref.getCol());
-            String contents = c.getStringCellValue();
-            assertEquals("Contents of cell retrieved by its named reference", contents, cellValue);
-        }
+        assertTrue("Should be exactly 1 cell in the named cell :'" +cellName+"'", aref.isSingleCell());
+        
+        CellReference cref = aref.getFirstCell();
+        assertNotNull(cref);
+        HSSFSheet s = wb.getSheet(cref.getSheetName());
+        assertNotNull(s);
+        HSSFRow r = sheet.getRow(cref.getRow());
+        HSSFCell c = r.getCell(cref.getCol());
+        String contents = c.getRichStringCellValue().getString();
+        assertEquals("Contents of cell retrieved by its named reference", contents, cellValue);
     }
 
     /**



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@poi.apache.org
For additional commands, e-mail: commits-help@poi.apache.org


Mime
View raw message