Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java Fri Dec 27 23:00:13 2019 @@ -19,6 +19,7 @@ package org.apache.poi.ss.formula.atp; import static org.apache.poi.ss.formula.eval.ErrorEval.NAME_INVALID; import static org.apache.poi.ss.formula.eval.ErrorEval.VALUE_INVALID; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; @@ -30,10 +31,9 @@ import org.apache.poi.ss.formula.eval.Ar import org.apache.poi.ss.formula.eval.NumericValueEval; import org.apache.poi.ss.formula.eval.StringEval; import org.apache.poi.ss.formula.eval.ValueEval; +import org.junit.Test; -import junit.framework.TestCase; - -public class TestNetworkdaysFunction extends TestCase { +public class TestNetworkdaysFunction { private static final String STARTING_DATE = "2008/10/01"; private static final String END_DATE = "2009/03/01"; @@ -43,46 +43,54 @@ public class TestNetworkdaysFunction ext private static final OperationEvaluationContext EC = new OperationEvaluationContext(null, null, 1, 1, 1, null); + @Test public void testFailWhenNoArguments() { assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[0], null)); } + @Test public void testFailWhenLessThan2Arguments() { assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[1], null)); } + @Test public void testFailWhenMoreThan3Arguments() { assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[4], null)); } + @Test public void testFailWhenArgumentsAreNotDates() { assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[]{ new StringEval("Potato"), new StringEval("Cucumber") }, EC)); } + @Test public void testFailWhenStartDateAfterEndDate() { assertEquals(NAME_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[]{ new StringEval(END_DATE), new StringEval(STARTING_DATE) }, EC)); } + @Test public void testReturnNetworkdays() { assertEquals(108, (int) ((NumericValueEval) NetworkdaysFunction.instance.evaluate(new ValueEval[]{ new StringEval(STARTING_DATE), new StringEval(END_DATE) }, EC)).getNumberValue()); } + @Test public void testReturnNetworkdaysWithAHoliday() { assertEquals(107, (int) ((NumericValueEval) NetworkdaysFunction.instance.evaluate(new ValueEval[]{ new StringEval(STARTING_DATE), new StringEval(END_DATE), new StringEval(FIRST_HOLIDAY) }, EC)).getNumberValue()); } + @Test public void testReturnNetworkdaysWithManyHolidays() { assertEquals(105, (int) ((NumericValueEval) NetworkdaysFunction.instance.evaluate(new ValueEval[]{ new StringEval(STARTING_DATE), new StringEval(END_DATE), - new MockAreaEval(FIRST_HOLIDAY, SECOND_HOLIDAY, THIRD_HOLIDAY) }, EC)).getNumberValue()); + new MockAreaEval(FIRST_HOLIDAY, SECOND_HOLIDAY, THIRD_HOLIDAY)}, EC)).getNumberValue()); } - private class MockAreaEval extends AreaEvalBase { + private static class MockAreaEval extends AreaEvalBase { private List<ValueEval> holidays;
Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java Fri Dec 27 23:00:13 2019 @@ -16,6 +16,8 @@ ==================================================================== */ package org.apache.poi.ss.formula.atp; +import static org.junit.Assert.assertEquals; + import org.apache.poi.ss.formula.eval.AreaEval; import org.apache.poi.ss.formula.eval.BlankEval; import org.apache.poi.ss.formula.eval.BoolEval; @@ -24,24 +26,12 @@ import org.apache.poi.ss.formula.eval.Nu import org.apache.poi.ss.formula.eval.ValueEval; import org.apache.poi.ss.formula.functions.AggregateFunction; import org.apache.poi.ss.formula.functions.EvalFactory; - -import junit.framework.TestCase; +import org.junit.Test; /** * Testcase for Excel function PERCENTILE() - * - * @author T. Gordon */ -public class TestPercentile extends TestCase { - - public void testPercentile() { - testBasic(); - testUnusualArgs(); - testUnusualArgs2(); - testUnusualArgs3(); - testErrors(); - testErrors2(); - } +public class TestPercentile { private static ValueEval invokePercentile(ValueEval[] args, ValueEval percentile) { AreaEval aeA = EvalFactory.createAreaEval("A1:A" + args.length, args); @@ -62,6 +52,7 @@ public class TestPercentile extends Test assertEquals(expectedError.getErrorCode(), ((ErrorEval) result).getErrorCode()); } + @Test public void testBasic() { ValueEval[] values = { new NumberEval(210.128), new NumberEval(65.2182), new NumberEval(32.231), new NumberEval(12.123), new NumberEval(45.32) }; @@ -69,6 +60,7 @@ public class TestPercentile extends Test confirmPercentile(percentile, values, 181.14604); } + @Test public void testBlanks() { ValueEval[] values = { new NumberEval(210.128), new NumberEval(65.2182), new NumberEval(32.231), BlankEval.instance, new NumberEval(45.32) }; @@ -76,6 +68,7 @@ public class TestPercentile extends Test confirmPercentile(percentile, values, 188.39153); } + @Test public void testUnusualArgs() { ValueEval[] values = { new NumberEval(1), new NumberEval(2), BoolEval.TRUE, BoolEval.FALSE }; ValueEval percentile = new NumberEval(0.95); @@ -83,6 +76,7 @@ public class TestPercentile extends Test } //percentile has to be between 0 and 1 - here we test less than zero + @Test public void testUnusualArgs2() { ValueEval[] values = { new NumberEval(1), new NumberEval(2), }; ValueEval percentile = new NumberEval(-0.1); @@ -90,6 +84,7 @@ public class TestPercentile extends Test } //percentile has to be between 0 and 1 - here we test more than 1 + @Test public void testUnusualArgs3() { ValueEval[] values = { new NumberEval(1), new NumberEval(2) }; ValueEval percentile = new NumberEval(1.1); @@ -97,6 +92,7 @@ public class TestPercentile extends Test } //here we test where there are errors as part of inputs + @Test public void testErrors() { ValueEval[] values = { new NumberEval(1), ErrorEval.NAME_INVALID, new NumberEval(3), ErrorEval.DIV_ZERO, }; ValueEval percentile = new NumberEval(0.95); @@ -104,6 +100,7 @@ public class TestPercentile extends Test } //here we test where there are errors as part of inputs + @Test public void testErrors2() { ValueEval[] values = { new NumberEval(1), new NumberEval(2), new NumberEval(3), ErrorEval.DIV_ZERO, }; ValueEval percentile = new NumberEval(0.95); Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java Fri Dec 27 23:00:13 2019 @@ -16,7 +16,8 @@ ==================================================================== */ package org.apache.poi.ss.formula.atp; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.ss.formula.eval.ErrorEval; @@ -26,38 +27,37 @@ import org.apache.poi.ss.usermodel.Formu import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; +import org.junit.Before; +import org.junit.Test; /** * Testcase for 'Analysis Toolpak' function RANDBETWEEN() - * - * @author Brendan Nolan */ -public class TestRandBetween extends TestCase { +public class TestRandBetween { private Workbook wb; private FormulaEvaluator evaluator; private Cell bottomValueCell; private Cell topValueCell; private Cell formulaCell; - - @Override - protected void setUp() throws Exception { - super.setUp(); + + @Before + public void setUp() throws Exception { wb = HSSFTestDataSamples.openSampleWorkbook("TestRandBetween.xls"); evaluator = wb.getCreationHelper().createFormulaEvaluator(); - + Sheet sheet = wb.createSheet("RandBetweenSheet"); Row row = sheet.createRow(0); bottomValueCell = row.createCell(0); topValueCell = row.createCell(1); formulaCell = row.createCell(2, CellType.FORMULA); } - + /** * Check where values are the same */ + @Test public void testRandBetweenSameValues() { - evaluator.clearAllCachedResultValues(); formulaCell.setCellFormula("RANDBETWEEN(1,1)"); evaluator.evaluateFormulaCell(formulaCell); @@ -69,6 +69,7 @@ public class TestRandBetween extends Tes } + @Test public void testRandBetweenLargeLongs() { for (int i = 0; i < 100; i++) { evaluator.clearAllCachedResultValues(); @@ -79,70 +80,70 @@ public class TestRandBetween extends Tes assertTrue("rand is less than or equal to upperbound", value <= 9999999999.0); } } - + /** - * Check special case where rounded up bottom value is greater than + * Check special case where rounded up bottom value is greater than * top value. */ + @Test public void testRandBetweenSpecialCase() { - - - bottomValueCell.setCellValue(0.05); + bottomValueCell.setCellValue(0.05); topValueCell.setCellValue(0.1); formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); evaluator.clearAllCachedResultValues(); evaluator.evaluateFormulaCell(formulaCell); assertEquals(1, formulaCell.getNumericCellValue(), 0); - bottomValueCell.setCellValue(-0.1); + bottomValueCell.setCellValue(-0.1); topValueCell.setCellValue(-0.05); formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); evaluator.clearAllCachedResultValues(); evaluator.evaluateFormulaCell(formulaCell); assertEquals(0, formulaCell.getNumericCellValue(), 0); - bottomValueCell.setCellValue(-1.1); + bottomValueCell.setCellValue(-1.1); topValueCell.setCellValue(-1.05); formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); evaluator.clearAllCachedResultValues(); evaluator.evaluateFormulaCell(formulaCell); assertEquals(-1, formulaCell.getNumericCellValue(), 0); - bottomValueCell.setCellValue(-1.1); + bottomValueCell.setCellValue(-1.1); topValueCell.setCellValue(-1.1); formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); evaluator.clearAllCachedResultValues(); evaluator.evaluateFormulaCell(formulaCell); assertEquals(-1, formulaCell.getNumericCellValue(), 0); } - + /** * Check top value of BLANK which Excel will evaluate as 0 */ + @Test public void testRandBetweenTopBlank() { - - bottomValueCell.setCellValue(-1); + bottomValueCell.setCellValue(-1); topValueCell.setBlank(); formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); evaluator.clearAllCachedResultValues(); evaluator.evaluateFormulaCell(formulaCell); assertTrue(formulaCell.getNumericCellValue() == 0 || formulaCell.getNumericCellValue() == -1); - + } /** * Check where input values are of wrong type */ + @Test public void testRandBetweenWrongInputTypes() { // Check case where bottom input is of the wrong type - bottomValueCell.setCellValue("STRING"); + bottomValueCell.setCellValue("STRING"); topValueCell.setCellValue(1); formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); evaluator.clearAllCachedResultValues(); evaluator.evaluateFormulaCell(formulaCell); assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultType()); assertEquals(ErrorEval.VALUE_INVALID.getErrorCode(), formulaCell.getErrorCellValue()); - - + + // Check case where top input is of the wrong type bottomValueCell.setCellValue(1); - topValueCell.setCellValue("STRING"); + topValueCell.setCellValue("STRING"); formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); evaluator.clearAllCachedResultValues(); evaluator.evaluateFormulaCell(formulaCell); @@ -151,29 +152,28 @@ public class TestRandBetween extends Tes // Check case where both inputs are of wrong type bottomValueCell.setCellValue("STRING"); - topValueCell.setCellValue("STRING"); + topValueCell.setCellValue("STRING"); formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); evaluator.clearAllCachedResultValues(); evaluator.evaluateFormulaCell(formulaCell); assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultType()); assertEquals(ErrorEval.VALUE_INVALID.getErrorCode(), formulaCell.getErrorCellValue()); - } - + /** * Check case where bottom is greater than top */ + @Test public void testRandBetweenBottomGreaterThanTop() { - // Check case where bottom is greater than top - bottomValueCell.setCellValue(1); + bottomValueCell.setCellValue(1); topValueCell.setCellValue(0); formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); evaluator.clearAllCachedResultValues(); evaluator.evaluateFormulaCell(formulaCell); assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultType()); - assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), formulaCell.getErrorCellValue()); - bottomValueCell.setCellValue(1); + assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), formulaCell.getErrorCellValue()); + bottomValueCell.setCellValue(1); topValueCell.setBlank(); formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); evaluator.clearAllCachedResultValues(); @@ -181,19 +181,17 @@ public class TestRandBetween extends Tes assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultType()); assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), formulaCell.getErrorCellValue()); } - + /** * Boundary check of Double MIN and MAX values */ + @Test public void testRandBetweenBoundaryCheck() { - - bottomValueCell.setCellValue(Double.MIN_VALUE); + bottomValueCell.setCellValue(Double.MIN_VALUE); topValueCell.setCellValue(Double.MAX_VALUE); formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); evaluator.clearAllCachedResultValues(); evaluator.evaluateFormulaCell(formulaCell); - assertTrue(formulaCell.getNumericCellValue() >= Double.MIN_VALUE && formulaCell.getNumericCellValue() <= Double.MAX_VALUE); - + assertTrue(formulaCell.getNumericCellValue() >= Double.MIN_VALUE && formulaCell.getNumericCellValue() <= Double.MAX_VALUE); } - } Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java Fri Dec 27 23:00:13 2019 @@ -18,8 +18,9 @@ package org.apache.poi.ss.formula.eval; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.IOException; @@ -33,8 +34,6 @@ import org.apache.poi.ss.usermodel.Sheet import org.apache.poi.ss.usermodel.Workbook; import org.junit.Test; -import junit.framework.AssertionFailedError; - /** * Common superclass for testing cases of circular references * both for HSSF and XSSF @@ -54,13 +53,13 @@ public abstract class BaseTestCircularRe /** * Translates StackOverflowError into AssertionFailedError */ - private CellValue evaluateWithCycles(Workbook wb, Cell testCell) - throws AssertionFailedError { + private CellValue evaluateWithCycles(Workbook wb, Cell testCell) { FormulaEvaluator evaluator = _testDataProvider.createFormulaEvaluator(wb); try { return evaluator.evaluate(testCell); } catch (StackOverflowError e) { - throw new AssertionFailedError( "circular reference caused stack overflow error"); + fail( "circular reference caused stack overflow error"); + return null; } } /** @@ -78,28 +77,28 @@ public abstract class BaseTestCircularRe */ @Test public void testIndexFormula() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet("Sheet1"); - int colB = 1; - sheet.createRow(0).createCell(colB).setCellValue(1); - sheet.createRow(1).createCell(colB).setCellValue(2); - sheet.createRow(2).createCell(colB).setCellValue(3); - Row row4 = sheet.createRow(3); - Cell testCell = row4.createCell(0); - // This formula should evaluate to the contents of B2, - testCell.setCellFormula("INDEX(A1:B4,2,2)"); - // However the range A1:B4 also includes the current cell A4. If the other parameters - // were 4 and 1, this would represent a circular reference. Prior to v3.2 POI would - // 'fully' evaluate ref arguments before invoking operators, which raised the possibility of - // cycles / StackOverflowErrors. - - - CellValue cellValue = evaluateWithCycles(wb, testCell); - - assertSame(cellValue.getCellType(), CellType.NUMERIC); - assertEquals(2, cellValue.getNumberValue(), 0); - wb.close(); + int colB = 1; + sheet.createRow(0).createCell(colB).setCellValue(1); + sheet.createRow(1).createCell(colB).setCellValue(2); + sheet.createRow(2).createCell(colB).setCellValue(3); + Row row4 = sheet.createRow(3); + Cell testCell = row4.createCell(0); + // This formula should evaluate to the contents of B2, + testCell.setCellFormula("INDEX(A1:B4,2,2)"); + // However the range A1:B4 also includes the current cell A4. If the other parameters + // were 4 and 1, this would represent a circular reference. Prior to v3.2 POI would + // 'fully' evaluate ref arguments before invoking operators, which raised the possibility of + // cycles / StackOverflowErrors. + + + CellValue cellValue = evaluateWithCycles(wb, testCell); + assertNotNull(cellValue); + assertSame(cellValue.getCellType(), CellType.NUMERIC); + assertEquals(2, cellValue.getNumberValue(), 0); + } } /** @@ -107,18 +106,18 @@ public abstract class BaseTestCircularRe */ @Test public void testSimpleCircularReference() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet("Sheet1"); - Row row = sheet.createRow(0); - Cell testCell = row.createCell(0); - testCell.setCellFormula("A1"); - - CellValue cellValue = evaluateWithCycles(wb, testCell); - - confirmCycleErrorCode(cellValue); - - wb.close(); + Row row = sheet.createRow(0); + Cell testCell = row.createCell(0); + testCell.setCellFormula("A1"); + + CellValue cellValue = evaluateWithCycles(wb, testCell); + assertNotNull(cellValue); + confirmCycleErrorCode(cellValue); + + } } /** @@ -126,67 +125,66 @@ public abstract class BaseTestCircularRe */ @Test public void testMultiLevelCircularReference() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet("Sheet1"); - Row row = sheet.createRow(0); - row.createCell(0).setCellFormula("B1"); - row.createCell(1).setCellFormula("C1"); - row.createCell(2).setCellFormula("D1"); - Cell testCell = row.createCell(3); - testCell.setCellFormula("A1"); - - CellValue cellValue = evaluateWithCycles(wb, testCell); - - confirmCycleErrorCode(cellValue); - - wb.close(); + Row row = sheet.createRow(0); + row.createCell(0).setCellFormula("B1"); + row.createCell(1).setCellFormula("C1"); + row.createCell(2).setCellFormula("D1"); + Cell testCell = row.createCell(3); + testCell.setCellFormula("A1"); + + CellValue cellValue = evaluateWithCycles(wb, testCell); + assertNotNull(cellValue); + confirmCycleErrorCode(cellValue); + } } @Test public void testIntermediateCircularReferenceResults_bug46898() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet("Sheet1"); + + Row row = sheet.createRow(0); - Row row = sheet.createRow(0); + Cell cellA1 = row.createCell(0); + Cell cellB1 = row.createCell(1); + Cell cellC1 = row.createCell(2); + Cell cellD1 = row.createCell(3); + Cell cellE1 = row.createCell(4); + + cellA1.setCellFormula("IF(FALSE, 1+B1, 42)"); + cellB1.setCellFormula("1+C1"); + cellC1.setCellFormula("1+D1"); + cellD1.setCellFormula("1+E1"); + cellE1.setCellFormula("1+A1"); + + FormulaEvaluator fe = _testDataProvider.createFormulaEvaluator(wb); + CellValue cv; + + // Happy day flow - evaluate A1 first + cv = fe.evaluate(cellA1); + assertEquals(CellType.NUMERIC, cv.getCellType()); + assertEquals(42.0, cv.getNumberValue(), 0.0); + cv = fe.evaluate(cellB1); // no circ-ref-error because A1 result is cached + assertEquals(CellType.NUMERIC, cv.getCellType()); + assertEquals(46.0, cv.getNumberValue(), 0.0); + + // Show the bug - evaluate another cell from the loop first + fe.clearAllCachedResultValues(); + cv = fe.evaluate(cellB1); + // Identified bug 46898 + assertNotEquals(cv.getCellType(), ErrorEval.CIRCULAR_REF_ERROR.getErrorCode()); + assertEquals(CellType.NUMERIC, cv.getCellType()); + assertEquals(46.0, cv.getNumberValue(), 0.0); + + // start evaluation on another cell + fe.clearAllCachedResultValues(); + cv = fe.evaluate(cellE1); + assertEquals(CellType.NUMERIC, cv.getCellType()); + assertEquals(43.0, cv.getNumberValue(), 0.0); - Cell cellA1 = row.createCell(0); - Cell cellB1 = row.createCell(1); - Cell cellC1 = row.createCell(2); - Cell cellD1 = row.createCell(3); - Cell cellE1 = row.createCell(4); - - cellA1.setCellFormula("IF(FALSE, 1+B1, 42)"); - cellB1.setCellFormula("1+C1"); - cellC1.setCellFormula("1+D1"); - cellD1.setCellFormula("1+E1"); - cellE1.setCellFormula("1+A1"); - - FormulaEvaluator fe = _testDataProvider.createFormulaEvaluator(wb); - CellValue cv; - - // Happy day flow - evaluate A1 first - cv = fe.evaluate(cellA1); - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(42.0, cv.getNumberValue(), 0.0); - cv = fe.evaluate(cellB1); // no circ-ref-error because A1 result is cached - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(46.0, cv.getNumberValue(), 0.0); - - // Show the bug - evaluate another cell from the loop first - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cellB1); - // Identified bug 46898 - assertNotEquals(cv.getCellType(), ErrorEval.CIRCULAR_REF_ERROR.getErrorCode()); - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(46.0, cv.getNumberValue(), 0.0); - - // start evaluation on another cell - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cellE1); - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(43.0, cv.getNumberValue(), 0.0); - - wb.close(); + } } } Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java Fri Dec 27 23:00:13 2019 @@ -17,21 +17,22 @@ package org.apache.poi.ss.formula.eval; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.ptg.AreaPtg; import org.apache.poi.ss.formula.functions.EvalFactory; +import org.apache.poi.ss.formula.ptg.AreaPtg; import org.apache.poi.ss.util.AreaReference; +import org.junit.Test; /** * Tests for <tt>AreaEval</tt> - * - * @author Josh Micich */ -public final class TestAreaEval extends TestCase { +public final class TestAreaEval { + @Test public void testGetValue_bug44950() { // TODO - this test probably isn't testing much anymore AreaPtg ptg = new AreaPtg(new AreaReference("B2:D3", SpreadsheetVersion.EXCEL97)); @@ -45,9 +46,7 @@ public final class TestAreaEval extends new NumberEval(6), }; AreaEval ae = EvalFactory.createAreaEval(ptg, values); - if (one == ae.getAbsoluteValue(1, 2)) { - throw new AssertionFailedError("Identified bug 44950 a"); - } + assertNotEquals("Identified bug 44950 a", one, ae.getAbsoluteValue(1, 2)); confirm(1, ae, 1, 1); confirm(2, ae, 1, 2); confirm(3, ae, 1, 3); Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java Fri Dec 27 23:00:13 2019 @@ -17,17 +17,16 @@ package org.apache.poi.ss.formula.eval; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; import org.apache.poi.ss.formula.functions.EvalFactory; import org.apache.poi.ss.formula.functions.NumericFunctionInvoker; +import org.junit.Test; /** * Test for divide operator evaluator. - * - * @author Josh Micich */ -public final class TestDivideEval extends TestCase { +public final class TestDivideEval { private static void confirm(ValueEval arg0, ValueEval arg1, double expectedResult) { ValueEval[] args = { @@ -39,6 +38,7 @@ public final class TestDivideEval extend assertEquals(expectedResult, result, 0); } + @Test public void testBasic() { confirm(new NumberEval(5), new NumberEval(2), 2.5); confirm(new NumberEval(3), new NumberEval(16), 0.1875); @@ -47,11 +47,14 @@ public final class TestDivideEval extend confirm(BoolEval.TRUE, new StringEval("-0.2"), -5.0); } + @Test public void test1x1Area() { AreaEval ae0 = EvalFactory.createAreaEval("B2:B2", new ValueEval[] { new NumberEval(50), }); AreaEval ae1 = EvalFactory.createAreaEval("C2:C2", new ValueEval[] { new NumberEval(10), }); confirm(ae0, ae1, 5); } + + @Test public void testDivZero() { ValueEval[] args = { new NumberEval(5), NumberEval.ZERO, Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java Fri Dec 27 23:00:13 2019 @@ -17,25 +17,23 @@ package org.apache.poi.ss.formula.eval; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; import org.apache.poi.ss.formula.functions.EvalFactory; import org.apache.poi.ss.formula.functions.Function; +import org.junit.Test; /** - * Test for {@link EqualEval} - * - * @author Josh Micich + * Test for EqualEval */ -public final class TestEqualEval extends TestCase { - // convenient access to namepace - private static final EvalInstances EI = null; - +public final class TestEqualEval { /** * Test for bug observable at svn revision 692218 (Sep 2008)<br> * The value from a 1x1 area should be taken immediately, regardless of srcRow and srcCol */ + @Test public void test1x1AreaOperand() { ValueEval[] values = { BoolEval.FALSE, }; @@ -44,17 +42,15 @@ public final class TestEqualEval extends BoolEval.FALSE, }; ValueEval result = evaluate(EvalInstances.Equal, args, 10, 10); - if (result instanceof ErrorEval) { - if (result == ErrorEval.VALUE_INVALID) { - throw new AssertionFailedError("Identified bug in evaluation of 1x1 area"); - } - } - assertEquals(BoolEval.class, result.getClass()); + assertNotEquals("Identified bug in evaluation of 1x1 area", ErrorEval.VALUE_INVALID, result); + assertTrue(result instanceof BoolEval); assertTrue(((BoolEval)result).getBooleanValue()); } + /** * Empty string is equal to blank */ + @Test public void testBlankEqualToEmptyString() { ValueEval[] args = { @@ -64,19 +60,14 @@ public final class TestEqualEval extends ValueEval result = evaluate(EvalInstances.Equal, args, 10, 10); assertEquals(BoolEval.class, result.getClass()); BoolEval be = (BoolEval) result; - if (!be.getBooleanValue()) { - throw new AssertionFailedError("Identified bug blank/empty string equality"); - } - assertTrue(be.getBooleanValue()); + assertTrue("Identified bug blank/empty string equality", be.getBooleanValue()); } /** * Test for bug 46613 (observable at svn r737248) */ + @Test public void testStringInsensitive_bug46613() { - if (!evalStringCmp("abc", "aBc", EvalInstances.Equal)) { - throw new AssertionFailedError("Identified bug 46613"); - } assertTrue(evalStringCmp("abc", "aBc", EvalInstances.Equal)); assertTrue(evalStringCmp("ABC", "azz", EvalInstances.LessThan)); assertTrue(evalStringCmp("abc", "AZZ", EvalInstances.LessThan)); @@ -95,6 +86,7 @@ public final class TestEqualEval extends return be.getBooleanValue(); } + @Test public void testBooleanCompares() { confirmCompares(BoolEval.TRUE, new StringEval("TRUE"), +1); confirmCompares(BoolEval.TRUE, new NumberEval(1.0), +1); @@ -106,6 +98,7 @@ public final class TestEqualEval extends confirmCompares(BoolEval.FALSE, new NumberEval(0.0), +1); confirmCompares(BoolEval.FALSE, BoolEval.FALSE, 0); } + private static void confirmCompares(ValueEval a, ValueEval b, int expRes) { confirm(a, b, expRes>0, EvalInstances.GreaterThan); confirm(a, b, expRes>=0, EvalInstances.GreaterEqual); @@ -119,6 +112,7 @@ public final class TestEqualEval extends confirm(b, a, expRes>=0, EvalInstances.LessEqual); confirm(b, a, expRes>0, EvalInstances.LessThan); } + private static void confirm(ValueEval a, ValueEval b, boolean expectedResult, Function cmpOp) { ValueEval[] args = { a, b, }; ValueEval result = evaluate(cmpOp, args, 10, 20); @@ -135,22 +129,21 @@ public final class TestEqualEval extends * "Excel considers -0.0 to be equal to 0.0" which is NQR * See {@link TestMinusZeroResult} for more specific tests regarding -0.0. */ + @Test public void testZeroEquality_bug47198() { NumberEval zero = new NumberEval(0.0); NumberEval mZero = (NumberEval) evaluate(UnaryMinusEval.instance, new ValueEval[] { zero, }, 0, 0); - if (Double.doubleToLongBits(mZero.getNumberValue()) == 0x8000000000000000L) { - throw new AssertionFailedError("Identified bug 47198: unary minus should convert -0.0 to 0.0"); - } + assertNotEquals("Identified bug 47198: unary minus should convert -0.0 to 0.0", + 0x8000000000000000L, Double.doubleToLongBits(mZero.getNumberValue())); ValueEval[] args = { zero, mZero, }; BoolEval result = (BoolEval) evaluate(EvalInstances.Equal, args, 0, 0); - if (!result.getBooleanValue()) { - throw new AssertionFailedError("Identified bug 47198: -0.0 != 0.0"); - } + assertTrue("Identified bug 47198: -0.0 != 0.0", result.getBooleanValue()); } + @Test public void testRounding_bug47598() { double x = 1+1.0028-0.9973; // should be 1.0055, but has IEEE rounding - assertFalse(x == 1.0055); + assertNotEquals(1.0055, x, 0.0); NumberEval a = new NumberEval(x); NumberEval b = new NumberEval(1.0055); @@ -158,9 +151,7 @@ public final class TestEqualEval extends ValueEval[] args = { a, b, }; BoolEval result = (BoolEval) evaluate(EvalInstances.Equal, args, 0, 0); - if (!result.getBooleanValue()) { - throw new AssertionFailedError("Identified bug 47598: 1+1.0028-0.9973 != 1.0055"); - } + assertTrue("Identified bug 47598: 1+1.0028-0.9973 != 1.0055", result.getBooleanValue()); } private static ValueEval evaluate(Function oper, ValueEval[] args, int srcRowIx, int srcColIx) { Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java Fri Dec 27 23:00:13 2019 @@ -17,81 +17,67 @@ package org.apache.poi.ss.formula.eval; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.udf.DefaultUDFFinder; -import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; -import org.apache.poi.ss.formula.udf.UDFFinder; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; 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.ss.formula.OperationEvaluationContext; +import org.apache.poi.ss.formula.functions.FreeRefFunction; +import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; +import org.apache.poi.ss.formula.udf.DefaultUDFFinder; +import org.apache.poi.ss.formula.udf.UDFFinder; +import org.junit.Test; -/** - * @author Josh Micich - * @author Petr Udalau - registering UDFs in workbook and using ToolPacks. - */ -public final class TestExternalFunction extends TestCase { - - private static class MyFunc implements FreeRefFunction { - public MyFunc() { - // - } +public final class TestExternalFunction { - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 1 || !(args[0] instanceof StringEval)) { - return ErrorEval.VALUE_INVALID; - } - StringEval input = (StringEval) args[0]; - return new StringEval(input.getStringValue() + "abc"); + private static ValueEval myFunc1(ValueEval[] args, OperationEvaluationContext ec) { + if (args.length != 1 || !(args[0] instanceof StringEval)) { + return ErrorEval.VALUE_INVALID; } + StringEval input = (StringEval) args[0]; + return new StringEval(input.getStringValue() + "abc"); } - private static class MyFunc2 implements FreeRefFunction { - public MyFunc2() { - // - } - - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 1 || !(args[0] instanceof StringEval)) { - return ErrorEval.VALUE_INVALID; - } - StringEval input = (StringEval) args[0]; - return new StringEval(input.getStringValue() + "abc2"); + private static ValueEval myFunc2(ValueEval[] args, OperationEvaluationContext ec) { + if (args.length != 1 || !(args[0] instanceof StringEval)) { + return ErrorEval.VALUE_INVALID; } + StringEval input = (StringEval) args[0]; + return new StringEval(input.getStringValue() + "abc2"); } /** - * Checks that an external function can get invoked from the formula - * evaluator. + * Checks that an external function can get invoked from the formula evaluator. */ - public void testInvoke() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testNames.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - - /** - * register the two test UDFs in a UDF finder, to be passed to the evaluator - */ - UDFFinder udff1 = new DefaultUDFFinder(new String[] { "myFunc", }, - new FreeRefFunction[] { new MyFunc(), }); - UDFFinder udff2 = new DefaultUDFFinder(new String[] { "myFunc2", }, - new FreeRefFunction[] { new MyFunc2(), }); - UDFFinder udff = new AggregatingUDFFinder(udff1, udff2); - - - HSSFRow row = sheet.getRow(0); - HSSFCell myFuncCell = row.getCell(1); // =myFunc("_") - - HSSFCell myFunc2Cell = row.getCell(2); // =myFunc2("_") - - HSSFFormulaEvaluator fe = HSSFFormulaEvaluator.create(wb, null, udff); - assertEquals("_abc", fe.evaluate(myFuncCell).getStringValue()); - assertEquals("_abc2", fe.evaluate(myFunc2Cell).getStringValue()); + @Test + public void testInvoke() throws IOException { + try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testNames.xls")) { + HSSFSheet sheet = wb.getSheetAt(0); + + /* + * register the two test UDFs in a UDF finder, to be passed to the evaluator + */ + UDFFinder udff1 = new DefaultUDFFinder(new String[]{"myFunc",}, + new FreeRefFunction[]{TestExternalFunction::myFunc1}); + UDFFinder udff2 = new DefaultUDFFinder(new String[]{"myFunc2",}, + new FreeRefFunction[]{TestExternalFunction::myFunc2,}); + UDFFinder udff = new AggregatingUDFFinder(udff1, udff2); + + + HSSFRow row = sheet.getRow(0); + HSSFCell myFuncCell = row.getCell(1); // =myFunc("_") + + HSSFCell myFunc2Cell = row.getCell(2); // =myFunc2("_") + + HSSFFormulaEvaluator fe = HSSFFormulaEvaluator.create(wb, null, udff); + assertEquals("_abc", fe.evaluate(myFuncCell).getStringValue()); + assertEquals("_abc2", fe.evaluate(myFunc2Cell).getStringValue()); + } } } Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java Fri Dec 27 23:00:13 2019 @@ -43,8 +43,6 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; -import junit.framework.AssertionFailedError; - /** * Tests formulas and operators as loaded from a test data spreadsheet.<p> * This class does not test implementors of <tt>Function</tt> and <tt>OperationEval</tt> in @@ -60,11 +58,11 @@ public final class TestFormulasFromSprea private static Sheet sheet; private static HSSFFormulaEvaluator evaluator; private static Locale userLocale; - + /** * This class defines constants for navigating around the test data spreadsheet used for these tests. */ - private static interface SS { + private interface SS { /** * Name of the test spreadsheet (found in the standard test data folder) @@ -99,6 +97,7 @@ public final class TestFormulasFromSprea int NUMBER_OF_ROWS_PER_FUNCTION = 4; } + @SuppressWarnings("DefaultAnnotationParam") @Parameter(value = 0) public String targetFunctionName; @Parameter(value = 1) @@ -113,7 +112,7 @@ public final class TestFormulasFromSprea } @Parameters(name="{0}") - public static Collection<Object[]> data() throws Exception { + public static Collection<Object[]> data() { // Function "Text" uses custom-formats which are locale specific // can't set the locale on a per-testrun execution, as some settings have been // already set, when we would try to change the locale by then @@ -123,24 +122,23 @@ public final class TestFormulasFromSprea workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME); sheet = workbook.getSheetAt( 0 ); evaluator = new HSSFFormulaEvaluator(workbook); - + List<Object[]> data = new ArrayList<>(); - - processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, null); - processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, null); + + processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX); + processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX); // example for debugging individual functions/operators: // processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, "ConcatEval"); // processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, "Text"); return data; } - + /** * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * @param testFocusFunctionName name of a single function/operator to test alone. * Typically pass <code>null</code> to test all functions */ - private static void processFunctionGroup(List<Object[]> data, int startRowIndex, String testFocusFunctionName) { + private static void processFunctionGroup(List<Object[]> data, int startRowIndex) { for (int rowIndex = startRowIndex; true; rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION) { Row r = sheet.getRow(rowIndex); String targetFunctionName = getTargetFunctionName(r); @@ -151,16 +149,14 @@ public final class TestFormulasFromSprea // found end of functions list break; } - if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - // expected results are on the row below - Row expectedValuesRow = sheet.getRow(rowIndex + 1); - int missingRowNum = rowIndex + 2; //+1 for 1-based, +1 for next row - assertNotNull("Missing expected values row for function '" - + targetFunctionName + " (row " + missingRowNum + ")", expectedValuesRow); + // expected results are on the row below + Row expectedValuesRow = sheet.getRow(rowIndex + 1); + int missingRowNum = rowIndex + 2; //+1 for 1-based, +1 for next row + assertNotNull("Missing expected values row for function '" + + targetFunctionName + " (row " + missingRowNum + ")", expectedValuesRow); - data.add(new Object[]{targetFunctionName, rowIndex, rowIndex + 1}); - } + data.add(new Object[]{targetFunctionName, rowIndex, rowIndex + 1}); } } @@ -235,7 +231,7 @@ public final class TestFormulasFromSprea return cell.getRichStringCellValue().getString(); } - throw new AssertionFailedError("Bad cell type for 'function name' column: (" - + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); + fail("Bad cell type for 'function name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); + return null; } } Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java Fri Dec 27 23:00:13 2019 @@ -17,11 +17,12 @@ package org.apache.poi.ss.formula.eval; -import junit.framework.ComparisonFailure; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.apache.poi.ss.formula.functions.Function; -import org.apache.poi.util.HexDump; +import org.junit.Test; /** * IEEE 754 defines a quantity '-0.0' which is distinct from '0.0'. @@ -35,11 +36,11 @@ import org.apache.poi.util.HexDump; * <li>For most operation results '-0.0' is converted to '0.0'.</li> * <li>Comparison operators have slightly different rules regarding '-0.0'.</li> * </ol> - * @author Josh Micich */ -public final class TestMinusZeroResult extends TestCase { +public final class TestMinusZeroResult { private static final double MINUS_ZERO = -0.0; + @Test public void testSimpleOperators() { // unary plus is a no-op @@ -61,12 +62,14 @@ public final class TestMinusZeroResult e * These results are hard to see in Excel (since -0.0 is usually converted to +0.0 before it * gets to the comparison operator) */ + @Test public void testComparisonOperators() { checkEval(false, EvalInstances.Equal, 0.0, MINUS_ZERO); checkEval(true, EvalInstances.GreaterThan, 0.0, MINUS_ZERO); checkEval(true, EvalInstances.LessThan, MINUS_ZERO, 0.0); } + @Test public void testTextRendering() { confirmTextRendering(MINUS_ZERO); // sub-normal negative numbers also display as '-0' @@ -103,6 +106,7 @@ public final class TestMinusZeroResult e /** * Not really a POI test - just shows similar behaviour of '-0.0' in Java. */ + @Test public void testJava() { assertEquals(0x8000000000000000L, Double.doubleToLongBits(MINUS_ZERO)); @@ -141,9 +145,6 @@ public final class TestMinusZeroResult e private static void assertDouble(double a, double b) { long bitsA = Double.doubleToLongBits(a); long bitsB = Double.doubleToLongBits(b); - if (bitsA != bitsB) { - throw new ComparisonFailure("value different to expected", - HexDump.longToHex(bitsA), HexDump.longToHex(bitsB)); - } + assertEquals(bitsA, bitsB); } } Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java Fri Dec 27 23:00:13 2019 @@ -17,58 +17,56 @@ package org.apache.poi.ss.formula.eval; -import java.util.EmptyStackException; +import static org.junit.Assert.assertEquals; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; +import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellValue; +import org.junit.Test; /** * Tests for {@link MissingArgEval} - * - * @author Josh Micich */ -public final class TestMissingArgEval extends TestCase { - - public void testEvaluateMissingArgs() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFCell cell = sheet.createRow(0).createCell(0); - - cell.setCellFormula("if(true,)"); - fe.clearAllCachedResultValues(); - CellValue cv; - try { - cv = fe.evaluate(cell); - } catch (EmptyStackException e) { - throw new AssertionFailedError("Missing args evaluation not implemented (bug 43354"); +public final class TestMissingArgEval { + + @Test + public void testEvaluateMissingArgs() throws IOException { + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); + HSSFSheet sheet = wb.createSheet("Sheet1"); + HSSFCell cell = sheet.createRow(0).createCell(0); + + cell.setCellFormula("if(true,)"); + fe.clearAllCachedResultValues(); + // EmptyStackException -> Missing args evaluation not implemented (bug 43354) + CellValue cv = fe.evaluate(cell); + // MissingArg -> BlankEval -> zero (as formula result) + assertEquals(0.0, cv.getNumberValue(), 0.0); + + // MissingArg -> BlankEval -> empty string (in concatenation) + cell.setCellFormula("\"abc\"&if(true,)"); + fe.clearAllCachedResultValues(); + assertEquals("abc", fe.evaluate(cell).getStringValue()); } - // MissingArg -> BlankEval -> zero (as formula result) - assertEquals(0.0, cv.getNumberValue(), 0.0); - - // MissingArg -> BlankEval -> empty string (in concatenation) - cell.setCellFormula("\"abc\"&if(true,)"); - fe.clearAllCachedResultValues(); - assertEquals("abc", fe.evaluate(cell).getStringValue()); } - - public void testCountFuncs() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFCell cell = sheet.createRow(0).createCell(0); - - cell.setCellFormula("COUNT(C5,,,,)"); // 4 missing args, C5 is blank - assertEquals(4.0, fe.evaluate(cell).getNumberValue(), 0.0); - - cell.setCellFormula("COUNTA(C5,,)"); // 2 missing args, C5 is blank - fe.clearAllCachedResultValues(); - assertEquals(2.0, fe.evaluate(cell).getNumberValue(), 0.0); + + @Test + public void testCountFuncs() throws IOException { + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); + HSSFSheet sheet = wb.createSheet("Sheet1"); + HSSFCell cell = sheet.createRow(0).createCell(0); + + cell.setCellFormula("COUNT(C5,,,,)"); // 4 missing args, C5 is blank + assertEquals(4.0, fe.evaluate(cell).getNumberValue(), 0.0); + + cell.setCellFormula("COUNTA(C5,,)"); // 2 missing args, C5 is blank + fe.clearAllCachedResultValues(); + assertEquals(2.0, fe.evaluate(cell).getNumberValue(), 0.0); + } } } Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java Fri Dec 27 23:00:13 2019 @@ -17,14 +17,16 @@ package org.apache.poi.ss.formula.eval; -import java.io.PrintStream; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.Locale; -import junit.framework.Assert; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -34,21 +36,16 @@ import org.apache.poi.ss.usermodel.CellT import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; /** * Tests formulas for multi sheet reference (i.e. SUM(Sheet1:Sheet5!A1)) */ -public final class TestMultiSheetEval extends TestCase { - private static final POILogger logger = POILogFactory.getLogger(TestFormulasFromSpreadsheet.class); - - private static final class Result { - public static final int SOME_EVALUATIONS_FAILED = -1; - public static final int ALL_EVALUATIONS_SUCCEEDED = +1; - public static final int NO_EVALUATIONS_FOUND = 0; - } - +@RunWith(Parameterized.class) +public final class TestMultiSheetEval { /** * This class defines constants for navigating around the test data spreadsheet used for these tests. */ @@ -89,250 +86,116 @@ public final class TestMultiSheetEval ex public static final String TEST_SHEET_NAME = "test"; } - private HSSFWorkbook workbook; - private Sheet sheet; - // Note - multiple failures are aggregated before ending. - // If one or more functions fail, a single AssertionFailedError is thrown at the end - private int _functionFailureCount; - private int _functionSuccessCount; - private int _evaluationFailureCount; - private int _evaluationSuccessCount; - - private static void confirmExpectedResult(String msg, Cell expected, CellValue actual) { - if (expected == null) { - throw new AssertionFailedError(msg + " - Bad setup data expected value is null"); - } - if(actual == null) { - throw new AssertionFailedError(msg + " - actual value was null"); - } - - final CellType cellType = expected.getCellType(); + private static HSSFFormulaEvaluator evaluator; + private static Collection<String> funcs; - switch (cellType) { - case BLANK: - assertEquals(msg, CellType.BLANK, actual.getCellType()); - break; - case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actual.getCellType()); - assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue()); - break; - case ERROR: - assertEquals(msg, CellType.ERROR, actual.getCellType()); - assertEquals(msg, ErrorEval.getText(expected.getErrorCellValue()), ErrorEval.getText(actual.getErrorValue())); - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - throw new AssertionFailedError("Cannot expect formula as result of formula evaluation: " + msg); - case NUMERIC: - assertEquals(msg, CellType.NUMERIC, actual.getCellType()); - TestMathX.assertEquals(msg, expected.getNumericCellValue(), actual.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); - break; - case STRING: - assertEquals(msg, CellType.STRING, actual.getCellType()); - assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getStringValue()); - break; - default: - throw new AssertionFailedError("Unexpected cell type: " + cellType); - } - } + @SuppressWarnings("DefaultAnnotationParam") + @Parameter(value = 0) + public String testName; + + @Parameter(value = 1) + public String functionName; + + @Parameter(value = 2) + public Cell expected; + + @Parameter(value = 3) + public Row testRow; + + @Parameterized.Parameters(name="{0}") + public static Collection<Object[]> data() { + HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME); + Sheet sheet = workbook.getSheet(SS.TEST_SHEET_NAME); + evaluator = new HSSFFormulaEvaluator(workbook); + funcs = FunctionEval.getSupportedFunctionNames(); + List<Object[]> data = new ArrayList<>(); + for (int rowIndex = SS.START_FUNCTIONS_ROW_INDEX;true;rowIndex++) { + Row r = sheet.getRow(rowIndex); - @Override - protected void setUp() { - if (workbook == null) { - workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME); - sheet = workbook.getSheet( SS.TEST_SHEET_NAME ); - } - _functionFailureCount = 0; - _functionSuccessCount = 0; - _evaluationFailureCount = 0; - _evaluationSuccessCount = 0; - } + // only evaluate non empty row + if (r == null) { + continue; + } - public void testFunctionsFromTestSpreadsheet() { + String targetFunctionName = getTargetFunctionName(r); + assertNotNull("Expected function name or '" + SS.FUNCTION_NAMES_END_SENTINEL + "'", targetFunctionName); + if (targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { + // found end of functions list + break; + } + String targetTestName = getTargetTestName(r); - processFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, null); + // expected results are on the row below + Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); + assertNotNull("Missing expected values cell for function '" + targetFunctionName, expectedValueCell); - // confirm results - String successMsg = "There were " - + _evaluationSuccessCount + " successful evaluation(s) and " - + _functionSuccessCount + " function(s) without error"; - if(_functionFailureCount > 0) { - String msg = _functionFailureCount + " function(s) failed in " - + _evaluationFailureCount + " evaluation(s). " + successMsg; - throw new AssertionFailedError(msg); + data.add(new Object[]{ targetTestName, targetFunctionName, expectedValueCell, r }); } - logger.log(POILogger.INFO, getClass().getName() + ": " + successMsg); - } - /** - * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * @param testFocusFunctionName name of a single function/operator to test alone. - * Typically pass <code>null</code> to test all functions - */ - private void processFunctionGroup(int startRowIndex, String testFocusFunctionName) { - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook); - Collection<String> funcs = FunctionEval.getSupportedFunctionNames(); - - int rowIndex = startRowIndex; - while (true) { - Row r = sheet.getRow(rowIndex); - - // only evaluate non empty row - if( r != null ) - { - String targetFunctionName = getTargetFunctionName(r); - String targetTestName = getTargetTestName(r); - if(targetFunctionName == null) { - throw new AssertionFailedError("Test spreadsheet cell empty on row (" - + (rowIndex+1) + "). Expected function name or '" - + SS.FUNCTION_NAMES_END_SENTINEL + "'"); - } - if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { - // found end of functions list - break; - } - if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - - // expected results are on the row below - Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); - if(expectedValueCell == null) { - int missingRowNum = rowIndex + 1; - throw new AssertionFailedError("Missing expected values cell for function '" - + targetFunctionName + ", test" + targetTestName + " (row " + - missingRowNum + ")"); - } - - switch(processFunctionRow(evaluator, targetFunctionName, targetTestName, r, expectedValueCell)) { - case Result.ALL_EVALUATIONS_SUCCEEDED: _functionSuccessCount++; break; - case Result.SOME_EVALUATIONS_FAILED: _functionFailureCount++; break; - default: - throw new RuntimeException("unexpected result"); - case Result.NO_EVALUATIONS_FOUND: // do nothing - String uname = targetFunctionName.toUpperCase(Locale.ROOT); - if(startRowIndex >= SS.START_FUNCTIONS_ROW_INDEX && - funcs.contains(uname)) { - logger.log(POILogger.WARN, uname + ": function is supported but missing test data"); - } - break; - } - } - } - rowIndex ++; - } + return data; } - /** - * - * @return a constant from the local Result class denoting whether there were any evaluation - * cases, and whether they all succeeded. - */ - private int processFunctionRow(HSSFFormulaEvaluator evaluator, String targetFunctionName, - String targetTestName, Row formulasRow, Cell expectedValueCell) { - - int result = Result.NO_EVALUATIONS_FOUND; // so far + @Test + public void testFunction() { - Cell c = formulasRow.getCell(SS.COLUMN_INDEX_ACTUAL_VALUE); + Cell c = testRow.getCell(SS.COLUMN_INDEX_ACTUAL_VALUE); if (c == null || c.getCellType() != CellType.FORMULA) { - return result; + // missing test data + assertTrue(testRow.getRowNum() >= SS.START_FUNCTIONS_ROW_INDEX); + assertTrue("unsupported function", funcs.contains(functionName.toUpperCase(Locale.ROOT))); + return; } - CellValue actualValue = evaluator.evaluate(c); + CellValue actual = evaluator.evaluate(c); - try { - confirmExpectedResult("Function '" + targetFunctionName + "': Test: '" + targetTestName + "' Formula: " + c.getCellFormula() - + " @ " + formulasRow.getRowNum() + ":" + SS.COLUMN_INDEX_ACTUAL_VALUE, - expectedValueCell, actualValue); - _evaluationSuccessCount ++; - if(result != Result.SOME_EVALUATIONS_FAILED) { - result = Result.ALL_EVALUATIONS_SUCCEEDED; - } - } catch (AssertionFailedError e) { - _evaluationFailureCount ++; - printShortStackTrace(System.err, e); - result = Result.SOME_EVALUATIONS_FAILED; - } - - return result; - } + assertNotNull("Bad setup data expected value is null", expected); + assertNotNull("actual value was null", actual); - /** - * Useful to keep output concise when expecting many failures to be reported by this test case - */ - private static void printShortStackTrace(PrintStream ps, AssertionFailedError e) { - StackTraceElement[] stes = e.getStackTrace(); + final CellType cellType = expected.getCellType(); - int startIx = 0; - // skip any top frames inside junit.framework.Assert - while(startIx<stes.length) { - if(!stes[startIx].getClassName().equals(Assert.class.getName())) { + switch (cellType) { + case BLANK: + assertEquals(CellType.BLANK, actual.getCellType()); break; - } - startIx++; - } - // skip bottom frames (part of junit framework) - int endIx = startIx+1; - while(endIx < stes.length) { - if(stes[endIx].getClassName().equals(TestCase.class.getName())) { + case BOOLEAN: + assertEquals(CellType.BOOLEAN, actual.getCellType()); + assertEquals(expected.getBooleanCellValue(), actual.getBooleanValue()); + break; + case ERROR: + assertEquals(CellType.ERROR, actual.getCellType()); + assertEquals(ErrorEval.getText(expected.getErrorCellValue()), ErrorEval.getText(actual.getErrorValue())); + break; + case FORMULA: // will never be used, since we will call method after formula evaluation + fail("Cannot expect formula as result of formula evaluation."); + break; + case NUMERIC: + assertEquals(CellType.NUMERIC, actual.getCellType()); + TestMathX.assertEquals("", expected.getNumericCellValue(), actual.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); + break; + case STRING: + assertEquals(CellType.STRING, actual.getCellType()); + assertEquals(expected.getRichStringCellValue().getString(), actual.getStringValue()); + break; + default: + fail("Unexpected cell type: " + cellType); break; - } - endIx++; - } - if(startIx >= endIx) { - // something went wrong. just print the whole stack trace - e.printStackTrace(ps); - } - endIx -= 4; // skip 4 frames of reflection invocation - ps.println(e); - for(int i=startIx; i<endIx; i++) { - ps.println("\tat " + stes[i]); } } - /** - * @return <code>null</code> if cell is missing, empty or blank - */ private static String getTargetFunctionName(Row r) { - if(r == null) { - System.err.println("Warning - given null row, can't figure out function name"); - return null; - } + assertNotNull("given null row, can't figure out function name", r); Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME); - if(cell == null) { - System.err.println("Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name"); - return null; - } - if(cell.getCellType() == CellType.BLANK) { - return null; - } - if(cell.getCellType() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - - throw new AssertionFailedError("Bad cell type for 'function name' column: (" - + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); + assertNotNull("Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name", cell); + assertEquals(CellType.STRING, cell.getCellType()); + return cell.getRichStringCellValue().getString(); } - /** - * @return <code>null</code> if cell is missing, empty or blank - */ + private static String getTargetTestName(Row r) { - if(r == null) { - System.err.println("Warning - given null row, can't figure out test name"); - return null; - } + assertNotNull("Given null row, can't figure out test name", r); Cell cell = r.getCell(SS.COLUMN_INDEX_TEST_NAME); - if(cell == null) { - System.err.println("Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_TEST_NAME + ", can't figure out test name"); - return null; - } - if(cell.getCellType() == CellType.BLANK) { - return null; - } - if(cell.getCellType() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - - throw new AssertionFailedError("Bad cell type for 'test name' column: (" - + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); + assertNotNull("Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_TEST_NAME + ", can't figure out test name", cell); + assertEquals(CellType.STRING, cell.getCellType()); + return cell.getRichStringCellValue().getString(); } - } Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java Fri Dec 27 23:00:13 2019 @@ -17,67 +17,62 @@ package org.apache.poi.ss.formula.eval; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import java.util.LinkedHashMap; import java.util.Map; +import org.junit.Test; + /** * Tests for <tt>OperandResolver</tt> - * - * @author Brendan Nolan */ -public final class TestOperandResolver extends TestCase { - +public final class TestOperandResolver { + @Test public void testParseDouble_bug48472() { - final Double resolvedValue; - - try { - resolvedValue = OperandResolver.parseDouble("-"); - } catch (StringIndexOutOfBoundsException e) { - throw new AssertionFailedError("Identified bug 48472"); - } - + // bug 48472 - StringIndexOutOfBoundsException + Double resolvedValue = OperandResolver.parseDouble("-"); assertNull(resolvedValue); } - + + @Test public void testParseDouble_bug49723() { String value = ".1"; - Double resolvedValue = OperandResolver.parseDouble(value); - + assertNotNull("Identified bug 49723", resolvedValue); } - + /** - * * Tests that a list of valid strings all return a non null value from {@link OperandResolver#parseDouble(String)} - * */ + @Test public void testParseDoubleValidStrings() { String[] values = new String[]{".19", "0.19", "1.9", "1E4", "-.19", "-0.19", "8.5","-1E4", ".5E6","+1.5","+1E5", " +1E5 ", " 123 ", "1E4", "-123" }; for (String value : values) { - assertNotNull(OperandResolver.parseDouble(value)); - assertEquals(OperandResolver.parseDouble(value), Double.parseDouble(value)); + Double act = OperandResolver.parseDouble(value); + assertNotNull(act); + assertEquals(act, Double.parseDouble(value), 0); } } - + /** - * * Tests that a list of invalid strings all return null from {@link OperandResolver#parseDouble(String)} - * */ + @Test public void testParseDoubleInvalidStrings() { String[] values = new String[]{"-", "ABC", "-X", "1E5a", "Infinity", "NaN", ".5F", "1,000"}; - + for (String value : values) { assertNull(OperandResolver.parseDouble(value)); } } + @Test public void testCoerceDateStringToNumber() throws EvaluationException { Map<String, Double> values = new LinkedHashMap<>(); values.put("2019/1/18", 43483.); @@ -90,6 +85,7 @@ public final class TestOperandResolver e } } + @Test public void testCoerceTimeStringToNumber() throws EvaluationException { Map<String, Double> values = new LinkedHashMap<>(); values.put("00:00", 0.0); Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java Fri Dec 27 23:00:13 2019 @@ -17,25 +17,25 @@ package org.apache.poi.ss.formula.eval; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.apache.poi.ss.formula.functions.NumericFunctionInvoker; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; 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.ss.formula.functions.EvalFactory; +import org.apache.poi.ss.formula.functions.NumericFunctionInvoker; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.CellValue; +import org.junit.Test; /** * Test for percent operator evaluator. - * - * @author Josh Micich */ -public final class TestPercentEval extends TestCase { +public final class TestPercentEval { private static void confirm(ValueEval arg, double expectedResult) { ValueEval[] args = { @@ -47,6 +47,7 @@ public final class TestPercentEval exten assertEquals(expectedResult, result, 0); } + @Test public void testBasic() { confirm(new NumberEval(5), 0.05); confirm(new NumberEval(3000), 30.0); @@ -55,30 +56,27 @@ public final class TestPercentEval exten confirm(BoolEval.TRUE, 0.01); } + @Test public void test1x1Area() { AreaEval ae = EvalFactory.createAreaEval("B2:B2", new ValueEval[] { new NumberEval(50), }); confirm(ae, 0.5); } - public void testInSpreadSheet() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("B1%"); - row.createCell(1).setCellValue(50.0); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue cv; - try { - cv = fe.evaluate(cell); - } catch (RuntimeException e) { - if(e.getCause() instanceof NullPointerException) { - throw new AssertionFailedError("Identified bug 44608"); - } - // else some other unexpected error - throw e; + + @Test + public void testInSpreadSheet() throws IOException { + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFSheet sheet = wb.createSheet("Sheet1"); + HSSFRow row = sheet.createRow(0); + HSSFCell cell = row.createCell(0); + cell.setCellFormula("B1%"); + row.createCell(1).setCellValue(50.0); + + HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); + + // bug 44608 - NullPointerException + CellValue cv = fe.evaluate(cell); + assertEquals(CellType.NUMERIC, cv.getCellType()); + assertEquals(0.5, cv.getNumberValue(), 0.0); } - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(0.5, cv.getNumberValue(), 0.0); } } Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java Fri Dec 27 23:00:13 2019 @@ -17,29 +17,29 @@ package org.apache.poi.ss.formula.eval; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; + import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; 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.ss.formula.functions.Function; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.CellValue; +import org.junit.Test; /** * Tests for power operator evaluator. - * - * @author Bob van den Berge */ -public final class TestPowerEval extends TestCase { - +public final class TestPowerEval { + @Test public void testPositiveValues() { confirm(0, 0, 1); confirm(1, 1, 0); confirm(9, 3, 2); } + @Test public void testNegativeValues() { confirm(-1, -1, 1); confirm(1, 1, -1); @@ -47,18 +47,22 @@ public final class TestPowerEval extends confirm((1.0/3), 3, -1); } + @Test public void testPositiveDecimalValues() { confirm(3, 27, (1/3.0)); } + @Test public void testNegativeDecimalValues() { confirm(-3, -27, (1/3.0)); } + @Test public void testErrorValues() { confirmError(-1.00001, 1.1); } + @Test public void testInSpreadSheet() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("Sheet1"); @@ -72,27 +76,27 @@ public final class TestPowerEval extends CellValue cv = fe.evaluate(cell); assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(-3.0, cv.getNumberValue()); + assertEquals(-3.0, cv.getNumberValue(), 0); } private void confirm(double expected, double a, double b) { - NumberEval result = (NumberEval) evaluate(EvalInstances.Power, a, b); + NumberEval result = (NumberEval) evaluate(a, b); - assertEquals(expected, result.getNumberValue()); + assertEquals(expected, result.getNumberValue(), 0); } private void confirmError(double a, double b) { - ErrorEval result = (ErrorEval) evaluate(EvalInstances.Power, a, b); + ErrorEval result = (ErrorEval) evaluate(a, b); assertEquals("#NUM!", result.getErrorString()); } - private static ValueEval evaluate(Function instance, double... dArgs) { + private static ValueEval evaluate(double... dArgs) { ValueEval[] evalArgs; evalArgs = new ValueEval[dArgs.length]; for (int i = 0; i < evalArgs.length; i++) { evalArgs[i] = new NumberEval(dArgs[i]); } - return instance.evaluate(evalArgs, -1, (short) -1); + return EvalInstances.Power.evaluate(evalArgs, -1, (short) -1); } } Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java Fri Dec 27 23:00:13 2019 @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.eval; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; @@ -34,14 +34,13 @@ import org.apache.poi.ss.formula.ptg.Are import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.CellReference; +import org.junit.Test; /** * Test for unary plus operator evaluator. - * - * @author Josh Micich */ -public final class TestRangeEval extends TestCase { - +public final class TestRangeEval { + @Test public void testPermutations() { confirm("B3", "D7", "B3:D7"); @@ -58,7 +57,7 @@ public final class TestRangeEval extends createRefEval(refA), createRefEval(refB), }; - List<SpreadsheetVersion> versions = Arrays.asList(new SpreadsheetVersion[] {SpreadsheetVersion.EXCEL97, SpreadsheetVersion.EXCEL2007}); + List<SpreadsheetVersion> versions = Arrays.asList(SpreadsheetVersion.EXCEL97, SpreadsheetVersion.EXCEL2007); for(SpreadsheetVersion version : versions) { AreaReference ar = new AreaReference(expectedAreaRef, version); ValueEval result = EvalInstances.Range.evaluate(args, 0, (short)0); @@ -136,6 +135,7 @@ public final class TestRangeEval extends } } + @Test public void testRangeUsingOffsetFunc_bug46948() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFRow row = wb.createSheet("Sheet1").createRow(0); @@ -151,15 +151,8 @@ public final class TestRangeEval extends cellB1.setCellValue(1.0); // range will be C1:D1 HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue cv; - try { - cv = fe.evaluate(cellA1); - } catch (IllegalArgumentException e) { - if (e.getMessage().equals("Unexpected ref arg class (org.apache.poi.ss.formula.LazyAreaEval)")) { - throw new AssertionFailedError("Identified bug 46948"); - } - throw e; - } + // bug 46948 - Unexpected ref arg class (org.apache.poi.ss.formula.LazyAreaEval) + CellValue cv = fe.evaluate(cellA1); assertEquals(12.0, cv.getNumberValue(), 0.0); Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java Fri Dec 27 23:00:13 2019 @@ -17,23 +17,23 @@ package org.apache.poi.ss.formula.eval; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; -import org.apache.poi.ss.formula.ptg.AreaPtg; import org.apache.poi.ss.formula.functions.EvalFactory; import org.apache.poi.ss.formula.functions.NumericFunctionInvoker; +import org.apache.poi.ss.formula.ptg.AreaPtg; +import org.junit.Test; /** * Test for unary plus operator evaluator. - * - * @author Josh Micich */ -public final class TestUnaryPlusEval extends TestCase { +public final class TestUnaryPlusEval { /** * Test for bug observable at svn revision 618865 (5-Feb-2008)<br> * The code for handling column operands had been copy-pasted from the row handling code. */ + @Test public void testColumnOperand() { short firstRow = (short)8; Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java Fri Dec 27 23:00:13 2019 @@ -17,14 +17,13 @@ package org.apache.poi.ss.formula.function; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; -/** - * - * @author Josh Micich - */ -public final class TestFunctionMetadataRegistry extends TestCase { +import org.junit.Test; +public final class TestFunctionMetadataRegistry { + @Test public void testWellKnownFunctions() { confirmFunction(0, "COUNT"); confirmFunction(1, "IF"); Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java Fri Dec 27 23:00:13 2019 @@ -18,6 +18,7 @@ package org.apache.poi.ss.formula.function; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import java.io.IOException; @@ -29,7 +30,6 @@ import org.apache.poi.ss.formula.ptg.Fun import org.apache.poi.ss.formula.ptg.Ptg; import org.junit.Test; -import junit.framework.AssertionFailedError; /** * Tests parsing of some built-in functions that were not properly * registered in POI as of bug #44675, #44733 (March/April 2008). @@ -42,33 +42,30 @@ public final class TestParseMissingBuilt book.close(); return ptgs; } - + private static void confirmFunc(String formula, int expPtgArraySize, boolean isVarArgFunc, int funcIx) throws IOException { Ptg[] ptgs = parse(formula); Ptg ptgF = ptgs[ptgs.length-1]; // func is last RPN token in all these formulas - + // Check critical things in the Ptg array encoding. if(!(ptgF instanceof AbstractFunctionPtg)) { throw new RuntimeException("function token missing"); } AbstractFunctionPtg func = (AbstractFunctionPtg) ptgF; - if(func.getFunctionIndex() == 255) { - throw new AssertionFailedError("Failed to recognise built-in function in formula '" - + formula + "'"); - } + assertNotEquals("Failed to recognise built-in function in formula", 255, func.getFunctionIndex()); assertEquals(expPtgArraySize, ptgs.length); assertEquals(funcIx, func.getFunctionIndex()); Class<? extends AbstractFunctionPtg> expCls = isVarArgFunc ? FuncVarPtg.class : FuncPtg.class; assertEquals(expCls, ptgF.getClass()); - + // check that parsed Ptg array converts back to formula text OK HSSFWorkbook book = new HSSFWorkbook(); String reRenderedFormula = HSSFFormulaParser.toFormulaString(book, ptgs); assertEquals(formula, reRenderedFormula); book.close(); } - + @Test public void testDatedif() throws IOException { int expSize = 4; // NB would be 5 if POI added tAttrVolatile properly @@ -79,12 +76,12 @@ public final class TestParseMissingBuilt public void testDdb() throws IOException { confirmFunc("DDB(1,1,1,1,1)", 6, true, 144); } - + @Test public void testAtan() throws IOException { confirmFunc("ATAN(1)", 2, false, 18); } - + @Test public void testUsdollar() throws IOException { confirmFunc("USDOLLAR(1)", 2, true, 204); @@ -94,12 +91,12 @@ public final class TestParseMissingBuilt public void testDBCS() throws IOException { confirmFunc("DBCS(\"abc\")", 2, false, 215); } - + @Test public void testIsnontext() throws IOException { confirmFunc("ISNONTEXT(\"abc\")", 2, false, 190); } - + @Test public void testDproduct() throws IOException { confirmFunc("DPRODUCT(C1:E5,\"HarvestYield\",G1:H2)", 4, false, 189); Modified: poi/trunk/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java?rev=1872041&r1=1872040&r2=1872041&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java (original) +++ poi/trunk/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java Fri Dec 27 23:00:13 2019 @@ -17,17 +17,15 @@ package org.apache.poi.ss.formula.functions; -import junit.framework.AssertionFailedError; +import static org.junit.Assert.fail; import org.apache.poi.ss.formula.eval.ErrorEval; +import org.apache.poi.ss.formula.eval.NotImplementedException; import org.apache.poi.ss.formula.eval.NumericValueEval; import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.eval.NotImplementedException; /** * Test helper class for invoking functions with numeric results. - * - * @author Josh Micich */ public final class NumericFunctionInvoker { @@ -64,8 +62,8 @@ public final class NumericFunctionInvoke try { return invokeInternal(f, args, srcCellRow, srcCellCol); } catch (NumericEvalEx e) { - throw new AssertionFailedError("Evaluation of function (" + f.getClass().getName() - + ") failed: " + e.getMessage()); + fail("Evaluation of function (" + f.getClass().getName() + ") failed: " + e.getMessage()); + return -1; } } /** @@ -96,16 +94,9 @@ public final class NumericFunctionInvoke NumericValueEval result = (NumericValueEval) evalResult; return result.getNumberValue(); } + private static String formatErrorMessage(ErrorEval ee) { - if(errorCodesAreEqual(ee, ErrorEval.VALUE_INVALID)) { - return "Error code: #VALUE! (invalid value)"; - } - return "Error code=" + ee.getErrorCode(); - } - private static boolean errorCodesAreEqual(ErrorEval a, ErrorEval b) { - if(a==b) { - return true; - } - return a.getErrorCode() == b.getErrorCode(); + boolean b = (ee == ErrorEval.VALUE_INVALID || ee.getErrorCode() == ErrorEval.VALUE_INVALID.getErrorCode()); + return b ? "Error code: #VALUE! (invalid value)" : "Error code=" + ee.getErrorCode(); } } --------------------------------------------------------------------- To unsubscribe, e-mail: commits-unsubscr...@poi.apache.org For additional commands, e-mail: commits-h...@poi.apache.org