package org.apache.poi.hssf.record;
-import org.apache.poi.ss.usermodel.ErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.util.HexDump;
import org.apache.poi.util.LittleEndianOutput;
* see bugzilla bug 16560 for an explanation
*/
public void setValue(byte value) {
- switch(value) {
- case ErrorConstants.ERROR_NULL:
- case ErrorConstants.ERROR_DIV_0:
- case ErrorConstants.ERROR_VALUE:
- case ErrorConstants.ERROR_REF:
- case ErrorConstants.ERROR_NAME:
- case ErrorConstants.ERROR_NUM:
- case ErrorConstants.ERROR_NA:
+ switch(FormulaError.forInt(value)) {
+ case NULL:
+ case DIV0:
+ case VALUE:
+ case REF:
+ case NAME:
+ case NUM:
+ case NA:
_value = value;
_isError = true;
return;
+ default:
+ throw new IllegalArgumentException("Error Value can only be 0,7,15,23,29,36 or 42. It cannot be "+value);
}
- throw new IllegalArgumentException("Error Value can only be 0,7,15,23,29,36 or 42. It cannot be "+value);
}
/**
sb.append(getBooleanValue());
} else {
sb.append(" .errCode = ");
- sb.append(ErrorConstants.getText(getErrorValue()));
+ sb.append(FormulaError.forInt(getErrorValue()).getString());
sb.append(" (").append(HexDump.byteToHex(getErrorValue())).append(")");
}
}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-import org.apache.poi.ss.usermodel.ErrorConstants;
-
-/**
- * Contains raw Excel error codes (as defined in OOO's excelfileformat.pdf (2.5.6)
- */
-public final class HSSFErrorConstants extends ErrorConstants {
-}
import org.apache.poi.ss.formula.ptg.FuncVarPtg;
import org.apache.poi.ss.formula.ptg.GreaterEqualPtg;
import org.apache.poi.ss.formula.ptg.GreaterThanPtg;
-import org.apache.poi.ss.formula.ptg.IntersectionPtg;
import org.apache.poi.ss.formula.ptg.IntPtg;
+import org.apache.poi.ss.formula.ptg.IntersectionPtg;
import org.apache.poi.ss.formula.ptg.LessEqualPtg;
import org.apache.poi.ss.formula.ptg.LessThanPtg;
import org.apache.poi.ss.formula.ptg.MemAreaPtg;
import org.apache.poi.ss.formula.ptg.UnaryPlusPtg;
import org.apache.poi.ss.formula.ptg.UnionPtg;
import org.apache.poi.ss.formula.ptg.ValueOperatorPtg;
-import org.apache.poi.ss.usermodel.ErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
}
switch(part1.charAt(0)) {
- case 'V':
- if(part1.equals("VALUE")) {
+ case 'V': {
+ FormulaError fe = FormulaError.VALUE;
+ if(part1.equals(fe.name())) {
Match('!');
- return ErrorConstants.ERROR_VALUE;
+ return fe.getCode();
}
- throw expected("#VALUE!");
- case 'R':
- if(part1.equals("REF")) {
+ throw expected(fe.getString());
+ }
+ case 'R': {
+ FormulaError fe = FormulaError.REF;
+ if(part1.equals(fe.name())) {
Match('!');
- return ErrorConstants.ERROR_REF;
+ return fe.getCode();
}
- throw expected("#REF!");
- case 'D':
+ throw expected(fe.getString());
+ }
+ case 'D': {
+ FormulaError fe = FormulaError.DIV0;
if(part1.equals("DIV")) {
Match('/');
Match('0');
Match('!');
- return ErrorConstants.ERROR_DIV_0;
+ return fe.getCode();
}
- throw expected("#DIV/0!");
- case 'N':
- if(part1.equals("NAME")) {
- Match('?'); // only one that ends in '?'
- return ErrorConstants.ERROR_NAME;
+ throw expected(fe.getString());
+ }
+ case 'N': {
+ FormulaError fe = FormulaError.NAME;
+ if(part1.equals(fe.name())) {
+ // only one that ends in '?'
+ Match('?');
+ return fe.getCode();
}
- if(part1.equals("NUM")) {
+ fe = FormulaError.NUM;
+ if(part1.equals(fe.name())) {
Match('!');
- return ErrorConstants.ERROR_NUM;
+ return fe.getCode();
}
- if(part1.equals("NULL")) {
+ fe = FormulaError.NULL;
+ if(part1.equals(fe.name())) {
Match('!');
- return ErrorConstants.ERROR_NULL;
+ return fe.getCode();
}
+ fe = FormulaError.NA;
if(part1.equals("N")) {
Match('/');
if(look != 'A' && look != 'a') {
- throw expected("#N/A");
+ throw expected(fe.getString());
}
Match(look);
// Note - no '!' or '?' suffix
- return ErrorConstants.ERROR_NA;
+ return fe.getCode();
}
throw expected("#NAME?, #NUM!, #NULL! or #N/A");
-
+ }
}
throw expected("#VALUE!, #REF!, #DIV/0!, #NAME?, #NUM!, #NULL! or #N/A");
}
package org.apache.poi.ss.formula.constant;
-import org.apache.poi.ss.usermodel.ErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
/**
*
* This class is a type-safe wrapper for a 16-bit int value performing a similar job to
* <tt>ErrorEval</tt>.
- *
- * @author Josh Micich
*/
public class ErrorConstant {
- private static POILogger logger = POILogFactory.getLogger(ErrorConstant.class);
- // convenient access to name space
- private static final ErrorConstants EC = null;
-
- @SuppressWarnings("static-access")
- private static final ErrorConstant NULL = new ErrorConstant(EC.ERROR_NULL);
- @SuppressWarnings("static-access")
- private static final ErrorConstant DIV_0 = new ErrorConstant(EC.ERROR_DIV_0);
- @SuppressWarnings("static-access")
- private static final ErrorConstant VALUE = new ErrorConstant(EC.ERROR_VALUE);
- @SuppressWarnings("static-access")
- private static final ErrorConstant REF = new ErrorConstant(EC.ERROR_REF);
- @SuppressWarnings("static-access")
- private static final ErrorConstant NAME = new ErrorConstant(EC.ERROR_NAME);
- @SuppressWarnings("static-access")
- private static final ErrorConstant NUM = new ErrorConstant(EC.ERROR_NUM);
- @SuppressWarnings("static-access")
- private static final ErrorConstant NA = new ErrorConstant(EC.ERROR_NA);
+ private static final POILogger logger = POILogFactory.getLogger(ErrorConstant.class);
+ private static final ErrorConstant NULL = new ErrorConstant(FormulaError.NULL.getCode());
+ private static final ErrorConstant DIV_0 = new ErrorConstant(FormulaError.DIV0.getCode());
+ private static final ErrorConstant VALUE = new ErrorConstant(FormulaError.VALUE.getCode());
+ private static final ErrorConstant REF = new ErrorConstant(FormulaError.REF.getCode());
+ private static final ErrorConstant NAME = new ErrorConstant(FormulaError.NAME.getCode());
+ private static final ErrorConstant NUM = new ErrorConstant(FormulaError.NUM.getCode());
+ private static final ErrorConstant NA = new ErrorConstant(FormulaError.NA.getCode());
private final int _errorCode;
public int getErrorCode() {
return _errorCode;
}
+
public String getText() {
- if(ErrorConstants.isValidCode(_errorCode)) {
- return ErrorConstants.getText(_errorCode);
+ if(FormulaError.isValidCode(_errorCode)) {
+ return FormulaError.forInt(_errorCode).getString();
}
return "unknown error code (" + _errorCode + ")";
}
public static ErrorConstant valueOf(int errorCode) {
- switch (errorCode) {
- case ErrorConstants.ERROR_NULL: return NULL;
- case ErrorConstants.ERROR_DIV_0: return DIV_0;
- case ErrorConstants.ERROR_VALUE: return VALUE;
- case ErrorConstants.ERROR_REF: return REF;
- case ErrorConstants.ERROR_NAME: return NAME;
- case ErrorConstants.ERROR_NUM: return NUM;
- case ErrorConstants.ERROR_NA: return NA;
- }
+ if (FormulaError.isValidCode(errorCode)) {
+ switch (FormulaError.forInt(errorCode)) {
+ case NULL: return NULL;
+ case DIV0: return DIV_0;
+ case VALUE: return VALUE;
+ case REF: return REF;
+ case NAME: return NAME;
+ case NUM: return NUM;
+ case NA: return NA;
+ default: break;
+ }
+ }
logger.log( POILogger.WARN, "Warning - unexpected error code (" + errorCode + ")");
return new ErrorConstant(errorCode);
}
+
public String toString() {
StringBuffer sb = new StringBuffer(64);
sb.append(getClass().getName()).append(" [");
import org.apache.poi.ss.formula.eval.NumberEval;
import org.apache.poi.ss.formula.eval.OperandResolver;
import org.apache.poi.ss.formula.eval.ValueEval;
-import org.apache.poi.ss.usermodel.ErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
/**
* Implementation for the ERROR.TYPE() Excel function.
}
private int translateErrorCodeToErrorTypeValue(int errorCode) {
- switch (errorCode) {
- case ErrorConstants.ERROR_NULL: return 1;
- case ErrorConstants.ERROR_DIV_0: return 2;
- case ErrorConstants.ERROR_VALUE: return 3;
- case ErrorConstants.ERROR_REF: return 4;
- case ErrorConstants.ERROR_NAME: return 5;
- case ErrorConstants.ERROR_NUM: return 6;
- case ErrorConstants.ERROR_NA : return 7;
+ switch (FormulaError.forInt(errorCode)) {
+ case NULL: return 1;
+ case DIV0: return 2;
+ case VALUE: return 3;
+ case REF: return 4;
+ case NAME: return 5;
+ case NUM: return 6;
+ case NA: return 7;
+ default:
+ throw new IllegalArgumentException("Invalid error code (" + errorCode + ")");
}
- throw new IllegalArgumentException("Invalid error code (" + errorCode + ")");
}
}
package org.apache.poi.ss.formula.ptg;
-import org.apache.poi.ss.usermodel.ErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.util.LittleEndianInput;
import org.apache.poi.util.LittleEndianOutput;
}
public String toFormulaString() {
- return ErrorConstants.getText(ErrorConstants.ERROR_REF);
+ return FormulaError.REF.getString();
}
public byte getDefaultOperandClass() {
package org.apache.poi.ss.formula.ptg;
import org.apache.poi.ss.formula.SheetNameFormatter;
-import org.apache.poi.ss.usermodel.ErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.util.LittleEndianOutput;
}
sb.append("sheet=").append(getSheetName());
sb.append(" ! ");
- sb.append(ErrorConstants.getText(ErrorConstants.ERROR_REF));
+ sb.append(FormulaError.REF.getString());
sb.append("]");
return sb.toString();
}
SheetNameFormatter.appendFormat(sb, sheetName);
}
sb.append('!');
- sb.append(ErrorConstants.getText(ErrorConstants.ERROR_REF));
+ sb.append(FormulaError.REF.getString());
return sb.toString();
}
package org.apache.poi.ss.formula.ptg;
-import org.apache.poi.ss.usermodel.ErrorConstants;
import org.apache.poi.ss.formula.FormulaRenderingWorkbook;
import org.apache.poi.ss.formula.WorkbookDependentFormula;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.util.LittleEndianInput;
import org.apache.poi.util.LittleEndianOutput;
unused2 = in.readInt();
}
public String toFormulaString(FormulaRenderingWorkbook book) {
- return ExternSheetNameResolver.prependSheetName(book, field_1_index_extern_sheet,
- ErrorConstants.getText(ErrorConstants.ERROR_REF));
+ return ExternSheetNameResolver.prependSheetName(book, field_1_index_extern_sheet, FormulaError.REF.getString());
}
public String toFormulaString() {
throw new RuntimeException("3D references need a workbook to determine formula text");
package org.apache.poi.ss.formula.ptg;
-import org.apache.poi.ss.usermodel.ErrorConstants;
import org.apache.poi.ss.formula.FormulaRenderingWorkbook;
import org.apache.poi.ss.formula.WorkbookDependentFormula;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.util.LittleEndianInput;
import org.apache.poi.util.LittleEndianOutput;
/**
* Title: Deleted Reference 3D Ptg <P>
* Description: Defined a cell in extern sheet. <P>
- * REFERENCE: <P>
- * @author Patrick Luby
- * @version 1.0-pre
+ * @since 1.0-pre
*/
public final class DeletedRef3DPtg extends OperandPtg implements WorkbookDependentFormula {
public final static byte sid = 0x3c;
}
public String toFormulaString(FormulaRenderingWorkbook book) {
- return ExternSheetNameResolver.prependSheetName(book, field_1_index_extern_sheet,
- ErrorConstants.getText(ErrorConstants.ERROR_REF));
+ return ExternSheetNameResolver.prependSheetName(book, field_1_index_extern_sheet, FormulaError.REF.getString());
}
public String toFormulaString() {
throw new RuntimeException("3D references need a workbook to determine formula text");
package org.apache.poi.ss.formula.ptg;
-import org.apache.poi.ss.usermodel.ErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.util.LittleEndianInput;
import org.apache.poi.util.LittleEndianOutput;
-/**
- * @author Daniel Noll (daniel at nuix dot com dot au)
- */
public final class ErrPtg extends ScalarConstantPtg {
- // convenient access to namespace
- private static final ErrorConstants EC = null;
-
/** <b>#NULL!</b> - Intersection of two cell ranges is empty */
- @SuppressWarnings("static-access")
- public static final ErrPtg NULL_INTERSECTION = new ErrPtg(EC.ERROR_NULL);
+ public static final ErrPtg NULL_INTERSECTION = new ErrPtg(FormulaError.NULL.getCode());
/** <b>#DIV/0!</b> - Division by zero */
- @SuppressWarnings("static-access")
- public static final ErrPtg DIV_ZERO = new ErrPtg(EC.ERROR_DIV_0);
+ public static final ErrPtg DIV_ZERO = new ErrPtg(FormulaError.DIV0.getCode());
/** <b>#VALUE!</b> - Wrong type of operand */
- @SuppressWarnings("static-access")
- public static final ErrPtg VALUE_INVALID = new ErrPtg(EC.ERROR_VALUE);
+ public static final ErrPtg VALUE_INVALID = new ErrPtg(FormulaError.VALUE.getCode());
/** <b>#REF!</b> - Illegal or deleted cell reference */
- @SuppressWarnings("static-access")
- public static final ErrPtg REF_INVALID = new ErrPtg(EC.ERROR_REF);
+ public static final ErrPtg REF_INVALID = new ErrPtg(FormulaError.REF.getCode());
/** <b>#NAME?</b> - Wrong function or range name */
- @SuppressWarnings("static-access")
- public static final ErrPtg NAME_INVALID = new ErrPtg(EC.ERROR_NAME);
+ public static final ErrPtg NAME_INVALID = new ErrPtg(FormulaError.NAME.getCode());
/** <b>#NUM!</b> - Value range overflow */
- @SuppressWarnings("static-access")
- public static final ErrPtg NUM_ERROR = new ErrPtg(EC.ERROR_NUM);
+ public static final ErrPtg NUM_ERROR = new ErrPtg(FormulaError.NUM.getCode());
/** <b>#N/A</b> - Argument or function not available */
- @SuppressWarnings("static-access")
- public static final ErrPtg N_A = new ErrPtg(EC.ERROR_NA);
+ public static final ErrPtg N_A = new ErrPtg(FormulaError.NA.getCode());
public static final short sid = 0x1c;
/** Creates new ErrPtg */
private ErrPtg(int errorCode) {
- if(!ErrorConstants.isValidCode(errorCode)) {
+ if(!FormulaError.isValidCode(errorCode)) {
throw new IllegalArgumentException("Invalid error code (" + errorCode + ")");
}
field_1_error_code = errorCode;
}
public String toFormulaString() {
- return ErrorConstants.getText(field_1_error_code);
+ return FormulaError.forInt(field_1_error_code).getString();
}
public int getSize() {
}
public static ErrPtg valueOf(int code) {
- switch(code) {
- case ErrorConstants.ERROR_DIV_0: return DIV_ZERO;
- case ErrorConstants.ERROR_NA: return N_A;
- case ErrorConstants.ERROR_NAME: return NAME_INVALID;
- case ErrorConstants.ERROR_NULL: return NULL_INTERSECTION;
- case ErrorConstants.ERROR_NUM: return NUM_ERROR;
- case ErrorConstants.ERROR_REF: return REF_INVALID;
- case ErrorConstants.ERROR_VALUE: return VALUE_INVALID;
+ switch(FormulaError.forInt(code)) {
+ case DIV0: return DIV_ZERO;
+ case NA: return N_A;
+ case NAME: return NAME_INVALID;
+ case NULL: return NULL_INTERSECTION;
+ case NUM: return NUM_ERROR;
+ case REF: return REF_INVALID;
+ case VALUE: return VALUE_INVALID;
+ default:
+ throw new RuntimeException("Unexpected error code (" + code + ")");
}
- throw new RuntimeException("Unexpected error code (" + code + ")");
}
}
package org.apache.poi.ss.formula.ptg;
-import org.apache.poi.ss.usermodel.ErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.util.LittleEndianInput;
import org.apache.poi.util.LittleEndianOutput;
}
public String toFormulaString() {
- return ErrorConstants.getText(ErrorConstants.ERROR_REF);
+ return FormulaError.REF.getString();
}
public byte getDefaultOperandClass() {
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.ss.usermodel;
-
-/**
- * Contains raw Excel error codes (as defined in OOO's excelfileformat.pdf (2.5.6)
- *
- * @deprecated Use {@link FormulaError} instead where possible
- */
-public class ErrorConstants {
- protected ErrorConstants() {
- // no instances of this class
- }
-
- /** <b>#NULL!</b> - Intersection of two cell ranges is empty */
- public static final int ERROR_NULL = 0x00;
- /** <b>#DIV/0!</b> - Division by zero */
- public static final int ERROR_DIV_0 = 0x07;
- /** <b>#VALUE!</b> - Wrong type of operand */
- public static final int ERROR_VALUE = 0x0F;
- /** <b>#REF!</b> - Illegal or deleted cell reference */
- public static final int ERROR_REF = 0x17;
- /** <b>#NAME?</b> - Wrong function or range name */
- public static final int ERROR_NAME = 0x1D;
- /** <b>#NUM!</b> - Value range overflow */
- public static final int ERROR_NUM = 0x24;
- /** <b>#N/A</b> - Argument or function not available */
- public static final int ERROR_NA = 0x2A;
-
-
- /**
- * @return Standard Excel error literal for the specified error code.
- * @throws IllegalArgumentException if the specified error code is not one of the 7
- * standard error codes
- */
- public static final String getText(int errorCode) {
- switch(errorCode) {
- case ERROR_NULL: return "#NULL!";
- case ERROR_DIV_0: return "#DIV/0!";
- case ERROR_VALUE: return "#VALUE!";
- case ERROR_REF: return "#REF!";
- case ERROR_NAME: return "#NAME?";
- case ERROR_NUM: return "#NUM!";
- case ERROR_NA: return "#N/A";
- }
- throw new IllegalArgumentException("Bad error code (" + errorCode + ")");
- }
-
- /**
- * @return <code>true</code> if the specified error code is a standard Excel error code.
- */
- public static final boolean isValidCode(int errorCode) {
- // This method exists because it would be bad to force clients to catch
- // IllegalArgumentException if there were potential for passing an invalid error code.
- switch(errorCode) {
- case ERROR_NULL:
- case ERROR_DIV_0:
- case ERROR_VALUE:
- case ERROR_REF:
- case ERROR_NAME:
- case ERROR_NUM:
- case ERROR_NA:
- return true;
- }
- return false;
- }
-}
package org.apache.poi.hssf.model;
-import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.*;
-import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;
-import junit.framework.AssertionFailedError;
-import junit.framework.TestCase;
-
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.NameRecord;
import org.apache.poi.hssf.record.common.UnicodeString;
import org.apache.poi.hssf.usermodel.FormulaExtractor;
import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFErrorConstants;
import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
import org.apache.poi.hssf.usermodel.HSSFName;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.ss.formula.FormulaParser;
import org.apache.poi.ss.formula.FormulaType;
import org.apache.poi.ss.formula.constant.ErrorConstant;
-import org.apache.poi.ss.formula.ptg.*;
+import org.apache.poi.ss.formula.ptg.AbstractFunctionPtg;
+import org.apache.poi.ss.formula.ptg.AddPtg;
+import org.apache.poi.ss.formula.ptg.Area3DPtg;
+import org.apache.poi.ss.formula.ptg.AreaI;
+import org.apache.poi.ss.formula.ptg.AreaPtg;
+import org.apache.poi.ss.formula.ptg.AreaPtgBase;
+import org.apache.poi.ss.formula.ptg.ArrayPtg;
+import org.apache.poi.ss.formula.ptg.AttrPtg;
+import org.apache.poi.ss.formula.ptg.BoolPtg;
+import org.apache.poi.ss.formula.ptg.ConcatPtg;
+import org.apache.poi.ss.formula.ptg.DividePtg;
+import org.apache.poi.ss.formula.ptg.EqualPtg;
+import org.apache.poi.ss.formula.ptg.ErrPtg;
+import org.apache.poi.ss.formula.ptg.FuncPtg;
+import org.apache.poi.ss.formula.ptg.FuncVarPtg;
+import org.apache.poi.ss.formula.ptg.GreaterThanPtg;
+import org.apache.poi.ss.formula.ptg.IntPtg;
+import org.apache.poi.ss.formula.ptg.IntersectionPtg;
+import org.apache.poi.ss.formula.ptg.MemAreaPtg;
+import org.apache.poi.ss.formula.ptg.MemFuncPtg;
+import org.apache.poi.ss.formula.ptg.MissingArgPtg;
+import org.apache.poi.ss.formula.ptg.MultiplyPtg;
+import org.apache.poi.ss.formula.ptg.NamePtg;
+import org.apache.poi.ss.formula.ptg.NameXPtg;
+import org.apache.poi.ss.formula.ptg.NumberPtg;
+import org.apache.poi.ss.formula.ptg.ParenthesisPtg;
+import org.apache.poi.ss.formula.ptg.PercentPtg;
+import org.apache.poi.ss.formula.ptg.PowerPtg;
+import org.apache.poi.ss.formula.ptg.Ptg;
+import org.apache.poi.ss.formula.ptg.RangePtg;
+import org.apache.poi.ss.formula.ptg.Ref3DPtg;
+import org.apache.poi.ss.formula.ptg.RefPtg;
+import org.apache.poi.ss.formula.ptg.StringPtg;
+import org.apache.poi.ss.formula.ptg.SubtractPtg;
+import org.apache.poi.ss.formula.ptg.UnaryMinusPtg;
+import org.apache.poi.ss.formula.ptg.UnaryPlusPtg;
+import org.apache.poi.ss.formula.ptg.UnionPtg;
import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.util.HexRead;
import org.apache.poi.util.LittleEndianByteArrayInputStream;
* Test the low level formula parser functionality. High level tests are to
* be done via usermodel/HSSFCell.setFormulaValue().
*/
-public final class TestFormulaParser extends TestCase {
+public final class TestFormulaParser {
/**
* @return parsed token array already confirmed not <code>null</code>
return HSSFFormulaParser.toFormulaString((HSSFWorkbook)null, ptgs);
}
+ @Test
public void testSimpleFormula() {
confirmTokenClasses("2+2",IntPtg.class, IntPtg.class, AddPtg.class);
}
+ @Test
public void testFormulaWithSpace1() {
confirmTokenClasses(" 2 + 2 ",IntPtg.class, IntPtg.class, AddPtg.class);
}
+ @Test
public void testFormulaWithSpace2() {
Ptg[] ptgs = parseFormula("2+ sum( 3 , 4) ");
assertEquals(5, ptgs.length);
}
+ @Test
public void testFormulaWithSpaceNRef() {
Ptg[] ptgs = parseFormula("sum( A2:A3 )");
assertEquals(2, ptgs.length);
}
+ @Test
public void testFormulaWithString() {
Ptg[] ptgs = parseFormula("\"hello\" & \"world\" ");
assertEquals(3, ptgs.length);
}
+ @Test
public void testTRUE() {
Ptg[] ptgs = parseFormula("TRUE");
assertEquals(1, ptgs.length);
assertEquals(true, flag.getValue());
}
+ @Test
public void testSumIf() {
Ptg[] ptgs = parseFormula("SUMIF(A1:A5,\">4000\",B1:B5)");
assertEquals(4, ptgs.length);
* Refers to Bug <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=17582">#17582</a>
*
*/
+ @Test
public void testNonAlphaFormula() {
Ptg[] ptgs = parseFormula("\"TOTAL[\"&F3&\"]\"");
confirmTokenClasses(ptgs, StringPtg.class, RefPtg.class, ConcatPtg.class, StringPtg.class, ConcatPtg.class);
assertEquals("TOTAL[", ((StringPtg)ptgs[0]).getValue());
}
+ @Test
public void testMacroFunction() throws IOException {
// testNames.xls contains a VB function called 'myFunc'
final String testFile = "testNames.xls";
assertEquals(expected.toLowerCase(Locale.ROOT), actual.toLowerCase(Locale.ROOT));
}
+ @Test
public void testEmbeddedSlash() {
confirmTokenClasses("HYPERLINK(\"http://www.jakarta.org\",\"Jakarta\")",
StringPtg.class, StringPtg.class, FuncVarPtg.class);
}
+ @Test
public void testConcatenate() {
confirmTokenClasses("CONCATENATE(\"first\",\"second\")",
StringPtg.class, StringPtg.class, FuncVarPtg.class);
}
+ @Test
public void testWorksheetReferences() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.close();
}
+ @Test
public void testUnaryMinus() {
confirmTokenClasses("-A1", RefPtg.class, UnaryMinusPtg.class);
}
+ @Test
public void testUnaryPlus() {
confirmTokenClasses("+A1", RefPtg.class, UnaryPlusPtg.class);
}
* POI encodes formulas may cause unnecessary confusion. These non-critical tests
* check that POI follows the same encoding rules as Excel.
*/
+ @Test
public void testExactEncodingOfUnaryPlusAndMinus() {
// as tested in Excel:
confirmUnary("-3", -3, NumberPtg.class);
}
}
-
+ @Test
public void testLeadingSpaceInString() {
String value = " hi ";
Ptg[] ptgs = parseFormula("\"" + value + "\"");
assertTrue("ptg0 contains exact value", ((StringPtg)ptgs[0]).getValue().equals(value));
}
+ @Test
public void testLookupAndMatchFunctionArgs() {
Ptg[] ptgs = parseFormula("lookup(A1, A3:A52, B3:B52)");
confirmTokenClasses(ptgs, RefPtg.class, AreaPtg.class, AreaPtg.class, FuncVarPtg.class);
}
/** bug 33160*/
+ @Test
public void testLargeInt() {
confirmTokenClasses("40", IntPtg.class);
confirmTokenClasses("40000", IntPtg.class);
}
- /** bug 33160, testcase by Amol Deshmukh*/
+ /** bug 33160 */
+ @Test
public void testSimpleLongFormula() {
confirmTokenClasses("40000/2", IntPtg.class, IntPtg.class, DividePtg.class);
}
- /** bug 35027, underscore in sheet name
- * @throws IOException */
+ /** bug 35027, underscore in sheet name */
+ @Test
public void testUnderscore() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.close();
}
- /** bug 49725, defined names with underscore
- * @throws IOException */
+ /** bug 49725, defined names with underscore */
+ @Test
public void testNamesWithUnderscore() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); //or new XSSFWorkbook();
HSSFSheet sheet = wb.createSheet("NamesWithUnderscore");
}
// bug 38396 : Formula with exponential numbers not parsed correctly.
+ @Test
public void testExponentialParsing() {
confirmTokenClasses("1.3E21/2", NumberPtg.class, IntPtg.class, DividePtg.class);
confirmTokenClasses("1322E21/2", NumberPtg.class, IntPtg.class, DividePtg.class);
confirmTokenClasses("1.3E1/2", NumberPtg.class, IntPtg.class, DividePtg.class);
}
+ @Test
public void testExponentialInSheet() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.close();
}
+ @Test
public void testNumbers() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.close();
}
+ @Test
public void testRanges() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.close();
}
+ @Test
public void testMultiSheetReference() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
* 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() {
+ @Test
+ public void testToFormulaStringZeroArgFunction() throws IOException {
HSSFWorkbook book = new HSSFWorkbook();
Ptg[] ptgs = {
FuncPtg.create(10),
};
assertEquals("NA()", HSSFFormulaParser.toFormulaString(book, ptgs));
+
+ book.close();
}
+ @Test
public void testPercent() {
confirmTokenClasses("5%", IntPtg.class, PercentPtg.class);
/**
* Tests combinations of various operators in the absence of brackets
*/
+ @Test
public void testPrecedenceAndAssociativity() {
// TRUE=TRUE=2=2 evaluates to FALSE
}
}
+ @Test
public void testPower() {
confirmTokenClasses("2^5", IntPtg.class, IntPtg.class, PowerPtg.class);
}
return result;
}
+ @Test
public void testParseNumber() {
IntPtg ip;
FuncVarPtg.class);
}
+ @Test
public void testParseErrorLiterals() {
confirmParseErrorLiteral(ErrPtg.NULL_INTERSECTION, "#NULL!");
StringPtg sp = (StringPtg) parseSingleToken(formula, StringPtg.class);
assertEquals(expectedValue, sp.getValue());
}
+
+ @Test
public void testParseStringLiterals_bug28754() throws IOException {
StringPtg sp;
sp = (StringPtg) parseSingleToken("\"test\"\"ing\"", StringPtg.class);
} catch (RuntimeException e) {
if(e.getMessage().startsWith("Cannot Parse")) {
- throw new AssertionFailedError("Identified bug 28754a");
+ fail("Identified bug 28754a");
}
throw e;
}
cell.setCellFormula("right(\"test\"\"ing\", 3)");
String actualCellFormula = cell.getCellFormula();
if("RIGHT(\"test\"ing\",3)".equals(actualCellFormula)) {
- throw new AssertionFailedError("Identified bug 28754b");
+ fail("Identified bug 28754b");
}
assertEquals("RIGHT(\"test\"\"ing\",3)", actualCellFormula);
} finally {
}
}
+ @Test
public void testParseStringLiterals() {
confirmStringParse("goto considered harmful");
confirmStringParse(" ' ");
}
+ @Test
public void testParseSumIfSum() {
String formulaString;
Ptg[] ptgs;
formulaString = toFormulaString(ptgs);
assertEquals("IF(1<2,SUM(5,2,IF(3>2,SUM(A1:A2),6)),4)", formulaString);
}
+
+ @Test
public void testParserErrors() {
parseExpectedException(" 12 . 345 ");
parseExpectedException("1 .23 ");
private static void parseExpectedException(String formula) {
try {
parseFormula(formula);
- throw new AssertionFailedError("Expected FormulaParseException: " + formula);
+ fail("Expected FormulaParseException: " + formula);
} catch (FormulaParseException e) {
// expected during successful test
assertNotNull(e.getMessage());
}
}
+ @Test
public void testSetFormulaWithRowBeyond32768_Bug44539() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.close();
}
+ @Test
public void testSpaceAtStartOfFormula() {
// Simulating cell formula of "= 4" (note space)
// The same Ptg array can be observed if an excel file is saved with that exact formula
formulaString = toFormulaString(ptgs);
} catch (IllegalStateException e) {
if(e.getMessage().equalsIgnoreCase("too much stuff left on the stack")) {
- throw new AssertionFailedError("Identified bug 44609");
+ fail("Identified bug 44609");
}
// else some unexpected error
throw e;
/**
* Checks some internal error detecting logic ('stack underflow error' in toFormulaString)
*/
+ @Test
public void testTooFewOperandArgs() {
// Simulating badly encoded cell formula of "=/1"
// Not sure if Excel could ever produce this
* Excel tolerates the wrong Ptg and evaluates the formula OK (e.g. SIN), but in some cases
* (e.g. COUNTIF) Excel fails to evaluate the formula, giving '#VALUE!' instead.
*/
+ @Test
public void testFuncPtgSelection() {
Ptg[] ptgs = parseFormula("countif(A1:A2, 1)");
assertEquals(3, ptgs.length);
if(ptgs[2] instanceof FuncVarPtg) {
- throw new AssertionFailedError("Identified bug 44675");
+ fail("Identified bug 44675");
}
confirmTokenClasses(ptgs, AreaPtg.class, IntPtg.class, FuncPtg.class);
confirmTokenClasses("sin(1)", IntPtg.class, FuncPtg.class);
}
- public void testWrongNumberOfFunctionArgs() {
+ @Test
+ public void testWrongNumberOfFunctionArgs() throws IOException {
confirmArgCountMsg("sin()", "Too few arguments to function 'SIN'. Expected 1 but got 0.");
confirmArgCountMsg("countif(1, 2, 3, 4)", "Too many arguments to function 'COUNTIF'. Expected 2 but got 4.");
confirmArgCountMsg("index(1, 2, 3, 4, 5, 6)", "Too many arguments to function 'INDEX'. At most 4 were expected but got 6.");
confirmArgCountMsg("vlookup(1, 2)", "Too few arguments to function 'VLOOKUP'. At least 3 were expected but got 2.");
}
- private static void confirmArgCountMsg(String formula, String expectedMessage) {
+ private static void confirmArgCountMsg(String formula, String expectedMessage) throws IOException {
HSSFWorkbook book = new HSSFWorkbook();
try {
HSSFFormulaParser.parse(formula, book);
- throw new AssertionFailedError("Didn't get parse exception as expected");
+ fail("Didn't get parse exception as expected");
} catch (FormulaParseException e) {
confirmParseException(e, expectedMessage);
}
+ book.close();
}
+ @Test
public void testParseErrorExpectedMsg() {
try {
parseFormula("round(3.14;2)");
- throw new AssertionFailedError("Didn't get parse exception as expected");
+ fail("Didn't get parse exception as expected");
} catch (FormulaParseException e) {
confirmParseException(e,
"Parse error near char 10 ';' in specified formula 'round(3.14;2)'. Expected ',' or ')'");
try {
parseFormula(" =2+2");
- throw new AssertionFailedError("Didn't get parse exception as expected");
+ fail("Didn't get parse exception as expected");
} catch (FormulaParseException e) {
confirmParseException(e,
"The specified formula ' =2+2' starts with an equals sign which is not allowed.");
/**
* this function name has a dot in it.
*/
+ @Test
public void testParseErrorTypeFunction() {
Ptg[] ptgs;
ptgs = parseFormula("error.type(A1)");
} catch (IllegalArgumentException e) {
if (e.getMessage().equals("Invalid Formula cell reference: 'error'")) {
- throw new AssertionFailedError("Identified bug 45334");
+ fail("Identified bug 45334");
}
throw e;
}
assertEquals("ERROR.TYPE", ((FuncPtg) ptgs[1]).getName());
}
- public void testNamedRangeThatLooksLikeCell() {
+ @Test
+ public void testNamedRangeThatLooksLikeCell() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Sheet1");
HSSFName name = wb.createName();
ptgs = HSSFFormulaParser.parse("count(pfy1)", wb);
} catch (IllegalArgumentException e) {
if (e.getMessage().equals("Specified colIx (1012) is out of range")) {
- throw new AssertionFailedError("Identified bug 45354");
+ fail("Identified bug 45354");
}
+ wb.close();
throw e;
}
confirmTokenClasses(ptgs, NamePtg.class, FuncVarPtg.class);
assertEquals("COUNT(pfy1)", cell.getCellFormula());
try {
cell.setCellFormula("count(pf1)");
- throw new AssertionFailedError("Expected formula parse execption");
+ fail("Expected formula parse execption");
} catch (FormulaParseException e) {
confirmParseException(e,
"Specified named range 'pf1' does not exist in the current workbook.");
}
cell.setCellFormula("count(fp1)"); // plain cell ref, col is in range
+ wb.close();
}
- public void testParseAreaRefHighRow_bug45358() {
+ @Test
+ public void testParseAreaRefHighRow_bug45358() throws IOException {
Ptg[] ptgs;
AreaI aptg;
ptgs = HSSFFormulaParser.parse("Sheet1!A10:A40000", book);
aptg = (AreaI) ptgs[0];
if (aptg.getLastRow() == -25537) {
- throw new AssertionFailedError("Identified bug 45358");
+ fail("Identified bug 45358");
}
assertEquals(39999, aptg.getLastRow());
aptg = (AreaI) ptgs[0];
assertEquals(65535, aptg.getLastRow());
+ book.close();
}
+
+ @Test
public void testParseArray() {
Ptg[] ptgs;
ptgs = parseFormula("mode({1,2,2,#REF!;FALSE,3,3,2})");
ArrayPtg aptg = (ArrayPtg) ptgs[0];
Object[][] values = aptg.getTokenArrayValues();
- assertEquals(ErrorConstant.valueOf(HSSFErrorConstants.ERROR_REF), values[0][3]);
+ assertEquals(ErrorConstant.valueOf(FormulaError.REF.getCode()), values[0][3]);
assertEquals(Boolean.FALSE, values[1][0]);
}
+ @Test
public void testParseStringElementInArray() {
Ptg[] ptgs;
ptgs = parseFormula("MAX({\"5\"},3)");
Object element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0];
if (element instanceof UnicodeString) {
// this would cause ClassCastException below
- throw new AssertionFailedError("Wrong encoding of array element value");
+ fail("Wrong encoding of array element value");
}
assertEquals(String.class, element.getClass());
confirmTokenClasses(ptgs2, ArrayPtg.class, IntPtg.class, FuncVarPtg.class);
}
+ @Test
public void testParseArrayNegativeElement() {
Ptg[] ptgs;
try {
ptgs = parseFormula("{-42}");
} catch (FormulaParseException e) {
if (e.getMessage().equals("Parse error near char 1 '-' in specified formula '{-42}'. Expected Integer")) {
- throw new AssertionFailedError("Identified bug - failed to parse negative array element.");
+ fail("Identified bug - failed to parse negative array element.");
}
throw e;
}
assertEquals(-5.0, ((Double)element).doubleValue(), 0.0);
}
+ @Test
public void testRangeOperator() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.close();
}
+ @Test
public void testBooleanNamedSheet() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("true");
wb.close();
}
- public void testParseExternalWorkbookReference() {
+ @Test
+ public void testParseExternalWorkbookReference() throws IOException {
HSSFWorkbook wbA = HSSFTestDataSamples.openSampleWorkbook("multibookFormulaA.xls");
HSSFCell cell = wbA.getSheetAt(0).getRow(0).getCell(0);
// try setting the same formula in a cell
cell.setCellFormula("[multibookFormulaB.xls]AnotherSheet!B1");
assertEquals("[multibookFormulaB.xls]AnotherSheet!B1", cell.getCellFormula());
+
+ wbA.close();
}
+
private static void confirmSingle3DRef(Ptg[] ptgs, int expectedExternSheetIndex) {
assertEquals(1, ptgs.length);
Ptg ptg0 = ptgs[0];
assertEquals(expectedExternSheetIndex, ((Ref3DPtg)ptg0).getExternSheetIndex());
}
- public void testUnion() {
+ @Test
+ public void testUnion() throws IOException {
String formula = "Sheet1!$B$2:$C$3,OFFSET(Sheet1!$E$2:$E$4,1,Sheet1!$A$1),Sheet1!$D$6";
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet("Sheet1");
// We don't check the type of the operands.
confirmTokenClasses("1,2", MemAreaPtg.class, IntPtg.class, IntPtg.class, UnionPtg.class);
+
+ wb.close();
}
- public void testIntersection() {
+ @Test
+ public void testIntersection() throws IOException {
String formula = "Sheet1!$B$2:$C$3 OFFSET(Sheet1!$E$2:$E$4, 1,Sheet1!$A$1) Sheet1!$D$6";
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet("Sheet1");
// This used to be an error but now parses. Union has the same behaviour.
confirmTokenClasses("1 2", MemAreaPtg.class, IntPtg.class, IntPtg.class, IntersectionPtg.class);
+
+ wb.close();
}
+ @Test
public void testComparisonInParen() {
confirmTokenClasses("(A1 > B2)",
RefPtg.class,
);
}
+ @Test
public void testUnionInParen() {
confirmTokenClasses("(A1:B2,B2:C3)",
MemAreaPtg.class,
);
}
+ @Test
public void testIntersectionInParen() {
confirmTokenClasses("(A1:B2 B2:C3)",
MemAreaPtg.class,
);
}
- public void testRange_bug46643() {
+ @Test
+ public void testRange_bug46643() throws IOException {
String formula = "Sheet1!A1:Sheet1!B3";
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet("Sheet1");
if (ptgs.length == 3) {
confirmTokenClasses(ptgs, Ref3DPtg.class, Ref3DPtg.class, RangePtg.class);
- throw new AssertionFailedError("Identified bug 46643");
+ fail("Identified bug 46643");
}
confirmTokenClasses(ptgs,
);
MemFuncPtg mf = (MemFuncPtg)ptgs[0];
assertEquals(15, mf.getLenRefSubexpression());
+ wb.close();
}
- /** Named ranges with backslashes, e.g. 'POI\\2009'
- * @throws IOException */
+ /** Named ranges with backslashes, e.g. 'POI\\2009' */
+ @Test
public void testBackSlashInNames() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
* TODO - delete equiv test:
* {@link BaseTestBugzillaIssues#test42448()}
*/
- public void testParseAbnormalSheetNamesAndRanges_bug42448() {
+ @Test
+ public void testParseAbnormalSheetNamesAndRanges_bug42448() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet("A");
try {
HSSFFormulaParser.parse("SUM(A!C7:A!C67)", wb);
} catch (StringIndexOutOfBoundsException e) {
- throw new AssertionFailedError("Identified bug 42448");
+ fail("Identified bug 42448");
}
// the exact example from the bugzilla description:
HSSFFormulaParser.parse("SUMPRODUCT(A!C7:A!C67, B8:B68) / B69", wb);
+
+ wb.close();
}
- public void testRangeFuncOperand_bug46951() {
+ @Test
+ public void testRangeFuncOperand_bug46951() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
Ptg[] ptgs;
try {
ptgs = HSSFFormulaParser.parse("SUM(C1:OFFSET(C1,0,B1))", wb);
} catch (RuntimeException e) {
if (e.getMessage().equals("Specified named range 'OFFSET' does not exist in the current workbook.")) {
- throw new AssertionFailedError("Identified bug 46951");
+ fail("Identified bug 46951");
}
+ wb.close();
throw e;
}
confirmTokenClasses(ptgs,
RangePtg.class, //
AttrPtg.class // [sum ]
);
-
+ wb.close();
}
- public void testUnionOfFullCollFullRowRef() {
+ @Test
+ public void testUnionOfFullCollFullRowRef() throws IOException {
Ptg[] ptgs;
ptgs = parseFormula("3:4");
ptgs = parseFormula("$Z:$AC");
Area3DPtg.class,
UnionPtg.class
);
+
+ wb.close();
}
-
- public void testExplicitRangeWithTwoSheetNames() {
+ @Test
+ public void testExplicitRangeWithTwoSheetNames() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet("Sheet1");
Ptg[] ptgs = HSSFFormulaParser.parse("Sheet1!F1:Sheet1!G2", wb);
MemFuncPtg mf;
mf = (MemFuncPtg)ptgs[0];
assertEquals(15, mf.getLenRefSubexpression());
+ wb.close();
}
/**
* Checks that the area-ref and explicit range operators get the right associativity
* and that the {@link MemFuncPtg} / {@link MemAreaPtg} is added correctly
*/
+ @Test
public void testComplexExplicitRangeEncodings() {
Ptg[] ptgs;
* Mostly confirming that erroneous conditions are detected. Actual error message wording is not critical.
*
*/
- public void testEdgeCaseParserErrors() {
+ @Test
+ public void testEdgeCaseParserErrors() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet("Sheet1");
confirmParseError(wb, "foobar", "Specified named range 'foobar' does not exist in the current workbook.");
confirmParseError(wb, "A1:1", "The RHS of the range operator ':' at position 3 is not a proper reference.");
+ wb.close();
}
private static void confirmParseError(HSSFWorkbook wb, String formula, String expectedMessage) {
try {
HSSFFormulaParser.parse(formula, wb);
- throw new AssertionFailedError("Expected formula parse execption");
+ fail("Expected formula parse execption");
} catch (FormulaParseException e) {
confirmParseException(e, expectedMessage);
}
* In bug 47078, POI had trouble evaluating a defined name flagged as 'complex'.
* POI should also be able to parse such defined names.
*/
- public void testParseComplexName() {
+ @Test
+ public void testParseComplexName() throws IOException {
// Mock up a spreadsheet to match the critical details of the sample
HSSFWorkbook wb = new HSSFWorkbook();
result = HSSFFormulaParser.parse("1+foo", wb);
} catch (FormulaParseException e) {
if (e.getMessage().equals("Specified name 'foo' is not a range as expected.")) {
- throw new AssertionFailedError("Identified bug 47078c");
+ fail("Identified bug 47078c");
}
+ wb.close();
throw e;
}
confirmTokenClasses(result, IntPtg.class, NamePtg.class, AddPtg.class);
+
+ wb.close();
}
/**
* In addition, leading zeros (on the row component) should be removed from cell
* references during parsing.
*/
- public void testZeroRowRefs() {
+ @Test
+ public void testZeroRowRefs() throws IOException {
String badCellRef = "B0"; // bad because zero is not a valid row number
String leadingZeroCellRef = "B000001"; // this should get parsed as "B1"
HSSFWorkbook wb = new HSSFWorkbook();
try {
HSSFFormulaParser.parse(badCellRef, wb);
- throw new AssertionFailedError("Identified bug 47312b - Shouldn't be able to parse cell ref '"
+ fail("Identified bug 47312b - Shouldn't be able to parse cell ref '"
+ badCellRef + "'.");
} catch (FormulaParseException e) {
// expected during successful test
confirmParseException(e, "Specified named range '"
+ leadingZeroCellRef + "' does not exist in the current workbook.");
// close but no cigar
- throw new AssertionFailedError("Identified bug 47312c - '"
- + leadingZeroCellRef + "' should parse as 'B1'.");
+ fail("Identified bug 47312c - '" + leadingZeroCellRef + "' should parse as 'B1'.");
}
// create a defined name called 'B0' and try again
n.setRefersToFormula("1+1");
ptgs = HSSFFormulaParser.parse("B0", wb);
confirmTokenClasses(ptgs, NamePtg.class);
+
+ wb.close();
}
private static void confirmParseException(FormulaParseException e, String expMsg) {
}
@Test
- public void test57196_Formula() {
+ public void test57196_Formula() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
Ptg[] ptgs = HSSFFormulaParser.parse("DEC2HEX(HEX2DEC(O8)-O2+D2)", wb, FormulaType.CELL, -1);
assertNotNull("Ptg array should not be null", ptgs);
assertEquals("O2", o2.toFormulaString());
assertEquals("D2", d2.toFormulaString());
assertEquals(255, dec2Hex.getFunctionIndex());
+
+ wb.close();
}
}
package org.apache.poi.hssf.record;
-import junit.framework.AssertionFailedError;
-import junit.framework.TestCase;
-
+import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.formula.ptg.AttrPtg;
import org.apache.poi.ss.formula.ptg.FuncVarPtg;
import org.apache.poi.ss.formula.ptg.IntPtg;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.formula.ptg.RefPtg;
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
+
+import junit.framework.AssertionFailedError;
+import junit.framework.TestCase;
/**
* Tests for {@link FormulaRecord}
// 8 bytes cached number is a 'special value' in this case
0x02, // special cached value type 'error'
0x00,
- HSSFErrorConstants.ERROR_DIV_0,
+ FormulaError.DIV0.getCode(),
0x00,
0x00,
0x00,
// test some other cached value types
fr0.setValue(3.5);
assertEquals(3.5, fr0.getValue(), 0.0);
- fr0.setCachedResultErrorCode(HSSFErrorConstants.ERROR_REF);
- assertEquals(HSSFErrorConstants.ERROR_REF, fr0.getCachedErrorValue());
+ fr0.setCachedResultErrorCode(FormulaError.REF.getCode());
+ assertEquals(FormulaError.REF.getCode(), fr0.getCachedErrorValue());
fr0.setCachedResultBoolean(false);
fr1.setCachedResultBoolean(true);
import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.junit.Test;
-/**
- *
- * @author Josh Micich
- */
public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
public TestHSSFFormulaEvaluator() {
cellB1.setCellFormula("A1+1");
HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
- cellA1.setCellErrorValue((byte)HSSFErrorConstants.ERROR_NAME);
+ cellA1.setCellErrorValue(FormulaError.NAME.getCode());
fe.evaluateFormulaCell(cellB1);
cellA1.setCellValue(2.5);
package org.apache.poi.ss.formula.constant;
-import java.util.Arrays;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.util.Arrays;
import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.apache.poi.hssf.usermodel.HSSFErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.util.HexRead;
import org.apache.poi.util.LittleEndianByteArrayOutputStream;
import org.apache.poi.util.LittleEndianInput;
-/**
- *
- * @author Josh Micich
- */
-public final class TestConstantValueParser extends TestCase {
+import org.junit.Test;
+
+public final class TestConstantValueParser {
private static final Object[] SAMPLE_VALUES = {
Boolean.TRUE,
null,
new Double(1.1),
"Sample text",
- ErrorConstant.valueOf(HSSFErrorConstants.ERROR_DIV_0),
+ ErrorConstant.valueOf(FormulaError.DIV0.getCode()),
};
private static final byte[] SAMPLE_ENCODING = HexRead.readFromString(
"04 01 00 00 00 00 00 00 00 " +
"02 0B 00 00 53 61 6D 70 6C 65 20 74 65 78 74 " +
"10 07 00 00 00 00 00 00 00");
+ @Test
public void testGetEncodedSize() {
int actual = ConstantValueParser.getEncodedSize(SAMPLE_VALUES);
assertEquals(51, actual);
}
+
+ @Test
public void testEncode() {
int size = ConstantValueParser.getEncodedSize(SAMPLE_VALUES);
byte[] data = new byte[size];
fail("Encoding differs");
}
}
+
+ @Test
public void testDecode() {
LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(SAMPLE_ENCODING);
import org.apache.poi.ss.formula.eval.NumberEval;
import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.ss.usermodel.DateUtil;
-import org.apache.poi.ss.usermodel.ErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.util.LocaleUtil;
import org.junit.Test;
public void testEDateInvalidValues() {
EDate eDate = new EDate();
ErrorEval result = (ErrorEval) eDate.evaluate(new ValueEval[]{new NumberEval(1000)}, null);
- assertEquals(ErrorConstants.ERROR_VALUE, result.getErrorCode(), 0);
+ assertEquals(FormulaError.VALUE.getCode(), result.getErrorCode(), 0);
}
@Test
import org.apache.poi.ss.formula.eval.StringEval;\r
import org.apache.poi.ss.formula.eval.ValueEval;\r
import org.apache.poi.ss.usermodel.DateUtil;\r
-import org.apache.poi.ss.usermodel.ErrorConstants;\r
+import org.apache.poi.ss.usermodel.FormulaError;\r
import org.apache.poi.util.LocaleUtil;\r
import org.junit.Test;\r
\r
public void testEOMonthInvalidArguments() {\r
ValueEval result = eOMonth.evaluate(new ValueEval[] {new NumberEval(DATE_1902_09_26)}, ec);\r
assertTrue(result instanceof ErrorEval);\r
- assertEquals(ErrorConstants.ERROR_VALUE, ((ErrorEval) result).getErrorCode(), 0);\r
+ assertEquals(FormulaError.VALUE.getCode(), ((ErrorEval) result).getErrorCode(), 0);\r
\r
result = eOMonth.evaluate(new ValueEval[] {new StringEval("a"), new StringEval("b")}, ec);\r
assertTrue(result instanceof ErrorEval);\r
- assertEquals(ErrorConstants.ERROR_VALUE, ((ErrorEval) result).getErrorCode(), 0);\r
+ assertEquals(FormulaError.VALUE.getCode(), ((ErrorEval) result).getErrorCode(), 0);\r
}\r
\r
@Test\r
package org.apache.poi.ss.formula.functions;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFErrorConstants;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellValue;
+import org.apache.poi.ss.usermodel.FormulaError;
+import org.junit.Test;
/**
* Tests for {@link Financed}
- *
- * @author Torstein Svendsen (torstei@officenet.no)
*/
-public final class TestFind extends TestCase {
+public final class TestFind {
- public void testFind() {
+ @Test
+ public void testFind() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFCell cell = wb.createSheet().createRow(0).createCell(0);
confirmResult(fe, cell, "find(5, 87654)", 4);
// Errors
- confirmError(fe, cell, "find(\"n\", \"haystack\")", HSSFErrorConstants.ERROR_VALUE);
- confirmError(fe, cell, "find(\"k\", \"haystack\",9)", HSSFErrorConstants.ERROR_VALUE);
- confirmError(fe, cell, "find(\"k\", \"haystack\",#REF!)", HSSFErrorConstants.ERROR_REF);
- confirmError(fe, cell, "find(\"k\", \"haystack\",0)", HSSFErrorConstants.ERROR_VALUE);
- confirmError(fe, cell, "find(#DIV/0!, #N/A, #REF!)", HSSFErrorConstants.ERROR_DIV_0);
- confirmError(fe, cell, "find(2, #N/A, #REF!)", HSSFErrorConstants.ERROR_NA);
+ confirmError(fe, cell, "find(\"n\", \"haystack\")", FormulaError.VALUE);
+ confirmError(fe, cell, "find(\"k\", \"haystack\",9)", FormulaError.VALUE);
+ confirmError(fe, cell, "find(\"k\", \"haystack\",#REF!)", FormulaError.REF);
+ confirmError(fe, cell, "find(\"k\", \"haystack\",0)", FormulaError.VALUE);
+ confirmError(fe, cell, "find(#DIV/0!, #N/A, #REF!)", FormulaError.DIV0);
+ confirmError(fe, cell, "find(2, #N/A, #REF!)", FormulaError.NA);
+
+ wb.close();
}
private static void confirmResult(HSSFFormulaEvaluator fe, HSSFCell cell, String formulaText,
}
private static void confirmError(HSSFFormulaEvaluator fe, HSSFCell cell, String formulaText,
- int expectedErrorCode) {
+ FormulaError expectedErrorCode) {
cell.setCellFormula(formulaText);
fe.notifyUpdateCell(cell);
CellValue result = fe.evaluate(cell);
assertEquals(result.getCellType(), HSSFCell.CELL_TYPE_ERROR);
- assertEquals(expectedErrorCode, result.getErrorValue());
+ assertEquals(expectedErrorCode.getCode(), result.getErrorValue());
}
}
package org.apache.poi.ss.formula.functions;
-import java.io.IOException;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
-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.ss.formula.eval.ValueEval;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
-import org.apache.poi.ss.usermodel.ErrorConstants;
+import org.apache.poi.ss.usermodel.FormulaError;
+import org.junit.Before;
+import org.junit.Test;
-public final class TestFixed extends TestCase {
+public final class TestFixed {
private HSSFCell cell11;
private HSSFFormulaEvaluator evaluator;
- @Override
+ @Before
public void setUp() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
try {
}
}
+ @Test
public void testValid() {
// thousands separator
confirm("FIXED(1234.56789,2,TRUE)", "1234.57");
confirm("FIXED(99.9,0,TRUE)", "100");
}
+ @Test
public void testOptionalParams() {
Fixed fixed = new Fixed();
ValueEval evaluate = fixed.evaluate(0, 0, new NumberEval(1234.56789));
CellValue cv = evaluator.evaluate(cell11);
assertTrue("Wrong result type: " + cv.formatAsString(),
cv.getCellType() == Cell.CELL_TYPE_ERROR
- && cv.getErrorValue() == ErrorConstants.ERROR_VALUE);
+ && cv.getErrorValue() == FormulaError.VALUE.getCode());
}
}
package org.apache.poi.ss.formula.functions;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
-import org.apache.poi.ss.formula.eval.NumberEval;
-import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFErrorConstants;
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.formula.eval.NumberEval;
+import org.apache.poi.ss.formula.eval.ValueEval;
+import org.apache.poi.ss.usermodel.FormulaError;
+import org.junit.Test;
/**
* Tests for {@link FinanceFunction#NPER}
- *
- * @author Josh Micich
*/
-public final class TestNper extends TestCase {
- public void testSimpleEvaluate() {
+public final class TestNper {
+ @Test
+ public void testSimpleEvaluate() {
ValueEval[] args = {
new NumberEval(0.05),
new NumberEval(250),
assertEquals(4.57353557, ((NumberEval)result).getNumberValue(), 0.00000001);
}
- public void testEvaluate_bug_45732() {
+ @Test
+ public void testEvaluate_bug_45732() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Sheet1");
HSSFCell cell = sheet.createRow(0).createCell(0);
HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
fe.evaluateFormulaCell(cell);
assertEquals(HSSFCell.CELL_TYPE_ERROR, cell.getCachedFormulaResultType());
- assertEquals(HSSFErrorConstants.ERROR_NUM, cell.getErrorCellValue());
+ assertEquals(FormulaError.NUM.getCode(), cell.getErrorCellValue());
+ wb.close();
}
}
package org.apache.poi.ss.formula.functions;
-import junit.framework.AssertionFailedError;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
import org.apache.poi.ss.formula.eval.ErrorEval;
-import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.ss.formula.eval.NumberEval;
-import org.apache.poi.hssf.usermodel.HSSFErrorConstants;
+import org.apache.poi.ss.formula.eval.ValueEval;
+import org.apache.poi.ss.usermodel.FormulaError;
+import org.junit.Test;
-/**
- * @author Josh Micich
- */
-public final class TestPmt extends TestCase {
+public final class TestPmt {
private static void confirm(double expected, NumberEval ne) {
// only asserting accuracy to 4 fractional digits
private static NumberEval invokeNormal(ValueEval[] args) {
ValueEval ev = invoke(args);
if(ev instanceof ErrorEval) {
- throw new AssertionFailedError("Normal evaluation failed with error code: "
- + ev.toString());
+ fail("Normal evaluation failed with error code: " + ev.toString());
}
return (NumberEval) ev;
}
confirm(expected, invokeNormal(args));
}
-
+ @Test
public void testBasic() {
confirm(-1037.0321, (0.08/12), 10, 10000, 0, false);
confirm(-1030.1643, (0.08/12), 10, 10000, 0, true);
}
+ @Test
public void test3args() {
ValueEval[] args = {
ValueEval ev = invoke(args);
if(ev instanceof ErrorEval) {
ErrorEval err = (ErrorEval) ev;
- if(err.getErrorCode() == HSSFErrorConstants.ERROR_VALUE) {
- throw new AssertionFailedError("Identified bug 44691");
+ if(err.getErrorCode() == FormulaError.VALUE.getCode()) {
+ fail("Identified bug 44691");
}
}
import org.junit.Test;
/**
- * Common superclass for testing implementatiosn of{@link FormulaEvaluator}
- *
- * @author Yegor Kozlov
+ * Common superclass for testing implementation of {@link FormulaEvaluator}
*/
public abstract class BaseTestFormulaEvaluator {
cellB1.setCellFormula("A1+1");
FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator();
- cellA1.setCellErrorValue((byte)ErrorConstants.ERROR_NAME);
+ cellA1.setCellErrorValue(FormulaError.NAME.getCode());
fe.evaluateFormulaCell(cellB1);
cellA1.setCellValue(2.5);