From cbecd918ab99c788d6208e75736b39c066b39cc0 Mon Sep 17 00:00:00 2001 From: Nick Burch Date: Mon, 7 Apr 2008 12:51:50 +0000 Subject: [PATCH] Merged revisions 638786-638802,638805-638811,638813-638814,638816-639230,639233-639241,639243-639253,639255-639486,639488-639601,639603-639835,639837-639917,639919-640056,640058-640710,640712-641156,641158-641184,641186-641795,641797-641798,641800-641933,641935-641963,641965-641966,641968-641995,641997-642230,642232-642562,642564-642565,642568-642570,642572-642573,642576-642736,642739-642877,642879,642881-642890,642892-642903,642905-642945,642947-643624,643626-643653,643655-643669,643671,643673-643830,643832-643833,643835-644342,644344-644472,644474-644508,644510-645478 via svnmerge from https://svn.apache.org:443/repos/asf/poi/trunk ........ r645348 | josh | 2008-04-07 04:02:03 +0100 (Mon, 07 Apr 2008) | 1 line refactored all hssf junits to get test sample data in the in one place ........ r645352 | josh | 2008-04-07 04:23:04 +0100 (Mon, 07 Apr 2008) | 2 lines 30311 - More work on Conditional Formatting - patch from Dmitriy ........ git-svn-id: https://svn.apache.org/repos/asf/poi/branches/ooxml@645483 13f79535-47bb-0310-9956-ffa450edef68 --- src/documentation/content/xdocs/changes.xml | 2 + src/documentation/content/xdocs/status.xml | 2 + .../apache/poi/hssf/record/CFRuleRecord.java | 40 +- .../poi/hssf/record/cf/FontFormatting.java | 92 +- .../hssf/usermodel/HSSFBorderFormatting.java | 5 + .../HSSFConditionalFormattingRule.java | 48 +- .../hssf/usermodel/HSSFFontFormatting.java | 300 ++-- .../hssf/usermodel/HSSFPatternFormatting.java | 80 +- src/java/org/apache/poi/util/HexRead.java | 15 +- .../org/apache/poi/TestPOIDocumentMain.java | 134 +- .../apache/poi/hssf/HSSFTestDataSamples.java | 175 ++ .../eventusermodel/TestHSSFEventFactory.java | 101 +- .../TestMissingRecordAwareHSSFListener.java | 7 +- .../hssf/extractor/TestExcelExtractor.java | 57 +- .../apache/poi/hssf/record/TestBOFRecord.java | 41 +- .../poi/hssf/record/TestCFRuleRecord.java | 20 +- .../record/TestChartTitleFormatRecord.java | 91 +- .../poi/hssf/record/TestFormulaRecord.java | 169 +- .../poi/hssf/record/TestRecordFactory.java | 45 +- .../poi/hssf/record/TestSSTDeserializer.java | 73 +- .../apache/poi/hssf/record/TestSSTRecord.java | 113 +- .../hssf/record/TestUnicodeNameRecord.java | 32 +- .../aggregates/TestValueRecordsAggregate.java | 16 +- .../record/formula/AbstractPtgTestCase.java | 36 +- .../formula/TestExternalFunctionFormulas.java | 14 +- .../record/formula/eval/TestFormulaBugs.java | 42 +- .../eval/TestFormulasFromSpreadsheet.java | 14 +- .../function/TestReadMissingBuiltInFuncs.java | 10 +- .../TestLookupFunctionsFromSpreadsheet.java | 116 +- .../poi/hssf/usermodel/TestBug42464.java | 25 +- .../apache/poi/hssf/usermodel/TestBugs.java | 1202 +++++--------- .../usermodel/TestFormulaEvaluatorBugs.java | 332 ++-- .../poi/hssf/usermodel/TestFormulas.java | 670 ++++---- .../poi/hssf/usermodel/TestHSSFCell.java | 194 +-- .../poi/hssf/usermodel/TestHSSFComment.java | 19 +- .../TestHSSFConditionalFormatting.java | 20 +- .../poi/hssf/usermodel/TestHSSFDateUtil.java | 173 +- .../hssf/usermodel/TestHSSFHeaderFooter.java | 182 +-- .../poi/hssf/usermodel/TestHSSFHyperlink.java | 22 +- .../poi/hssf/usermodel/TestHSSFPalette.java | 112 +- .../poi/hssf/usermodel/TestHSSFPicture.java | 7 +- .../hssf/usermodel/TestHSSFPictureData.java | 27 +- .../poi/hssf/usermodel/TestHSSFSheet.java | 1412 ++++++++--------- .../poi/hssf/usermodel/TestHSSFWorkbook.java | 72 +- .../poi/hssf/usermodel/TestNamedRange.java | 746 ++++----- .../poi/hssf/usermodel/TestOLE2Embeding.java | 25 +- .../hssf/usermodel/TestPOIFSProperties.java | 33 +- .../hssf/usermodel/TestReadWriteChart.java | 59 +- .../poi/hssf/usermodel/TestSheetHiding.java | 24 +- .../hssf/usermodel/TestSheetShiftRows.java | 124 +- .../poi/hssf/usermodel/TestUnfixedBugs.java | 55 +- .../hssf/usermodel/TestUppercaseWorkbook.java | 24 +- .../poi/hssf/usermodel/TestWorkbook.java | 353 ++--- .../poi/hssf/util/TestAreaReference.java | 33 +- .../TestOffice2007XMLException.java | 49 +- .../poifs/filesystem/TestPOIFSFileSystem.java | 22 +- .../poifs/filesystem/TestPropertySorter.java | 75 +- 57 files changed, 3483 insertions(+), 4498 deletions(-) create mode 100644 src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java diff --git a/src/documentation/content/xdocs/changes.xml b/src/documentation/content/xdocs/changes.xml index e2e6faef7e..f214e05e12 100644 --- a/src/documentation/content/xdocs/changes.xml +++ b/src/documentation/content/xdocs/changes.xml @@ -37,6 +37,8 @@ + 30311 - More work on Conditional Formatting + refactored all junits' usage of HSSF.testdata.path to one place 44739 - Small fixes for conditional formatting (regions with max row/col index) Implement Sheet.removeShape(Shape shape) in HSLF 44694 - HPSF: Support for property sets without sections diff --git a/src/documentation/content/xdocs/status.xml b/src/documentation/content/xdocs/status.xml index 7a1d2e9717..7bdc284dad 100644 --- a/src/documentation/content/xdocs/status.xml +++ b/src/documentation/content/xdocs/status.xml @@ -34,6 +34,8 @@ + 30311 - More work on Conditional Formatting + refactored all junits' usage of HSSF.testdata.path to one place 44739 - Small fixes for conditional formatting (regions with max row/col index) 44694 - HPSF: Support for property sets without sections Implement Sheet.removeShape(Shape shape) in HSLF diff --git a/src/java/org/apache/poi/hssf/record/CFRuleRecord.java b/src/java/org/apache/poi/hssf/record/CFRuleRecord.java index 43da6260ac..0890f1f32d 100644 --- a/src/java/org/apache/poi/hssf/record/CFRuleRecord.java +++ b/src/java/org/apache/poi/hssf/record/CFRuleRecord.java @@ -238,6 +238,17 @@ public final class CFRuleRecord extends Record this.fontFormatting = fontFormatting; setOptionFlag(fontFormatting != null, font); } + public FontFormatting getFontFormatting() + { + if( containsFontFormattingBlock()) + { + return fontFormatting; + } + else + { + return null; + } + } public boolean containsAlignFormattingBlock() { @@ -257,6 +268,17 @@ public final class CFRuleRecord extends Record this.borderFormatting = borderFormatting; setOptionFlag(borderFormatting != null, bord); } + public BorderFormatting getBorderFormatting() + { + if( containsBorderFormattingBlock()) + { + return borderFormatting; + } + else + { + return null; + } + } public boolean containsPatternFormattingBlock() { @@ -267,7 +289,17 @@ public final class CFRuleRecord extends Record this.patternFormatting = patternFormatting; setOptionFlag(patternFormatting!=null, patt); } - + public PatternFormatting getPatternFormatting() + { + if( containsPatternFormattingBlock()) + { + return patternFormatting; + } + else + { + return null; + } + } public boolean containsProtectionFormattingBlock() { @@ -616,12 +648,6 @@ public final class CFRuleRecord extends Record return rec; } - public FontFormatting getFontFormatting() - { - return fontFormatting; - } - - /** * @return null if formula was null. */ diff --git a/src/java/org/apache/poi/hssf/record/cf/FontFormatting.java b/src/java/org/apache/poi/hssf/record/cf/FontFormatting.java index 1e6abee7c9..eaae02de30 100644 --- a/src/java/org/apache/poi/hssf/record/cf/FontFormatting.java +++ b/src/java/org/apache/poi/hssf/record/cf/FontFormatting.java @@ -45,8 +45,8 @@ public class FontFormatting private static final int OFFSET_OPTION_FLAGS = 88; private static final int OFFSET_ESCAPEMENT_TYPE_MODIFIED = 92; private static final int OFFSET_UNDERLINE_TYPE_MODIFIED = 96; - private static final int OFFSET_NOT_USED1 = 100; - private static final int OFFSET_NOT_USED2 = 104; + private static final int OFFSET_FONT_WEIGHT_MODIFIED = 100; + private static final int OFFSET_NOT_USED = 104; private static final int OFFSET_FONT_FORMATING_END = 116; @@ -56,7 +56,6 @@ public class FontFormatting private static final BitField posture = BitFieldFactory.getInstance(0x00000002); private static final BitField outline = BitFieldFactory.getInstance(0x00000008); private static final BitField shadow = BitFieldFactory.getInstance(0x00000010); - private static final BitField condense = BitFieldFactory.getInstance(0x00000020); private static final BitField cancellation = BitFieldFactory.getInstance(0x00000080); // OPTION FLAGS MASKS @@ -64,7 +63,6 @@ public class FontFormatting private static final BitField styleModified = BitFieldFactory.getInstance(0x00000002); private static final BitField outlineModified = BitFieldFactory.getInstance(0x00000008); private static final BitField shadowModified = BitFieldFactory.getInstance(0x00000010); - private static final BitField condenseModified = BitFieldFactory.getInstance(0x00000020); private static final BitField cancellationModified = BitFieldFactory.getInstance(0x00000080); /** @@ -125,10 +123,9 @@ public class FontFormatting this.setFontHeight((short)-1); this.setItalic(false); - this.setBold(false); + this.setFontWieghtModified(false); this.setOutline(false); this.setShadow(false); - this.setCondense(false); this.setStrikeout(false); this.setEscapementType((short)0); this.setUnderlineType((byte)0); @@ -137,15 +134,13 @@ public class FontFormatting this.setFontStyleModified(false); this.setFontOutlineModified(false); this.setFontShadowModified(false); - this.setFontCondenseModified(false); this.setFontCancellationModified(false); this.setEscapementTypeModified(false); this.setUnderlineTypeModified(false); LittleEndian.putShort(record, OFFSET_FONT_NAME, (short)0); - LittleEndian.putInt(record, OFFSET_NOT_USED1, 0x00000001); - LittleEndian.putInt(record, OFFSET_NOT_USED2, 0x00000001); + LittleEndian.putInt(record, OFFSET_NOT_USED, 0x00000001); LittleEndian.putShort(record, OFFSET_FONT_FORMATING_END, (short)0x0001); } @@ -249,16 +244,6 @@ public class FontFormatting return getFontOption(shadow); } - public void setCondense(boolean on) - { - setFontOption(on, condense); - } - - public boolean isCondenseOn() - { - return getFontOption(condense); - } - /** * set the font to be stricken out or not * @@ -420,6 +405,7 @@ public class FontFormatting return getOptionFlag(styleModified); } + public void setFontStyleModified(boolean modified) { setOptionFlag(modified, styleModified); @@ -444,16 +430,6 @@ public class FontFormatting { setOptionFlag(modified, shadowModified); } - public boolean isFontCondenseModified() - { - return getOptionFlag(condenseModified); - } - - public void setFontCondenseModified(boolean modified) - { - setOptionFlag(modified, condenseModified); - } - public void setFontCancellationModified(boolean modified) { setOptionFlag(modified, cancellationModified); @@ -469,7 +445,6 @@ public class FontFormatting int value = modified? 0 : 1; LittleEndian.putInt(record,OFFSET_ESCAPEMENT_TYPE_MODIFIED, value); } - public boolean isEscapementTypeModified() { int escapementModified = LittleEndian.getInt(record,OFFSET_ESCAPEMENT_TYPE_MODIFIED); @@ -488,6 +463,18 @@ public class FontFormatting return underlineModified == 0; } + public void setFontWieghtModified(boolean modified) + { + int value = modified? 0 : 1; + LittleEndian.putInt(record,OFFSET_FONT_WEIGHT_MODIFIED, value); + } + + public boolean isFontWeightModified() + { + int fontStyleModified = LittleEndian.getInt(record,OFFSET_FONT_WEIGHT_MODIFIED); + return fontStyleModified == 0; + } + public String toString() { StringBuffer buffer = new StringBuffer(); @@ -521,14 +508,6 @@ public class FontFormatting { buffer.append(" .font shadow is not modified\n"); } - if( isFontCondenseModified() ) - { - buffer.append(" .font condense = ").append(isCondenseOn()).append("\n"); - } - else - { - buffer.append(" .font condense is not modified\n"); - } if( isFontCancellationModified() ) { @@ -572,11 +551,32 @@ public class FontFormatting } buffer.append(" .color index = ").append("0x"+Integer.toHexString(getFontColorIndex()).toUpperCase()).append("\n"); + + buffer.append(" ====\n"); + buffer.append(" ["+OFFSET_FONT_HEIGHT+"] FONT HEIGHT: "+intToHex(OFFSET_FONT_HEIGHT)+"\n"); + buffer.append(" ["+OFFSET_FONT_OPTIONS+"] FONT OPTIONS: "+intToHex(OFFSET_FONT_OPTIONS)+"\n"); + buffer.append(" ["+OFFSET_FONT_WEIGHT+"] FONT WEIGHT: "+shortToHex(OFFSET_FONT_WEIGHT)+"\n"); + buffer.append(" ["+OFFSET_ESCAPEMENT_TYPE+"] FONT ESCAPEMENT: "+shortToHex(OFFSET_ESCAPEMENT_TYPE)+"\n"); + buffer.append(" ["+OFFSET_UNDERLINE_TYPE+"] FONT UNDERLINE: "+byteToHex(OFFSET_UNDERLINE_TYPE)+"\n"); + buffer.append(" ["+(OFFSET_UNDERLINE_TYPE+1)+"] FONT NOT USED: "+byteToHex(OFFSET_UNDERLINE_TYPE+1)+"\n"); + buffer.append(" ["+(OFFSET_UNDERLINE_TYPE+2)+"] FONT NOT USED: "+byteToHex(OFFSET_UNDERLINE_TYPE+2)+"\n"); + buffer.append(" ["+(OFFSET_UNDERLINE_TYPE+3)+"] FONT NOT USED: "+byteToHex(OFFSET_UNDERLINE_TYPE+3)+"\n"); + buffer.append(" ["+OFFSET_FONT_COLOR_INDEX+"] FONT COLIDX: "+intToHex(OFFSET_FONT_COLOR_INDEX)+"\n"); + buffer.append(" ["+(OFFSET_FONT_COLOR_INDEX+4)+"] FONT NOT USED: "+intToHex(OFFSET_FONT_COLOR_INDEX+4)+"\n"); + buffer.append(" ["+OFFSET_OPTION_FLAGS+"] FONT OPTIONS: "+intToHex(OFFSET_OPTION_FLAGS)+"\n"); + buffer.append(" ["+OFFSET_ESCAPEMENT_TYPE_MODIFIED+"] FONT ESC MOD: "+intToHex(OFFSET_ESCAPEMENT_TYPE_MODIFIED)+"\n"); + buffer.append(" ["+OFFSET_UNDERLINE_TYPE_MODIFIED+"] FONT UND MOD: "+intToHex(OFFSET_UNDERLINE_TYPE_MODIFIED)+"\n"); + buffer.append(" ["+OFFSET_FONT_WEIGHT+"] FONT WGH MOD: "+intToHex(OFFSET_FONT_WEIGHT)+"\n"); + buffer.append(" ["+OFFSET_NOT_USED+"] FONT NOT USED: "+intToHex(OFFSET_NOT_USED)+"\n"); + buffer.append(" ["+(OFFSET_NOT_USED+4)+"] FONT NOT USED: "+intToHex(OFFSET_NOT_USED+4)+"\n"); + buffer.append(" ["+(OFFSET_NOT_USED+8)+"] FONT NOT USED: "+intToHex(OFFSET_NOT_USED+8)+"\n"); + buffer.append(" ["+OFFSET_FONT_FORMATING_END+"] FONT FORMATTING END: "+shortToHex(OFFSET_FONT_FORMATING_END)+"\n"); + buffer.append(" ====\n"); buffer.append(" [/Font Formatting]\n"); return buffer.toString(); } - + public Object clone() { FontFormatting rec = new FontFormatting(); @@ -588,4 +588,18 @@ public class FontFormatting } return rec; } + + private String intToHex(int offset) + { + return Integer.toHexString(LittleEndian.getInt(record, offset)); + } + private String shortToHex(int offset) + { + return Integer.toHexString(LittleEndian.getShort(record, offset)&0xFFFF); + } + private String byteToHex(int offset) + { + return Integer.toHexString(record[offset]&0xFF); + } + } diff --git a/src/java/org/apache/poi/hssf/usermodel/HSSFBorderFormatting.java b/src/java/org/apache/poi/hssf/usermodel/HSSFBorderFormatting.java index 408c774b62..ba2d587624 100644 --- a/src/java/org/apache/poi/hssf/usermodel/HSSFBorderFormatting.java +++ b/src/java/org/apache/poi/hssf/usermodel/HSSFBorderFormatting.java @@ -65,6 +65,11 @@ public final class HSSFBorderFormatting borderFormatting = new BorderFormatting(); } + protected HSSFBorderFormatting(BorderFormatting borderFormatting) + { + this.borderFormatting = borderFormatting; + } + protected BorderFormatting getBorderFormattingBlock() { return borderFormatting; diff --git a/src/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingRule.java b/src/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingRule.java index 8f220fdf6e..490ff4d342 100644 --- a/src/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingRule.java +++ b/src/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingRule.java @@ -17,8 +17,6 @@ package org.apache.poi.hssf.usermodel; -import java.util.List; - import org.apache.poi.hssf.model.FormulaParser; import org.apache.poi.hssf.model.Workbook; import org.apache.poi.hssf.record.CFRuleRecord; @@ -40,9 +38,6 @@ import org.apache.poi.hssf.record.formula.Ptg; public final class HSSFConditionalFormattingRule { private static final byte CELL_COMPARISON = CFRuleRecord.CONDITION_TYPE_CELL_VALUE_IS; - - - private final CFRuleRecord cfRuleRecord; private final Workbook workbook; @@ -73,6 +68,19 @@ public final class HSSFConditionalFormattingRule FontFormatting block = fontFmt==null ? null : fontFmt.getFontFormattingBlock(); cfRuleRecord.setFontFormatting(block); } + + /** + * @return - font formatting object if defined, null otherwise + */ + public HSSFFontFormatting getFontFormatting() + { + FontFormatting ff = cfRuleRecord.getFontFormatting(); + if ( ff == null ) { + return null; + } + return new HSSFFontFormatting(ff); + } + /** * @param borderFmt pass null to signify 'border unchanged' */ @@ -81,6 +89,17 @@ public final class HSSFConditionalFormattingRule BorderFormatting block = borderFmt==null ? null : borderFmt.getBorderFormattingBlock(); cfRuleRecord.setBorderFormatting(block); } + /** + * @return - border formatting object if defined, null otherwise + */ + public HSSFBorderFormatting getBorderFormatting() + { + BorderFormatting bf = cfRuleRecord.getBorderFormatting(); + if ( bf == null ) { + return null; + } + return new HSSFBorderFormatting(bf); + } /** * @param patternFmt pass null to signify 'pattern unchanged' */ @@ -89,6 +108,17 @@ public final class HSSFConditionalFormattingRule PatternFormatting block = patternFmt==null ? null : patternFmt.getPatternFormattingBlock(); cfRuleRecord.setPatternFormatting(block); } + /** + * @return - pattern formatting object if defined, null otherwise + */ + public HSSFPatternFormatting getPatternFormatting() + { + PatternFormatting pf = cfRuleRecord.getPatternFormatting(); + if ( pf == null ) { + return null; + } + return new HSSFPatternFormatting(pf); + } public String getFormula1() { @@ -112,11 +142,9 @@ public final class HSSFConditionalFormattingRule private String toFormulaString(Ptg[] parsedExpression) { - String formula = null; - if(parsedExpression!=null) - { - formula = FormulaParser.toFormulaString(workbook, parsedExpression); + if(parsedExpression ==null) { + return null; } - return formula; + return FormulaParser.toFormulaString(workbook, parsedExpression); } } diff --git a/src/java/org/apache/poi/hssf/usermodel/HSSFFontFormatting.java b/src/java/org/apache/poi/hssf/usermodel/HSSFFontFormatting.java index ee1352fc8c..12ea90698f 100644 --- a/src/java/org/apache/poi/hssf/usermodel/HSSFFontFormatting.java +++ b/src/java/org/apache/poi/hssf/usermodel/HSSFFontFormatting.java @@ -25,64 +25,51 @@ import org.apache.poi.hssf.record.cf.FontFormatting; * @author Dmitriy Kumshayev * */ -public class HSSFFontFormatting +public final class HSSFFontFormatting { - /** - * Escapement type - None - */ - public final static short SS_NONE = FontFormatting.SS_NONE; + /** Escapement type - None */ + public final static short SS_NONE = FontFormatting.SS_NONE; + /** Escapement type - Superscript */ + public final static short SS_SUPER = FontFormatting.SS_SUPER; + /** Escapement type - Subscript */ + public final static short SS_SUB = FontFormatting.SS_SUB; - /** - * Escapement type - Superscript - */ - public final static short SS_SUPER = FontFormatting.SS_SUPER; + /** Underline type - None */ + public final static byte U_NONE = FontFormatting.U_NONE; + /** Underline type - Single */ + public final static byte U_SINGLE = FontFormatting.U_SINGLE; + /** Underline type - Double */ + public final static byte U_DOUBLE = FontFormatting.U_DOUBLE; + /** Underline type - Single Accounting */ + public final static byte U_SINGLE_ACCOUNTING = FontFormatting.U_SINGLE_ACCOUNTING; + /** Underline type - Double Accounting */ + public final static byte U_DOUBLE_ACCOUNTING = FontFormatting.U_DOUBLE_ACCOUNTING; - /** - * Escapement type - Subscript - */ - public final static short SS_SUB = FontFormatting.SS_SUB; - - /** - * Underline type - None - */ - public final static byte U_NONE = FontFormatting.U_NONE; - /** - * Underline type - Single - */ - public final static byte U_SINGLE = FontFormatting.U_SINGLE; - /** - * Underline type - Double - */ - public final static byte U_DOUBLE = FontFormatting.U_DOUBLE; - /** - * Underline type - Single Accounting - */ - public final static byte U_SINGLE_ACCOUNTING = FontFormatting.U_SINGLE_ACCOUNTING; - /** - * Underline type - Double Accounting - */ - public final static byte U_DOUBLE_ACCOUNTING = FontFormatting.U_DOUBLE_ACCOUNTING; - - private FontFormatting fontFormatting; + private final FontFormatting fontFormatting; public HSSFFontFormatting() { fontFormatting = new FontFormatting(); } + protected HSSFFontFormatting(FontFormatting ff) + { + fontFormatting = ff; + } + protected FontFormatting getFontFormattingBlock() { return fontFormatting; } - /** - * get the type of super or subscript for the font - * - * @return super or subscript option - * @see #SS_NONE - * @see #SS_SUPER - * @see #SS_SUB - */ + /** + * get the type of super or subscript for the font + * + * @return super or subscript option + * @see #SS_NONE + * @see #SS_SUPER + * @see #SS_SUB + */ public short getEscapementType() { return fontFormatting.getEscapementType(); @@ -96,22 +83,22 @@ public class HSSFFontFormatting return fontFormatting.getFontColorIndex(); } - /** - * gets the height of the font in 1/20th point units - * - * @return fontheight (in points/20); or -1 if not modified - */ + /** + * gets the height of the font in 1/20th point units + * + * @return fontheight (in points/20); or -1 if not modified + */ public short getFontHeight() { return fontFormatting.getFontHeight(); } - /** - * get the font weight for this font (100-1000dec or 0x64-0x3e8). Default is - * 0x190 for normal and 0x2bc for bold - * - * @return bw - a number between 100-1000 for the fonts "boldness" - */ + /** + * get the font weight for this font (100-1000dec or 0x64-0x3e8). Default is + * 0x190 for normal and 0x2bc for bold + * + * @return bw - a number between 100-1000 for the fonts "boldness" + */ public short getFontWeight() { @@ -127,38 +114,30 @@ public class HSSFFontFormatting return fontFormatting.getRawRecord(); } - /** - * get the type of underlining for the font - * - * @return font underlining type - * - * @see #U_NONE - * @see #U_SINGLE - * @see #U_DOUBLE - * @see #U_SINGLE_ACCOUNTING - * @see #U_DOUBLE_ACCOUNTING - */ + /** + * get the type of underlining for the font + * + * @return font underlining type + * + * @see #U_NONE + * @see #U_SINGLE + * @see #U_DOUBLE + * @see #U_SINGLE_ACCOUNTING + * @see #U_DOUBLE_ACCOUNTING + */ public short getUnderlineType() { return fontFormatting.getUnderlineType(); } - /** - * get whether the font weight is set to bold or not - * - * @return bold - whether the font is bold or not - */ - public boolean isBold() - { - return fontFormatting.isBold(); - } - /** - * @return whether the font is condense or not + * get whether the font weight is set to bold or not + * + * @return bold - whether the font is bold or not */ - public boolean isCondenseOn() + public boolean isBold() { - return fontFormatting.isFontOutlineModified() && fontFormatting.isCondenseOn(); + return fontFormatting.isFontWeightModified() && fontFormatting.isBold(); } /** @@ -177,14 +156,6 @@ public class HSSFFontFormatting return fontFormatting.isFontCancellationModified(); } - /** - * @return true if font condense type was modified from default - */ - public boolean isFontCondenseModified() - { - return fontFormatting.isFontCondenseModified(); - } - /** * @return true if font outline type was modified from default */ @@ -249,66 +220,61 @@ public class HSSFFontFormatting return fontFormatting.isUnderlineTypeModified(); } - /** - * set font style options. - * - * @param italic - if true, set posture style to italic, otherwise to normal - * @param bold- if true, set font weight to bold, otherwise to normal - */ + /** + * @return true if font weight was modified from default + */ + public boolean isFontWeightModified() + { + return fontFormatting.isFontWeightModified(); + } + + /** + * set font style options. + * + * @param italic - if true, set posture style to italic, otherwise to normal + * @param bold- if true, set font weight to bold, otherwise to normal + */ public void setFontStyle(boolean italic, boolean bold) { - boolean modified = italic || bold; - fontFormatting.setItalic(italic); - fontFormatting.setBold(bold); - fontFormatting.setFontStyleModified(modified); + boolean modified = italic || bold; + fontFormatting.setItalic(italic); + fontFormatting.setBold(bold); + fontFormatting.setFontStyleModified(modified); + fontFormatting.setFontWieghtModified(modified); } - /** - * set font style options to default values (non-italic, non-bold) - */ + /** + * set font style options to default values (non-italic, non-bold) + */ public void resetFontStyle() { setFontStyle(false,false); } - /** - * set the escapement type for the font - * - * @param escapementType super or subscript option - * @see #SS_NONE - * @see #SS_SUPER - * @see #SS_SUB - */ - public void setCondense(boolean on) - { - fontFormatting.setCondense(on); - fontFormatting.setFontCondenseModified(on); - } - - /** - * set the escapement type for the font - * - * @param escapementType super or subscript option - * @see #SS_NONE - * @see #SS_SUPER - * @see #SS_SUB - */ + /** + * set the escapement type for the font + * + * @param escapementType super or subscript option + * @see #SS_NONE + * @see #SS_SUPER + * @see #SS_SUB + */ public void setEscapementType(short escapementType) { - switch(escapementType) - { - case HSSFFontFormatting.SS_SUB: - case HSSFFontFormatting.SS_SUPER: - fontFormatting.setEscapementType(escapementType); - fontFormatting.setEscapementTypeModified(true); - break; - case HSSFFontFormatting.SS_NONE: - fontFormatting.setEscapementType(escapementType); - fontFormatting.setEscapementTypeModified(false); - break; - default: - } + switch(escapementType) + { + case HSSFFontFormatting.SS_SUB: + case HSSFFontFormatting.SS_SUPER: + fontFormatting.setEscapementType(escapementType); + fontFormatting.setEscapementTypeModified(true); + break; + case HSSFFontFormatting.SS_NONE: + fontFormatting.setEscapementType(escapementType); + fontFormatting.setEscapementTypeModified(false); + break; + default: + } } /** @@ -338,15 +304,6 @@ public class HSSFFontFormatting fontFormatting.setFontColorIndex(fci); } - /** - * @param modified - * @see org.apache.poi.hssf.record.cf.FontFormatting#setFontCondenseModified(boolean) - */ - public void setFontCondenseModified(boolean modified) - { - fontFormatting.setFontCondenseModified(modified); - } - /** * @param height * @see org.apache.poi.hssf.record.cf.FontFormatting#setFontHeight(short) @@ -413,35 +370,35 @@ public class HSSFFontFormatting fontFormatting.setFontCancellationModified(strike); } - /** - * set the type of underlining type for the font - * - * @param u super or subscript option - * - * @see #U_NONE - * @see #U_SINGLE - * @see #U_DOUBLE - * @see #U_SINGLE_ACCOUNTING - * @see #U_DOUBLE_ACCOUNTING - */ + /** + * set the type of underlining type for the font + * + * @param u super or subscript option + * + * @see #U_NONE + * @see #U_SINGLE + * @see #U_DOUBLE + * @see #U_SINGLE_ACCOUNTING + * @see #U_DOUBLE_ACCOUNTING + */ public void setUnderlineType(short underlineType) { - switch(underlineType) - { - case HSSFFontFormatting.U_SINGLE: - case HSSFFontFormatting.U_DOUBLE: - case HSSFFontFormatting.U_SINGLE_ACCOUNTING: - case HSSFFontFormatting.U_DOUBLE_ACCOUNTING: - fontFormatting.setUnderlineType(underlineType); - setUnderlineTypeModified(true); - break; - - case HSSFFontFormatting.U_NONE: - fontFormatting.setUnderlineType(underlineType); - setUnderlineTypeModified(false); - break; - default: - } + switch(underlineType) + { + case HSSFFontFormatting.U_SINGLE: + case HSSFFontFormatting.U_DOUBLE: + case HSSFFontFormatting.U_SINGLE_ACCOUNTING: + case HSSFFontFormatting.U_DOUBLE_ACCOUNTING: + fontFormatting.setUnderlineType(underlineType); + setUnderlineTypeModified(true); + break; + + case HSSFFontFormatting.U_NONE: + fontFormatting.setUnderlineType(underlineType); + setUnderlineTypeModified(false); + break; + default: + } } /** @@ -452,5 +409,4 @@ public class HSSFFontFormatting { fontFormatting.setUnderlineTypeModified(modified); } - } diff --git a/src/java/org/apache/poi/hssf/usermodel/HSSFPatternFormatting.java b/src/java/org/apache/poi/hssf/usermodel/HSSFPatternFormatting.java index 352a5b4872..b94d19601a 100644 --- a/src/java/org/apache/poi/hssf/usermodel/HSSFPatternFormatting.java +++ b/src/java/org/apache/poi/hssf/usermodel/HSSFPatternFormatting.java @@ -27,44 +27,44 @@ import org.apache.poi.hssf.record.cf.PatternFormatting; */ public class HSSFPatternFormatting { - /** No background */ - public final static short NO_FILL = PatternFormatting.NO_FILL; - /** Solidly filled */ - public final static short SOLID_FOREGROUND = PatternFormatting.SOLID_FOREGROUND; - /** Small fine dots */ - public final static short FINE_DOTS = PatternFormatting.FINE_DOTS; - /** Wide dots */ - public final static short ALT_BARS = PatternFormatting.ALT_BARS; - /** Sparse dots */ - public final static short SPARSE_DOTS = PatternFormatting.SPARSE_DOTS; - /** Thick horizontal bands */ - public final static short THICK_HORZ_BANDS = PatternFormatting.THICK_HORZ_BANDS; - /** Thick vertical bands */ - public final static short THICK_VERT_BANDS = PatternFormatting.THICK_VERT_BANDS; - /** Thick backward facing diagonals */ - public final static short THICK_BACKWARD_DIAG = PatternFormatting.THICK_BACKWARD_DIAG; - /** Thick forward facing diagonals */ - public final static short THICK_FORWARD_DIAG = PatternFormatting.THICK_FORWARD_DIAG; - /** Large spots */ - public final static short BIG_SPOTS = PatternFormatting.BIG_SPOTS; - /** Brick-like layout */ - public final static short BRICKS = PatternFormatting.BRICKS; - /** Thin horizontal bands */ - public final static short THIN_HORZ_BANDS = PatternFormatting.THIN_HORZ_BANDS; - /** Thin vertical bands */ - public final static short THIN_VERT_BANDS = PatternFormatting.THIN_VERT_BANDS; - /** Thin backward diagonal */ - public final static short THIN_BACKWARD_DIAG = PatternFormatting.THIN_BACKWARD_DIAG; - /** Thin forward diagonal */ - public final static short THIN_FORWARD_DIAG = PatternFormatting.THIN_FORWARD_DIAG; - /** Squares */ - public final static short SQUARES = PatternFormatting.SQUARES; - /** Diamonds */ - public final static short DIAMONDS = PatternFormatting.DIAMONDS; - /** Less Dots */ - public final static short LESS_DOTS = PatternFormatting.LESS_DOTS; - /** Least Dots */ - public final static short LEAST_DOTS = PatternFormatting.LEAST_DOTS; + /** No background */ + public final static short NO_FILL = PatternFormatting.NO_FILL; + /** Solidly filled */ + public final static short SOLID_FOREGROUND = PatternFormatting.SOLID_FOREGROUND; + /** Small fine dots */ + public final static short FINE_DOTS = PatternFormatting.FINE_DOTS; + /** Wide dots */ + public final static short ALT_BARS = PatternFormatting.ALT_BARS; + /** Sparse dots */ + public final static short SPARSE_DOTS = PatternFormatting.SPARSE_DOTS; + /** Thick horizontal bands */ + public final static short THICK_HORZ_BANDS = PatternFormatting.THICK_HORZ_BANDS; + /** Thick vertical bands */ + public final static short THICK_VERT_BANDS = PatternFormatting.THICK_VERT_BANDS; + /** Thick backward facing diagonals */ + public final static short THICK_BACKWARD_DIAG = PatternFormatting.THICK_BACKWARD_DIAG; + /** Thick forward facing diagonals */ + public final static short THICK_FORWARD_DIAG = PatternFormatting.THICK_FORWARD_DIAG; + /** Large spots */ + public final static short BIG_SPOTS = PatternFormatting.BIG_SPOTS; + /** Brick-like layout */ + public final static short BRICKS = PatternFormatting.BRICKS; + /** Thin horizontal bands */ + public final static short THIN_HORZ_BANDS = PatternFormatting.THIN_HORZ_BANDS; + /** Thin vertical bands */ + public final static short THIN_VERT_BANDS = PatternFormatting.THIN_VERT_BANDS; + /** Thin backward diagonal */ + public final static short THIN_BACKWARD_DIAG = PatternFormatting.THIN_BACKWARD_DIAG; + /** Thin forward diagonal */ + public final static short THIN_FORWARD_DIAG = PatternFormatting.THIN_FORWARD_DIAG; + /** Squares */ + public final static short SQUARES = PatternFormatting.SQUARES; + /** Diamonds */ + public final static short DIAMONDS = PatternFormatting.DIAMONDS; + /** Less Dots */ + public final static short LESS_DOTS = PatternFormatting.LESS_DOTS; + /** Least Dots */ + public final static short LEAST_DOTS = PatternFormatting.LEAST_DOTS; private PatternFormatting patternFormatting; @@ -72,6 +72,10 @@ public class HSSFPatternFormatting { patternFormatting = new PatternFormatting(); } + protected HSSFPatternFormatting(PatternFormatting patternFormatting) + { + this.patternFormatting = patternFormatting; + } protected PatternFormatting getPatternFormattingBlock() { diff --git a/src/java/org/apache/poi/util/HexRead.java b/src/java/org/apache/poi/util/HexRead.java index 868258d01a..cd11ccc640 100644 --- a/src/java/org/apache/poi/util/HexRead.java +++ b/src/java/org/apache/poi/util/HexRead.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,7 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.util; @@ -25,6 +23,7 @@ import java.util.ArrayList; /** * Utilities to read hex from files. + * TODO - move to test packages * * @author Marc Johnson * @author Glen Stampoultzis (glens at apache.org) @@ -62,10 +61,8 @@ public class HexRead * * @see #readData(String) */ - public static byte[] readData( String filename, String section ) throws IOException - { - File file = new File( filename ); - FileInputStream stream = new FileInputStream( file ); + public static byte[] readData(InputStream stream, String section ) throws IOException { + try { StringBuffer sectionText = new StringBuffer(); @@ -100,6 +97,12 @@ public class HexRead } throw new IOException( "Section '" + section + "' not found" ); } + public static byte[] readData( String filename, String section ) throws IOException + { + File file = new File( filename ); + FileInputStream stream = new FileInputStream( file ); + return readData(stream, section); + } static public byte[] readData( InputStream stream, int eofChar ) throws IOException diff --git a/src/testcases/org/apache/poi/TestPOIDocumentMain.java b/src/testcases/org/apache/poi/TestPOIDocumentMain.java index 5d4d7df19e..2e877acf12 100644 --- a/src/testcases/org/apache/poi/TestPOIDocumentMain.java +++ b/src/testcases/org/apache/poi/TestPOIDocumentMain.java @@ -15,17 +15,17 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - - package org.apache.poi; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + import junit.framework.TestCase; -import java.io.*; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.*; +import org.apache.poi.hssf.HSSFTestDataSamples; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; /** * Tests that POIDocument correctly loads and saves the common @@ -36,85 +36,73 @@ import org.apache.poi.poifs.filesystem.*; * * @author Nick Burch (nick at torchbox dot com) */ -public class TestPOIDocumentMain extends TestCase { +public final class TestPOIDocumentMain extends TestCase { // The POI Documents to work on private POIDocument doc; private POIDocument doc2; - // POIFS primed on the test (two different hssf) data - private POIFSFileSystem pfs; - private POIFSFileSystem pfs2; /** - * Set things up, using a PowerPoint document and - * a Word Document for our testing + * Set things up, two spreadsheets for our testing */ - public void setUp() throws Exception { - String dirnameHSSF = System.getProperty("HSSF.testdata.path"); - String filenameHSSF = dirnameHSSF + "/DateFormats.xls"; - String filenameHSSF2 = dirnameHSSF + "/StringFormulas.xls"; + public void setUp() { + + doc = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls"); + doc2 = HSSFTestDataSamples.openSampleWorkbook("StringFormulas.xls"); + } + + public void testReadProperties() throws Exception { + // We should have both sets + assertNotNull(doc.getDocumentSummaryInformation()); + assertNotNull(doc.getSummaryInformation()); + + // Check they are as expected for the test doc + assertEquals("Administrator", doc.getSummaryInformation().getAuthor()); + assertEquals(0, doc.getDocumentSummaryInformation().getByteCount()); + } - FileInputStream fisHSSF = new FileInputStream(filenameHSSF); - pfs = new POIFSFileSystem(fisHSSF); - doc = new HSSFWorkbook(pfs); + public void testReadProperties2() throws Exception { + // Check again on the word one + assertNotNull(doc2.getDocumentSummaryInformation()); + assertNotNull(doc2.getSummaryInformation()); - FileInputStream fisHSSF2 = new FileInputStream(filenameHSSF2); - pfs2 = new POIFSFileSystem(fisHSSF2); - doc2 = new HSSFWorkbook(pfs2); + assertEquals("Avik Sengupta", doc2.getSummaryInformation().getAuthor()); + assertEquals(null, doc2.getSummaryInformation().getKeywords()); + assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount()); } - - public void testReadProperties() throws Exception { - // We should have both sets - assertNotNull(doc.getDocumentSummaryInformation()); - assertNotNull(doc.getSummaryInformation()); - - // Check they are as expected for the test doc - assertEquals("Administrator", doc.getSummaryInformation().getAuthor()); - assertEquals(0, doc.getDocumentSummaryInformation().getByteCount()); - } - - public void testReadProperties2() throws Exception { - // Check again on the word one - assertNotNull(doc2.getDocumentSummaryInformation()); - assertNotNull(doc2.getSummaryInformation()); - - assertEquals("Avik Sengupta", doc2.getSummaryInformation().getAuthor()); - assertEquals(null, doc2.getSummaryInformation().getKeywords()); - assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount()); - } - public void testWriteProperties() throws Exception { - // Just check we can write them back out into a filesystem - POIFSFileSystem outFS = new POIFSFileSystem(); - doc.readProperties(); - doc.writeProperties(outFS); - - // Should now hold them - assertNotNull( - outFS.createDocumentInputStream("\005SummaryInformation") - ); - assertNotNull( - outFS.createDocumentInputStream("\005DocumentSummaryInformation") - ); - } + public void testWriteProperties() throws Exception { + // Just check we can write them back out into a filesystem + POIFSFileSystem outFS = new POIFSFileSystem(); + doc.readProperties(); + doc.writeProperties(outFS); + + // Should now hold them + assertNotNull( + outFS.createDocumentInputStream("\005SummaryInformation") + ); + assertNotNull( + outFS.createDocumentInputStream("\005DocumentSummaryInformation") + ); + } - public void testWriteReadProperties() throws Exception { + public void testWriteReadProperties() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - // Write them out - POIFSFileSystem outFS = new POIFSFileSystem(); - doc.readProperties(); - doc.writeProperties(outFS); - outFS.writeFilesystem(baos); - - // Create a new version - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - POIFSFileSystem inFS = new POIFSFileSystem(bais); - - // Check they're still there - doc.filesystem = inFS; - doc.readProperties(); - - // Delegate test - testReadProperties(); - } + // Write them out + POIFSFileSystem outFS = new POIFSFileSystem(); + doc.readProperties(); + doc.writeProperties(outFS); + outFS.writeFilesystem(baos); + + // Create a new version + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + POIFSFileSystem inFS = new POIFSFileSystem(bais); + + // Check they're still there + doc.filesystem = inFS; + doc.readProperties(); + + // Delegate test + testReadProperties(); + } } diff --git a/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java b/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java new file mode 100644 index 0000000000..703551f88e --- /dev/null +++ b/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java @@ -0,0 +1,175 @@ +/* ==================================================================== + 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; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; + +/** + * Centralises logic for finding/opening sample files in the src/testcases/org/apache/poi/hssf/hssf/data folder. + * + * @author Josh Micich + */ +public final class HSSFTestDataSamples { + + private static final String TEST_DATA_DIR_SYS_PROPERTY_NAME = "HSSF.testdata.path"; + + private static boolean _isInitialised; + private static File _resolvedDataDir; + /** true if standard system propery is not set, + * but the data is available on the test runtime classpath */ + private static boolean _sampleDataIsAvaliableOnClassPath; + + /** + * Opens a sample file from the standard HSSF test data directory + * + * @return an open InputStream for the specified sample file + */ + public static InputStream openSampleFileStream(String sampleFileName) { + + if(!_isInitialised) { + try { + initialise(); + } finally { + _isInitialised = true; + } + } + if (_sampleDataIsAvaliableOnClassPath) { + InputStream result = openClasspathResource(sampleFileName); + if(result == null) { + throw new RuntimeException("specified test sample file '" + sampleFileName + + "' not found on the classpath"); + } +// System.out.println("opening cp: " + sampleFileName); + // wrap to avoid temp warning method about auto-closing input stream + return new NonSeekableInputStream(result); + } + if (_resolvedDataDir == null) { + throw new RuntimeException("Must set system property '" + + TEST_DATA_DIR_SYS_PROPERTY_NAME + + "' properly before running tests"); + } + + File f = new File(_resolvedDataDir, sampleFileName); + if (!f.exists()) { + throw new RuntimeException("Sample file '" + sampleFileName + + "' not found in data dir '" + _resolvedDataDir.getAbsolutePath() + "'"); + } +// System.out.println("opening " + f.getAbsolutePath()); + try { + return new FileInputStream(f); + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + } + + private static void initialise() { + String dataDirName = System.getProperty(TEST_DATA_DIR_SYS_PROPERTY_NAME); + if (dataDirName == null) { + // check to see if we can just get the resources from the classpath + InputStream is = openClasspathResource("SampleSS.xls"); + if(is != null) { + try { + is.close(); // be nice + } catch (IOException e) { + throw new RuntimeException(e); + } + _sampleDataIsAvaliableOnClassPath = true; + return; + } + + + throw new RuntimeException("Must set system property '" + + TEST_DATA_DIR_SYS_PROPERTY_NAME + + "' before running tests"); + } + File dataDir = new File(dataDirName); + if (!dataDir.exists()) { + throw new RuntimeException("Data dir '" + dataDirName + + "' specified by system property '" + + TEST_DATA_DIR_SYS_PROPERTY_NAME + "' does not exist"); + } + // convert to canonical file, to make any subsequent error messages clearer. + try { + _resolvedDataDir = dataDir.getCanonicalFile(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Opens a test sample file from the 'data' sub-package of this class's package. + * @return null if the sample file is not deployed on the classpath. + */ + private static InputStream openClasspathResource(String sampleFileName) { + return HSSFTestDataSamples.class.getResourceAsStream("data/" + sampleFileName); + } + + private static final class NonSeekableInputStream extends InputStream { + + private final InputStream _is; + + public NonSeekableInputStream(InputStream is) { + _is = is; + } + + public int read() throws IOException { + return _is.read(); + } + public int read(byte[] b, int off, int len) throws IOException { + return _is.read(b, off, len); + } + public boolean markSupported() { + return false; + } + public void close() throws IOException { + _is.close(); + } + } + + public static HSSFWorkbook openSampleWorkbook(String sampleFileName) { + try { + return new HSSFWorkbook(openSampleFileStream(sampleFileName)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + /** + * Writes a spreadsheet to a ByteArrayOutputStream and reads it back + * from a ByteArrayInputStream.

+ * Useful for verifying that the serialisation round trip + */ + public static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) { + + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); + original.write(baos); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + return new HSSFWorkbook(bais); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java index 049b43ef93..74e1ceb4a5 100644 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java +++ b/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java @@ -16,109 +16,108 @@ ==================================================================== */ package org.apache.poi.hssf.eventusermodel; -import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; -import org.apache.poi.hssf.eventusermodel.HSSFListener; - -import java.io.File; -import java.io.FileInputStream; +import java.io.InputStream; import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; +import org.apache.poi.hssf.record.ContinueRecord; import org.apache.poi.hssf.record.DVALRecord; import org.apache.poi.hssf.record.DVRecord; import org.apache.poi.hssf.record.EOFRecord; import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.ContinueRecord; import org.apache.poi.hssf.record.SelectionRecord; import org.apache.poi.hssf.record.WindowTwoRecord; import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -import junit.framework.TestCase; - -public class TestHSSFEventFactory extends TestCase { - private String dirname; +/** + * + */ +public final class TestHSSFEventFactory extends TestCase { - public TestHSSFEventFactory() { - dirname = System.getProperty("HSSF.testdata.path"); + private static final InputStream openSample(String sampleFileName) { + return HSSFTestDataSamples.openSampleFileStream(sampleFileName); } public void testWithMissingRecords() throws Exception { - File f = new File(dirname + "/SimpleWithSkip.xls"); HSSFRequest req = new HSSFRequest(); MockHSSFListener mockListen = new MockHSSFListener(); req.addListenerForAllRecords(mockListen); - POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f)); + POIFSFileSystem fs = new POIFSFileSystem(openSample("SimpleWithSkip.xls")); HSSFEventFactory factory = new HSSFEventFactory(); factory.processWorkbookEvents(req, fs); + Record[] recs = mockListen.getRecords(); // Check we got the records - System.out.println("Processed, found " + mockListen.records.size() + " records"); - assertTrue( mockListen.records.size() > 100 ); + assertTrue( recs.length > 100 ); // Check that the last few records are as we expect // (Makes sure we don't accidently skip the end ones) - int numRec = mockListen.records.size(); - assertEquals(WindowTwoRecord.class, mockListen.records.get(numRec-3).getClass()); - assertEquals(SelectionRecord.class, mockListen.records.get(numRec-2).getClass()); - assertEquals(EOFRecord.class, mockListen.records.get(numRec-1).getClass()); + int numRec = recs.length; + assertEquals(WindowTwoRecord.class, recs[numRec-3].getClass()); + assertEquals(SelectionRecord.class, recs[numRec-2].getClass()); + assertEquals(EOFRecord.class, recs[numRec-1].getClass()); } public void testWithCrazyContinueRecords() throws Exception { // Some files have crazy ordering of their continue records // Check that we don't break on them (bug #42844) - - File f = new File(dirname + "/ContinueRecordProblem.xls"); HSSFRequest req = new HSSFRequest(); MockHSSFListener mockListen = new MockHSSFListener(); req.addListenerForAllRecords(mockListen); - POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f)); + POIFSFileSystem fs = new POIFSFileSystem(openSample("ContinueRecordProblem.xls")); HSSFEventFactory factory = new HSSFEventFactory(); factory.processWorkbookEvents(req, fs); + Record[] recs = mockListen.getRecords(); // Check we got the records - System.out.println("Processed, found " + mockListen.records.size() + " records"); - assertTrue( mockListen.records.size() > 100 ); + assertTrue( recs.length > 100 ); // And none of them are continue ones - Record[] r = (Record[])mockListen.records.toArray( - new Record[mockListen.records.size()] ); - for(int i=0; i 40960); } - public void testStringConcat() throws Exception { - String path = System.getProperty("HSSF.testdata.path"); - FileInputStream fin = new FileInputStream(path + File.separator + "SimpleWithFormula.xls"); + public void testStringConcat() { - ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); + ExcelExtractor extractor = createExtractor("SimpleWithFormula.xls"); // Comes out as NaN if treated as a number // And as XYZ if treated as a string @@ -97,11 +106,9 @@ public class TestExcelExtractor extends TestCase { assertEquals("Sheet1\nreplaceme\nreplaceme\nCONCATENATE(A1,A2)\nSheet2\nSheet3\n", extractor.getText()); } - public void testStringFormula() throws Exception { - String path = System.getProperty("HSSF.testdata.path"); - FileInputStream fin = new FileInputStream(path + File.separator + "StringFormulas.xls"); + public void testStringFormula() { - ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); + ExcelExtractor extractor = createExtractor("StringFormulas.xls"); // Comes out as NaN if treated as a number // And as XYZ if treated as a string diff --git a/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java index 63f5cc317e..843e17d2a6 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,36 +14,28 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.record; -import java.io.File; -import java.io.FileInputStream; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import java.io.InputStream; +import junit.framework.AssertionFailedError; import junit.framework.TestCase; -public class TestBOFRecord extends TestCase -{ - private String _test_file_path; - private static final String _test_file_path_property = "HSSF.testdata.path"; - - public TestBOFRecord() - { - super(); - _test_file_path = System.getProperty( _test_file_path_property ) + - File.separator + "bug_42794.xls"; - } - +import org.apache.poi.hssf.HSSFTestDataSamples; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +/** + * + */ +public final class TestBOFRecord extends TestCase { public void testBOFRecord() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem( - new FileInputStream(_test_file_path) - ); - - // This used to throw an error before - HSSFWorkbook hssf = new HSSFWorkbook(fs); + InputStream is = HSSFTestDataSamples.openSampleFileStream("bug_42794.xls"); + + // This used to throw an error before + try { + new HSSFWorkbook(is); + } catch (ArrayIndexOutOfBoundsException e) { + throw new AssertionFailedError("Identified bug 42794"); + } } } diff --git a/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java index e65025a31d..c068f29a67 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java @@ -182,14 +182,13 @@ public final class TestCFRuleRecord extends TestCase // Check for defaults assertFalse(fontFormatting.isEscapementTypeModified()); assertFalse(fontFormatting.isFontCancellationModified()); - assertFalse(fontFormatting.isFontCondenseModified()); assertFalse(fontFormatting.isFontOutlineModified()); assertFalse(fontFormatting.isFontShadowModified()); assertFalse(fontFormatting.isFontStyleModified()); assertFalse(fontFormatting.isUnderlineTypeModified()); + assertFalse(fontFormatting.isFontWeightModified()); assertFalse(fontFormatting.isBold()); - assertFalse(fontFormatting.isCondenseOn()); assertFalse(fontFormatting.isItalic()); assertFalse(fontFormatting.isOutlineOn()); assertFalse(fontFormatting.isShadowOn()); @@ -198,7 +197,7 @@ public final class TestCFRuleRecord extends TestCase assertEquals(0, fontFormatting.getEscapementType()); assertEquals(-1, fontFormatting.getFontColorIndex()); assertEquals(-1, fontFormatting.getFontHeight()); - assertEquals(400, fontFormatting.getFontWeight()); + assertEquals(0, fontFormatting.getFontWeight()); assertEquals(0, fontFormatting.getUnderlineType()); fontFormatting.setBold(true); @@ -206,11 +205,6 @@ public final class TestCFRuleRecord extends TestCase fontFormatting.setBold(false); assertFalse(fontFormatting.isBold()); - fontFormatting.setCondense(true); - assertTrue(fontFormatting.isCondenseOn()); - fontFormatting.setCondense(false); - assertFalse(fontFormatting.isCondenseOn()); - fontFormatting.setEscapementType(FontFormatting.SS_SUB); assertEquals(FontFormatting.SS_SUB, fontFormatting.getEscapementType()); fontFormatting.setEscapementType(FontFormatting.SS_SUPER); @@ -223,6 +217,11 @@ public final class TestCFRuleRecord extends TestCase fontFormatting.setEscapementTypeModified(true); assertTrue(fontFormatting.isEscapementTypeModified()); + fontFormatting.setFontWieghtModified(false); + assertFalse(fontFormatting.isFontWeightModified()); + fontFormatting.setFontWieghtModified(true); + assertTrue(fontFormatting.isFontWeightModified()); + fontFormatting.setFontCancellationModified(false); assertFalse(fontFormatting.isFontCancellationModified()); fontFormatting.setFontCancellationModified(true); @@ -231,11 +230,6 @@ public final class TestCFRuleRecord extends TestCase fontFormatting.setFontColorIndex((short)10); assertEquals(10,fontFormatting.getFontColorIndex()); - fontFormatting.setFontCondenseModified(false); - assertFalse(fontFormatting.isFontCondenseModified()); - fontFormatting.setFontCondenseModified(true); - assertTrue(fontFormatting.isFontCondenseModified()); - fontFormatting.setFontHeight((short)100); assertEquals(100,fontFormatting.getFontHeight()); diff --git a/src/testcases/org/apache/poi/hssf/record/TestChartTitleFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/TestChartTitleFormatRecord.java index d9931ef7f5..5e285021b1 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestChartTitleFormatRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestChartTitleFormatRecord.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,65 +14,57 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.record; -import java.io.File; -import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; import org.apache.poi.hssf.eventusermodel.HSSFListener; import org.apache.poi.hssf.eventusermodel.HSSFRequest; -import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; +/** + * + */ +public final class TestChartTitleFormatRecord extends TestCase { -import junit.framework.TestCase; - -public class TestChartTitleFormatRecord extends TestCase -{ - private String _test_file_path; - private static final String _test_file_path_property = "HSSF.testdata.path"; - - public TestChartTitleFormatRecord() - { - super(); - _test_file_path = System.getProperty( _test_file_path_property ) + - File.separator + "WithFormattedGraphTitle.xls"; - } - - public void testRecord() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem( - new FileInputStream(_test_file_path) - ); - - // Check we can open the file via usermodel - HSSFWorkbook hssf = new HSSFWorkbook(fs); - - // Now process it through eventusermodel, and - // look out for the title records - ChartTitleFormatRecordGrabber grabber = - new ChartTitleFormatRecordGrabber(); - InputStream din = fs.createDocumentInputStream("Workbook"); - HSSFRequest req = new HSSFRequest(); - req.addListenerForAllRecords(grabber); - HSSFEventFactory factory = new HSSFEventFactory(); - factory.processEvents(req, din); - din.close(); - - // Should've found one - assertEquals(1, grabber.chartTitleFormatRecords.size()); - // And it should be of something interesting - ChartTitleFormatRecord r = - (ChartTitleFormatRecord)grabber.chartTitleFormatRecords.get(0); - assertEquals(3, r.getFormatCount()); - } - - public static class ChartTitleFormatRecordGrabber implements HSSFListener { - private ArrayList chartTitleFormatRecords = new ArrayList(); + public void testRecord() throws Exception { + POIFSFileSystem fs = new POIFSFileSystem( + HSSFTestDataSamples.openSampleFileStream("WithFormattedGraphTitle.xls")); + + // Check we can open the file via usermodel + HSSFWorkbook hssf = new HSSFWorkbook(fs); + + // Now process it through eventusermodel, and + // look out for the title records + ChartTitleFormatRecordGrabber grabber = new ChartTitleFormatRecordGrabber(); + InputStream din = fs.createDocumentInputStream("Workbook"); + HSSFRequest req = new HSSFRequest(); + req.addListenerForAllRecords(grabber); + HSSFEventFactory factory = new HSSFEventFactory(); + factory.processEvents(req, din); + din.close(); + + // Should've found one + assertEquals(1, grabber.chartTitleFormatRecords.size()); + // And it should be of something interesting + ChartTitleFormatRecord r = + (ChartTitleFormatRecord)grabber.chartTitleFormatRecords.get(0); + assertEquals(3, r.getFormatCount()); + } + + private static final class ChartTitleFormatRecordGrabber implements HSSFListener { + private final List chartTitleFormatRecords; + + public ChartTitleFormatRecordGrabber() { + chartTitleFormatRecords = new ArrayList(); + } public void processRecord(Record record) { if(record instanceof ChartTitleFormatRecord) { @@ -82,6 +73,6 @@ public class TestChartTitleFormatRecord extends TestCase ); } } - - } + + } } diff --git a/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java index 9cf746ce00..abe6943c79 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,8 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - - package org.apache.poi.hssf.record; @@ -39,36 +36,29 @@ import junit.framework.TestCase; * * @author Andrew C. Oliver */ -public class TestFormulaRecord - extends TestCase -{ - - public TestFormulaRecord(String name) - { - super(name); - } +public final class TestFormulaRecord extends TestCase { - public void testCreateFormulaRecord () { - FormulaRecord record = new FormulaRecord(); - record.setColumn((short)0); - //record.setRow((short)1); - record.setRow(1); - record.setXFIndex((short)4); - - assertEquals(record.getColumn(),(short)0); - //assertEquals(record.getRow(),(short)1); - assertEquals((short)record.getRow(),(short)1); - assertEquals(record.getXFIndex(),(short)4); - } - - /** - * Make sure a NAN value is preserved - * This formula record is a representation of =1/0 at row 0, column 0 - */ - public void testCheckNanPreserve() { - byte[] formulaByte = new byte[29]; - for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0; - formulaByte[4] = (byte)0x0F; + public void testCreateFormulaRecord () { + FormulaRecord record = new FormulaRecord(); + record.setColumn((short)0); + //record.setRow((short)1); + record.setRow(1); + record.setXFIndex((short)4); + + assertEquals(record.getColumn(),(short)0); + //assertEquals(record.getRow(),(short)1); + assertEquals((short)record.getRow(),(short)1); + assertEquals(record.getXFIndex(),(short)4); + } + + /** + * Make sure a NAN value is preserved + * This formula record is a representation of =1/0 at row 0, column 0 + */ + public void testCheckNanPreserve() { + byte[] formulaByte = new byte[29]; + for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0; + formulaByte[4] = (byte)0x0F; formulaByte[6] = (byte)0x02; formulaByte[8] = (byte)0x07; formulaByte[12] = (byte)0xFF; @@ -80,7 +70,7 @@ public class TestFormulaRecord formulaByte[23] = (byte)0x01; formulaByte[25] = (byte)0x1E; formulaByte[28] = (byte)0x06; - + FormulaRecord record = new FormulaRecord(new TestcaseRecordInputStream(FormulaRecord.sid, (short)29, formulaByte)); assertEquals("Row", 0, record.getRow()); assertEquals("Column", 0, record.getColumn()); @@ -92,19 +82,18 @@ public class TestFormulaRecord for (int i = 5; i < 13;i++) { assertEquals("FormulaByte NaN doesn't match", formulaByte[i], output[i+4]); } + } + + /** + * Tests to see if the shared formula cells properly reserialize the expPtg + * + */ + public void testExpFormula() { + byte[] formulaByte = new byte[27]; - } - - /** - * Tests to see if the shared formula cells properly reserialize the expPtg - * - */ - public void testExpFormula() { - byte[] formulaByte = new byte[27]; - for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0; - - formulaByte[4] =(byte)0x0F; + + formulaByte[4] =(byte)0x0F; formulaByte[14]=(byte)0x08; formulaByte[18]=(byte)0xE0; formulaByte[19]=(byte)0xFD; @@ -115,19 +104,19 @@ public class TestFormulaRecord assertEquals("Column", 0, record.getColumn()); byte[] output = record.serialize(); assertEquals("Output size", 31, output.length); //includes sid+recordlength - assertEquals("Offset 22", 1, output[26]); - } - - public void testWithConcat() throws Exception { - // =CHOOSE(2,A2,A3,A4) - byte[] data = new byte[] { - 6, 0, 68, 0, - 1, 0, 1, 0, 15, 0, 0, 0, 0, 0, 0, 0, 57, + assertEquals("Offset 22", 1, output[26]); + } + + public void testWithConcat() throws Exception { + // =CHOOSE(2,A2,A3,A4) + byte[] data = new byte[] { + 6, 0, 68, 0, + 1, 0, 1, 0, 15, 0, 0, 0, 0, 0, 0, 0, 57, 64, 0, 0, 12, 0, 12, -4, 46, 0, - 30, 2, 0, // Int - 2 + 30, 2, 0, // Int - 2 25, 4, 3, 0, // Attr - 8, 0, // Concat - 17, 0, // Range + 8, 0, // Concat + 17, 0, // Range 26, 0, 35, 0, // Bit like an attr 36, 1, 0, 0, -64, // Ref - A2 25, 8, 21, 0, // Attr @@ -136,43 +125,35 @@ public class TestFormulaRecord 36, 3, 0, 0, -64, // Ref - A4 25, 8, 3, 0, // Attr 66, 4, 100, 0 // CHOOSE - }; - RecordInputStream inp = new RecordInputStream( - new ByteArrayInputStream(data) - ); - inp.nextRecord(); - - FormulaRecord fr = new FormulaRecord(inp); - - assertEquals(14, fr.getNumberOfExpressionTokens()); - assertEquals(IntPtg.class, fr.getParsedExpression().get(0).getClass()); - assertEquals(AttrPtg.class, fr.getParsedExpression().get(1).getClass()); - assertEquals(ConcatPtg.class, fr.getParsedExpression().get(2).getClass()); - assertEquals(UnknownPtg.class, fr.getParsedExpression().get(3).getClass()); - assertEquals(RangePtg.class, fr.getParsedExpression().get(4).getClass()); - assertEquals(UnknownPtg.class, fr.getParsedExpression().get(5).getClass()); - assertEquals(AttrPtg.class, fr.getParsedExpression().get(6).getClass()); - assertEquals(ReferencePtg.class, fr.getParsedExpression().get(7).getClass()); - assertEquals(AttrPtg.class, fr.getParsedExpression().get(8).getClass()); - assertEquals(ReferencePtg.class, fr.getParsedExpression().get(9).getClass()); - assertEquals(AttrPtg.class, fr.getParsedExpression().get(10).getClass()); - assertEquals(ReferencePtg.class, fr.getParsedExpression().get(11).getClass()); - assertEquals(AttrPtg.class, fr.getParsedExpression().get(12).getClass()); - assertEquals(FuncVarPtg.class, fr.getParsedExpression().get(13).getClass()); - - FuncVarPtg choose = (FuncVarPtg)fr.getParsedExpression().get(13); - assertEquals("CHOOSE", choose.getName()); - } - - - public static void main(String [] ignored_args) - { - String filename = System.getProperty("HSSF.testdata.path"); - - System.out - .println("Testing org.apache.poi.hssf.record.FormulaRecord"); - junit.textui.TestRunner.run(TestFormulaRecord.class); - } - - + }; + RecordInputStream inp = new RecordInputStream( + new ByteArrayInputStream(data) + ); + inp.nextRecord(); + + FormulaRecord fr = new FormulaRecord(inp); + + assertEquals(14, fr.getNumberOfExpressionTokens()); + assertEquals(IntPtg.class, fr.getParsedExpression().get(0).getClass()); + assertEquals(AttrPtg.class, fr.getParsedExpression().get(1).getClass()); + assertEquals(ConcatPtg.class, fr.getParsedExpression().get(2).getClass()); + assertEquals(UnknownPtg.class, fr.getParsedExpression().get(3).getClass()); + assertEquals(RangePtg.class, fr.getParsedExpression().get(4).getClass()); + assertEquals(UnknownPtg.class, fr.getParsedExpression().get(5).getClass()); + assertEquals(AttrPtg.class, fr.getParsedExpression().get(6).getClass()); + assertEquals(ReferencePtg.class, fr.getParsedExpression().get(7).getClass()); + assertEquals(AttrPtg.class, fr.getParsedExpression().get(8).getClass()); + assertEquals(ReferencePtg.class, fr.getParsedExpression().get(9).getClass()); + assertEquals(AttrPtg.class, fr.getParsedExpression().get(10).getClass()); + assertEquals(ReferencePtg.class, fr.getParsedExpression().get(11).getClass()); + assertEquals(AttrPtg.class, fr.getParsedExpression().get(12).getClass()); + assertEquals(FuncVarPtg.class, fr.getParsedExpression().get(13).getClass()); + + FuncVarPtg choose = (FuncVarPtg)fr.getParsedExpression().get(13); + assertEquals("CHOOSE", choose.getName()); + } + + public static void main(String [] ignored_args) { + junit.textui.TestRunner.run(TestFormulaRecord.class); + } } diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java b/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java index 4f721a798e..6927c6820a 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java +++ b/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,7 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.record; @@ -34,20 +32,8 @@ import org.apache.poi.util.HexRead; * @author Andrew C. Oliver (acoliver at apache dot org) * @author Csaba Nagy (ncsaba at yahoo dot com) */ +public final class TestRecordFactory extends TestCase { -public class TestRecordFactory - extends TestCase -{ - - /** - * Creates new TestRecordFactory - * @param testCaseName - */ - - public TestRecordFactory(String testCaseName) - { - super(testCaseName); - } /** * TEST NAME: Test Basic Record Construction

@@ -57,13 +43,9 @@ public class TestRecordFactory * FAILURE: The wrong records are creates or contain the wrong values

* */ - - public void testBasicRecordConstruction() - throws Exception - { + public void testBasicRecordConstruction() { short recType = BOFRecord.sid; - byte[] data = new byte[] - { + byte[] data = { 0, 6, 5, 0, -2, 28, -51, 7, -55, 64, 0, 0, 6, 1, 0, 0 }; short size = 16; @@ -106,13 +88,9 @@ public class TestRecordFactory * FAILURE: The wrong records are created or contain the wrong values

* */ - - public void testSpecial() - throws Exception - { + public void testSpecial() { short recType = RKRecord.sid; - byte[] data = new byte[] - { + byte[] data = { 0, 0, 0, 0, 21, 0, 0, 0, 0, 0 }; short size = 10; @@ -138,10 +116,8 @@ public class TestRecordFactory * FAILURE: The wrong records are created or contain the wrong values

* */ - public void testContinuedUnknownRecord() - { - byte[] data = new byte[] - { + public void testContinuedUnknownRecord() { + byte[] data = { 0, -1, 0, 0, // an unknown record with 0 length 0x3C , 0, 3, 0, 1, 2, 3, // a continuation record with 3 bytes of data 0x3C , 0, 1, 0, 4 // one more continuation record with 1 byte of data @@ -178,7 +154,7 @@ public class TestRecordFactory */ public void testMixedContinue() throws Exception { /** - * Taken from a real file $HSSF.testdata.path/39512.xls. See Bug 39512 for details. + * Taken from a real test sample file 39512.xls. See Bug 39512 for details. */ String dump = //OBJ @@ -228,10 +204,7 @@ public class TestRecordFactory assertTrue(Arrays.equals(data, ser)); } - public static void main(String [] ignored_args) - { - System.out - .println("Testing org.apache.poi.hssf.record.TestRecordFactory"); + public static void main(String [] ignored_args) { junit.textui.TestRunner.run(TestRecordFactory.class); } } diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java b/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java index 0e530a64a4..1cb1252b45 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java +++ b/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,51 +14,47 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.record; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.IntMapper; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import java.io.File; +import java.io.IOException; +import java.io.InputStream; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; +import org.apache.poi.util.HexRead; +import org.apache.poi.util.IntMapper; + /** * Exercise the SSTDeserializer class. * * @author Glen Stampoultzis (glens at apache.org) */ -public class TestSSTDeserializer - extends TestCase -{ - private String _test_file_path; - private static final String _test_file_path_property = "HSSF.testdata.path"; - - public TestSSTDeserializer( String s ) - { - super( s ); - } +public final class TestSSTDeserializer extends TestCase { - protected void setUp() throws Exception - { - _test_file_path = System.getProperty( _test_file_path_property ); - } private byte[] joinArray(byte[] array1, byte[] array2) { - byte[] bigArray = new byte[array1.length+array2.length]; - System.arraycopy(array1, 0, bigArray, 0, array1.length); - System.arraycopy(array2, 0, bigArray, array1.length, array2.length); - return bigArray; + byte[] bigArray = new byte[array1.length + array2.length]; + System.arraycopy(array1, 0, bigArray, 0, array1.length); + System.arraycopy(array2, 0, bigArray, array1.length, array2.length); + return bigArray; + } + + private static byte[] readSampleHexData(String sampleFileName, String sectionName) { + InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName); + try { + return HexRead.readData(is, sectionName); + } catch (IOException e) { + throw new RuntimeException(e); + } } public void testSpanRichTextToPlainText() throws Exception { - byte[] header = HexRead.readData( _test_file_path + File.separator + "richtextdata.txt", "header" ); - byte[] continueBytes = HexRead.readData( _test_file_path + File.separator + "richtextdata.txt", "continue1" ); + byte[] header = readSampleHexData("richtextdata.txt", "header" ); + byte[] continueBytes = readSampleHexData("richtextdata.txt", "continue1" ); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); @@ -74,8 +69,8 @@ public class TestSSTDeserializer public void testContinuationWithNoOverlap() throws Exception { - byte[] header = HexRead.readData( _test_file_path + File.separator + "evencontinuation.txt", "header" ); - byte[] continueBytes = HexRead.readData( _test_file_path + File.separator + "evencontinuation.txt", "continue1" ); + byte[] header = readSampleHexData("evencontinuation.txt", "header" ); + byte[] continueBytes = readSampleHexData("evencontinuation.txt", "continue1" ); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); @@ -93,10 +88,10 @@ public class TestSSTDeserializer public void testStringAcross2Continuations() throws Exception { - byte[] header = HexRead.readData( _test_file_path + File.separator + "stringacross2continuations.txt", "header" ); - byte[] continue1 = HexRead.readData( _test_file_path + File.separator + "stringacross2continuations.txt", "continue1" ); + byte[] header = readSampleHexData("stringacross2continuations.txt", "header" ); + byte[] continue1 = readSampleHexData("stringacross2continuations.txt", "continue1" ); continue1 = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continue1.length, continue1); - byte[] continue2 = HexRead.readData( _test_file_path + File.separator + "stringacross2continuations.txt", "continue2" ); + byte[] continue2 = readSampleHexData("stringacross2continuations.txt", "continue2" ); continue2 = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continue2.length, continue2); byte[] bytes = joinArray(header, continue1); @@ -111,11 +106,9 @@ public class TestSSTDeserializer assertEquals( "At a dinner partyAt a dinner party", strings.get( 1 ) + "" ); } - public void testExtendedStrings() - throws Exception - { - byte[] header = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "rich-header" ); - byte[] continueBytes = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "rich-continue1" ); + public void testExtendedStrings() { + byte[] header = readSampleHexData("extendedtextstrings.txt", "rich-header" ); + byte[] continueBytes = readSampleHexData("extendedtextstrings.txt", "rich-continue1" ); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); @@ -126,8 +119,8 @@ public class TestSSTDeserializer assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" ); - header = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "norich-header" ); - continueBytes = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "norich-continue1" ); + header = readSampleHexData("extendedtextstrings.txt", "norich-header" ); + continueBytes = readSampleHexData("extendedtextstrings.txt", "norich-continue1" ); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); @@ -136,7 +129,5 @@ public class TestSSTDeserializer deserializer.manufactureStrings( 1, in); assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" ); - } - } diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java index f7b22f25e9..de443e1897 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,54 +14,33 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.record; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.Iterator; + import junit.framework.TestCase; + +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.HexRead; import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianConsts; -import org.apache.poi.util.TempFile; - -import java.io.*; -import java.util.Arrays; -import java.util.Iterator; /** * @author Marc Johnson (mjohnson at apache dot org) * @author Glen Stampoultzis (glens at apache.org) */ -public class TestSSTRecord - extends TestCase -{ - private String _test_file_path; - private static final String _test_file_path_property = "HSSF.testdata.path"; - - /** - * Creates new TestSSTRecord - * - * @param name - */ - - public TestSSTRecord( String name ) - { - super( name ); - _test_file_path = System.getProperty( _test_file_path_property ); - } +public final class TestSSTRecord extends TestCase { /** * test processContinueRecord - * - * @exception IOException */ - - public void testProcessContinueRecord() - throws IOException - { + public void testProcessContinueRecord() { //jmh byte[] testdata = HexRead.readData( _test_file_path + File.separator + "BigSSTRecord" ); //jmh byte[] input = new byte[testdata.length - 4]; //jmh @@ -182,9 +160,7 @@ public class TestSSTRecord * @exception IOException */ - public void testHugeStrings() - throws IOException - { + public void testHugeStrings() { SSTRecord record = new SSTRecord(); byte[][] bstrings = { @@ -265,12 +241,8 @@ public class TestSSTRecord /** * test SSTRecord boundary conditions - * - * @exception IOException */ - public void testSSTRecordBug() - throws IOException - { + public void testSSTRecordBug() { // create an SSTRecord and write a certain pattern of strings // to it ... then serialize it and verify the content SSTRecord record = new SSTRecord(); @@ -349,38 +321,6 @@ public class TestSSTRecord } } - /** - * test reader constructor - * - * @exception IOException - */ - - public void testReaderConstructor() - throws IOException - { -/* JMH this test case data is crap because it does not contain a full record. Ie the last string - is missing a record - - byte[] testdata = HexRead.readData( _test_file_path + File.separator + "BigSSTRecord" ); -// byte[] input = new byte[testdata.length - 4]; - - System.arraycopy( testdata, 4, input, 0, input.length ); - SSTRecord record = new SSTRecord( new TestcaseRecordInputStream(LittleEndian.getShort( testdata, 0 ), - LittleEndian.getShort( testdata, 2 ), - input) ); - - assertEquals( 1464, record.getNumStrings() ); - assertEquals( 688, record.getNumUniqueStrings() ); - assertEquals( 492, record.countStrings() ); - assertEquals( 1, record.getDeserializer().getContinuationExpectedChars() ); - assertEquals( "Consolidated B-24J Liberator The Dragon & His Tai", - record.getDeserializer().getUnfinishedString() ); -// assertEquals( 52, record.getDeserializer().getTotalLength() ); -// assertEquals( 3, record.getDeserializer().getStringDataOffset() ); - assertTrue( !record.getDeserializer().isWideChar() ); - */ - } - /** * test simple constructor */ @@ -413,9 +353,7 @@ public class TestSSTRecord * @param ignored_args */ - public static void main( String[] ignored_args ) - { - System.out.println( "Testing hssf.record.SSTRecord functionality" ); + public static void main( String[] ignored_args ) { junit.textui.TestRunner.run( TestSSTRecord.class ); } @@ -425,25 +363,16 @@ public class TestSSTRecord public void testReadWriteDuplicatedRichText1() throws Exception { - File file = new File( _test_file_path + File.separator + "duprich1.xls" ); - InputStream stream = new FileInputStream( file ); - HSSFWorkbook wb = new HSSFWorkbook( stream ); - stream.close(); + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("duprich1.xls"); HSSFSheet sheet = wb.getSheetAt( 1 ); assertEquals( "01/05 (Wed)", sheet.getRow( 0 ).getCell( (short) 8 ).getStringCellValue() ); assertEquals( "01/05 (Wed)", sheet.getRow( 1 ).getCell( (short) 8 ).getStringCellValue() ); - file = TempFile.createTempFile( "testout", "xls" ); - FileOutputStream outStream = new FileOutputStream( file ); - wb.write( outStream ); - outStream.close(); - file.delete(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + wb.write( baos ); // test the second file. - file = new File( _test_file_path + File.separator + "duprich2.xls" ); - stream = new FileInputStream( file ); - wb = new HSSFWorkbook( stream ); - stream.close(); + wb = HSSFTestDataSamples.openSampleWorkbook("duprich2.xls"); sheet = wb.getSheetAt( 0 ); int row = 0; assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() ); @@ -453,12 +382,6 @@ public class TestSSTRecord assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() ); assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() ); -// file = new File("/tryme.xls"); - file = TempFile.createTempFile( "testout", ".xls" ); - outStream = new FileOutputStream( file ); - wb.write( outStream ); - outStream.close(); - file.delete(); + wb.write( baos ); } - } diff --git a/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java index 2677c4c42e..6ec0803849 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java @@ -14,39 +14,23 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.record; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; - import junit.framework.TestCase; -import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -public class TestUnicodeNameRecord extends TestCase { - private String _test_file_path; - private static final String _test_file_path_property = "HSSF.testdata.path"; - - public TestUnicodeNameRecord() - { - super(); - _test_file_path = System.getProperty( _test_file_path_property ) + - File.separator + "unicodeNameRecord.xls"; - } +/** + * + */ +public final class TestUnicodeNameRecord extends TestCase { - public void testReadBook() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem( - new FileInputStream(_test_file_path) - ); + public void testReadBook() { // This bit used to crash - HSSFWorkbook book = new HSSFWorkbook(fs); - HSSFSheet sheet = book.getSheetAt(0); + HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("unicodeNameRecord.xls"); + book.getSheetAt(0); } } diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java index 8e8a72ece7..5c14b70e15 100755 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java +++ b/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java @@ -29,6 +29,7 @@ import java.util.zip.CRC32; import junit.framework.AssertionFailedError; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.record.BlankRecord; import org.apache.poi.hssf.record.FormulaRecord; import org.apache.poi.hssf.record.Record; @@ -250,22 +251,14 @@ public class TestValueRecordsAggregate extends TestCase * */ public void testSpuriousSharedFormulaFlag() { - File dataDir = new File(System.getProperty("HSSF.testdata.path")); - File testFile = new File(dataDir, ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE); - long actualCRC = getFileCRC(testFile); + long actualCRC = getFileCRC(HSSFTestDataSamples.openSampleFileStream(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE)); long expectedCRC = 2277445406L; if(actualCRC != expectedCRC) { System.err.println("Expected crc " + expectedCRC + " but got " + actualCRC); throw failUnexpectedTestFileChange(); } - HSSFWorkbook wb; - try { - FileInputStream in = new FileInputStream(testFile); - wb = new HSSFWorkbook(in); - } catch (IOException e) { - throw new RuntimeException(e); - } + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE); HSSFSheet s = wb.getSheetAt(0); // Sheet1 @@ -311,11 +304,10 @@ public class TestValueRecordsAggregate extends TestCase /** * gets a CRC checksum for the content of a file */ - private static long getFileCRC(File f) { + private static long getFileCRC(InputStream is) { CRC32 crc = new CRC32(); byte[] buf = new byte[2048]; try { - InputStream is = new FileInputStream(f); while(true) { int bytesRead = is.read(buf); if(bytesRead < 1) { diff --git a/src/testcases/org/apache/poi/hssf/record/formula/AbstractPtgTestCase.java b/src/testcases/org/apache/poi/hssf/record/formula/AbstractPtgTestCase.java index 0912b97611..b8d223a4a8 100644 --- a/src/testcases/org/apache/poi/hssf/record/formula/AbstractPtgTestCase.java +++ b/src/testcases/org/apache/poi/hssf/record/formula/AbstractPtgTestCase.java @@ -25,6 +25,7 @@ import java.io.InputStream; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.model.Workbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; @@ -36,40 +37,27 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; * @author Daniel Noll (daniel at nuix dot com dot au) */ public abstract class AbstractPtgTestCase extends TestCase { - /** Directory containing the test data. */ - private static String dataDir = System.getProperty("HSSF.testdata.path"); /** * Loads a workbook from the given filename in the test data dir. * - * @param filename the filename. + * @param sampleFileName the filename. * @return the loaded workbook. - * @throws IOException if an error occurs loading the workbook. */ - protected static final HSSFWorkbook loadWorkbook(String filename) - throws IOException { - File file = new File(dataDir, filename); - InputStream stream = new BufferedInputStream(new FileInputStream(file)); - // TODO - temp workaround to keep stdout quiet due to warning msg in POIFS - // When that warning msg is disabled, remove this wrapper and the close() call, - InputStream wrappedStream = POIFSFileSystem.createNonClosingInputStream(stream); - try { - return new HSSFWorkbook(wrappedStream); - } finally { - stream.close(); - } + protected static final HSSFWorkbook loadWorkbook(String sampleFileName) { + return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); } /** * Creates a new Workbook and adds one sheet with the specified name */ protected static final Workbook createWorkbookWithSheet(String sheetName) { - - Workbook book = Workbook.createWorkbook(); - // this creates sheet if it doesn't exist - book.checkExternSheet(0); - // TODO - this call alone does not create the sheet even though the javadoc says it does - book.setSheetName(0, sheetName); - return book; - } + + Workbook book = Workbook.createWorkbook(); + // this creates sheet if it doesn't exist + book.checkExternSheet(0); + // TODO - this call alone does not create the sheet even though the javadoc says it does + book.setSheetName(0, sheetName); + return book; + } } diff --git a/src/testcases/org/apache/poi/hssf/record/formula/TestExternalFunctionFormulas.java b/src/testcases/org/apache/poi/hssf/record/formula/TestExternalFunctionFormulas.java index 8c89dadea7..6d35dcdec0 100755 --- a/src/testcases/org/apache/poi/hssf/record/formula/TestExternalFunctionFormulas.java +++ b/src/testcases/org/apache/poi/hssf/record/formula/TestExternalFunctionFormulas.java @@ -17,11 +17,9 @@ package org.apache.poi.hssf.record.formula; -import java.io.FileInputStream; -import java.io.IOException; - import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; /** @@ -37,15 +35,7 @@ public final class TestExternalFunctionFormulas extends TestCase { * tests NameXPtg.toFormulaString(Workbook) and logic in Workbook below that */ public void testReadFormulaContainingExternalFunction() { - String filePath = System.getProperty("HSSF.testdata.path")+ "/" - + "externalFunctionExample.xls"; - HSSFWorkbook wb; - try { - FileInputStream fin = new FileInputStream(filePath); - wb = new HSSFWorkbook( fin ); - } catch (IOException e) { - throw new RuntimeException(e); - } + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("externalFunctionExample.xls"); String expectedFormula = "YEARFRAC(B1,C1)"; HSSFSheet sht = wb.getSheetAt(0); diff --git a/src/testcases/org/apache/poi/hssf/record/formula/eval/TestFormulaBugs.java b/src/testcases/org/apache/poi/hssf/record/formula/eval/TestFormulaBugs.java index a833b77c0d..a614d6f193 100755 --- a/src/testcases/org/apache/poi/hssf/record/formula/eval/TestFormulaBugs.java +++ b/src/testcases/org/apache/poi/hssf/record/formula/eval/TestFormulaBugs.java @@ -17,9 +17,6 @@ package org.apache.poi.hssf.record.formula.eval; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -27,6 +24,7 @@ import java.io.InputStream; import junit.framework.AssertionFailedError; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFRow; @@ -43,49 +41,13 @@ import org.apache.poi.ss.usermodel.FormulaEvaluator.CellValue; */ public final class TestFormulaBugs extends TestCase { - private static final String TEST_DATA_DIR_SYS_PROPERTY_NAME = "HSSF.testdata.path"; - - /** - * Opens a sample file from the standard HSSF test data directory - * - * @return an open InputStream for the specified sample file - */ - private static InputStream openSampleFileStream(String sampleFileName) { - // TODO - move this method somewhere common - String dataDirName = System - .getProperty(TEST_DATA_DIR_SYS_PROPERTY_NAME); - if (dataDirName == null) { - throw new RuntimeException("Must set system property '" - + TEST_DATA_DIR_SYS_PROPERTY_NAME - + "' before running tests"); - } - File dataDir = new File(dataDirName); - if (!dataDir.exists()) { - throw new RuntimeException("Data dir '" + dataDirName - + "' specified by system property '" - + TEST_DATA_DIR_SYS_PROPERTY_NAME + "' does not exist"); - } - File f = new File(dataDir, sampleFileName); - if (!f.exists()) { - throw new RuntimeException("Sample file '" + sampleFileName - + "' not found in data dir '" + dataDirName + "'"); - } - InputStream is; - try { - is = new FileInputStream(f); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - return is; - } - /** * Bug 27349 - VLOOKUP with reference to another sheet.

This test was * added long after the relevant functionality was fixed. */ public void test27349() { // 27349-vlookupAcrossSheets.xls is bugzilla/attachment.cgi?id=10622 - InputStream is = openSampleFileStream("27349-vlookupAcrossSheets.xls"); + InputStream is = HSSFTestDataSamples.openSampleFileStream("27349-vlookupAcrossSheets.xls"); HSSFWorkbook wb; try { // original bug may have thrown exception here, or output warning to diff --git a/src/testcases/org/apache/poi/hssf/record/formula/eval/TestFormulasFromSpreadsheet.java b/src/testcases/org/apache/poi/hssf/record/formula/eval/TestFormulasFromSpreadsheet.java index 1575c29dbb..546d16d057 100644 --- a/src/testcases/org/apache/poi/hssf/record/formula/eval/TestFormulasFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/hssf/record/formula/eval/TestFormulasFromSpreadsheet.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.record.formula.eval; -import java.io.FileInputStream; import java.io.PrintStream; import junit.framework.Assert; import junit.framework.AssertionFailedError; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.record.formula.functions.TestMathX; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; @@ -155,9 +155,7 @@ public final class TestFormulasFromSpreadsheet extends TestCase { protected void setUp() throws Exception { if (workbook == null) { - String filePath = System.getProperty("HSSF.testdata.path")+ "/" + SS.FILENAME; - FileInputStream fin = new FileInputStream( filePath ); - workbook = new HSSFWorkbook( fin ); + workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME); sheet = workbook.getSheetAt( 0 ); } _functionFailureCount = 0; @@ -178,14 +176,14 @@ public final class TestFormulasFromSpreadsheet extends TestCase { String successMsg = "There were " + _evaluationSuccessCount + " successful evaluation(s) and " + _functionSuccessCount + " function(s) without error"; - if(_functionFailureCount > 0) { + if(_functionFailureCount > 0) { String msg = _functionFailureCount + " function(s) failed in " + _evaluationFailureCount + " evaluation(s). " + successMsg; throw new AssertionFailedError(msg); } - if(false) { // normally no output for successful tests - System.out.println(getClass().getName() + ": " + successMsg); - } + if(false) { // normally no output for successful tests + System.out.println(getClass().getName() + ": " + successMsg); + } } /** diff --git a/src/testcases/org/apache/poi/hssf/record/formula/function/TestReadMissingBuiltInFuncs.java b/src/testcases/org/apache/poi/hssf/record/formula/function/TestReadMissingBuiltInFuncs.java index 14799bd0a7..6766f2fc07 100644 --- a/src/testcases/org/apache/poi/hssf/record/formula/function/TestReadMissingBuiltInFuncs.java +++ b/src/testcases/org/apache/poi/hssf/record/formula/function/TestReadMissingBuiltInFuncs.java @@ -23,6 +23,7 @@ import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.record.RecordFormatException; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -45,14 +46,7 @@ public final class TestReadMissingBuiltInFuncs extends TestCase { private static HSSFSheet getSheet() { if (_sheet == null) { - String cwd = System.getProperty("HSSF.testdata.path"); - HSSFWorkbook wb; - try { - InputStream is = new FileInputStream(new File(cwd, SAMPLE_SPREADSHEET_FILE_NAME)); - wb = new HSSFWorkbook(is); - } catch (IOException e) { - throw new RuntimeException(e); - } + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_SPREADSHEET_FILE_NAME); _sheet = wb.getSheetAt(0); } return _sheet; diff --git a/src/testcases/org/apache/poi/hssf/record/formula/functions/TestLookupFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/hssf/record/formula/functions/TestLookupFunctionsFromSpreadsheet.java index 958654b060..1ff0ff6629 100644 --- a/src/testcases/org/apache/poi/hssf/record/formula/functions/TestLookupFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/hssf/record/formula/functions/TestLookupFunctionsFromSpreadsheet.java @@ -26,6 +26,7 @@ import junit.framework.Assert; import junit.framework.AssertionFailedError; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.record.formula.eval.ErrorEval; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; @@ -66,17 +67,17 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase { public final static String README_SHEET_NAME = "Read Me"; - /** Row (zero-based) in each sheet where the evaluation cases start. */ + /** Row (zero-based) in each sheet where the evaluation cases start. */ public static final int START_TEST_CASES_ROW_INDEX = 4; // Row '5' /** Index of the column that contains the function names */ - public static final short COLUMN_INDEX_MARKER = 0; // Column 'A' - public static final short COLUMN_INDEX_EVALUATION = 1; // Column 'B' - public static final short COLUMN_INDEX_EXPECTED_RESULT = 2; // Column 'C' - public static final short COLUMN_ROW_COMMENT = 3; // Column 'D' + public static final short COLUMN_INDEX_MARKER = 0; // Column 'A' + public static final short COLUMN_INDEX_EVALUATION = 1; // Column 'B' + public static final short COLUMN_INDEX_EXPECTED_RESULT = 2; // Column 'C' + public static final short COLUMN_ROW_COMMENT = 3; // Column 'D' - /** Used to indicate when there are no more test cases on the current sheet */ + /** Used to indicate when there are no more test cases on the current sheet */ public static final String TEST_CASES_END_MARKER = ""; - /** Used to indicate that the test on the current row should be ignored */ + /** Used to indicate that the test on the current row should be ignored */ public static final String SKIP_CURRENT_TEST_CASE_MARKER = ""; } @@ -90,8 +91,8 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase { - private static void confirmExpectedResult(String msg, HSSFCell expected, CellValue actual) { - if (expected == null) { + private static void confirmExpectedResult(String msg, HSSFCell expected, CellValue actual) { + if (expected == null) { throw new AssertionFailedError(msg + " - Bad setup data expected value is null"); } if(actual == null) { @@ -108,21 +109,21 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase { throw wrongTypeError(msg, expected, actual); } - + switch (expected.getCellType()) { case HSSFCell.CELL_TYPE_BOOLEAN: - assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue()); - break; + assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue()); + break; case HSSFCell.CELL_TYPE_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); + throw new AssertionFailedError("Cannot expect formula as result of formula evaluation: " + msg); case HSSFCell.CELL_TYPE_NUMERIC: - assertEquals(expected.getNumericCellValue(), actual.getNumberValue(), 0.0); - break; + assertEquals(expected.getNumericCellValue(), actual.getNumberValue(), 0.0); + break; case HSSFCell.CELL_TYPE_STRING: - assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getRichTextStringValue().getString()); - break; + assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getRichTextStringValue().getString()); + break; } - } + } private static AssertionFailedError wrongTypeError(String msgPrefix, HSSFCell expectedCell, CellValue actualValue) { @@ -178,55 +179,48 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase { protected void setUp() throws Exception { - _sheetFailureCount = 0; - _sheetSuccessCount = 0; - _evaluationFailureCount = 0; - _evaluationSuccessCount = 0; - } - - public void testFunctionsFromTestSpreadsheet() { - String filePath = System.getProperty("HSSF.testdata.path")+ "/" + SS.FILENAME; - HSSFWorkbook workbook; - try { - FileInputStream fin = new FileInputStream( filePath ); - workbook = new HSSFWorkbook( fin ); - } catch (IOException e) { - throw new RuntimeException(e); - } + _sheetFailureCount = 0; + _sheetSuccessCount = 0; + _evaluationFailureCount = 0; + _evaluationSuccessCount = 0; + } + + public void testFunctionsFromTestSpreadsheet() { + HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME); - confirmReadMeSheet(workbook); - int nSheets = workbook.getNumberOfSheets(); - for(int i=1; i< nSheets; i++) { - int sheetResult = processTestSheet(workbook, i, workbook.getSheetName(i)); - switch(sheetResult) { - case Result.ALL_EVALUATIONS_SUCCEEDED: _sheetSuccessCount ++; break; - case Result.SOME_EVALUATIONS_FAILED: _sheetFailureCount ++; break; - } - } - - // confirm results - String successMsg = "There were " - + _sheetSuccessCount + " successful sheets(s) and " + confirmReadMeSheet(workbook); + int nSheets = workbook.getNumberOfSheets(); + for(int i=1; i< nSheets; i++) { + int sheetResult = processTestSheet(workbook, i, workbook.getSheetName(i)); + switch(sheetResult) { + case Result.ALL_EVALUATIONS_SUCCEEDED: _sheetSuccessCount ++; break; + case Result.SOME_EVALUATIONS_FAILED: _sheetFailureCount ++; break; + } + } + + // confirm results + String successMsg = "There were " + + _sheetSuccessCount + " successful sheets(s) and " + _evaluationSuccessCount + " function(s) without error"; if(_sheetFailureCount > 0) { String msg = _sheetFailureCount + " sheets(s) failed with " + _evaluationFailureCount + " evaluation(s). " + successMsg; - throw new AssertionFailedError(msg); - } + throw new AssertionFailedError(msg); + } if(false) { // normally no output for successful tests System.out.println(getClass().getName() + ": " + successMsg); } } - private int processTestSheet(HSSFWorkbook workbook, int sheetIndex, String sheetName) { + private int processTestSheet(HSSFWorkbook workbook, int sheetIndex, String sheetName) { HSSFSheet sheet = workbook.getSheetAt(sheetIndex); HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet, workbook); int maxRows = sheet.getLastRowNum()+1; - int result = Result.NO_EVALUATIONS_FOUND; // so far + int result = Result.NO_EVALUATIONS_FOUND; // so far String currentGroupComment = null; for(int rowIndex=SS.START_TEST_CASES_ROW_INDEX; rowIndexnull if cell is missing, empty or blank - */ + */ private static String getCellTextValue(HSSFRow r, int colIndex, String columnName) { if(r == null) { return null; diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java b/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java index f137ef6e9a..c209054117 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java @@ -14,42 +14,35 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ + package org.apache.poi.hssf.usermodel; -import java.io.File; -import java.io.FileInputStream; import java.util.Iterator; import java.util.List; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.record.FormulaRecord; import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; import org.apache.poi.ss.usermodel.FormulaEvaluator.CellValue; import org.apache.poi.hssf.util.CellReference; +/** + * + */ public final class TestBug42464 extends TestCase { - String dirname; - - protected void setUp() throws Exception { - super.setUp(); - dirname = System.getProperty("HSSF.testdata.path"); - } public void testOKFile() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook( - new FileInputStream(new File(dirname,"42464-ExpPtg-ok.xls")) - ); + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-ok.xls"); process(wb); } public void testExpSharedBadFile() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook( - new FileInputStream(new File(dirname,"42464-ExpPtg-bad.xls")) - ); + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-bad.xls"); process(wb); } - protected void process(HSSFWorkbook wb) { + private static void process(HSSFWorkbook wb) { for(int i=0; i0) { // fetch the first merged region...EXCEPTION OCCURS HERE template.getMergedRegionAt(0); - } + } //make sure we dont exception - + } - + /*Tests read and write of Unicode strings in formula results * bug and testcase submitted by Sompop Kumnoonsate - * The file contains THAI unicode characters. + * The file contains THAI unicode characters. */ - public void testUnicodeStringFormulaRead() throws Exception { - - String filename = System.getProperty("HSSF.testdata.path"); - filename=filename+"/25695.xls"; - FileInputStream in = new FileInputStream(filename); - HSSFWorkbook w; - w = new HSSFWorkbook(in); - in.close(); - - HSSFCell a1 = w.getSheetAt(0).getRow(0).getCell((short) 0); - HSSFCell a2 = w.getSheetAt(0).getRow(0).getCell((short) 1); - HSSFCell b1 = w.getSheetAt(0).getRow(1).getCell((short) 0); - HSSFCell b2 = w.getSheetAt(0).getRow(1).getCell((short) 1); - HSSFCell c1 = w.getSheetAt(0).getRow(2).getCell((short) 0); - HSSFCell c2 = w.getSheetAt(0).getRow(2).getCell((short) 1); - HSSFCell d1 = w.getSheetAt(0).getRow(3).getCell((short) 0); - HSSFCell d2 = w.getSheetAt(0).getRow(3).getCell((short) 1); - - /* // THAI code page - System.out.println("a1="+unicodeString(a1.getStringCellValue())); - System.out.println("a2="+unicodeString(a2.getStringCellValue())); - // US code page - System.out.println("b1="+unicodeString(b1.getStringCellValue())); - System.out.println("b2="+unicodeString(b2.getStringCellValue())); - // THAI+US - System.out.println("c1="+unicodeString(c1.getStringCellValue())); - System.out.println("c2="+unicodeString(c2.getStringCellValue())); - // US+THAI - System.out.println("d1="+unicodeString(d1.getStringCellValue())); - System.out.println("d2="+unicodeString(d2.getStringCellValue())); -*/ - assertEquals("String Cell value", a1.getStringCellValue(), a2.getStringCellValue()); - assertEquals("String Cell value", b1.getStringCellValue(), b2.getStringCellValue()); - assertEquals("String Cell value", c1.getStringCellValue(), c2.getStringCellValue()); - assertEquals("String Cell value", d1.getStringCellValue(), d2.getStringCellValue()); - - File xls = TempFile.createTempFile("testFormulaUnicode", ".xls"); - FileOutputStream out = new FileOutputStream(xls); - w.write(out); - out.close(); - in = new FileInputStream(xls); - - HSSFWorkbook rw = new HSSFWorkbook(in); - in.close(); - - HSSFCell ra1 = rw.getSheetAt(0).getRow(0).getCell((short) 0); - HSSFCell ra2 = rw.getSheetAt(0).getRow(0).getCell((short) 1); - HSSFCell rb1 = rw.getSheetAt(0).getRow(1).getCell((short) 0); - HSSFCell rb2 = rw.getSheetAt(0).getRow(1).getCell((short) 1); - HSSFCell rc1 = rw.getSheetAt(0).getRow(2).getCell((short) 0); - HSSFCell rc2 = rw.getSheetAt(0).getRow(2).getCell((short) 1); - HSSFCell rd1 = rw.getSheetAt(0).getRow(3).getCell((short) 0); - HSSFCell rd2 = rw.getSheetAt(0).getRow(3).getCell((short) 1); - - assertEquals("Re-Written String Cell value", a1.getStringCellValue(), ra1.getStringCellValue()); - assertEquals("Re-Written String Cell value", b1.getStringCellValue(), rb1.getStringCellValue()); - assertEquals("Re-Written String Cell value", c1.getStringCellValue(), rc1.getStringCellValue()); - assertEquals("Re-Written String Cell value", d1.getStringCellValue(), rd1.getStringCellValue()); - assertEquals("Re-Written Formula String Cell value", a1.getStringCellValue(), ra2.getStringCellValue()); - assertEquals("Re-Written Formula String Cell value", b1.getStringCellValue(), rb2.getStringCellValue()); - assertEquals("Re-Written Formula String Cell value", c1.getStringCellValue(), rc2.getStringCellValue()); - assertEquals("Re-Written Formula String Cell value", d1.getStringCellValue(), rd2.getStringCellValue()); - - } - - private static String unicodeString(String ss) { + public void testUnicodeStringFormulaRead() { + + HSSFWorkbook w = openSample("25695.xls"); + + HSSFCell a1 = w.getSheetAt(0).getRow(0).getCell((short) 0); + HSSFCell a2 = w.getSheetAt(0).getRow(0).getCell((short) 1); + HSSFCell b1 = w.getSheetAt(0).getRow(1).getCell((short) 0); + HSSFCell b2 = w.getSheetAt(0).getRow(1).getCell((short) 1); + HSSFCell c1 = w.getSheetAt(0).getRow(2).getCell((short) 0); + HSSFCell c2 = w.getSheetAt(0).getRow(2).getCell((short) 1); + HSSFCell d1 = w.getSheetAt(0).getRow(3).getCell((short) 0); + HSSFCell d2 = w.getSheetAt(0).getRow(3).getCell((short) 1); + + if (false) { + // THAI code page + System.out.println("a1="+unicodeString(a1)); + System.out.println("a2="+unicodeString(a2)); + // US code page + System.out.println("b1="+unicodeString(b1)); + System.out.println("b2="+unicodeString(b2)); + // THAI+US + System.out.println("c1="+unicodeString(c1)); + System.out.println("c2="+unicodeString(c2)); + // US+THAI + System.out.println("d1="+unicodeString(d1)); + System.out.println("d2="+unicodeString(d2)); + } + confirmSameCellText(a1, a2); + confirmSameCellText(b1, b2); + confirmSameCellText(c1, c2); + confirmSameCellText(d1, d2); + + HSSFWorkbook rw = writeOutAndReadBack(w); + + HSSFCell ra1 = rw.getSheetAt(0).getRow(0).getCell((short) 0); + HSSFCell ra2 = rw.getSheetAt(0).getRow(0).getCell((short) 1); + HSSFCell rb1 = rw.getSheetAt(0).getRow(1).getCell((short) 0); + HSSFCell rb2 = rw.getSheetAt(0).getRow(1).getCell((short) 1); + HSSFCell rc1 = rw.getSheetAt(0).getRow(2).getCell((short) 0); + HSSFCell rc2 = rw.getSheetAt(0).getRow(2).getCell((short) 1); + HSSFCell rd1 = rw.getSheetAt(0).getRow(3).getCell((short) 0); + HSSFCell rd2 = rw.getSheetAt(0).getRow(3).getCell((short) 1); + + confirmSameCellText(a1, ra1); + confirmSameCellText(b1, rb1); + confirmSameCellText(c1, rc1); + confirmSameCellText(d1, rd1); + + confirmSameCellText(a1, ra2); + confirmSameCellText(b1, rb2); + confirmSameCellText(c1, rc2); + confirmSameCellText(d1, rd2); + } + + private static void confirmSameCellText(HSSFCell a, HSSFCell b) { + assertEquals(a.getRichStringCellValue().getString(), b.getRichStringCellValue().getString()); + } + private static String unicodeString(HSSFCell cell) { + String ss = cell.getRichStringCellValue().getString(); char s[] = ss.toCharArray(); - java.lang.StringBuffer sb=new java.lang.StringBuffer(); + StringBuffer sb = new StringBuffer(); for (int x=0;xROUND(B2*D2,2),ROUND(A2*B2*C2,2),ROUND(B2*D2,2))"; + "IF(ROUND(A2*B2*C2,2)>ROUND(B2*D2,2),ROUND(A2*B2*C2,2),ROUND(B2*D2,2))"; cell.setCellFormula(formulaText); assertEquals(formulaText, cell.getCellFormula()); - if(false) { - // this file can be inspected manually - try { - OutputStream os = new FileOutputStream("/tmp/output28031.xls"); - wb.write(os); - os.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } + writeTestOutputFileForViewing(wb, "output28031.xls"); + } + + public void test33082() { + openSample("33082.xls"); + } + + public void test34775() { + try { + openSample("34775.xls"); + } catch (NullPointerException e) { + throw new AssertionFailedError("identified bug 34775"); } } - - public void test33082() throws java.io.IOException { - String filename = System.getProperty("HSSF.testdata.path"); - filename=filename+"/33082.xls"; - FileInputStream in = new FileInputStream(filename); - HSSFWorkbook wb = new HSSFWorkbook(in); - assertTrue("Read book fine!" , true); - } - - /*NullPointerException on reading file*/ - public void test34775() throws java.io.IOException { - String filename = System.getProperty("HSSF.testdata.path"); - filename=filename+"/34775.xls"; - FileInputStream in = new FileInputStream(filename); - HSSFWorkbook wb = new HSSFWorkbook(in); - assertTrue("Read book fine!" , true); - } - - /** Error when reading then writing ArrayValues in NameRecord's*/ - public void test37630() throws java.io.IOException { - String filename = System.getProperty("HSSF.testdata.path"); - filename=filename+"/37630.xls"; - FileInputStream in = new FileInputStream(filename); - HSSFWorkbook wb = new HSSFWorkbook(in); - File file = TempFile.createTempFile("test37630",".xls"); - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - - assertTrue("Read book fine!" , true); - } - - protected String cwd = System.getProperty("HSSF.testdata.path"); + + /** Error when reading then writing ArrayValues in NameRecord's*/ + public void test37630() { + HSSFWorkbook wb = openSample("37630.xls"); + writeOutAndReadBack(wb); + } /** * Bug 25183: org.apache.poi.hssf.usermodel.HSSFSheet.setPropertiesFromSheet */ - public void test25183() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "25183.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + public void test25183() { + HSSFWorkbook wb = openSample("25183.xls"); + writeOutAndReadBack(wb); } /** * Bug 26100: 128-character message in IF statement cell causes HSSFWorkbook open failure */ - public void test26100() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "26100.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - assertTrue("No Exceptions while reading file", true); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + public void test26100() { + HSSFWorkbook wb = openSample("26100.xls"); + writeOutAndReadBack(wb); } /** * Bug 27933: Unable to use a template (xls) file containing a wmf graphic */ - public void test27933() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "27933.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + public void test27933() { + HSSFWorkbook wb = openSample("27933.xls"); + writeOutAndReadBack(wb); } /** - * Bug 29206: NPE on HSSFSheet.getRow for blank rows + * Bug 29206: NPE on HSSFSheet.getRow for blank rows */ - public void test29206() throws Exception { + public void test29206() { //the first check with blank workbook HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(); @@ -630,50 +486,34 @@ extends TestCase { for(int i = 1; i < 400; i++) { HSSFRow row = sheet.getRow(i); if(row != null) { - HSSFCell cell = row.getCell((short)0); + row.getCell((short)0); } } //now check on an existing xls file - FileInputStream in = new FileInputStream(new File(cwd, "Simple.xls")); - wb = new HSSFWorkbook(in); - in.close(); + wb = openSample("Simple.xls"); for(int i = 1; i < 400; i++) { HSSFRow row = sheet.getRow(i); if(row != null) { - HSSFCell cell = row.getCell((short)0); + row.getCell((short)0); } } - - assertTrue("No Exceptions while reading file", true); } /** * Bug 29675: POI 2.5 final corrupts output when starting workbook has a graphic */ - public void test29675() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "29675.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + public void test29675() { + HSSFWorkbook wb = openSample("29675.xls"); + writeOutAndReadBack(wb); } /** * Bug 29942: Importing Excel files that have been created by Open Office on Linux */ - public void test29942() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "29942.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); + public void test29942() { + HSSFWorkbook wb = openSample("29942.xls"); HSSFSheet sheet = wb.getSheetAt(0); int count = 0; @@ -686,170 +526,84 @@ extends TestCase { } } assertEquals(85, count); //should read 85 rows - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + writeOutAndReadBack(wb); } /** * Bug 29982: Unable to read spreadsheet when dropdown list cell is selected - * Unable to construct record instance */ - public void test29982() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "29982.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + public void test29982() { + HSSFWorkbook wb = openSample("29982.xls"); + writeOutAndReadBack(wb); } /** * Bug 30540: HSSFSheet.setRowBreak throws NullPointerException */ - public void test30540() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "30540.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); + public void test30540() { + HSSFWorkbook wb = openSample("30540.xls"); HSSFSheet s = wb.getSheetAt(0); s.setRowBreak(1); - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + writeOutAndReadBack(wb); } /** * Bug 31749: {Need help urgently}[This is critical] workbook.write() corrupts the file......? */ - public void test31749() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "31749.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + public void test31749() { + HSSFWorkbook wb = openSample("31749.xls"); + writeOutAndReadBack(wb); } /** * Bug 31979: {urgent help needed .....}poi library does not support form objects properly. */ - public void test31979() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "31979.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - //wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); - + public void test31979() { + HSSFWorkbook wb = openSample("31979.xls"); + writeOutAndReadBack(wb); } /** * Bug 35564: HSSFCell.java: NullPtrExc in isGridsPrinted() and getProtect() * when HSSFWorkbook is created from file */ - public void test35564() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "35564.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); + public void test35564() { + HSSFWorkbook wb = openSample("35564.xls"); HSSFSheet sheet = wb.getSheetAt( 0 ); assertEquals(false, sheet.isGridsPrinted()); assertEquals(false, sheet.getProtect()); - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); - + writeOutAndReadBack(wb); } /** * Bug 35565: HSSFCell.java: NullPtrExc in getColumnBreaks() when HSSFWorkbook is created from file */ - public void test35565() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "35565.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); + public void test35565() { + HSSFWorkbook wb = openSample("35565.xls"); HSSFSheet sheet = wb.getSheetAt( 0 ); assertNotNull(sheet); - - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); - + writeOutAndReadBack(wb); } /** * Bug 37376: Cannot open the saved Excel file if checkbox controls exceed certain limit */ - public void test37376() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "37376.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); - + public void test37376() { + HSSFWorkbook wb = openSample("37376.xls"); + writeOutAndReadBack(wb); } /** - * Bug 40285: CellIterator Skips First Column + * Bug 40285: CellIterator Skips First Column */ - public void test40285() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "40285.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); + public void test40285() { + HSSFWorkbook wb = openSample("40285.xls"); HSSFSheet sheet = wb.getSheetAt( 0 ); int rownum = 0; @@ -865,18 +619,16 @@ extends TestCase { } /** - * Bug 40296: HSSFCell.setCellFormula throws + * Bug 40296: HSSFCell.setCellFormula throws * ClassCastException if cell is created using HSSFRow.createCell(short column, int type) */ - public void test40296() throws Exception { + public void test40296() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook workBook = new HSSFWorkbook(); HSSFSheet workSheet = workBook.createSheet("Sheet1"); HSSFCell cell; - HSSFRow row; - - row = workSheet.createRow(0); + HSSFRow row = workSheet.createRow(0); cell = row.createCell((short)0, HSSFCell.CELL_TYPE_NUMERIC); cell.setCellValue(1.0); cell = row.createCell((short)1, HSSFCell.CELL_TYPE_NUMERIC); @@ -884,13 +636,7 @@ extends TestCase { cell = row.createCell((short)2, HSSFCell.CELL_TYPE_FORMULA); cell.setCellFormula("SUM(A1:B1)"); - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + writeOutAndReadBack(wb); } /** @@ -903,12 +649,10 @@ extends TestCase { * 3. Try adding a row break (via sheet.setRowBreak()) to the sheet mentioned in step #1 * 4. Get a NullPointerException */ - public void test38266() throws Exception { + public void test38266() { String[] files = {"Simple.xls", "SimpleMultiCell.xls", "duprich1.xls"}; for (int i = 0; i < files.length; i++) { - FileInputStream in = new FileInputStream(new File(cwd, files[i])); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); + HSSFWorkbook wb = openSample(files[i]); HSSFSheet sheet = wb.getSheetAt( 0 ); int[] breaks = sheet.getRowBreaks(); @@ -918,142 +662,60 @@ extends TestCase { for (int j = 1; j <= 3; j++) { sheet.setRowBreak(j*20); } - - assertTrue("No Exceptions while adding row breaks in " + files[i], true); } } - public void test40738() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "SimpleWithAutofilter.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); - + public void test40738() { + HSSFWorkbook wb = openSample("SimpleWithAutofilter.xls"); + writeOutAndReadBack(wb); } /** * Bug 44200: Sheet not cloneable when Note added to excel cell */ - public void test44200() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "44200.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); + public void test44200() { + HSSFWorkbook wb = openSample("44200.xls"); wb.cloneSheet(0); - assertTrue("No Exceptions while cloning sheet", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); - + writeOutAndReadBack(wb); } /** * Bug 44201: Sheet not cloneable when validation added to excel cell */ - public void test44201() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "44201.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - wb.cloneSheet(0); - assertTrue("No Exceptions while cloning sheet", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); - + public void test44201() { + HSSFWorkbook wb = openSample("44201.xls"); + writeOutAndReadBack(wb); } /** * Bug 37684 : Unhandled Continue Record Error */ - public void test37684 () throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "37684-1.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - assertTrue("No exceptions while reading workbook", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - assertTrue("No exceptions while saving workbook", true); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No exceptions while reading saved stream", true); - - - in = new FileInputStream(new File(cwd, "37684-2.xls")); - wb = new HSSFWorkbook(in); - in.close(); + public void test37684 () { + HSSFWorkbook wb = openSample("37684-1.xls"); + writeOutAndReadBack(wb); - assertTrue("No exceptions while reading workbook", true); - //serialize and read again - out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - assertTrue("No exceptions while saving workbook", true); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No exceptions while reading saved stream", true); + wb = openSample("37684-2.xls"); + writeOutAndReadBack(wb); } /** * Bug 41139: Constructing HSSFWorkbook is failed,threw threw ArrayIndexOutOfBoundsException for creating UnknownRecord */ - public void test41139() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "41139.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + public void test41139() { + HSSFWorkbook wb = openSample("41139.xls"); + writeOutAndReadBack(wb); } /** * Bug 41546: Constructing HSSFWorkbook is failed, * Unknown Ptg in Formula: 0x1a (26) */ - public void test41546() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "41546.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - assertTrue("No Exceptions while reading file", true); + public void test41546() { + HSSFWorkbook wb = openSample("41546.xls"); assertEquals(1, wb.getNumberOfSheets()); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + wb = writeOutAndReadBack(wb); assertEquals(1, wb.getNumberOfSheets()); } @@ -1061,189 +723,159 @@ extends TestCase { * Bug 42564: Some files from Access were giving a RecordFormatException * when reading the BOFRecord */ - public void test42564() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "42564.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); + public void test42564() { + HSSFWorkbook wb = openSample("42564.xls"); + writeOutAndReadBack(wb); } - + /** * Bug 42564: Some files from Access also have issues * with the NameRecord, once you get past the BOFRecord * issue. - * TODO - still broken */ - public void DISABLEDtest42564Alt() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "42564-2.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); - } - - /** - * Bug 42618: RecordFormatException reading a file containing - * =CHOOSE(2,A2,A3,A4) - * TODO - support getCellFormula too! - */ - public void test42618() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "SimpleWithChoose.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - assertTrue("No Exceptions while reading file", true); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); - + public void DISABLEDtest42564Alt() { + HSSFWorkbook wb = openSample("42564-2.xls"); + writeOutAndReadBack(wb); + } + + /** + * Bug 42618: RecordFormatException reading a file containing + * =CHOOSE(2,A2,A3,A4) + */ + public void test42618() { + HSSFWorkbook wb = openSample("SimpleWithChoose.xls"); + wb = writeOutAndReadBack(wb); // Check we detect the string properly too HSSFSheet s = wb.getSheetAt(0); - + // Textual value HSSFRow r1 = s.getRow(0); HSSFCell c1 = r1.getCell((short)1); assertEquals("=CHOOSE(2,A2,A3,A4)", c1.getRichStringCellValue().toString()); - + // Formula Value HSSFRow r2 = s.getRow(1); HSSFCell c2 = r2.getCell((short)1); assertEquals(25, (int)c2.getNumericCellValue()); - - // This will blow up with a - // "EmptyStackException" - //assertEquals("=CHOOSE(2,A2,A3,A4)", c2.getCellFormula()); + + if (false) { // TODO (Apr-2008) This will blow up with IllegalStateException (stack underflow) + // excel function "CHOOSE" probably needs some special handling in FormulaParser.toFormulaString() + assertEquals("=CHOOSE(2,A2,A3,A4)", c2.getCellFormula()); + } } - + /** * Something up with the FileSharingRecord */ - public void test43251() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "43251.xls")); - + public void test43251() { + // Used to blow up with an IllegalArgumentException // when creating a FileSharingRecord - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - + HSSFWorkbook wb; + try { + wb = openSample("43251.xls"); + } catch (IllegalArgumentException e) { + throw new AssertionFailedError("identified bug 43251"); + } + assertEquals(1, wb.getNumberOfSheets()); } - + /** - * Crystal reports generates files with short + * Crystal reports generates files with short * StyleRecords, which is against the spec */ - public void test44471() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "OddStyleRecord.xls")); - + public void test44471() { + // Used to blow up with an ArrayIndexOutOfBounds // when creating a StyleRecord - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - + HSSFWorkbook wb; + try { + wb = openSample("OddStyleRecord.xls"); + } catch (ArrayIndexOutOfBoundsException e) { + throw new AssertionFailedError("Identified bug 44471"); + } + assertEquals(1, wb.getNumberOfSheets()); } - + /** * Files with "read only recommended" were giving * grief on the FileSharingRecord */ - public void test44536() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "ReadOnlyRecommended.xls")); - + public void test44536() { + // Used to blow up with an IllegalArgumentException // when creating a FileSharingRecord - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - + HSSFWorkbook wb = openSample("ReadOnlyRecommended.xls"); + // Check read only advised assertEquals(3, wb.getNumberOfSheets()); assertTrue(wb.isWriteProtected()); - + // But also check that another wb isn't - in = new FileInputStream(new File(cwd, "SimpleWithChoose.xls")); - wb = new HSSFWorkbook(in); - in.close(); + wb = openSample("SimpleWithChoose.xls"); assertFalse(wb.isWriteProtected()); } - + /** * Some files were having problems with the DVRecord, * probably due to dropdowns */ - public void test44593() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "44593.xls")); - + public void test44593() { + // Used to blow up with an IllegalArgumentException // when creating a DVRecord // Now won't, but no idea if this means we have // rubbish in the DVRecord or not... - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - + HSSFWorkbook wb; + try { + wb = openSample("44593.xls"); + } catch (IllegalArgumentException e) { + throw new AssertionFailedError("Identified bug 44593"); + } + assertEquals(2, wb.getNumberOfSheets()); } - + /** * Used to give problems due to trying to read a zero * length string, but that's now properly handled */ - public void test44643() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "44643.xls")); - + public void test44643() { + // Used to blow up with an IllegalArgumentException - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - + HSSFWorkbook wb; + try { + wb = openSample("44643.xls"); + } catch (IllegalArgumentException e) { + throw new AssertionFailedError("identified bug 44643"); + } + assertEquals(1, wb.getNumberOfSheets()); } - + /** * User reported the wrong number of rows from the * iterator, but we can't replicate that */ - public void test44693() throws Exception { - FileInputStream in = new FileInputStream(new File(cwd, "44693.xls")); - - HSSFWorkbook wb = new HSSFWorkbook(in); + public void test44693() { + + HSSFWorkbook wb = openSample("44693.xls"); HSSFSheet s = wb.getSheetAt(0); // Rows are 1 to 713 assertEquals(0, s.getFirstRowNum()); assertEquals(712, s.getLastRowNum()); assertEquals(713, s.getPhysicalNumberOfRows()); - + // Now check the iterator int rowsSeen = 0; for(Iterator i = s.rowIterator(); i.hasNext(); ) { - HSSFRow r = (HSSFRow)i.next(); - rowsSeen++; + HSSFRow r = (HSSFRow)i.next(); + assertNotNull(r); + rowsSeen++; } assertEquals(713, rowsSeen); } } - - - diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java index 87a760f714..007cbd5760 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java @@ -14,31 +14,31 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ -package org.apache.poi.hssf.usermodel; -import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; -import org.apache.poi.hssf.record.formula.AreaPtg; -import org.apache.poi.hssf.record.formula.FuncVarPtg; +package org.apache.poi.hssf.usermodel; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Iterator; import java.util.List; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; +import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; +import org.apache.poi.hssf.record.formula.AreaPtg; +import org.apache.poi.hssf.record.formula.FuncVarPtg; +/** + * + */ public final class TestFormulaEvaluatorBugs extends TestCase { - private String dirName; + private String tmpDirName; - protected void setUp() throws Exception { - super.setUp(); - dirName = System.getProperty("HSSF.testdata.path"); + protected void setUp() { + tmpDirName = System.getProperty("java.io.tmpdir"); } - + /** * An odd problem with evaluateFormulaCell giving the * right values when file is opened, but changes @@ -51,39 +51,39 @@ public final class TestFormulaEvaluatorBugs extends TestCase { public void test44636() throws Exception { // Open the existing file, tweak one value and // re-calculate - FileInputStream in = new FileInputStream(new File(dirName,"44636.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); + + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44636.xls"); HSSFSheet sheet = wb.getSheetAt (0); HSSFRow row = sheet.getRow (0); - + row.getCell((short)0).setCellValue(4.2); row.getCell((short)2).setCellValue(25); - + HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); assertEquals(4.2*25, row.getCell((short)3).getNumericCellValue(), 0.0001); - + // Save File existing = new File(tmpDirName,"44636-existing.xls"); FileOutputStream out = new FileOutputStream(existing); wb.write(out); out.close(); System.err.println("Existing file for bug #44636 written to " + existing.toString()); - - + + // Now, do a new file from scratch wb = new HSSFWorkbook(); sheet = wb.createSheet(); - + row = sheet.createRow(0); row.createCell((short)0).setCellValue(1.2); row.createCell((short)1).setCellValue(4.2); - + row = sheet.createRow(1); row.createCell((short)0).setCellFormula("SUM(A1:B1)"); - + HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); assertEquals(5.4, row.getCell((short)0).getNumericCellValue(), 0.0001); - + // Save File scratch = new File(tmpDirName,"44636-scratch.xls"); out = new FileOutputStream(scratch); @@ -99,72 +99,71 @@ public final class TestFormulaEvaluatorBugs extends TestCase { * * @author Yegor Kozlov */ - public void test44297() throws IOException { - FileInputStream in = new FileInputStream(new File(dirName, "44297.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - HSSFRow row; - HSSFCell cell; - - HSSFSheet sheet = wb.getSheetAt(0); - - HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb); - - row = (HSSFRow)sheet.getRow(0); - cell = row.getCell((short)0); - assertEquals("31+46", cell.getCellFormula()); - eva.setCurrentRow(row); - assertEquals(77, eva.evaluate(cell).getNumberValue(), 0); - - row = (HSSFRow)sheet.getRow(1); - cell = row.getCell((short)0); - assertEquals("30+53", cell.getCellFormula()); - eva.setCurrentRow(row); - assertEquals(83, eva.evaluate(cell).getNumberValue(), 0); - - row = (HSSFRow)sheet.getRow(2); - cell = row.getCell((short)0); - assertEquals("SUM(A1:A2)", cell.getCellFormula()); - eva.setCurrentRow(row); - assertEquals(160, eva.evaluate(cell).getNumberValue(), 0); - - row = (HSSFRow)sheet.getRow(4); - cell = row.getCell((short)0); - assertEquals("32767+32768", cell.getCellFormula()); - eva.setCurrentRow(row); - assertEquals(65535, eva.evaluate(cell).getNumberValue(), 0); - - row = (HSSFRow)sheet.getRow(7); - cell = row.getCell((short)0); - assertEquals("32744+42333", cell.getCellFormula()); - eva.setCurrentRow(row); - assertEquals(75077, eva.evaluate(cell).getNumberValue(), 0); - - row = (HSSFRow)sheet.getRow(8); - cell = row.getCell((short)0); - assertEquals("327680.0/32768", cell.getCellFormula()); - eva.setCurrentRow(row); - assertEquals(10, eva.evaluate(cell).getNumberValue(), 0); - - row = (HSSFRow)sheet.getRow(9); - cell = row.getCell((short)0); - assertEquals("32767+32769", cell.getCellFormula()); - eva.setCurrentRow(row); - assertEquals(65536, eva.evaluate(cell).getNumberValue(), 0); - - row = (HSSFRow)sheet.getRow(10); - cell = row.getCell((short)0); - assertEquals("35000+36000", cell.getCellFormula()); - eva.setCurrentRow(row); - assertEquals(71000, eva.evaluate(cell).getNumberValue(), 0); - - row = (HSSFRow)sheet.getRow(11); - cell = row.getCell((short)0); - assertEquals("-1000000.0-3000000.0", cell.getCellFormula()); - eva.setCurrentRow(row); - assertEquals(-4000000, eva.evaluate(cell).getNumberValue(), 0); - } + public void test44297() { + + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44297.xls"); + + HSSFRow row; + HSSFCell cell; + + HSSFSheet sheet = wb.getSheetAt(0); + + HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb); + + row = sheet.getRow(0); + cell = row.getCell((short)0); + assertEquals("31+46", cell.getCellFormula()); + eva.setCurrentRow(row); + assertEquals(77, eva.evaluate(cell).getNumberValue(), 0); + + row = sheet.getRow(1); + cell = row.getCell((short)0); + assertEquals("30+53", cell.getCellFormula()); + eva.setCurrentRow(row); + assertEquals(83, eva.evaluate(cell).getNumberValue(), 0); + + row = sheet.getRow(2); + cell = row.getCell((short)0); + assertEquals("SUM(A1:A2)", cell.getCellFormula()); + eva.setCurrentRow(row); + assertEquals(160, eva.evaluate(cell).getNumberValue(), 0); + + row = sheet.getRow(4); + cell = row.getCell((short)0); + assertEquals("32767+32768", cell.getCellFormula()); + eva.setCurrentRow(row); + assertEquals(65535, eva.evaluate(cell).getNumberValue(), 0); + + row = sheet.getRow(7); + cell = row.getCell((short)0); + assertEquals("32744+42333", cell.getCellFormula()); + eva.setCurrentRow(row); + assertEquals(75077, eva.evaluate(cell).getNumberValue(), 0); + + row = sheet.getRow(8); + cell = row.getCell((short)0); + assertEquals("327680.0/32768", cell.getCellFormula()); + eva.setCurrentRow(row); + assertEquals(10, eva.evaluate(cell).getNumberValue(), 0); + + row = sheet.getRow(9); + cell = row.getCell((short)0); + assertEquals("32767+32769", cell.getCellFormula()); + eva.setCurrentRow(row); + assertEquals(65536, eva.evaluate(cell).getNumberValue(), 0); + + row = sheet.getRow(10); + cell = row.getCell((short)0); + assertEquals("35000+36000", cell.getCellFormula()); + eva.setCurrentRow(row); + assertEquals(71000, eva.evaluate(cell).getNumberValue(), 0); + + row = sheet.getRow(11); + cell = row.getCell((short)0); + assertEquals("-1000000.0-3000000.0", cell.getCellFormula()); + eva.setCurrentRow(row); + assertEquals(-4000000, eva.evaluate(cell).getNumberValue(), 0); + } /** * Bug 44410: SUM(C:C) is valid in excel, and means a sum @@ -172,86 +171,85 @@ public final class TestFormulaEvaluatorBugs extends TestCase { * * @author Nick Burch */ - public void test44410() throws IOException { - FileInputStream in = new FileInputStream(new File(dirName, "SingleLetterRanges.xls")); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - HSSFSheet sheet = wb.getSheetAt(0); - - HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb); - - // =index(C:C,2,1) -> 2 - HSSFRow rowIDX = (HSSFRow)sheet.getRow(3); - // =sum(C:C) -> 6 - HSSFRow rowSUM = (HSSFRow)sheet.getRow(4); - // =sum(C:D) -> 66 - HSSFRow rowSUM2D = (HSSFRow)sheet.getRow(5); - - // Test the sum - HSSFCell cellSUM = rowSUM.getCell((short)0); - - FormulaRecordAggregate frec = - (FormulaRecordAggregate)cellSUM.getCellValueRecord(); - List ops = frec.getFormulaRecord().getParsedExpression(); - assertEquals(2, ops.size()); - assertEquals(AreaPtg.class, ops.get(0).getClass()); - assertEquals(FuncVarPtg.class, ops.get(1).getClass()); - - // Actually stored as C1 to C65536 - // (last row is -1 === 65535) - AreaPtg ptg = (AreaPtg)ops.get(0); - assertEquals(2, ptg.getFirstColumn()); - assertEquals(2, ptg.getLastColumn()); - assertEquals(0, ptg.getFirstRow()); - assertEquals(65535, ptg.getLastRow()); - assertEquals("C:C", ptg.toFormulaString(wb.getWorkbook())); - - // Will show as C:C, but won't know how many - // rows it covers as we don't have the sheet - // to hand when turning the Ptgs into a string - assertEquals("SUM(C:C)", cellSUM.getCellFormula()); - eva.setCurrentRow(rowSUM); - - // But the evaluator knows the sheet, so it - // can do it properly - assertEquals(6, eva.evaluate(cellSUM).getNumberValue(), 0); - - - // Test the index - // Again, the formula string will be right but - // lacking row count, evaluated will be right - HSSFCell cellIDX = rowIDX.getCell((short)0); - assertEquals("INDEX(C:C,2,1)", cellIDX.getCellFormula()); - eva.setCurrentRow(rowIDX); - assertEquals(2, eva.evaluate(cellIDX).getNumberValue(), 0); - - // Across two colums - HSSFCell cellSUM2D = rowSUM2D.getCell((short)0); - assertEquals("SUM(C:D)", cellSUM2D.getCellFormula()); - eva.setCurrentRow(rowSUM2D); - assertEquals(66, eva.evaluate(cellSUM2D).getNumberValue(), 0); - } + public void test44410() { + + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SingleLetterRanges.xls"); + + HSSFSheet sheet = wb.getSheetAt(0); + + HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb); + + // =index(C:C,2,1) -> 2 + HSSFRow rowIDX = sheet.getRow(3); + // =sum(C:C) -> 6 + HSSFRow rowSUM = sheet.getRow(4); + // =sum(C:D) -> 66 + HSSFRow rowSUM2D = sheet.getRow(5); + + // Test the sum + HSSFCell cellSUM = rowSUM.getCell((short)0); + + FormulaRecordAggregate frec = + (FormulaRecordAggregate)cellSUM.getCellValueRecord(); + List ops = frec.getFormulaRecord().getParsedExpression(); + assertEquals(2, ops.size()); + assertEquals(AreaPtg.class, ops.get(0).getClass()); + assertEquals(FuncVarPtg.class, ops.get(1).getClass()); + + // Actually stored as C1 to C65536 + // (last row is -1 === 65535) + AreaPtg ptg = (AreaPtg)ops.get(0); + assertEquals(2, ptg.getFirstColumn()); + assertEquals(2, ptg.getLastColumn()); + assertEquals(0, ptg.getFirstRow()); + assertEquals(65535, ptg.getLastRow()); + assertEquals("C:C", ptg.toFormulaString(wb.getWorkbook())); + + // Will show as C:C, but won't know how many + // rows it covers as we don't have the sheet + // to hand when turning the Ptgs into a string + assertEquals("SUM(C:C)", cellSUM.getCellFormula()); + eva.setCurrentRow(rowSUM); + + // But the evaluator knows the sheet, so it + // can do it properly + assertEquals(6, eva.evaluate(cellSUM).getNumberValue(), 0); + + + // Test the index + // Again, the formula string will be right but + // lacking row count, evaluated will be right + HSSFCell cellIDX = rowIDX.getCell((short)0); + assertEquals("INDEX(C:C,2,1)", cellIDX.getCellFormula()); + eva.setCurrentRow(rowIDX); + assertEquals(2, eva.evaluate(cellIDX).getNumberValue(), 0); + + // Across two colums + HSSFCell cellSUM2D = rowSUM2D.getCell((short)0); + assertEquals("SUM(C:D)", cellSUM2D.getCellFormula()); + eva.setCurrentRow(rowSUM2D); + assertEquals(66, eva.evaluate(cellSUM2D).getNumberValue(), 0); + } /** * Tests that we can evaluate boolean cells properly */ - public void testEvaluateBooleanInCell_bug44508() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - wb.setSheetName(0, "Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell((short)0); - - cell.setCellFormula("1=1"); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(sheet, wb); - fe.setCurrentRow(row); - try { - fe.evaluateInCell(cell); - } catch (NumberFormatException e) { - fail("Identified bug 44508"); - } - assertEquals(true, cell.getBooleanCellValue()); - } + public void testEvaluateBooleanInCell_bug44508() { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet(); + wb.setSheetName(0, "Sheet1"); + HSSFRow row = sheet.createRow(0); + HSSFCell cell = row.createCell((short)0); + + cell.setCellFormula("1=1"); + + HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(sheet, wb); + fe.setCurrentRow(row); + try { + fe.evaluateInCell(cell); + } catch (NumberFormatException e) { + fail("Identified bug 44508"); + } + assertEquals(true, cell.getBooleanCellValue()); + } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java index 9eb12bd4e1..80bab8a445 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,7 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.usermodel; @@ -27,6 +25,7 @@ import java.util.Date; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.util.CellReference; import org.apache.poi.util.TempFile; @@ -34,64 +33,62 @@ import org.apache.poi.util.TempFile; * @author Andrew C. Oliver (acoliver at apache dot org) * @author Avik Sengupta */ +public final class TestFormulas extends TestCase { -public class TestFormulas -extends TestCase { - public TestFormulas(String s) { - super(s); + private static HSSFWorkbook openSample(String sampleFileName) { + return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); } - + /** * Add 1+1 -- WHoohoo! */ - + public void testBasicAddIntegers() throws Exception { - - short rownum = 0; + File file = TempFile.createTempFile("testFormula",".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; - + //get our minimum values r = s.createRow((short)1); c = r.createCell((short)1); c.setCellFormula(1 + "+" + 1); - + wb.write(out); out.close(); - + FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheetAt(0); r = s.getRow((short)1); c = r.getCell((short)1); - + assertTrue("Formula is as expected",("1+1".equals(c.getCellFormula()))); in.close(); } - + /** * Add various integers */ - + public void testAddIntegers() throws Exception { binomialOperator("+"); } - + /** * Multiply various integers */ - + public void testMultplyIntegers() throws Exception { binomialOperator("*"); } - + /** * Subtract various integers */ @@ -99,7 +96,7 @@ extends TestCase { throws Exception { binomialOperator("-"); } - + /** * Subtract various integers */ @@ -107,7 +104,7 @@ extends TestCase { throws Exception { binomialOperator("/"); } - + /** * Exponentialize various integers; */ @@ -119,36 +116,36 @@ extends TestCase { /** * Concatinate two numbers 1&2 = 12 */ - public void testConcatIntegers() + public void testConcatIntegers() throws Exception { binomialOperator("&"); } - + /** * tests 1*2+3*4 */ - public void testOrderOfOperationsMultiply() + public void testOrderOfOperationsMultiply() throws Exception { orderTest("1*2+3*4"); } - + /** * tests 1*2+3^4 */ - public void testOrderOfOperationsPower() + public void testOrderOfOperationsPower() throws Exception { orderTest("1*2+3^4"); } - + /** * Tests that parenthesis are obeyed */ - public void testParenthesis() + public void testParenthesis() throws Exception { orderTest("(1*3)+2+(1+2)*(3^4)^5"); } - - public void testReferencesOpr() + + public void testReferencesOpr() throws Exception { String[] operation = new String[] { "+", "-", "*", "/", "^", "&" @@ -157,7 +154,7 @@ extends TestCase { operationRefTest(operation[k]); } } - + /** * Tests creating a file with floating point in a formula. * @@ -167,32 +164,31 @@ extends TestCase { floatTest("*"); floatTest("/"); } - + private void floatTest(String operator) throws Exception { - short rownum = 0; File file = TempFile.createTempFile("testFormulaFloat",".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; - + //get our minimum values - + r = s.createRow((short)0); c = r.createCell((short)1); c.setCellFormula(""+Float.MIN_VALUE + operator + Float.MIN_VALUE); - + for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2) ) { r = s.createRow((short) x); - + for (short y = 1; y < 256 && y > 0; y= (short) (y +2)) { - + c = r.createCell((short) y); c.setCellFormula("" + x+"."+y + operator + y +"."+x); - - + + } } if (s.getLastRowNum() < Short.MAX_VALUE) { @@ -205,21 +201,20 @@ extends TestCase { assertTrue("file exists",file.exists()); out=null;wb=null; //otherwise we get out of memory error! floatVerify(operator,file); - + } - + private void floatVerify(String operator, File file) throws Exception { - short rownum = 0; - + FileInputStream in = new FileInputStream(file); HSSFWorkbook wb = new HSSFWorkbook(in); HSSFSheet s = wb.getSheetAt(0); HSSFRow r = null; HSSFCell c = null; - - // dont know how to check correct result .. for the moment, we just verify that the file can be read. - + + // dont know how to check correct result .. for the moment, we just verify that the file can be read. + for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { r = s.getRow((short) x); @@ -227,40 +222,40 @@ extends TestCase { c = r.getCell((short) y); assertTrue("got a formula",c.getCellFormula()!=null); - + assertTrue("loop Formula is as expected "+x+"."+y+operator+y+"."+x+"!="+c.getCellFormula(),( (""+x+"."+y+operator+y+"."+x).equals(c.getCellFormula()) )); - + } } - + in.close(); assertTrue("file exists",file.exists()); } - - public void testAreaSum() + + public void testAreaSum() throws Exception { areaFunctionTest("SUM"); } - - public void testAreaAverage() + + public void testAreaAverage() throws Exception { areaFunctionTest("AVERAGE"); } - - public void testRefArraySum() + + public void testRefArraySum() throws Exception { refArrayFunctionTest("SUM"); } - - public void testAreaArraySum() + + public void testAreaArraySum() throws Exception { refAreaArrayFunctionTest("SUM"); } - - - private void operationRefTest(String operator) + + + private void operationRefTest(String operator) throws Exception { File file = TempFile.createTempFile("testFormula",".xls"); FileOutputStream out = new FileOutputStream(file); @@ -268,17 +263,17 @@ extends TestCase { HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; - + //get our minimum values r = s.createRow((short)0); c = r.createCell((short)1); c.setCellFormula("A2" + operator + "A3"); - + for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { r = s.createRow((short) x); - for (short y = 1; y < 256 && y > 0; y++) { - + for (short y = 1; y < 256 && y > 0; y++) { + String ref=null; String ref2=null; short refx1=0; @@ -292,7 +287,7 @@ extends TestCase { refx1=(short)(x-4); refx2=(short)(x-3); } - + if (y+50 < 255) { refy1=(short)(y+50); refy2=(short)(y+49); @@ -300,7 +295,7 @@ extends TestCase { refy1=(short)(y-4); refy2=(short)(y-3); } - + c = r.getCell((short) y); CellReference cr= new CellReference(refx1,refy1, false, false); ref=cr.formatAsString(); @@ -309,39 +304,38 @@ extends TestCase { c = r.createCell((short) y); c.setCellFormula("" + ref + operator + ref2); - - + + } } - + //make sure we do the maximum value of the Int operator if (s.getLastRowNum() < Short.MAX_VALUE) { r = s.createRow((short)0); c = r.createCell((short)0); c.setCellFormula("" + "B1" + operator + "IV255"); } - + wb.write(out); out.close(); assertTrue("file exists",file.exists()); operationalRefVerify(operator,file); } - + /** * Opens the sheet we wrote out by binomialOperator and makes sure the formulas * all match what we expect (x operator y) */ private void operationalRefVerify(String operator, File file) throws Exception { - short rownum = 0; - + FileInputStream in = new FileInputStream(file); HSSFWorkbook wb = new HSSFWorkbook(in); HSSFSheet s = wb.getSheetAt(0); HSSFRow r = null; HSSFCell c = null; - + //get our minimum values r = s.getRow((short)0); c = r.getCell((short)1); @@ -350,12 +344,12 @@ extends TestCase { ( ("A2"+operator+"A3").equals(c.getCellFormula()) )); - + for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { r = s.getRow((short) x); - for (short y = 1; y < 256 && y > 0; y++) { - + for (short y = 1; y < 256 && y > 0; y++) { + String ref=null; String ref2=null; short refx1=0; @@ -369,7 +363,7 @@ extends TestCase { refx1=(short)(x-4); refx2=(short)(x-3); } - + if (y+50 < 255) { refy1=(short)(y+50); refy2=(short)(y+49); @@ -383,36 +377,36 @@ extends TestCase { ref=cr.formatAsString(); cr=new CellReference(refx2,refy2, false, false); ref2=cr.formatAsString(); - - + + assertTrue("loop Formula is as expected "+ref+operator+ref2+"!="+c.getCellFormula(),( (""+ref+operator+ref2).equals(c.getCellFormula()) ) ); - - + + } } - + //test our maximum values r = s.getRow((short)0); c = r.getCell((short)0); - + assertTrue("maxval Formula is as expected",( ("B1"+operator+"IV255").equals(c.getCellFormula()) ) ); - + in.close(); assertTrue("file exists",file.exists()); } - - + + /** * tests order wrting out == order writing in for a given formula - */ - private void orderTest(String formula) + */ + private void orderTest(String formula) throws Exception { File file = TempFile.createTempFile("testFormula",".xls"); FileOutputStream out = new FileOutputStream(file); @@ -420,12 +414,12 @@ extends TestCase { HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; - + //get our minimum values r = s.createRow((short)0); c = r.createCell((short)1); c.setCellFormula(formula); - + wb.write(out); out.close(); assertTrue("file exists",file.exists()); @@ -433,17 +427,17 @@ extends TestCase { FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheetAt(0); - + //get our minimum values r = s.getRow((short)0); c = r.getCell((short)1); assertTrue("minval Formula is as expected", formula.equals(c.getCellFormula()) ); - + in.close(); } - + /** * All multi-binomial operator tests use this to create a worksheet with a * huge set of x operator y formulas. Next we call binomialVerify and verify @@ -451,19 +445,18 @@ extends TestCase { */ private void binomialOperator(String operator) throws Exception { - short rownum = 0; File file = TempFile.createTempFile("testFormula",".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; - + //get our minimum values r = s.createRow((short)0); c = r.createCell((short)1); c.setCellFormula(1 + operator + 1); - + for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { r = s.createRow((short) x); @@ -471,45 +464,44 @@ extends TestCase { c = r.createCell((short) y); c.setCellFormula("" + x + operator + y); - + } } - + //make sure we do the maximum value of the Int operator if (s.getLastRowNum() < Short.MAX_VALUE) { r = s.createRow((short)0); c = r.createCell((short)0); c.setCellFormula("" + Short.MAX_VALUE + operator + Short.MAX_VALUE); } - + wb.write(out); out.close(); assertTrue("file exists",file.exists()); - + binomialVerify(operator,file); } - + /** * Opens the sheet we wrote out by binomialOperator and makes sure the formulas * all match what we expect (x operator y) */ private void binomialVerify(String operator, File file) throws Exception { - short rownum = 0; - + FileInputStream in = new FileInputStream(file); HSSFWorkbook wb = new HSSFWorkbook(in); HSSFSheet s = wb.getSheetAt(0); HSSFRow r = null; HSSFCell c = null; - + //get our minimum values r = s.getRow((short)0); c = r.getCell((short)1); assertTrue("minval Formula is as expected 1"+operator+"1 != "+c.getCellFormula(), ( ("1"+operator+"1").equals(c.getCellFormula()) )); - + for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { r = s.getRow((short) x); @@ -521,35 +513,34 @@ extends TestCase { (""+x+operator+y).equals(c.getCellFormula()) ) ); - - + + } } - + //test our maximum values r = s.getRow((short)0); c = r.getCell((short)0); - - + + assertTrue("maxval Formula is as expected",( (""+Short.MAX_VALUE+operator+Short.MAX_VALUE).equals(c.getCellFormula()) ) ); - + in.close(); assertTrue("file exists",file.exists()); } - - + + /** * Writes a function then tests to see if its correct * */ - public void areaFunctionTest(String function) + public void areaFunctionTest(String function) throws Exception { - - short rownum = 0; + File file = TempFile.createTempFile("testFormulaAreaFunction"+function,".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); @@ -567,27 +558,26 @@ extends TestCase { wb.write(out); out.close(); assertTrue("file exists",file.exists()); - + FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheetAt(0); r = s.getRow(0); c = r.getCell((short)0); - + assertTrue("function ="+function+"(A2:A3)", ( (function+"(A2:A3)").equals((function+"(A2:A3)")) ) ); in.close(); } - + /** * Writes a function then tests to see if its correct * */ - public void refArrayFunctionTest(String function) + public void refArrayFunctionTest(String function) throws Exception { - - short rownum = 0; + File file = TempFile.createTempFile("testFormulaArrayFunction"+function,".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); @@ -605,28 +595,27 @@ extends TestCase { wb.write(out); out.close(); assertTrue("file exists",file.exists()); - + FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheetAt(0); r = s.getRow(0); c = r.getCell((short)0); - + assertTrue("function ="+function+"(A2,A3)", ( (function+"(A2,A3)").equals(c.getCellFormula()) ) ); in.close(); } - - + + /** * Writes a function then tests to see if its correct * */ - public void refAreaArrayFunctionTest(String function) + public void refAreaArrayFunctionTest(String function) throws Exception { - - short rownum = 0; + File file = TempFile.createTempFile("testFormulaAreaArrayFunction"+function,".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); @@ -645,26 +634,26 @@ extends TestCase { wb.write(out); out.close(); assertTrue("file exists",file.exists()); - + FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheetAt(0); r = s.getRow(0); c = r.getCell((short)0); - + assertTrue("function ="+function+"(A2:A4,B2:B4)", ( (function+"(A2:A4,B2:B4)").equals(c.getCellFormula()) ) ); - + c=r.getCell((short) 1); assertTrue("function ="+function+"($A$2:$A4,B$2:B4)", ( (function+"($A$2:$A4,B$2:B4)").equals(c.getCellFormula()) ) ); in.close(); } - - - + + + public void testAbsRefs() throws Exception { File file = TempFile.createTempFile("testFormulaAbsRef",".xls"); FileOutputStream out = new FileOutputStream(file); @@ -686,11 +675,11 @@ extends TestCase { c.setCellFormula("$A$3+$A$2"); c=r.createCell( (short) 4); c.setCellFormula("SUM($A$3,$A$2)"); - + wb.write(out); out.close(); assertTrue("file exists",file.exists()); - + FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheetAt(0); @@ -707,12 +696,10 @@ extends TestCase { assertTrue("SUM($A$3,$A$2)", ("SUM($A$3,$A$2)").equals(c.getCellFormula())); in.close(); } - + public void testSheetFunctions() throws IOException { - String filename = System.getProperty("HSSF.testdata.path"); - File file = TempFile.createTempFile("testSheetFormula",".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); @@ -722,7 +709,7 @@ extends TestCase { r = s.createRow((short)0); c = r.createCell((short)0);c.setCellValue(1); c = r.createCell((short)1);c.setCellValue(2); - + s = wb.createSheet("B"); r = s.createRow((short)0); c=r.createCell((short)0); c.setCellFormula("AVERAGE(A!A1:B1)"); @@ -730,9 +717,9 @@ extends TestCase { c=r.createCell((short)2); c.setCellFormula("A!$A$1+A!$B1"); wb.write(out); out.close(); - + assertTrue("file exists",file.exists()); - + FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheet("B"); @@ -743,7 +730,7 @@ extends TestCase { assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula())); in.close(); } - + public void testRVAoperands() throws Exception { File file = TempFile.createTempFile("testFormulaRVA",".xls"); FileOutputStream out = new FileOutputStream(file); @@ -767,26 +754,24 @@ extends TestCase { c.setCellFormula("POWER(A2,A3)"); c=r.createCell( (short) 5); c.setCellFormula("SIN(A2)"); - + c=r.createCell( (short) 6); c.setCellFormula("SUM(A2:A3)"); - + c=r.createCell( (short) 7); c.setCellFormula("SUM(A2,A3)"); - + r = s.createRow((short) 1);c=r.createCell( (short) 0); c.setCellValue(2.0); r = s.createRow((short) 2);c=r.createCell( (short) 0); c.setCellValue(3.0); - + wb.write(out); out.close(); assertTrue("file exists",file.exists()); } - + public void testStringFormulas() throws IOException { - String readFilename = System.getProperty("HSSF.testdata.path"); - File file = TempFile.createTempFile("testStringFormula",".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); @@ -797,25 +782,21 @@ extends TestCase { c=r.createCell((short)1); c.setCellFormula("UPPER(\"abc\")"); c=r.createCell((short)2); c.setCellFormula("LOWER(\"ABC\")"); c=r.createCell((short)3); c.setCellFormula("CONCATENATE(\" my \",\" name \")"); - + wb.write(out); out.close(); - - assertTrue("file exists",file.exists()); - - FileInputStream in = new FileInputStream(readFilename+File.separator+"StringFormulas.xls"); - wb = new HSSFWorkbook(in); + + wb = openSample("StringFormulas.xls"); s = wb.getSheetAt(0); r = s.getRow(0); c = r.getCell((short)0); assertTrue("expected: UPPER(\"xyz\") got "+c.getCellFormula(), ("UPPER(\"xyz\")").equals(c.getCellFormula())); //c = r.getCell((short)1); //assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula())); - in.close(); } - - - + + + public void testLogicalFormulas() throws IOException { @@ -829,26 +810,24 @@ extends TestCase { r = s.createRow((short)0); c=r.createCell((short)1); c.setCellFormula("IF(A10)); - - File nestedIf = TempFile.createTempFile("testNestedIfFormula",".xls"); - out = new FileOutputStream(nestedIf); - wb = new HSSFWorkbook(); - s = wb.createSheet("testSheet1"); - r = null; - c = null; - r = s.createRow((short)0); - c=r.createCell((short)0); - c.setCellValue(1); - - c=r.createCell((short)1); - c.setCellValue(3); - - - HSSFCell formulaCell=r.createCell((short)3); - - r = s.createRow((short)1); - c=r.createCell((short)0); - c.setCellValue(3); - - c=r.createCell((short)1); - c.setCellValue(7); - - formulaCell.setCellFormula("IF(A1=B1,AVERAGE(A1:B1),AVERAGE(A2:B2))"); - - - wb.write(out); - out.close(); - assertTrue("file exists", nestedIf.exists()); - - assertTrue("length of nestedIf file is zero", (nestedIf.length()>0)); + + File simpleIf = TempFile.createTempFile("testSimpleIfFormulaWrite",".xls"); + out = new FileOutputStream(simpleIf); + wb = new HSSFWorkbook(); + s = wb.createSheet("testSheet1"); + r = null; + c = null; + r = s.createRow((short)0); + c=r.createCell((short)0); c.setCellFormula("IF(1=1,0,1)"); + + wb.write(out); + out.close(); + assertTrue("file exists", simpleIf.exists()); + + assertTrue("length of simpleIf file is zero", (simpleIf.length()>0)); + + File nestedIf = TempFile.createTempFile("testNestedIfFormula",".xls"); + out = new FileOutputStream(nestedIf); + wb = new HSSFWorkbook(); + s = wb.createSheet("testSheet1"); + r = null; + c = null; + r = s.createRow((short)0); + c=r.createCell((short)0); + c.setCellValue(1); + + c=r.createCell((short)1); + c.setCellValue(3); + + + HSSFCell formulaCell=r.createCell((short)3); + + r = s.createRow((short)1); + c=r.createCell((short)0); + c.setCellValue(3); + + c=r.createCell((short)1); + c.setCellValue(7); + + formulaCell.setCellFormula("IF(A1=B1,AVERAGE(A1:B1),AVERAGE(A2:B2))"); + + + wb.write(out); + out.close(); + assertTrue("file exists", nestedIf.exists()); + + assertTrue("length of nestedIf file is zero", (nestedIf.length()>0)); } - public void testSumIf() - throws IOException - { - String readFilename = System.getProperty("HSSF.testdata.path"); - String function ="SUMIF(A1:A5,\">4000\",B1:B5)"; - - File inFile = new File(readFilename+"/sumifformula.xls"); - FileInputStream in = new FileInputStream(inFile); - HSSFWorkbook wb = new HSSFWorkbook(in); - in.close(); - - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r = s.getRow(0); - HSSFCell c = r.getCell((short)2); - assertEquals(function, c.getCellFormula()); - - - File file = TempFile.createTempFile("testSumIfFormula",".xls"); - FileOutputStream out = new FileOutputStream(file); - wb = new HSSFWorkbook(); - s = wb.createSheet(); - - r = s.createRow((short)0); - c=r.createCell((short)0); c.setCellValue((double)1000); - c=r.createCell((short)1); c.setCellValue((double)1); - - - r = s.createRow((short)1); - c=r.createCell((short)0); c.setCellValue((double)2000); - c=r.createCell((short)1); c.setCellValue((double)2); - - r = s.createRow((short)2); - c=r.createCell((short)0); c.setCellValue((double)3000); - c=r.createCell((short)1); c.setCellValue((double)3); - - r = s.createRow((short)3); - c=r.createCell((short)0); c.setCellValue((double)4000); - c=r.createCell((short)1); c.setCellValue((double)4); - - r = s.createRow((short)4); - c=r.createCell((short)0); c.setCellValue((double)5000); - c=r.createCell((short)1); c.setCellValue((double)5); - - r = s.getRow(0); - c=r.createCell((short)2); c.setCellFormula(function); - - wb.write(out); - out.close(); - - assertTrue("sumif file doesnt exists", (file.exists())); - assertTrue("sumif == 0 bytes", file.length() > 0); - } - - public void testSquareMacro() throws IOException { - File dir = new File(System.getProperty("HSSF.testdata.path")); - File xls = new File(dir, "SquareMacro.xls"); - FileInputStream in = new FileInputStream(xls); - HSSFWorkbook w; - try { - w = new HSSFWorkbook(in); - } finally { - in.close(); - } + public void testSumIf() + throws IOException + { + String function ="SUMIF(A1:A5,\">4000\",B1:B5)"; + + HSSFWorkbook wb = openSample("sumifformula.xls"); + + HSSFSheet s = wb.getSheetAt(0); + HSSFRow r = s.getRow(0); + HSSFCell c = r.getCell((short)2); + assertEquals(function, c.getCellFormula()); + + + File file = TempFile.createTempFile("testSumIfFormula",".xls"); + FileOutputStream out = new FileOutputStream(file); + wb = new HSSFWorkbook(); + s = wb.createSheet(); + + r = s.createRow((short)0); + c=r.createCell((short)0); c.setCellValue((double)1000); + c=r.createCell((short)1); c.setCellValue((double)1); + + + r = s.createRow((short)1); + c=r.createCell((short)0); c.setCellValue((double)2000); + c=r.createCell((short)1); c.setCellValue((double)2); + + r = s.createRow((short)2); + c=r.createCell((short)0); c.setCellValue((double)3000); + c=r.createCell((short)1); c.setCellValue((double)3); + + r = s.createRow((short)3); + c=r.createCell((short)0); c.setCellValue((double)4000); + c=r.createCell((short)1); c.setCellValue((double)4); + + r = s.createRow((short)4); + c=r.createCell((short)0); c.setCellValue((double)5000); + c=r.createCell((short)1); c.setCellValue((double)5); + + r = s.getRow(0); + c=r.createCell((short)2); c.setCellFormula(function); + + wb.write(out); + out.close(); + + assertTrue("sumif file doesnt exists", (file.exists())); + assertTrue("sumif == 0 bytes", file.length() > 0); + } + + public void testSquareMacro() { + HSSFWorkbook w = openSample("SquareMacro.xls"); + HSSFSheet s0 = w.getSheetAt(0); HSSFRow[] r = {s0.getRow(0), s0.getRow(1)}; @@ -1071,78 +1035,58 @@ extends TestCase { assertEquals(4d, d2.getNumericCellValue(), 1e-9); } - public void testStringFormulaRead() throws IOException { - File dir = new File(System.getProperty("HSSF.testdata.path")); - File xls = new File(dir, "StringFormulas.xls"); - FileInputStream in = new FileInputStream(xls); - HSSFWorkbook w; - try { - w = new HSSFWorkbook(in); - } finally { - in.close(); - } + public void testStringFormulaRead() { + HSSFWorkbook w = openSample("StringFormulas.xls"); HSSFCell c = w.getSheetAt(0).getRow(0).getCell((short)0); - assertEquals("String Cell value","XYZ",c.getStringCellValue()); + assertEquals("String Cell value","XYZ",c.getRichStringCellValue().getString()); } - + /** test for bug 34021*/ public void testComplexSheetRefs () throws IOException { - HSSFWorkbook sb = new HSSFWorkbook(); - HSSFSheet s1 = sb.createSheet("Sheet a.1"); - HSSFSheet s2 = sb.createSheet("Sheet.A"); - s2.createRow(1).createCell((short) 2).setCellFormula("'Sheet a.1'!A1"); - s1.createRow(1).createCell((short) 2).setCellFormula("'Sheet.A'!A1"); - File file = TempFile.createTempFile("testComplexSheetRefs",".xls"); - sb.write(new FileOutputStream(file)); + HSSFWorkbook sb = new HSSFWorkbook(); + HSSFSheet s1 = sb.createSheet("Sheet a.1"); + HSSFSheet s2 = sb.createSheet("Sheet.A"); + s2.createRow(1).createCell((short) 2).setCellFormula("'Sheet a.1'!A1"); + s1.createRow(1).createCell((short) 2).setCellFormula("'Sheet.A'!A1"); + File file = TempFile.createTempFile("testComplexSheetRefs",".xls"); + sb.write(new FileOutputStream(file)); + } + + /*Unknown Ptg 3C*/ + public void test27272_1() throws Exception { + HSSFWorkbook wb = openSample("27272_1.xls"); + wb.getSheetAt(0); + assertEquals("Reference for named range ", "#REF!",wb.getNameAt(0).getReference()); + File outF = File.createTempFile("bug27272_1",".xls"); + wb.write(new FileOutputStream(outF)); + System.out.println("Open "+outF.getAbsolutePath()+" in Excel"); + } + /*Unknown Ptg 3D*/ + public void test27272_2() throws Exception { + HSSFWorkbook wb = openSample("27272_2.xls"); + assertEquals("Reference for named range ", "#REF!",wb.getNameAt(0).getReference()); + File outF = File.createTempFile("bug27272_2",".xls"); + wb.write(new FileOutputStream(outF)); + System.out.println("Open "+outF.getAbsolutePath()+" in Excel"); } - - /*Unknown Ptg 3C*/ - public void test27272_1() throws Exception { - String readFilename = System.getProperty("HSSF.testdata.path"); - File inFile = new File(readFilename+"/27272_1.xls"); - FileInputStream in = new FileInputStream(inFile); - HSSFWorkbook wb = new HSSFWorkbook(in); - wb.getSheetAt(0); - assertEquals("Reference for named range ", "#REF!",wb.getNameAt(0).getReference()); - File outF = File.createTempFile("bug27272_1",".xls"); - wb.write(new FileOutputStream(outF)); - System.out.println("Open "+outF.getAbsolutePath()+" in Excel"); - } - /*Unknown Ptg 3D*/ - public void test27272_2() throws Exception { - String readFilename = System.getProperty("HSSF.testdata.path"); - File inFile = new File(readFilename+"/27272_2.xls"); - FileInputStream in = new FileInputStream(inFile); - HSSFWorkbook wb = new HSSFWorkbook(in); - assertEquals("Reference for named range ", "#REF!",wb.getNameAt(0).getReference()); - File outF = File.createTempFile("bug27272_2",".xls"); - wb.write(new FileOutputStream(outF)); - System.out.println("Open "+outF.getAbsolutePath()+" in Excel"); - } - - /* MissingArgPtg */ - public void testMissingArgPtg() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell((short) 0); - cell.setCellFormula("IF(A1=\"A\",1,)"); - } - - public void testSharedFormula() throws Exception { - String readFilename = System.getProperty("HSSF.testdata.path"); - File inFile = new File(readFilename+"/SharedFormulaTest.xls"); - FileInputStream fis = new FileInputStream(inFile); - HSSFWorkbook wb = new HSSFWorkbook(fis); - - assertEquals("A$1*2", wb.getSheetAt(0).getRow(1).getCell((short)1).toString()); - assertEquals("$A11*2", wb.getSheetAt(0).getRow(11).getCell((short)1).toString()); - assertEquals("DZ2*2", wb.getSheetAt(0).getRow(1).getCell((short)128).toString()); - assertEquals("B32770*2", wb.getSheetAt(0).getRow(32768).getCell((short)1).toString()); - } - + + /* MissingArgPtg */ + public void testMissingArgPtg() throws Exception { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell((short) 0); + cell.setCellFormula("IF(A1=\"A\",1,)"); + } + + public void testSharedFormula() { + HSSFWorkbook wb = openSample("SharedFormulaTest.xls"); + + assertEquals("A$1*2", wb.getSheetAt(0).getRow(1).getCell((short)1).toString()); + assertEquals("$A11*2", wb.getSheetAt(0).getRow(11).getCell((short)1).toString()); + assertEquals("DZ2*2", wb.getSheetAt(0).getRow(1).getCell((short)128).toString()); + assertEquals("B32770*2", wb.getSheetAt(0).getRow(32768).getCell((short)1).toString()); + } + public static void main(String [] args) { - System.out - .println("Testing org.apache.poi.hssf.usermodel.TestFormulas"); junit.textui.TestRunner.run(TestFormulas.class); } - } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java index 38d3b89295..a2e8bd3baa 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java @@ -17,18 +17,21 @@ package org.apache.poi.hssf.usermodel; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.IOException; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.AssertionFailedError; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.model.Sheet; import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.TempFile; /** @@ -40,12 +43,26 @@ import org.apache.poi.util.TempFile; */ public final class TestHSSFCell extends TestCase { + private static HSSFWorkbook openSample(String sampleFileName) { + return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); + } + private static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) { + + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); + original.write(baos); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + return new HSSFWorkbook(bais); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + /** * test that Boolean and Error types (BoolErrRecord) are supported properly. */ public void testBoolErr() throws java.io.IOException { - String readFilename = System.getProperty("HSSF.testdata.path"); File file = TempFile.createTempFile("testBoolErr",".xls"); FileOutputStream out = new FileOutputStream(file); @@ -102,33 +119,24 @@ public final class TestHSSFCell extends TestCase { public void testDateWindowingRead() throws Exception { GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000 Date date = cal.getTime(); - String path = System.getProperty("HSSF.testdata.path"); // first check a file with 1900 Date Windowing - String filename = path + "/1900DateWindowing.xls"; - FileInputStream stream = new FileInputStream(filename); - POIFSFileSystem fs = new POIFSFileSystem(stream); - HSSFWorkbook workbook = new HSSFWorkbook(fs); + HSSFWorkbook workbook = openSample("1900DateWindowing.xls"); HSSFSheet sheet = workbook.getSheetAt(0); assertEquals("Date from file using 1900 Date Windowing", date.getTime(), sheet.getRow(0).getCell((short)0) .getDateCellValue().getTime()); - stream.close(); // now check a file with 1904 Date Windowing - filename = path + "/1904DateWindowing.xls"; - stream = new FileInputStream(filename); - fs = new POIFSFileSystem(stream); - workbook = new HSSFWorkbook(fs); + workbook = openSample("1904DateWindowing.xls"); sheet = workbook.getSheetAt(0); assertEquals("Date from file using 1904 Date Windowing", date.getTime(), sheet.getRow(0).getCell((short)0) .getDateCellValue().getTime()); - stream.close(); } /** @@ -140,55 +148,39 @@ public final class TestHSSFCell extends TestCase { public void testDateWindowingWrite() throws Exception { GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000 Date date = cal.getTime(); - String path = System.getProperty("HSSF.testdata.path"); // first check a file with 1900 Date Windowing - String filename = path + "/1900DateWindowing.xls"; - writeCell(filename, 0, (short) 1, date); + HSSFWorkbook wb; + wb = openSample("1900DateWindowing.xls"); + + setCell(wb, 0, 1, date); + wb = writeOutAndReadBack(wb); + assertEquals("Date from file using 1900 Date Windowing", date.getTime(), - readCell(filename, 0, (short) 1).getTime()); + readCell(wb, 0, 1).getTime()); // now check a file with 1904 Date Windowing - filename = path + "/1904DateWindowing.xls"; - writeCell(filename, 0, (short) 1, date); + wb = openSample("1904DateWindowing.xls"); + setCell(wb, 0, 1, date); + wb = writeOutAndReadBack(wb); assertEquals("Date from file using 1900 Date Windowing", date.getTime(), - readCell(filename, 0, (short) 1).getTime()); + readCell(wb, 0, 1).getTime()); } - /** - * Sets cell value and writes file. - */ - private void writeCell(String filename, - int rowIdx, short colIdx, Date date) throws Exception { - FileInputStream stream = new FileInputStream(filename); - POIFSFileSystem fs = new POIFSFileSystem(stream); - HSSFWorkbook workbook = new HSSFWorkbook(fs); + private static void setCell(HSSFWorkbook workbook, int rowIdx, int colIdx, Date date) { HSSFSheet sheet = workbook.getSheetAt(0); HSSFRow row = sheet.getRow(rowIdx); HSSFCell cell = row.getCell(colIdx); if (cell == null) { - cell = row.createCell(colIdx); + cell = row.createCell((short)colIdx); } cell.setCellValue(date); - - // Write the file - stream.close(); - FileOutputStream oStream = new FileOutputStream(filename); - workbook.write(oStream); - oStream.close(); } - /** - * Reads cell value from file. - */ - private Date readCell(String filename, - int rowIdx, short colIdx) throws Exception { - FileInputStream stream = new FileInputStream(filename); - POIFSFileSystem fs = new POIFSFileSystem(stream); - HSSFWorkbook workbook = new HSSFWorkbook(fs); + private static Date readCell(HSSFWorkbook workbook, int rowIdx, int colIdx) { HSSFSheet sheet = workbook.getSheetAt(0); HSSFRow row = sheet.getRow(rowIdx); HSSFCell cell = row.getCell(colIdx); @@ -201,12 +193,7 @@ public final class TestHSSFCell extends TestCase { public void testActiveCell() throws Exception { //read in sample - String dir = System.getProperty("HSSF.testdata.path"); - File sample = new File(dir + "/Simple.xls"); - assertTrue("Simple.xls exists and is readable", sample.canRead()); - FileInputStream fis = new FileInputStream(sample); - HSSFWorkbook book = new HSSFWorkbook(fis); - fis.close(); + HSSFWorkbook book = openSample("Simple.xls"); //check initial position HSSFSheet umSheet = book.getSheetAt(0); @@ -225,14 +212,8 @@ public final class TestHSSFCell extends TestCase { 3, s.getActiveCellRow()); //write book to temp file; read and verify that position is serialized - File temp = TempFile.createTempFile("testActiveCell", ".xls"); - FileOutputStream fos = new FileOutputStream(temp); - book.write(fos); - fos.close(); - - fis = new FileInputStream(temp); - book = new HSSFWorkbook(fis); - fis.close(); + book = writeOutAndReadBack(book); + umSheet = book.getSheetAt(0); s = umSheet.getSheet(); @@ -245,12 +226,8 @@ public final class TestHSSFCell extends TestCase { /** * test that Cell Styles being applied to formulas remain intact */ - public void testFormulaStyle() - throws java.io.IOException { - String readFilename = System.getProperty("HSSF.testdata.path"); + public void testFormulaStyle() { - File file = TempFile.createTempFile("testFormulaStyle",".xls"); - FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet("testSheet1"); HSSFRow r = null; @@ -258,7 +235,7 @@ public final class TestHSSFCell extends TestCase { HSSFCellStyle cs = wb.createCellStyle(); HSSFFont f = wb.createFont(); f.setFontHeightInPoints((short) 20); - f.setColor((short) HSSFColor.RED.index); + f.setColor(HSSFColor.RED.index); f.setBoldweight(f.BOLDWEIGHT_BOLD); f.setFontName("Arial Unicode MS"); cs.setFillBackgroundColor((short)3); @@ -273,13 +250,7 @@ public final class TestHSSFCell extends TestCase { c.setCellStyle(cs); c.setCellFormula("2*3"); - wb.write(out); - out.close(); - - assertTrue("file exists",file.exists()); - - FileInputStream in = new FileInputStream(file); - wb = new HSSFWorkbook(in); + wb = writeOutAndReadBack(wb); s = wb.getSheetAt(0); r = s.getRow(0); c = r.getCell((short)0); @@ -293,17 +264,14 @@ public final class TestHSSFCell extends TestCase { assertTrue("Left Border", (cs.getBorderLeft() == (short)1)); assertTrue("Right Border", (cs.getBorderRight() == (short)1)); assertTrue("Bottom Border", (cs.getBorderBottom() == (short)1)); - - in.close(); } /** * Test reading hyperlinks */ - public void testWithHyperlink() throws Exception { - String dir = System.getProperty("HSSF.testdata.path"); - File f = new File(dir, "WithHyperlink.xls"); - HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(f)); + public void testWithHyperlink() { + + HSSFWorkbook wb = openSample("WithHyperlink.xls"); HSSFSheet sheet = wb.getSheetAt(0); HSSFCell cell = sheet.getRow(4).getCell((short)0); @@ -320,10 +288,9 @@ public final class TestHSSFCell extends TestCase { * Test reading hyperlinks */ public void testWithTwoHyperlinks() throws Exception { - String dir = System.getProperty("HSSF.testdata.path"); - File f = new File(dir, "WithTwoHyperLinks.xls"); - HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(f)); - + + HSSFWorkbook wb = openSample("WithTwoHyperLinks.xls"); + HSSFSheet sheet = wb.getSheetAt(0); HSSFCell cell1 = sheet.getRow(4).getCell((short)0); @@ -346,38 +313,38 @@ public final class TestHSSFCell extends TestCase { /*tests the toString() method of HSSFCell*/ public void testToString() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet("Sheet1"); - HSSFRow r = s.createRow(0); - HSSFCell c; - c=r.createCell((short) 0); c.setCellValue(true); - assertEquals("Boolean", "TRUE", c.toString()); - c=r.createCell((short) 1); c.setCellValue(1.5); - assertEquals("Numeric", "1.5", c.toString()); - c=r.createCell((short)(2)); c.setCellValue("Astring"); - assertEquals("String", "Astring", c.toString()); - c=r.createCell((short) 3); c.setCellErrorValue((byte) 7); - assertEquals("Error", "#ERR7", c.toString()); - c=r.createCell((short)4); c.setCellFormula("A1+B1"); - assertEquals("Formula", "A1+B1", c.toString()); - - //Write out the file, read it in, and then check cell values - File f = File.createTempFile("testCellToString",".xls"); - wb.write(new FileOutputStream(f)); - wb = new HSSFWorkbook(new FileInputStream(f)); - assertTrue("File exists and can be read", f.canRead()); - - s = wb.getSheetAt(0);r=s.getRow(0); - c=r.getCell((short) 0); - assertEquals("Boolean", "TRUE", c.toString()); - c=r.getCell((short) 1); - assertEquals("Numeric", "1.5", c.toString()); - c=r.getCell((short)(2)); - assertEquals("String", "Astring", c.toString()); - c=r.getCell((short) 3); - assertEquals("Error", "#ERR7", c.toString()); - c=r.getCell((short)4); - assertEquals("Formula", "A1+B1", c.toString()); + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet s = wb.createSheet("Sheet1"); + HSSFRow r = s.createRow(0); + HSSFCell c; + c=r.createCell((short) 0); c.setCellValue(true); + assertEquals("Boolean", "TRUE", c.toString()); + c=r.createCell((short) 1); c.setCellValue(1.5); + assertEquals("Numeric", "1.5", c.toString()); + c=r.createCell((short)(2)); c.setCellValue(new HSSFRichTextString("Astring")); + assertEquals("String", "Astring", c.toString()); + c=r.createCell((short) 3); c.setCellErrorValue((byte) 7); + assertEquals("Error", "#ERR7", c.toString()); + c=r.createCell((short)4); c.setCellFormula("A1+B1"); + assertEquals("Formula", "A1+B1", c.toString()); + + //Write out the file, read it in, and then check cell values + File f = File.createTempFile("testCellToString",".xls"); + wb.write(new FileOutputStream(f)); + wb = new HSSFWorkbook(new FileInputStream(f)); + assertTrue("File exists and can be read", f.canRead()); + + s = wb.getSheetAt(0);r=s.getRow(0); + c=r.getCell((short) 0); + assertEquals("Boolean", "TRUE", c.toString()); + c=r.getCell((short) 1); + assertEquals("Numeric", "1.5", c.toString()); + c=r.getCell((short)(2)); + assertEquals("String", "Astring", c.toString()); + c=r.getCell((short) 3); + assertEquals("Error", "#ERR7", c.toString()); + c=r.getCell((short)4); + assertEquals("Formula", "A1+B1", c.toString()); } public void testSetStringInFormulaCell_bug44606() { @@ -392,10 +359,7 @@ public final class TestHSSFCell extends TestCase { } public static void main(String [] args) { - System.out - .println("Testing org.apache.poi.hssf.usermodel.TestHSSFCell"); junit.textui.TestRunner.run(TestHSSFCell.class); } - } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java index 6a977effb8..369aa26658 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java @@ -20,13 +20,14 @@ import junit.framework.TestCase; import java.io.*; +import org.apache.poi.hssf.HSSFTestDataSamples; + /** * Tests TestHSSFCellComment. * * @author Yegor Kozlov */ - -public class TestHSSFComment extends TestCase { +public final class TestHSSFComment extends TestCase { /** * Test that we can create cells and add comments to it. @@ -103,12 +104,9 @@ public class TestHSSFComment extends TestCase { /** * test that we can read cell comments from an existing workbook. */ - public static void testReadComments() throws Exception { + public static void testReadComments() { - String dir = System.getProperty("HSSF.testdata.path"); - FileInputStream is = new FileInputStream(new File(dir, "SimpleWithComments.xls")); - HSSFWorkbook wb = new HSSFWorkbook(is); - is.close(); + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithComments.xls"); HSSFSheet sheet = wb.getSheetAt(0); @@ -143,12 +141,9 @@ public class TestHSSFComment extends TestCase { /** * test that we can modify existing cell comments */ - public static void testModifyComments() throws Exception { + public static void testModifyComments() throws IOException { - String dir = System.getProperty("HSSF.testdata.path"); - FileInputStream is = new FileInputStream(new File(dir, "SimpleWithComments.xls")); - HSSFWorkbook wb = new HSSFWorkbook(is); - is.close(); + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithComments.xls"); HSSFSheet sheet = wb.getSheetAt(0); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java index d03a3a4071..930970ea22 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java @@ -28,7 +28,7 @@ import org.apache.poi.ss.util.Region; */ public final class TestHSSFConditionalFormatting extends TestCase { - public void testLastAndFirstColumns() + public void testCreateCF() { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(); @@ -82,9 +82,27 @@ public final class TestHSSFConditionalFormatting extends TestCase HSSFConditionalFormattingRule rule1 = cf.getRule(0); assertEquals("7",rule1.getFormula1()); assertNull(rule1.getFormula2()); + + HSSFFontFormatting r1fp = rule1.getFontFormatting(); + assertNotNull(r1fp); + + assertTrue(r1fp.isItalic()); + assertFalse(r1fp.isBold()); + + HSSFBorderFormatting r1bf = rule1.getBorderFormatting(); + assertNotNull(r1bf); + assertEquals(HSSFBorderFormatting.BORDER_THIN, r1bf.getBorderBottom()); + assertEquals(HSSFBorderFormatting.BORDER_THICK,r1bf.getBorderTop()); + assertEquals(HSSFBorderFormatting.BORDER_DASHED,r1bf.getBorderLeft()); + assertEquals(HSSFBorderFormatting.BORDER_DOTTED,r1bf.getBorderRight()); + + HSSFPatternFormatting r1pf = rule1.getPatternFormatting(); + assertNotNull(r1pf); + assertEquals(HSSFColor.RED.index,r1pf.getFillBackgroundColor()); HSSFConditionalFormattingRule rule2 = cf.getRule(1); assertEquals("2",rule2.getFormula2()); assertEquals("1",rule2.getFormula1()); } + } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java index 766c14e07a..cd0901a291 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java @@ -19,16 +19,15 @@ package org.apache.poi.hssf.usermodel; -import junit.framework.TestCase; - -import java.io.FileInputStream; -import java.util.Date; import java.util.Calendar; +import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; +import junit.framework.TestCase; + +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.model.Workbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; /** * Class TestHSSFDateUtil @@ -40,16 +39,13 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; * @author Alex Jacoby (ajacoby at gmail.com) * @version %I%, %G% */ +public class TestHSSFDateUtil extends TestCase { -public class TestHSSFDateUtil - extends TestCase -{ - - public static final int CALENDAR_JANUARY = 0; - public static final int CALENDAR_FEBRUARY = 1; - public static final int CALENDAR_MARCH = 2; - public static final int CALENDAR_APRIL = 3; - public static final int CALENDAR_JULY = 6; + public static final int CALENDAR_JANUARY = 0; + public static final int CALENDAR_FEBRUARY = 1; + public static final int CALENDAR_MARCH = 2; + public static final int CALENDAR_APRIL = 3; + public static final int CALENDAR_JULY = 6; public static final int CALENDAR_OCTOBER = 9; public TestHSSFDateUtil(String s) @@ -223,77 +219,77 @@ public class TestHSSFDateUtil * Tests that we correctly detect date formats as such */ public void testIdentifyDateFormats() { - // First up, try with a few built in date formats - short[] builtins = new short[] { 0x0e, 0x0f, 0x10, 0x16, 0x2d, 0x2e }; - for(int i=0; iHSSFPicture. * @@ -58,9 +58,8 @@ public final class TestHSSFPicture extends TestCase{ private static byte[] getTestDataFileContent(String fileName) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); - String readFilename = System.getProperty("HSSF.testdata.path"); try { - InputStream fis = new FileInputStream(readFilename+File.separator+fileName); + InputStream fis = HSSFTestDataSamples.openSampleFileStream(fileName); byte[] buf = new byte[512]; while(true) { diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java index b58bb88d68..bac1ad5782 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java @@ -15,20 +15,19 @@ limitations under the License. ==================================================================== */ - -/* - * HSSFWorkbook.java - * - * Created on September 30, 2001, 3:37 PM - */ package org.apache.poi.hssf.usermodel; -import junit.framework.TestCase; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.Iterator; +import java.util.List; import javax.imageio.ImageIO; -import java.io.*; -import java.util.*; -import java.awt.image.BufferedImage; + +import junit.framework.TestCase; + +import org.apache.poi.hssf.HSSFTestDataSamples; /** * Test HSSFPictureData. @@ -37,14 +36,11 @@ import java.awt.image.BufferedImage; * @author Yegor Kozlov (yegor at apache dot org) * @author Trejkaz (trejkaz at trypticon dot org) */ -public class TestHSSFPictureData extends TestCase{ +public final class TestHSSFPictureData extends TestCase{ - static String cwd = System.getProperty("HSSF.testdata.path"); public void testPictures() throws IOException { - FileInputStream is = new FileInputStream(new File(cwd, "SimpleWithImages.xls")); - HSSFWorkbook wb = new HSSFWorkbook(is); - is.close(); + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithImages.xls"); List lst = wb.getAllPictures(); //assertEquals(2, lst.size()); @@ -69,6 +65,5 @@ public class TestHSSFPictureData extends TestCase{ //TODO: test code for PICT, WMF and EMF } } - } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java index f3283677b9..92a8325ef7 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,7 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.usermodel; @@ -27,6 +25,7 @@ import java.io.FileOutputStream; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.model.Sheet; import org.apache.poi.hssf.record.HCenterRecord; import org.apache.poi.hssf.record.PasswordRecord; @@ -35,7 +34,6 @@ import org.apache.poi.hssf.record.SCLRecord; import org.apache.poi.hssf.record.VCenterRecord; import org.apache.poi.hssf.record.WSBoolRecord; import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.util.Region; import org.apache.poi.util.TempFile; @@ -46,395 +44,381 @@ import org.apache.poi.util.TempFile; * @author Glen Stampoultzis (glens at apache.org) * @author Andrew C. Oliver (acoliver apache org) */ +public final class TestHSSFSheet extends TestCase { + + private static HSSFWorkbook openSample(String sampleFileName) { + return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); + } + + /** + * Test the gridset field gets set as expected. + */ + + public void testBackupRecord() + throws Exception + { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet s = wb.createSheet(); + Sheet sheet = s.getSheet(); + + assertEquals(true, sheet.getGridsetRecord().getGridset()); + s.setGridsPrinted(true); + assertEquals(false, sheet.getGridsetRecord().getGridset()); + } + + /** + * Test vertically centered output. + */ + + public void testVerticallyCenter() + throws Exception + { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet s = wb.createSheet(); + Sheet sheet = s.getSheet(); + VCenterRecord record = + (VCenterRecord) sheet.findFirstRecordBySid(VCenterRecord.sid); + + assertEquals(false, record.getVCenter()); + s.setVerticallyCenter(true); + assertEquals(true, record.getVCenter()); + + // wb.write(new FileOutputStream("c:\\test.xls")); + } + + /** + * Test horizontally centered output. + */ + + public void testHorizontallyCenter() + throws Exception + { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet s = wb.createSheet(); + Sheet sheet = s.getSheet(); + HCenterRecord record = + (HCenterRecord) sheet.findFirstRecordBySid(HCenterRecord.sid); + + assertEquals(false, record.getHCenter()); + s.setHorizontallyCenter(true); + assertEquals(true, record.getHCenter()); + + } + + + /** + * Test WSBboolRecord fields get set in the user model. + */ + + public void testWSBool() + { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet s = wb.createSheet(); + Sheet sheet = s.getSheet(); + WSBoolRecord record = + (WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid); + + // Check defaults + assertEquals(true, record.getAlternateExpression()); + assertEquals(true, record.getAlternateFormula()); + assertEquals(false, record.getAutobreaks()); + assertEquals(false, record.getDialog()); + assertEquals(false, record.getDisplayGuts()); + assertEquals(true, record.getFitToPage()); + assertEquals(false, record.getRowSumsBelow()); + assertEquals(false, record.getRowSumsRight()); + + // Alter + s.setAlternativeExpression(false); + s.setAlternativeFormula(false); + s.setAutobreaks(true); + s.setDialog(true); + s.setDisplayGuts(true); + s.setFitToPage(false); + s.setRowSumsBelow(true); + s.setRowSumsRight(true); + + // Check + assertEquals(false, record.getAlternateExpression()); + assertEquals(false, record.getAlternateFormula()); + assertEquals(true, record.getAutobreaks()); + assertEquals(true, record.getDialog()); + assertEquals(true, record.getDisplayGuts()); + assertEquals(false, record.getFitToPage()); + assertEquals(true, record.getRowSumsBelow()); + assertEquals(true, record.getRowSumsRight()); + assertEquals(false, s.getAlternateExpression()); + assertEquals(false, s.getAlternateFormula()); + assertEquals(true, s.getAutobreaks()); + assertEquals(true, s.getDialog()); + assertEquals(true, s.getDisplayGuts()); + assertEquals(false, s.getFitToPage()); + assertEquals(true, s.getRowSumsBelow()); + assertEquals(true, s.getRowSumsRight()); + } -public class TestHSSFSheet - extends TestCase -{ - public TestHSSFSheet(String s) - { - super(s); - } - - /** - * Test the gridset field gets set as expected. - */ - - public void testBackupRecord() - throws Exception - { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - Sheet sheet = s.getSheet(); - - assertEquals(true, sheet.getGridsetRecord().getGridset()); - s.setGridsPrinted(true); - assertEquals(false, sheet.getGridsetRecord().getGridset()); - } - - /** - * Test vertically centered output. - */ - - public void testVerticallyCenter() - throws Exception - { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - Sheet sheet = s.getSheet(); - VCenterRecord record = - (VCenterRecord) sheet.findFirstRecordBySid(VCenterRecord.sid); - - assertEquals(false, record.getVCenter()); - s.setVerticallyCenter(true); - assertEquals(true, record.getVCenter()); - - // wb.write(new FileOutputStream("c:\\test.xls")); - } - - /** - * Test horizontally centered output. - */ - - public void testHorizontallyCenter() - throws Exception - { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - Sheet sheet = s.getSheet(); - HCenterRecord record = - (HCenterRecord) sheet.findFirstRecordBySid(HCenterRecord.sid); - - assertEquals(false, record.getHCenter()); - s.setHorizontallyCenter(true); - assertEquals(true, record.getHCenter()); - - } - - - /** - * Test WSBboolRecord fields get set in the user model. - */ - - public void testWSBool() - { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - Sheet sheet = s.getSheet(); - WSBoolRecord record = - (WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid); - - // Check defaults - assertEquals(true, record.getAlternateExpression()); - assertEquals(true, record.getAlternateFormula()); - assertEquals(false, record.getAutobreaks()); - assertEquals(false, record.getDialog()); - assertEquals(false, record.getDisplayGuts()); - assertEquals(true, record.getFitToPage()); - assertEquals(false, record.getRowSumsBelow()); - assertEquals(false, record.getRowSumsRight()); - - // Alter - s.setAlternativeExpression(false); - s.setAlternativeFormula(false); - s.setAutobreaks(true); - s.setDialog(true); - s.setDisplayGuts(true); - s.setFitToPage(false); - s.setRowSumsBelow(true); - s.setRowSumsRight(true); - - // Check - assertEquals(false, record.getAlternateExpression()); - assertEquals(false, record.getAlternateFormula()); - assertEquals(true, record.getAutobreaks()); - assertEquals(true, record.getDialog()); - assertEquals(true, record.getDisplayGuts()); - assertEquals(false, record.getFitToPage()); - assertEquals(true, record.getRowSumsBelow()); - assertEquals(true, record.getRowSumsRight()); - assertEquals(false, s.getAlternateExpression()); - assertEquals(false, s.getAlternateFormula()); - assertEquals(true, s.getAutobreaks()); - assertEquals(true, s.getDialog()); - assertEquals(true, s.getDisplayGuts()); - assertEquals(false, s.getFitToPage()); - assertEquals(true, s.getRowSumsBelow()); - assertEquals(true, s.getRowSumsRight()); - } - - public void testReadBooleans() - throws Exception - { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test boolean"); - HSSFRow row = sheet.createRow((short) 2); - HSSFCell cell = row.createCell((short) 9); - cell.setCellValue(true); - cell = row.createCell((short) 11); - cell.setCellValue(true); - File tempFile = TempFile.createTempFile("bool", "test.xls"); - FileOutputStream stream = new FileOutputStream(tempFile); - workbook.write(stream); - stream.close(); - - FileInputStream readStream = new FileInputStream(tempFile); - workbook = new HSSFWorkbook(readStream); - sheet = workbook.getSheetAt(0); - row = sheet.getRow(2); - stream.close(); - tempFile.delete(); - assertNotNull(row); - assertEquals(2, row.getPhysicalNumberOfCells()); - } - - public void testRemoveRow() - { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test boolean"); - HSSFRow row = sheet.createRow((short) 2); - sheet.removeRow(row); - } - - public void testCloneSheet() { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test Clone"); - HSSFRow row = sheet.createRow((short) 0); - HSSFCell cell = row.createCell((short) 0); - cell.setCellValue("clone_test"); - HSSFSheet cloned = workbook.cloneSheet(0); + public void testReadBooleans() + throws Exception + { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet("Test boolean"); + HSSFRow row = sheet.createRow((short) 2); + HSSFCell cell = row.createCell((short) 9); + cell.setCellValue(true); + cell = row.createCell((short) 11); + cell.setCellValue(true); + File tempFile = TempFile.createTempFile("bool", "test.xls"); + FileOutputStream stream = new FileOutputStream(tempFile); + workbook.write(stream); + stream.close(); + + FileInputStream readStream = new FileInputStream(tempFile); + workbook = new HSSFWorkbook(readStream); + sheet = workbook.getSheetAt(0); + row = sheet.getRow(2); + stream.close(); + tempFile.delete(); + assertNotNull(row); + assertEquals(2, row.getPhysicalNumberOfCells()); + } + + public void testRemoveRow() + { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet("Test boolean"); + HSSFRow row = sheet.createRow((short) 2); + sheet.removeRow(row); + } + + public void testCloneSheet() { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet("Test Clone"); + HSSFRow row = sheet.createRow((short) 0); + HSSFCell cell = row.createCell((short) 0); + cell.setCellValue("clone_test"); + HSSFSheet cloned = workbook.cloneSheet(0); - //Check for a good clone - assertEquals(cloned.getRow((short)0).getCell((short)0).getStringCellValue(), "clone_test"); - - //Check that the cells are not somehow linked - cell.setCellValue("Difference Check"); - assertEquals(cloned.getRow((short)0).getCell((short)0).getStringCellValue(), "clone_test"); - } - - /** tests that the sheet name for multiple clones of the same sheet is unique - * BUG 37416 - */ - public void testCloneSheetMultipleTimes() { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test Clone"); - HSSFRow row = sheet.createRow((short) 0); - HSSFCell cell = row.createCell((short) 0); - cell.setCellValue("clone_test"); - //Clone the sheet multiple times - workbook.cloneSheet(0); - workbook.cloneSheet(0); - - assertNotNull(workbook.getSheet("Test Clone")); - assertNotNull(workbook.getSheet("Test Clone(1)")); - assertNotNull(workbook.getSheet("Test Clone(2)")); - } - - /** - * Setting landscape and portrait stuff on new sheets - */ - public void testPrintSetupLandscapeNew() throws Exception { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheetL = workbook.createSheet("LandscapeS"); - HSSFSheet sheetP = workbook.createSheet("LandscapeP"); - - // Check two aspects of the print setup - assertFalse(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetP.getPrintSetup().getLandscape()); - assertEquals(0, sheetL.getPrintSetup().getCopies()); - assertEquals(0, sheetP.getPrintSetup().getCopies()); - - // Change one on each - sheetL.getPrintSetup().setLandscape(true); - sheetP.getPrintSetup().setCopies((short)3); - - // Check taken - assertTrue(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetP.getPrintSetup().getLandscape()); - assertEquals(0, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetP.getPrintSetup().getCopies()); - - // Save and re-load, and check still there - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - - assertTrue(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetP.getPrintSetup().getLandscape()); - assertEquals(0, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetP.getPrintSetup().getCopies()); - } - - /** - * Setting landscape and portrait stuff on existing sheets - */ - public void testPrintSetupLandscapeExisting() throws Exception { - String filename = System.getProperty("HSSF.testdata.path"); - filename = filename + "/SimpleWithPageBreaks.xls"; - HSSFWorkbook workbook = - new HSSFWorkbook(new FileInputStream(filename)); - - assertEquals(3, workbook.getNumberOfSheets()); - - HSSFSheet sheetL = workbook.getSheetAt(0); - HSSFSheet sheetPM = workbook.getSheetAt(1); - HSSFSheet sheetLS = workbook.getSheetAt(2); - - // Check two aspects of the print setup - assertFalse(sheetL.getPrintSetup().getLandscape()); - assertTrue(sheetPM.getPrintSetup().getLandscape()); - assertTrue(sheetLS.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(1, sheetPM.getPrintSetup().getCopies()); - assertEquals(1, sheetLS.getPrintSetup().getCopies()); - - // Change one on each - sheetL.getPrintSetup().setLandscape(true); - sheetPM.getPrintSetup().setLandscape(false); - sheetPM.getPrintSetup().setCopies((short)3); - - // Check taken - assertTrue(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetPM.getPrintSetup().getLandscape()); - assertTrue(sheetLS.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetPM.getPrintSetup().getCopies()); - assertEquals(1, sheetLS.getPrintSetup().getCopies()); - - // Save and re-load, and check still there - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - - assertTrue(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetPM.getPrintSetup().getLandscape()); - assertTrue(sheetLS.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetPM.getPrintSetup().getCopies()); - assertEquals(1, sheetLS.getPrintSetup().getCopies()); - } - - public void testGroupRows() throws Exception { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet s = workbook.createSheet(); - HSSFRow r1 = s.createRow(0); - HSSFRow r2 = s.createRow(1); - HSSFRow r3 = s.createRow(2); - HSSFRow r4 = s.createRow(3); - HSSFRow r5 = s.createRow(4); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(0, r3.getOutlineLevel()); - assertEquals(0, r4.getOutlineLevel()); - assertEquals(0, r5.getOutlineLevel()); - - s.groupRow(2,3); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(1, r3.getOutlineLevel()); - assertEquals(1, r4.getOutlineLevel()); - assertEquals(0, r5.getOutlineLevel()); - - // Save and re-open - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook( - new ByteArrayInputStream(baos.toByteArray()) - ); - - s = workbook.getSheetAt(0); - r1 = s.getRow(0); - r2 = s.getRow(1); - r3 = s.getRow(2); - r4 = s.getRow(3); - r5 = s.getRow(4); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(1, r3.getOutlineLevel()); - assertEquals(1, r4.getOutlineLevel()); - assertEquals(0, r5.getOutlineLevel()); - } - - public void testGroupRowsExisting() throws Exception { - String filename = System.getProperty("HSSF.testdata.path"); - filename = filename + "/NoGutsRecords.xls"; - HSSFWorkbook workbook = - new HSSFWorkbook(new FileInputStream(filename)); - - HSSFSheet s = workbook.getSheetAt(0); - HSSFRow r1 = s.getRow(0); - HSSFRow r2 = s.getRow(1); - HSSFRow r3 = s.getRow(2); - HSSFRow r4 = s.getRow(3); - HSSFRow r5 = s.getRow(4); - HSSFRow r6 = s.getRow(5); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(0, r3.getOutlineLevel()); - assertEquals(0, r4.getOutlineLevel()); - assertEquals(0, r5.getOutlineLevel()); - assertEquals(0, r6.getOutlineLevel()); - - // This used to complain about lacking guts records - s.groupRow(2, 4); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(1, r3.getOutlineLevel()); - assertEquals(1, r4.getOutlineLevel()); - assertEquals(1, r5.getOutlineLevel()); - assertEquals(0, r6.getOutlineLevel()); - - // Save and re-open - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook( - new ByteArrayInputStream(baos.toByteArray()) - ); - - s = workbook.getSheetAt(0); - r1 = s.getRow(0); - r2 = s.getRow(1); - r3 = s.getRow(2); - r4 = s.getRow(3); - r5 = s.getRow(4); - r6 = s.getRow(5); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(1, r3.getOutlineLevel()); - assertEquals(1, r4.getOutlineLevel()); - assertEquals(1, r5.getOutlineLevel()); - assertEquals(0, r6.getOutlineLevel()); - } - - public void testGetDrawings() throws Exception { - String filename = System.getProperty("HSSF.testdata.path"); - HSSFWorkbook wb1c = new HSSFWorkbook( - new FileInputStream(new File(filename,"WithChart.xls")) - ); - HSSFWorkbook wb2c = new HSSFWorkbook( - new FileInputStream(new File(filename,"WithTwoCharts.xls")) - ); - - // 1 chart sheet -> data on 1st, chart on 2nd - assertNotNull(wb1c.getSheetAt(0).getDrawingPatriarch()); - assertNotNull(wb1c.getSheetAt(1).getDrawingPatriarch()); - assertFalse(wb1c.getSheetAt(0).getDrawingPatriarch().containsChart()); - assertTrue(wb1c.getSheetAt(1).getDrawingPatriarch().containsChart()); - - // 2 chart sheet -> data on 1st, chart on 2nd+3rd - assertNotNull(wb2c.getSheetAt(0).getDrawingPatriarch()); - assertNotNull(wb2c.getSheetAt(1).getDrawingPatriarch()); - assertNotNull(wb2c.getSheetAt(2).getDrawingPatriarch()); - assertFalse(wb2c.getSheetAt(0).getDrawingPatriarch().containsChart()); - assertTrue(wb2c.getSheetAt(1).getDrawingPatriarch().containsChart()); - assertTrue(wb2c.getSheetAt(2).getDrawingPatriarch().containsChart()); - } - + //Check for a good clone + assertEquals(cloned.getRow((short)0).getCell((short)0).getStringCellValue(), "clone_test"); + + //Check that the cells are not somehow linked + cell.setCellValue("Difference Check"); + assertEquals(cloned.getRow((short)0).getCell((short)0).getStringCellValue(), "clone_test"); + } + + /** tests that the sheet name for multiple clones of the same sheet is unique + * BUG 37416 + */ + public void testCloneSheetMultipleTimes() { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet("Test Clone"); + HSSFRow row = sheet.createRow((short) 0); + HSSFCell cell = row.createCell((short) 0); + cell.setCellValue("clone_test"); + //Clone the sheet multiple times + workbook.cloneSheet(0); + workbook.cloneSheet(0); + + assertNotNull(workbook.getSheet("Test Clone")); + assertNotNull(workbook.getSheet("Test Clone(1)")); + assertNotNull(workbook.getSheet("Test Clone(2)")); + } + + /** + * Setting landscape and portrait stuff on new sheets + */ + public void testPrintSetupLandscapeNew() throws Exception { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheetL = workbook.createSheet("LandscapeS"); + HSSFSheet sheetP = workbook.createSheet("LandscapeP"); + + // Check two aspects of the print setup + assertFalse(sheetL.getPrintSetup().getLandscape()); + assertFalse(sheetP.getPrintSetup().getLandscape()); + assertEquals(0, sheetL.getPrintSetup().getCopies()); + assertEquals(0, sheetP.getPrintSetup().getCopies()); + + // Change one on each + sheetL.getPrintSetup().setLandscape(true); + sheetP.getPrintSetup().setCopies((short)3); + + // Check taken + assertTrue(sheetL.getPrintSetup().getLandscape()); + assertFalse(sheetP.getPrintSetup().getLandscape()); + assertEquals(0, sheetL.getPrintSetup().getCopies()); + assertEquals(3, sheetP.getPrintSetup().getCopies()); + + // Save and re-load, and check still there + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + workbook.write(baos); + workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); + + assertTrue(sheetL.getPrintSetup().getLandscape()); + assertFalse(sheetP.getPrintSetup().getLandscape()); + assertEquals(0, sheetL.getPrintSetup().getCopies()); + assertEquals(3, sheetP.getPrintSetup().getCopies()); + } + + /** + * Setting landscape and portrait stuff on existing sheets + */ + public void testPrintSetupLandscapeExisting() throws Exception { + HSSFWorkbook workbook = openSample("SimpleWithPageBreaks.xls"); + + assertEquals(3, workbook.getNumberOfSheets()); + + HSSFSheet sheetL = workbook.getSheetAt(0); + HSSFSheet sheetPM = workbook.getSheetAt(1); + HSSFSheet sheetLS = workbook.getSheetAt(2); + + // Check two aspects of the print setup + assertFalse(sheetL.getPrintSetup().getLandscape()); + assertTrue(sheetPM.getPrintSetup().getLandscape()); + assertTrue(sheetLS.getPrintSetup().getLandscape()); + assertEquals(1, sheetL.getPrintSetup().getCopies()); + assertEquals(1, sheetPM.getPrintSetup().getCopies()); + assertEquals(1, sheetLS.getPrintSetup().getCopies()); + + // Change one on each + sheetL.getPrintSetup().setLandscape(true); + sheetPM.getPrintSetup().setLandscape(false); + sheetPM.getPrintSetup().setCopies((short)3); + + // Check taken + assertTrue(sheetL.getPrintSetup().getLandscape()); + assertFalse(sheetPM.getPrintSetup().getLandscape()); + assertTrue(sheetLS.getPrintSetup().getLandscape()); + assertEquals(1, sheetL.getPrintSetup().getCopies()); + assertEquals(3, sheetPM.getPrintSetup().getCopies()); + assertEquals(1, sheetLS.getPrintSetup().getCopies()); + + // Save and re-load, and check still there + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + workbook.write(baos); + workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); + + assertTrue(sheetL.getPrintSetup().getLandscape()); + assertFalse(sheetPM.getPrintSetup().getLandscape()); + assertTrue(sheetLS.getPrintSetup().getLandscape()); + assertEquals(1, sheetL.getPrintSetup().getCopies()); + assertEquals(3, sheetPM.getPrintSetup().getCopies()); + assertEquals(1, sheetLS.getPrintSetup().getCopies()); + } + + public void testGroupRows() throws Exception { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet s = workbook.createSheet(); + HSSFRow r1 = s.createRow(0); + HSSFRow r2 = s.createRow(1); + HSSFRow r3 = s.createRow(2); + HSSFRow r4 = s.createRow(3); + HSSFRow r5 = s.createRow(4); + + assertEquals(0, r1.getOutlineLevel()); + assertEquals(0, r2.getOutlineLevel()); + assertEquals(0, r3.getOutlineLevel()); + assertEquals(0, r4.getOutlineLevel()); + assertEquals(0, r5.getOutlineLevel()); + + s.groupRow(2,3); + + assertEquals(0, r1.getOutlineLevel()); + assertEquals(0, r2.getOutlineLevel()); + assertEquals(1, r3.getOutlineLevel()); + assertEquals(1, r4.getOutlineLevel()); + assertEquals(0, r5.getOutlineLevel()); + + // Save and re-open + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + workbook.write(baos); + workbook = new HSSFWorkbook( + new ByteArrayInputStream(baos.toByteArray()) + ); + + s = workbook.getSheetAt(0); + r1 = s.getRow(0); + r2 = s.getRow(1); + r3 = s.getRow(2); + r4 = s.getRow(3); + r5 = s.getRow(4); + + assertEquals(0, r1.getOutlineLevel()); + assertEquals(0, r2.getOutlineLevel()); + assertEquals(1, r3.getOutlineLevel()); + assertEquals(1, r4.getOutlineLevel()); + assertEquals(0, r5.getOutlineLevel()); + } + + public void testGroupRowsExisting() throws Exception { + HSSFWorkbook workbook = openSample("NoGutsRecords.xls"); + + HSSFSheet s = workbook.getSheetAt(0); + HSSFRow r1 = s.getRow(0); + HSSFRow r2 = s.getRow(1); + HSSFRow r3 = s.getRow(2); + HSSFRow r4 = s.getRow(3); + HSSFRow r5 = s.getRow(4); + HSSFRow r6 = s.getRow(5); + + assertEquals(0, r1.getOutlineLevel()); + assertEquals(0, r2.getOutlineLevel()); + assertEquals(0, r3.getOutlineLevel()); + assertEquals(0, r4.getOutlineLevel()); + assertEquals(0, r5.getOutlineLevel()); + assertEquals(0, r6.getOutlineLevel()); + + // This used to complain about lacking guts records + s.groupRow(2, 4); + + assertEquals(0, r1.getOutlineLevel()); + assertEquals(0, r2.getOutlineLevel()); + assertEquals(1, r3.getOutlineLevel()); + assertEquals(1, r4.getOutlineLevel()); + assertEquals(1, r5.getOutlineLevel()); + assertEquals(0, r6.getOutlineLevel()); + + // Save and re-open + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + workbook.write(baos); + workbook = new HSSFWorkbook( + new ByteArrayInputStream(baos.toByteArray()) + ); + + s = workbook.getSheetAt(0); + r1 = s.getRow(0); + r2 = s.getRow(1); + r3 = s.getRow(2); + r4 = s.getRow(3); + r5 = s.getRow(4); + r6 = s.getRow(5); + + assertEquals(0, r1.getOutlineLevel()); + assertEquals(0, r2.getOutlineLevel()); + assertEquals(1, r3.getOutlineLevel()); + assertEquals(1, r4.getOutlineLevel()); + assertEquals(1, r5.getOutlineLevel()); + assertEquals(0, r6.getOutlineLevel()); + } + + public void testGetDrawings() throws Exception { + HSSFWorkbook wb1c = openSample("WithChart.xls"); + HSSFWorkbook wb2c = openSample("WithTwoCharts.xls"); + + // 1 chart sheet -> data on 1st, chart on 2nd + assertNotNull(wb1c.getSheetAt(0).getDrawingPatriarch()); + assertNotNull(wb1c.getSheetAt(1).getDrawingPatriarch()); + assertFalse(wb1c.getSheetAt(0).getDrawingPatriarch().containsChart()); + assertTrue(wb1c.getSheetAt(1).getDrawingPatriarch().containsChart()); + + // 2 chart sheet -> data on 1st, chart on 2nd+3rd + assertNotNull(wb2c.getSheetAt(0).getDrawingPatriarch()); + assertNotNull(wb2c.getSheetAt(1).getDrawingPatriarch()); + assertNotNull(wb2c.getSheetAt(2).getDrawingPatriarch()); + assertFalse(wb2c.getSheetAt(0).getDrawingPatriarch().containsChart()); + assertTrue(wb2c.getSheetAt(1).getDrawingPatriarch().containsChart()); + assertTrue(wb2c.getSheetAt(2).getDrawingPatriarch().containsChart()); + } + /** * Test that the ProtectRecord is included when creating or cloning a sheet */ @@ -443,7 +427,7 @@ public class TestHSSFSheet HSSFSheet hssfSheet = workbook.createSheet(); Sheet sheet = hssfSheet.getSheet(); ProtectRecord protect = sheet.getProtect(); - + assertFalse(protect.getProtect()); // This will tell us that cloneSheet, and by extension, @@ -455,61 +439,61 @@ public class TestHSSFSheet assertTrue(hssfSheet.getProtect()); } - public void testProtectSheet() { - short expected = (short)0xfef1; + public void testProtectSheet() { + short expected = (short)0xfef1; HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - s.protectSheet("abcdefghij"); - Sheet sheet = s.getSheet(); + HSSFSheet s = wb.createSheet(); + s.protectSheet("abcdefghij"); + Sheet sheet = s.getSheet(); ProtectRecord protect = sheet.getProtect(); PasswordRecord pass = sheet.getPassword(); - assertTrue("protection should be on",protect.getProtect()); - assertTrue("object protection should be on",sheet.isProtected()[1]); - assertTrue("scenario protection should be on",sheet.isProtected()[2]); - assertEquals("well known value for top secret hash should be "+Integer.toHexString(expected).substring(4),expected,pass.getPassword()); - } - - - public void testZoom() - throws Exception - { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - assertEquals(-1, sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid)); - sheet.setZoom(3,4); - assertTrue(sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid) > 0); - SCLRecord sclRecord = (SCLRecord) sheet.getSheet().findFirstRecordBySid(SCLRecord.sid); - assertEquals(3, sclRecord.getNumerator()); - assertEquals(4, sclRecord.getDenominator()); - - int sclLoc = sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid); - int window2Loc = sheet.getSheet().findFirstRecordLocBySid(WindowTwoRecord.sid); - assertTrue(sclLoc == window2Loc + 1); - - } - + assertTrue("protection should be on",protect.getProtect()); + assertTrue("object protection should be on",sheet.isProtected()[1]); + assertTrue("scenario protection should be on",sheet.isProtected()[2]); + assertEquals("well known value for top secret hash should be "+Integer.toHexString(expected).substring(4),expected,pass.getPassword()); + } + + + public void testZoom() + throws Exception + { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet(); + assertEquals(-1, sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid)); + sheet.setZoom(3,4); + assertTrue(sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid) > 0); + SCLRecord sclRecord = (SCLRecord) sheet.getSheet().findFirstRecordBySid(SCLRecord.sid); + assertEquals(3, sclRecord.getNumerator()); + assertEquals(4, sclRecord.getDenominator()); + + int sclLoc = sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid); + int window2Loc = sheet.getSheet().findFirstRecordLocBySid(WindowTwoRecord.sid); + assertTrue(sclLoc == window2Loc + 1); + + } + /** * When removing one merged region, it would break * - */ + */ public void testRemoveMerged() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(); - Region region = new Region(0, (short)0, 1, (short)1); + Region region = new Region(0, (short)0, 1, (short)1); sheet.addMergedRegion(region); region = new Region(1, (short)0, 2, (short)1); sheet.addMergedRegion(region); - - sheet.removeMergedRegion(0); - - region = sheet.getMergedRegionAt(0); - assertEquals("Left over region should be starting at row 1", 1, region.getRowFrom()); - - sheet.removeMergedRegion(0); - + + sheet.removeMergedRegion(0); + + region = sheet.getMergedRegionAt(0); + assertEquals("Left over region should be starting at row 1", 1, region.getRowFrom()); + + sheet.removeMergedRegion(0); + assertEquals("there should be no merged regions left!", 0, sheet.getNumMergedRegions()); - + //an, add, remove, get(0) would null pointer sheet.addMergedRegion(region); assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions()); @@ -517,16 +501,16 @@ public class TestHSSFSheet assertEquals("there should now be zero merged regions!", 0, sheet.getNumMergedRegions()); //add it again! region.setRowTo(4); - + sheet.addMergedRegion(region); assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions()); - + //should exist now! assertTrue("there isn't more than one merged region in there", 1 <= sheet.getNumMergedRegions()); region = sheet.getMergedRegionAt(0); assertEquals("the merged row to doesnt match the one we put in ", 4, region.getRowTo()); - - } + + } public void testShiftMerged() { HSSFWorkbook wb = new HSSFWorkbook(); @@ -534,156 +518,132 @@ public class TestHSSFSheet HSSFRow row = sheet.createRow(0); HSSFCell cell = row.createCell((short)0); cell.setCellValue("first row, first cell"); - + row = sheet.createRow(1); cell = row.createCell((short)1); cell.setCellValue("second row, second cell"); - - Region region = new Region(1, (short)0, 1, (short)1); + + Region region = new Region(1, (short)0, 1, (short)1); sheet.addMergedRegion(region); - + sheet.shiftRows(1, 1, 1); - + region = sheet.getMergedRegionAt(0); assertEquals("Merged region not moved over to row 2", 2, region.getRowFrom()); - + + } + + /** + * Tests the display of gridlines, formulas, and rowcolheadings. + * @author Shawn Laubach (slaubach at apache dot org) + */ + public void testDisplayOptions() throws Exception { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet(); + + File tempFile = TempFile.createTempFile("display", "test.xls"); + FileOutputStream stream = new FileOutputStream(tempFile); + wb.write(stream); + stream.close(); + + FileInputStream readStream = new FileInputStream(tempFile); + wb = new HSSFWorkbook(readStream); + sheet = wb.getSheetAt(0); + readStream.close(); + + assertEquals(sheet.isDisplayGridlines(), true); + assertEquals(sheet.isDisplayRowColHeadings(), true); + assertEquals(sheet.isDisplayFormulas(), false); + + sheet.setDisplayGridlines(false); + sheet.setDisplayRowColHeadings(false); + sheet.setDisplayFormulas(true); + + tempFile = TempFile.createTempFile("display", "test.xls"); + stream = new FileOutputStream(tempFile); + wb.write(stream); + stream.close(); + + readStream = new FileInputStream(tempFile); + wb = new HSSFWorkbook(readStream); + sheet = wb.getSheetAt(0); + readStream.close(); + + + assertEquals(sheet.isDisplayGridlines(), false); + assertEquals(sheet.isDisplayRowColHeadings(), false); + assertEquals(sheet.isDisplayFormulas(), true); + } + + + /** + * Make sure the excel file loads work + * + */ + public void testPageBreakFiles() throws Exception{ + HSSFWorkbook wb = openSample("SimpleWithPageBreaks.xls"); + + HSSFSheet sheet = wb.getSheetAt(0); + assertNotNull(sheet); + + assertEquals("1 row page break", 1, sheet.getRowBreaks().length); + assertEquals("1 column page break", 1, sheet.getColumnBreaks().length); + + assertTrue("No row page break", sheet.isRowBroken(22)); + assertTrue("No column page break", sheet.isColumnBroken((short)4)); + + sheet.setRowBreak(10); + sheet.setColumnBreak((short)13); + + assertEquals("row breaks number", 2, sheet.getRowBreaks().length); + assertEquals("column breaks number", 2, sheet.getColumnBreaks().length); + + File tempFile = TempFile.createTempFile("display", "testPagebreaks.xls"); + FileOutputStream stream = new FileOutputStream(tempFile); + wb.write(stream); + stream.close(); + + wb = new HSSFWorkbook(new FileInputStream(tempFile)); + sheet = wb.getSheetAt(0); + + assertTrue("No row page break", sheet.isRowBroken(22)); + assertTrue("No column page break", sheet.isColumnBroken((short)4)); + + + assertEquals("row breaks number", 2, sheet.getRowBreaks().length); + assertEquals("column breaks number", 2, sheet.getColumnBreaks().length); + + + } + + public void testDBCSName () throws Exception { + HSSFWorkbook wb = openSample("DBCSSheetName.xls"); + HSSFSheet s= wb.getSheetAt(1); + assertEquals ("DBCS Sheet Name 2", wb.getSheetName(1),"\u090f\u0915" ); + assertEquals("DBCS Sheet Name 1", wb.getSheetName(0),"\u091c\u093e"); } - /** - * Tests the display of gridlines, formulas, and rowcolheadings. - * @author Shawn Laubach (slaubach at apache dot org) - */ - public void testDisplayOptions() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - - File tempFile = TempFile.createTempFile("display", "test.xls"); - FileOutputStream stream = new FileOutputStream(tempFile); - wb.write(stream); - stream.close(); - - FileInputStream readStream = new FileInputStream(tempFile); - wb = new HSSFWorkbook(readStream); - sheet = wb.getSheetAt(0); - readStream.close(); - - assertEquals(sheet.isDisplayGridlines(), true); - assertEquals(sheet.isDisplayRowColHeadings(), true); - assertEquals(sheet.isDisplayFormulas(), false); - - sheet.setDisplayGridlines(false); - sheet.setDisplayRowColHeadings(false); - sheet.setDisplayFormulas(true); - - tempFile = TempFile.createTempFile("display", "test.xls"); - stream = new FileOutputStream(tempFile); - wb.write(stream); - stream.close(); - - readStream = new FileInputStream(tempFile); - wb = new HSSFWorkbook(readStream); - sheet = wb.getSheetAt(0); - readStream.close(); - - - assertEquals(sheet.isDisplayGridlines(), false); - assertEquals(sheet.isDisplayRowColHeadings(), false); - assertEquals(sheet.isDisplayFormulas(), true); - } - - - /** - * Make sure the excel file loads work - * - */ - public void testPageBreakFiles() throws Exception{ - FileInputStream fis = null; - HSSFWorkbook wb = null; - - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/SimpleWithPageBreaks.xls"; - fis = new FileInputStream(filename); - wb = new HSSFWorkbook(fis); - fis.close(); - - HSSFSheet sheet = wb.getSheetAt(0); - assertNotNull(sheet); - - assertEquals("1 row page break", 1, sheet.getRowBreaks().length); - assertEquals("1 column page break", 1, sheet.getColumnBreaks().length); - - assertTrue("No row page break", sheet.isRowBroken(22)); - assertTrue("No column page break", sheet.isColumnBroken((short)4)); - - sheet.setRowBreak(10); - sheet.setColumnBreak((short)13); - - assertEquals("row breaks number", 2, sheet.getRowBreaks().length); - assertEquals("column breaks number", 2, sheet.getColumnBreaks().length); - - File tempFile = TempFile.createTempFile("display", "testPagebreaks.xls"); - FileOutputStream stream = new FileOutputStream(tempFile); - wb.write(stream); - stream.close(); - - wb = new HSSFWorkbook(new FileInputStream(tempFile)); - sheet = wb.getSheetAt(0); - - assertTrue("No row page break", sheet.isRowBroken(22)); - assertTrue("No column page break", sheet.isColumnBroken((short)4)); - - - assertEquals("row breaks number", 2, sheet.getRowBreaks().length); - assertEquals("column breaks number", 2, sheet.getColumnBreaks().length); - - - } - - public void testDBCSName () throws Exception { - FileInputStream fis = null; - HSSFWorkbook wb = null; - - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/DBCSSheetName.xls"; - fis = new FileInputStream(filename); - wb = new HSSFWorkbook(fis); - HSSFSheet s= wb.getSheetAt(1); - assertEquals ("DBCS Sheet Name 2", wb.getSheetName(1),"\u090f\u0915" ); - assertEquals("DBCS Sheet Name 1", wb.getSheetName(0),"\u091c\u093e"); - } - - /** - * Testing newly added method that exposes the WINDOW2.toprow - * parameter to allow setting the toprow in the visible view - * of the sheet when it is first opened. - */ - public void testTopRow() throws Exception - { - FileInputStream fis = null; - HSSFWorkbook wb = null; - - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/SimpleWithPageBreaks.xls"; - fis = new FileInputStream(filename); - wb = new HSSFWorkbook(fis); - fis.close(); - - HSSFSheet sheet = wb.getSheetAt(0); - assertNotNull(sheet); - - short toprow = (short) 100; - short leftcol = (short) 50; - sheet.showInPane(toprow,leftcol); - assertEquals("HSSFSheet.getTopRow()", toprow, sheet.getTopRow()); - assertEquals("HSSFSheet.getLeftCol()", leftcol, sheet.getLeftCol()); - } - - /** cell with formula becomes null on cloning a sheet*/ + /** + * Testing newly added method that exposes the WINDOW2.toprow + * parameter to allow setting the toprow in the visible view + * of the sheet when it is first opened. + */ + public void testTopRow() { + HSSFWorkbook wb = openSample("SimpleWithPageBreaks.xls"); + + HSSFSheet sheet = wb.getSheetAt(0); + assertNotNull(sheet); + + short toprow = (short) 100; + short leftcol = (short) 50; + sheet.showInPane(toprow,leftcol); + assertEquals("HSSFSheet.getTopRow()", toprow, sheet.getTopRow()); + assertEquals("HSSFSheet.getLeftCol()", leftcol, sheet.getLeftCol()); + } + + /** cell with formula becomes null on cloning a sheet*/ public void test35084() { - + HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s =wb.createSheet("Sheet1"); HSSFRow r = s.createRow(0); @@ -696,8 +656,8 @@ public class TestHSSFSheet assertEquals("formula", r.getCell((short)1).getCellFormula(), "A1*2"); } - /** test that new default column styles get applied */ - public void testDefaultColumnStyle() { + /** test that new default column styles get applied */ + public void testDefaultColumnStyle() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFCellStyle style = wb.createCellStyle(); HSSFSheet s = wb.createSheet(); @@ -705,53 +665,42 @@ public class TestHSSFSheet HSSFRow r = s.createRow(0); HSSFCell c = r.createCell((short)0); assertEquals("style should match", style.getIndex(), c.getCellStyle().getIndex()); - } - - - /** - * - */ - public void testAddEmptyRow() throws Exception { - //try to add 5 empty rows to a new sheet - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - for (int i = 0; i < 5; i++) sheet.createRow(i); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - workbook.write(out); - out.close(); - - workbook = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); - - //try adding empty rows in an existing worksheet - String cwd = System.getProperty("HSSF.testdata.path"); - FileInputStream in = new FileInputStream(new File(cwd, "Simple.xls")); - workbook = new HSSFWorkbook(in); - in.close(); - assertTrue("No Exceptions while reading file", true); - - sheet = workbook.getSheetAt(0); - for (int i = 3; i < 10; i++) sheet.createRow(i); - - out = new ByteArrayOutputStream(); - workbook.write(out); - out.close(); - - workbook = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - assertTrue("No Exceptions while reading file", true); - - } - - public void testAutoSizeColumn() throws Exception { - String filename = System.getProperty("HSSF.testdata.path"); - filename = filename + "/43902.xls"; + } + + + /** + * + */ + public void testAddEmptyRow() throws Exception { + //try to add 5 empty rows to a new sheet + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet(); + for (int i = 0; i < 5; i++) sheet.createRow(i); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + workbook.write(out); + out.close(); + + workbook = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); + + //try adding empty rows in an existing worksheet + workbook = openSample("Simple.xls"); + + sheet = workbook.getSheetAt(0); + for (int i = 3; i < 10; i++) sheet.createRow(i); + + out = new ByteArrayOutputStream(); + workbook.write(out); + out.close(); + + workbook = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); + } + + public void testAutoSizeColumn() throws Exception { + HSSFWorkbook wb = openSample("43902.xls"); String sheetName = "my sheet"; - FileInputStream is = new FileInputStream(filename); - POIFSFileSystem fs = new POIFSFileSystem(is); - HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheet(sheetName); - + // Can't use literal numbers for column sizes, as // will come out with different values on different // machines based on the fonts available. @@ -761,27 +710,27 @@ public class TestHSSFSheet int maxWithRow1And2 = 7800; int minWithRow1Only = 2750; int maxWithRow1Only = 3300; - + // autoSize the first column and check its size before the merged region (1,0,1,1) is set: // it has to be based on the 2nd row width sheet.autoSizeColumn((short)0); assertTrue("Column autosized with only one row: wrong width", sheet.getColumnWidth((short)0) >= minWithRow1And2); assertTrue("Column autosized with only one row: wrong width", sheet.getColumnWidth((short)0) <= maxWithRow1And2); - + //create a region over the 2nd row and auto size the first column sheet.addMergedRegion(new Region(1,(short)0,1,(short)1)); sheet.autoSizeColumn((short)0); ByteArrayOutputStream out = new ByteArrayOutputStream(); wb.write(out); out.close(); - + // check that the autoSized column width has ignored the 2nd row // because it is included in a merged region (Excel like behavior) HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); HSSFSheet sheet2 = wb2.getSheet(sheetName); assertTrue(sheet2.getColumnWidth((short)0) >= minWithRow1Only); assertTrue(sheet2.getColumnWidth((short)0) <= maxWithRow1Only); - + // remove the 2nd row merged region and check that the 2nd row value is used to the autoSizeColumn width sheet2.removeMergedRegion(1); sheet2.autoSizeColumn((short)0); @@ -792,143 +741,140 @@ public class TestHSSFSheet HSSFSheet sheet3 = wb3.getSheet(sheetName); assertTrue(sheet3.getColumnWidth((short)0) >= minWithRow1And2); assertTrue(sheet3.getColumnWidth((short)0) <= maxWithRow1And2); - } - - /** - * Setting ForceFormulaRecalculation on sheets - */ - public void testForceRecalculation() throws Exception { - String filename = System.getProperty("HSSF.testdata.path"); - filename = filename + "/UncalcedRecord.xls"; - HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(filename)); - - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFSheet sheet2 = workbook.getSheetAt(0); - HSSFRow row = sheet.getRow(0); - row.createCell((short) 0).setCellValue(5); - row.createCell((short) 1).setCellValue(8); + } + + /** + * Setting ForceFormulaRecalculation on sheets + */ + public void testForceRecalculation() throws Exception { + HSSFWorkbook workbook = openSample("UncalcedRecord.xls"); + + HSSFSheet sheet = workbook.getSheetAt(0); + HSSFSheet sheet2 = workbook.getSheetAt(0); + HSSFRow row = sheet.getRow(0); + row.createCell((short) 0).setCellValue(5); + row.createCell((short) 1).setCellValue(8); assertFalse(sheet.getForceFormulaRecalculation()); assertFalse(sheet2.getForceFormulaRecalculation()); - // Save and manually verify that on column C we have 0, value in template - File tempFile = new File(System.getProperty("java.io.tmpdir")+"/uncalced_err.xls" ); - tempFile.delete(); - FileOutputStream fout = new FileOutputStream( tempFile ); - workbook.write( fout ); - fout.close(); - sheet.setForceFormulaRecalculation(true); + // Save and manually verify that on column C we have 0, value in template + File tempFile = new File(System.getProperty("java.io.tmpdir")+"/uncalced_err.xls" ); + tempFile.delete(); + FileOutputStream fout = new FileOutputStream( tempFile ); + workbook.write( fout ); + fout.close(); + sheet.setForceFormulaRecalculation(true); assertTrue(sheet.getForceFormulaRecalculation()); - // Save and manually verify that on column C we have now 13, calculated value - tempFile = new File(System.getProperty("java.io.tmpdir")+"/uncalced_succ.xls" ); - tempFile.delete(); - fout = new FileOutputStream( tempFile ); - workbook.write( fout ); - fout.close(); + // Save and manually verify that on column C we have now 13, calculated value + tempFile = new File(System.getProperty("java.io.tmpdir")+"/uncalced_succ.xls" ); + tempFile.delete(); + fout = new FileOutputStream( tempFile ); + workbook.write( fout ); + fout.close(); - // Try it can be opened + // Try it can be opened HSSFWorkbook wb2 = new HSSFWorkbook(new FileInputStream(tempFile)); - + // And check correct sheet settings found sheet = wb2.getSheetAt(0); sheet2 = wb2.getSheetAt(1); assertTrue(sheet.getForceFormulaRecalculation()); assertFalse(sheet2.getForceFormulaRecalculation()); - + // Now turn if back off again sheet.setForceFormulaRecalculation(false); - - fout = new FileOutputStream( tempFile ); - wb2.write( fout ); - fout.close(); - wb2 = new HSSFWorkbook(new FileInputStream(tempFile)); - + + fout = new FileOutputStream( tempFile ); + wb2.write( fout ); + fout.close(); + wb2 = new HSSFWorkbook(new FileInputStream(tempFile)); + assertFalse(wb2.getSheetAt(0).getForceFormulaRecalculation()); assertFalse(wb2.getSheetAt(1).getForceFormulaRecalculation()); assertFalse(wb2.getSheetAt(2).getForceFormulaRecalculation()); - + // Now add a new sheet, and check things work // with old ones unset, new one set HSSFSheet s4 = wb2.createSheet(); s4.setForceFormulaRecalculation(true); - + assertFalse(sheet.getForceFormulaRecalculation()); assertFalse(sheet2.getForceFormulaRecalculation()); assertTrue(s4.getForceFormulaRecalculation()); - - fout = new FileOutputStream( tempFile ); - wb2.write( fout ); - fout.close(); - + + fout = new FileOutputStream( tempFile ); + wb2.write( fout ); + fout.close(); + HSSFWorkbook wb3 = new HSSFWorkbook(new FileInputStream(tempFile)); assertFalse(wb3.getSheetAt(0).getForceFormulaRecalculation()); assertFalse(wb3.getSheetAt(1).getForceFormulaRecalculation()); assertFalse(wb3.getSheetAt(2).getForceFormulaRecalculation()); assertTrue(wb3.getSheetAt(3).getForceFormulaRecalculation()); - } + } - - public static void main(java.lang.String[] args) { + + public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(TestHSSFSheet.class); } - public void testColumnWidth() throws Exception { - //check we can correctly read column widths from a reference workbook - String filename = System.getProperty("HSSF.testdata.path") + "/colwidth.xls"; - HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(filename)); - - //reference values - int[] ref = {365, 548, 731, 914, 1097, 1280, 1462, 1645, 1828, 2011, 2194, 2377, 2560, 2742, 2925, 3108, 3291, 3474, 3657}; - - HSSFSheet sh = wb.getSheetAt(0); - for (char i = 'A'; i <= 'S'; i++) { - int idx = i - 'A'; - int w = sh.getColumnWidth((short)idx); - assertEquals(ref[idx], w); - } - - //the second sheet doesn't have overridden column widths - sh = wb.getSheetAt(1); - int def_width = sh.getDefaultColumnWidth(); - for (char i = 'A'; i <= 'S'; i++) { - int idx = i - 'A'; - int w = sh.getColumnWidth((short)idx); - //getDefaultColumnWidth returns width measued in characters - //getColumnWidth returns width measued in 1/256th units - assertEquals(def_width*256, w); - } - - //test new workbook - wb = new HSSFWorkbook(); - sh = wb.createSheet(); - sh.setDefaultColumnWidth((short)10); - assertEquals(10, sh.getDefaultColumnWidth()); - assertEquals(256*10, sh.getColumnWidth((short)0)); - assertEquals(256*10, sh.getColumnWidth((short)1)); - assertEquals(256*10, sh.getColumnWidth((short)2)); - for (char i = 'D'; i <= 'F'; i++) { - short w = (short)(256*12); - sh.setColumnWidth((short)i, w); - assertEquals(w, sh.getColumnWidth((short)i)); - } - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - - wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - sh = wb.getSheetAt(0); - assertEquals(10, sh.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256*10, sh.getColumnWidth((short)0)); - assertEquals(256*10, sh.getColumnWidth((short)1)); - assertEquals(256*10, sh.getColumnWidth((short)2)); - //columns D-F have custom wodth - for (char i = 'D'; i <= 'F'; i++) { - short w = (short)(256*12); - assertEquals(w, sh.getColumnWidth((short)i)); - } - - } + public void testColumnWidth() throws Exception { + //check we can correctly read column widths from a reference workbook + HSSFWorkbook wb = openSample("colwidth.xls"); + + //reference values + int[] ref = {365, 548, 731, 914, 1097, 1280, 1462, 1645, 1828, 2011, 2194, 2377, 2560, 2742, 2925, 3108, 3291, 3474, 3657}; + + HSSFSheet sh = wb.getSheetAt(0); + for (char i = 'A'; i <= 'S'; i++) { + int idx = i - 'A'; + int w = sh.getColumnWidth((short)idx); + assertEquals(ref[idx], w); + } + + //the second sheet doesn't have overridden column widths + sh = wb.getSheetAt(1); + int def_width = sh.getDefaultColumnWidth(); + for (char i = 'A'; i <= 'S'; i++) { + int idx = i - 'A'; + int w = sh.getColumnWidth((short)idx); + //getDefaultColumnWidth returns width measued in characters + //getColumnWidth returns width measued in 1/256th units + assertEquals(def_width*256, w); + } + + //test new workbook + wb = new HSSFWorkbook(); + sh = wb.createSheet(); + sh.setDefaultColumnWidth((short)10); + assertEquals(10, sh.getDefaultColumnWidth()); + assertEquals(256*10, sh.getColumnWidth((short)0)); + assertEquals(256*10, sh.getColumnWidth((short)1)); + assertEquals(256*10, sh.getColumnWidth((short)2)); + for (char i = 'D'; i <= 'F'; i++) { + short w = (short)(256*12); + sh.setColumnWidth((short)i, w); + assertEquals(w, sh.getColumnWidth((short)i)); + } + + //serialize and read again + ByteArrayOutputStream out = new ByteArrayOutputStream(); + wb.write(out); + out.close(); + + wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); + sh = wb.getSheetAt(0); + assertEquals(10, sh.getDefaultColumnWidth()); + //columns A-C have default width + assertEquals(256*10, sh.getColumnWidth((short)0)); + assertEquals(256*10, sh.getColumnWidth((short)1)); + assertEquals(256*10, sh.getColumnWidth((short)2)); + //columns D-F have custom wodth + for (char i = 'D'; i <= 'F'; i++) { + short w = (short)(256*12); + assertEquals(w, sh.getColumnWidth((short)i)); + } + + } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java index 1be3a90855..3696bb940e 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java @@ -14,28 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.apache.poi.hssf.usermodel; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; +import junit.framework.TestCase; -import junit.framework.*; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.record.NameRecord; +/** + * + */ +public final class TestHSSFWorkbook extends TestCase { + private static HSSFWorkbook openSample(String sampleFileName) { + return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); + } -public class TestHSSFWorkbook extends TestCase -{ - HSSFWorkbook hssfWorkbook; - String filename; - - protected void setUp() throws Exception { - super.setUp(); - filename = System.getProperty("HSSF.testdata.path"); - } - - public void testSetRepeatingRowsAndColumns() throws Exception - { + public void testSetRepeatingRowsAndColumns() { // Test bug 29747 HSSFWorkbook b = new HSSFWorkbook( ); b.createSheet(); @@ -46,9 +40,7 @@ public class TestHSSFWorkbook extends TestCase assertEquals( 3, nameRecord.getIndexToSheet() ); } - public void testDuplicateNames() - throws Exception - { + public void testDuplicateNames() { HSSFWorkbook b = new HSSFWorkbook( ); b.createSheet("Sheet1"); b.createSheet(); @@ -105,15 +97,15 @@ public class TestHSSFWorkbook extends TestCase public void testSheetSelection() { HSSFWorkbook b = new HSSFWorkbook(); b.createSheet("Sheet One"); - HSSFSheet s = b.createSheet("Sheet Two"); + b.createSheet("Sheet Two"); b.setSelectedTab((short) 1); b.setDisplayedTab((short) 1); assertEquals(b.getSelectedTab(), 1); assertEquals(b.getDisplayedTab(), 1); } - public void testSheetClone() throws Exception { - // First up, try a simple file + public void testSheetClone() { + // First up, try a simple file HSSFWorkbook b = new HSSFWorkbook(); assertEquals(0, b.getNumberOfSheets()); b.createSheet("Sheet One"); @@ -122,24 +114,20 @@ public class TestHSSFWorkbook extends TestCase assertEquals(2, b.getNumberOfSheets()); b.cloneSheet(0); assertEquals(3, b.getNumberOfSheets()); - - // Now try a problem one with drawing records in it - b = new HSSFWorkbook( - new FileInputStream(new File(filename,"SheetWithDrawing.xls")) - ); + + // Now try a problem one with drawing records in it + b = openSample("SheetWithDrawing.xls"); assertEquals(1, b.getNumberOfSheets()); b.cloneSheet(0); assertEquals(2, b.getNumberOfSheets()); } - public void testReadWriteWithCharts() throws Exception { + public void testReadWriteWithCharts() { HSSFWorkbook b; HSSFSheet s; // Single chart, two sheets - b = new HSSFWorkbook( - new FileInputStream(new File(filename,"44010-SingleChart.xls")) - ); + b = openSample("44010-SingleChart.xls"); assertEquals(2, b.getNumberOfSheets()); s = b.getSheetAt(1); assertEquals(0, s.getFirstRowNum()); @@ -154,9 +142,7 @@ public class TestHSSFWorkbook extends TestCase // We've now called getDrawingPatriarch() so // everything will be all screwy // So, start again - b = new HSSFWorkbook( - new FileInputStream(new File(filename,"44010-SingleChart.xls")) - ); + b = openSample("44010-SingleChart.xls"); b = writeRead(b); assertEquals(2, b.getNumberOfSheets()); @@ -166,9 +152,7 @@ public class TestHSSFWorkbook extends TestCase // Two charts, three sheets - b = new HSSFWorkbook( - new FileInputStream(new File(filename,"44010-TwoCharts.xls")) - ); + b = openSample("44010-TwoCharts.xls"); assertEquals(3, b.getNumberOfSheets()); s = b.getSheetAt(1); @@ -188,9 +172,7 @@ public class TestHSSFWorkbook extends TestCase // We've now called getDrawingPatriarch() so // everything will be all screwy // So, start again - b = new HSSFWorkbook( - new FileInputStream(new File(filename,"44010-TwoCharts.xls")) - ); + b = openSample("44010-TwoCharts.xls"); b = writeRead(b); assertEquals(3, b.getNumberOfSheets()); @@ -203,11 +185,7 @@ public class TestHSSFWorkbook extends TestCase assertEquals(0, s.getLastRowNum()); } - private HSSFWorkbook writeRead(HSSFWorkbook b) throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - b.write(baos); - return new HSSFWorkbook( - new ByteArrayInputStream(baos.toByteArray()) - ); + private static HSSFWorkbook writeRead(HSSFWorkbook b) { + return HSSFTestDataSamples.writeOutAndReadBack(b); } } \ No newline at end of file diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestNamedRange.java b/src/testcases/org/apache/poi/hssf/usermodel/TestNamedRange.java index afbbde026e..98500960da 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestNamedRange.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestNamedRange.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,17 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.usermodel; -import junit.framework.TestCase; - -import org.apache.poi.hssf.util.AreaReference; -import org.apache.poi.hssf.util.CellReference; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.TempFile; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -33,6 +24,12 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import junit.framework.TestCase; + +import org.apache.poi.hssf.HSSFTestDataSamples; +import org.apache.poi.hssf.util.AreaReference; +import org.apache.poi.hssf.util.CellReference; +import org.apache.poi.util.TempFile; /** * @@ -41,115 +38,69 @@ import java.io.IOException; * @author Danny Mui (danny at muibros.com) * @author Amol S. Deshmukh < amol at ap ache dot org > */ -public class TestNamedRange - extends TestCase { - - public TestNamedRange(String testName) { - super(testName); - } - - public static void main(java.lang.String[] args) { - String filename = System.getProperty("HSSF.testdata.path"); - - // assume andy is running this in the debugger - if (filename == null) - { - if (args != null && args.length == 1) { - System.setProperty( - "HSSF.testdata.path", - args[0]); - } else { - System.err.println("Geesh, no HSSF.testdata.path system " + - "property, no command line arg with the path "+ - "what do you expect me to do, guess where teh data " + - "files are? Sorry, I give up!"); - - } - - } - - - junit.textui.TestRunner.run(TestNamedRange.class); - } - - /** Test of TestCase method, of class test.RangeTest. */ - public void testNamedRange() - throws IOException - { - FileInputStream fis = null; - POIFSFileSystem fs = null; - HSSFWorkbook wb = null; - - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/Simple.xls"; - - - fis = new FileInputStream(filename); - fs = new POIFSFileSystem(fis); - wb = new HSSFWorkbook(fs); - - - //Creating new Named Range - HSSFName newNamedRange = wb.createName(); - - //Getting Sheet Name for the reference - String sheetName = wb.getSheetName(0); - - //Setting its name - newNamedRange.setNameName("RangeTest"); - //Setting its reference - newNamedRange.setReference(sheetName + "!$D$4:$E$8"); +public final class TestNamedRange extends TestCase { + + private static HSSFWorkbook openSample(String sampleFileName) { + return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); + } + + public static void main(String[] args) { + junit.textui.TestRunner.run(TestNamedRange.class); + } + + /** Test of TestCase method, of class test.RangeTest. */ + public void testNamedRange() + throws IOException + { + HSSFWorkbook wb = openSample("Simple.xls"); + + //Creating new Named Range + HSSFName newNamedRange = wb.createName(); + + //Getting Sheet Name for the reference + String sheetName = wb.getSheetName(0); + + //Setting its name + newNamedRange.setNameName("RangeTest"); + //Setting its reference + newNamedRange.setReference(sheetName + "!$D$4:$E$8"); - //Getting NAmed Range - HSSFName namedRange1 = wb.getNameAt(0); - //Getting it sheet name - sheetName = namedRange1.getSheetName(); - //Getting its reference - String referece = namedRange1.getReference(); - - // sanity check - SanityChecker c = new SanityChecker(); - c.checkHSSFWorkbook(wb); - - File file = TempFile.createTempFile("testNamedRange", - ".xls"); - - FileOutputStream fileOut = new FileOutputStream(file); - wb.write(fileOut); - fis.close(); - fileOut.close(); - - assertTrue("file exists",file.exists()); - - FileInputStream in = new FileInputStream(file); - wb = new HSSFWorkbook(in); - HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest")); - assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName())); - assertEquals(wb.getSheetName(0)+"!$D$4:$E$8", nm.getReference()); - - - } - - /** - * Reads an excel file already containing a named range. - *

+ //Getting NAmed Range + HSSFName namedRange1 = wb.getNameAt(0); + //Getting it sheet name + sheetName = namedRange1.getSheetName(); + //Getting its reference + String referece = namedRange1.getReference(); + + // sanity check + SanityChecker c = new SanityChecker(); + c.checkHSSFWorkbook(wb); + + File file = TempFile.createTempFile("testNamedRange", ".xls"); + + FileOutputStream fileOut = new FileOutputStream(file); + wb.write(fileOut); + + fileOut.close(); + + assertTrue("file exists",file.exists()); + + FileInputStream in = new FileInputStream(file); + wb = new HSSFWorkbook(in); + HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest")); + assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName())); + assertEquals(wb.getSheetName(0)+"!$D$4:$E$8", nm.getReference()); + + + } + + /** + * Reads an excel file already containing a named range. + *

* Addresses Bug #9632 - */ - public void testNamedRead() throws IOException - { - FileInputStream fis = null; - POIFSFileSystem fs = null; - HSSFWorkbook wb = null; - - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/namedinput.xls"; - - - fis = new FileInputStream(filename); - fs = new POIFSFileSystem(fis); - wb = new HSSFWorkbook(fs); + */ + public void testNamedRead() { + HSSFWorkbook wb = openSample("namedinput.xls"); //Get index of the namedrange with the name = "NamedRangeName" , which was defined in input.xls as A1:D10 int NamedRangeIndex = wb.getNameIndex("NamedRangeName"); @@ -161,103 +112,86 @@ public class TestNamedRange //Getting its reference String reference = namedRange1.getReference(); - fis.close(); - assertEquals(sheetName+"!$A$1:$D$10", reference); - + HSSFName namedRange2 = wb.getNameAt(1); - + assertEquals(sheetName+"!$D$17:$G$27", namedRange2.getReference()); assertEquals("SecondNamedRange", namedRange2.getNameName()); - } - - /** - * Reads an excel file already containing a named range and updates it - *

- * Addresses Bug #16411 - */ - public void testNamedReadModify() throws IOException - { - FileInputStream fis = null; - POIFSFileSystem fs = null; - HSSFWorkbook wb = null; - - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/namedinput.xls"; - - - fis = new FileInputStream(filename); - fs = new POIFSFileSystem(fis); - wb = new HSSFWorkbook(fs); - - + + /** + * Reads an excel file already containing a named range and updates it + *

+ * Addresses Bug #16411 + */ + public void testNamedReadModify() { + HSSFWorkbook wb = openSample("namedinput.xls"); + HSSFName name = wb.getNameAt(0); String sheetName = wb.getSheetName(0); - + assertEquals(sheetName+"!$A$1:$D$10", name.getReference()); - - name = wb.getNameAt(1); + + name = wb.getNameAt(1); String newReference = sheetName +"!$A$1:$C$36"; - name.setReference(newReference); + name.setReference(newReference); assertEquals(newReference, name.getReference()); + } - } - /** * Test that multiple named ranges can be added written and read */ public void testMultipleNamedWrite() - throws IOException + throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet("testSheet1"); String sheetName = wb.getSheetName(0); - - assertEquals("testSheet1", sheetName); - + + assertEquals("testSheet1", sheetName); + //Creating new Named Range HSSFName newNamedRange = wb.createName(); newNamedRange.setNameName("RangeTest"); - newNamedRange.setReference(sheetName + "!$D$4:$E$8"); - - //Creating another new Named Range - HSSFName newNamedRange2 = wb.createName(); - - newNamedRange2.setNameName("AnotherTest"); - newNamedRange2.setReference(sheetName + "!$F$1:$G$6"); - - + newNamedRange.setReference(sheetName + "!$D$4:$E$8"); + + //Creating another new Named Range + HSSFName newNamedRange2 = wb.createName(); + + newNamedRange2.setNameName("AnotherTest"); + newNamedRange2.setReference(sheetName + "!$F$1:$G$6"); + + HSSFName namedRange1 = wb.getNameAt(0); String referece = namedRange1.getReference(); - - File file = TempFile.createTempFile("testMultiNamedRange", ".xls"); + + File file = TempFile.createTempFile("testMultiNamedRange", ".xls"); FileOutputStream fileOut = new FileOutputStream(file); wb.write(fileOut); fileOut.close(); - - + + assertTrue("file exists",file.exists()); - - + + FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest")); assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName())); assertTrue("Reference is "+nm.getReference(),(wb.getSheetName(0)+"!$D$4:$E$8").equals(nm.getReference())); - - nm = wb.getNameAt(wb.getNameIndex("AnotherTest")); - assertTrue("Name is "+nm.getNameName(),"AnotherTest".equals(nm.getNameName())); - assertTrue("Reference is "+nm.getReference(),newNamedRange2.getReference().equals(nm.getReference())); - - - } + + nm = wb.getNameAt(wb.getNameIndex("AnotherTest")); + assertTrue("Name is "+nm.getNameName(),"AnotherTest".equals(nm.getNameName())); + assertTrue("Reference is "+nm.getReference(),newNamedRange2.getReference().equals(nm.getReference())); + + + } /** * Test case provided by czhang@cambian.com (Chun Zhang) @@ -268,7 +202,7 @@ public class TestNamedRange public void testMultiNamedRange() throws IOException { - + // Create a new workbook HSSFWorkbook wb = new HSSFWorkbook (); @@ -276,14 +210,14 @@ public class TestNamedRange // Create a worksheet 'sheet1' in the new workbook wb.createSheet (); wb.setSheetName (0, "sheet1"); - + // Create another worksheet 'sheet2' in the new workbook wb.createSheet (); wb.setSheetName (1, "sheet2"); - + // Create a new named range for worksheet 'sheet1' HSSFName namedRange1 = wb.createName(); - + // Set the name for the named range for worksheet 'sheet1' namedRange1.setNameName("RangeTest1"); @@ -292,21 +226,21 @@ public class TestNamedRange // Create a new named range for worksheet 'sheet2' HSSFName namedRange2 = wb.createName(); - + // Set the name for the named range for worksheet 'sheet2' namedRange2.setNameName("RangeTest2"); // Set the reference for the named range for worksheet 'sheet2' - namedRange2.setReference("sheet2" + "!$A$1:$O$21"); + namedRange2.setReference("sheet2" + "!$A$1:$O$21"); // Write the workbook to a file File file = TempFile.createTempFile("testMuiltipletNamedRanges", ".xls"); FileOutputStream fileOut = new FileOutputStream(file); wb.write(fileOut); fileOut.close(); - + assertTrue("file exists",file.exists()); - + // Read the Excel file and verify its content FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); @@ -317,42 +251,42 @@ public class TestNamedRange HSSFName nm2 =wb.getNameAt(wb.getNameIndex("RangeTest2")); assertTrue("Name is "+nm2.getNameName(),"RangeTest2".equals(nm2.getNameName())); assertTrue("Reference is "+nm2.getReference(),(wb.getSheetName(1)+"!$A$1:$O$21").equals(nm2.getReference())); - } + } public void testUnicodeNamedRange() throws Exception { - HSSFWorkbook workBook = new HSSFWorkbook(); - HSSFSheet sheet = workBook.createSheet("Test"); - HSSFName name = workBook.createName(); - name.setNameName("\u03B1"); - name.setReference("Test!$D$3:$E$8"); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - workBook.write(out); - - HSSFWorkbook workBook2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); - HSSFName name2 = workBook2.getNameAt(0); - - assertEquals("\u03B1", name2.getNameName()); - assertEquals("Test!$D$3:$E$8", name2.getReference()); + HSSFWorkbook workBook = new HSSFWorkbook(); + HSSFSheet sheet = workBook.createSheet("Test"); + HSSFName name = workBook.createName(); + name.setNameName("\u03B1"); + name.setReference("Test!$D$3:$E$8"); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + workBook.write(out); + + HSSFWorkbook workBook2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); + HSSFName name2 = workBook2.getNameAt(0); + + assertEquals("\u03B1", name2.getNameName()); + assertEquals("Test!$D$3:$E$8", name2.getReference()); } - + /** * Test to see if the print areas can be retrieved/created in memory */ public void testSinglePrintArea() { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test Print Area"); - String sheetName = workbook.getSheetName(0); - - String reference = sheetName+"!$A$1:$B$1"; - workbook.setPrintArea(0, reference); - - String retrievedPrintArea = workbook.getPrintArea(0); - - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); - assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet("Test Print Area"); + String sheetName = workbook.getSheetName(0); + + String reference = sheetName+"!$A$1:$B$1"; + workbook.setPrintArea(0, reference); + + String retrievedPrintArea = workbook.getPrintArea(0); + + assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); + assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); + } /** @@ -360,53 +294,31 @@ public class TestNamedRange */ public void testSinglePrintAreaWOSheet() { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test Print Area"); + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet("Test Print Area"); String sheetName = workbook.getSheetName(0); - + String reference = "$A$1:$B$1"; workbook.setPrintArea(0, reference); - + String retrievedPrintArea = workbook.getPrintArea(0); - - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); + + assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); assertEquals("'" + sheetName + "'!" + reference, retrievedPrintArea); - + } /** * Test to see if the print area can be retrieved from an excel created file */ - public void testPrintAreaFileRead() - throws IOException - { - FileInputStream fis = null; - POIFSFileSystem fs = null; - HSSFWorkbook workbook = null; - - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/SimpleWithPrintArea.xls"; - - try { - - fis = new FileInputStream(filename); - fs = new POIFSFileSystem(fis); - workbook = new HSSFWorkbook(fs); - - String sheetName = workbook.getSheetName(0); - String reference = sheetName+"!$A$1:$C$5"; - - assertEquals(reference, workbook.getPrintArea(0)); - - } finally { - fis.close(); - - } - - - + public void testPrintAreaFileRead() { + HSSFWorkbook workbook = openSample("SimpleWithPrintArea.xls"); + + String sheetName = workbook.getSheetName(0); + String reference = sheetName+"!$A$1:$C$5"; + + assertEquals(reference, workbook.getPrintArea(0)); } @@ -416,29 +328,29 @@ public class TestNamedRange public void testPrintAreaFile() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test Print Area"); + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet("Test Print Area"); String sheetName = workbook.getSheetName(0); - + String reference = sheetName+"!$A$1:$B$1"; workbook.setPrintArea(0, reference); - - File file = TempFile.createTempFile("testPrintArea",".xls"); - - FileOutputStream fileOut = new FileOutputStream(file); - workbook.write(fileOut); - fileOut.close(); - - assertTrue("file exists",file.exists()); - - FileInputStream in = new FileInputStream(file); - workbook = new HSSFWorkbook(in); - - String retrievedPrintArea = workbook.getPrintArea(0); - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); + + File file = TempFile.createTempFile("testPrintArea",".xls"); + + FileOutputStream fileOut = new FileOutputStream(file); + workbook.write(fileOut); + fileOut.close(); + + assertTrue("file exists",file.exists()); + + FileInputStream in = new FileInputStream(file); + workbook = new HSSFWorkbook(in); + + String retrievedPrintArea = workbook.getPrintArea(0); + assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); assertEquals("References Match", "'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - + } /** @@ -447,180 +359,178 @@ public class TestNamedRange public void testMultiplePrintAreaFile() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - - HSSFSheet sheet = workbook.createSheet("Sheet1"); - sheet = workbook.createSheet("Sheet2"); - sheet = workbook.createSheet("Sheet3"); - - String sheetName = workbook.getSheetName(0); + HSSFWorkbook workbook = new HSSFWorkbook(); + + HSSFSheet sheet = workbook.createSheet("Sheet1"); + sheet = workbook.createSheet("Sheet2"); + sheet = workbook.createSheet("Sheet3"); + + String sheetName = workbook.getSheetName(0); String reference = null; reference = sheetName+"!$A$1:$B$1"; workbook.setPrintArea(0, reference); sheetName = workbook.getSheetName(1); - String reference2 = sheetName+"!$B$2:$D$5"; - workbook.setPrintArea(1, reference2); + String reference2 = sheetName+"!$B$2:$D$5"; + workbook.setPrintArea(1, reference2); sheetName = workbook.getSheetName(2); String reference3 = sheetName+"!$D$2:$F$5"; workbook.setPrintArea(2, reference3); - - File file = TempFile.createTempFile("testMultiPrintArea",".xls"); - - FileOutputStream fileOut = new FileOutputStream(file); - workbook.write(fileOut); - fileOut.close(); - - assertTrue("file exists",file.exists()); - - FileInputStream in = new FileInputStream(file); - workbook = new HSSFWorkbook(in); - - String retrievedPrintArea = workbook.getPrintArea(0); - assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea); - assertEquals(reference, retrievedPrintArea); - - String retrievedPrintArea2 = workbook.getPrintArea(1); - assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea2); - assertEquals(reference2, retrievedPrintArea2); - - String retrievedPrintArea3 = workbook.getPrintArea(2); - assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea3); - assertEquals(reference3, retrievedPrintArea3); - - + + File file = TempFile.createTempFile("testMultiPrintArea",".xls"); + + FileOutputStream fileOut = new FileOutputStream(file); + workbook.write(fileOut); + fileOut.close(); + + assertTrue("file exists",file.exists()); + + FileInputStream in = new FileInputStream(file); + workbook = new HSSFWorkbook(in); + + String retrievedPrintArea = workbook.getPrintArea(0); + assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea); + assertEquals(reference, retrievedPrintArea); + + String retrievedPrintArea2 = workbook.getPrintArea(1); + assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea2); + assertEquals(reference2, retrievedPrintArea2); + + String retrievedPrintArea3 = workbook.getPrintArea(2); + assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea3); + assertEquals(reference3, retrievedPrintArea3); + + } - - /** - * Tests the setting of print areas with coordinates (Row/Column designations) - * - */ - public void testPrintAreaCoords(){ - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test Print Area"); + + /** + * Tests the setting of print areas with coordinates (Row/Column designations) + * + */ + public void testPrintAreaCoords(){ + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet("Test Print Area"); String sheetName = workbook.getSheetName(0); - + String reference = sheetName+"!$A$1:$B$1"; workbook.setPrintArea(0, 0, 1, 0, 0); - + String retrievedPrintArea = workbook.getPrintArea(0); - - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); - assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - } - - - /** - * Tests the parsing of union area expressions, and re-display in the presence of sheet names - * with special characters. - */ - public void testPrintAreaUnion(){ - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test Print Area"); + + assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); + assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); + } + + + /** + * Tests the parsing of union area expressions, and re-display in the presence of sheet names + * with special characters. + */ + public void testPrintAreaUnion(){ + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet("Test Print Area"); String sheetName = workbook.getSheetName(0); - + - String reference = sheetName + "!$A$1:$B$1, " + sheetName + "!$D$1:$F$2"; + String reference = sheetName + "!$A$1:$B$1, " + sheetName + "!$D$1:$F$2"; String expResult = "'" + sheetName + "'!$A$1:$B$1,'" + sheetName + "'!$D$1:$F$2"; workbook.setPrintArea(0, reference); - + String retrievedPrintArea = workbook.getPrintArea(0); - - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); - assertEquals(expResult, retrievedPrintArea); - } - - /** - * Verifies an existing print area is deleted - * - */ - public void testPrintAreaRemove() { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test Print Area"); + + assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); + assertEquals(expResult, retrievedPrintArea); + } + + /** + * Verifies an existing print area is deleted + * + */ + public void testPrintAreaRemove() { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet("Test Print Area"); String sheetName = workbook.getSheetName(0); - + String reference = sheetName+"!$A$1:$B$1"; workbook.setPrintArea(0, 0, 1, 0, 0); - + String retrievedPrintArea = workbook.getPrintArea(0); - - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); - - workbook.removePrintArea(0); - assertNull("PrintArea was not removed", workbook.getPrintArea(0)); - } - - /** - * Verifies correct functioning for "single cell named range" (aka "named cell") - */ - public void testNamedCell_1() { - - // setup for this testcase - String sheetName = "Test Named Cell"; - String cellName = "A name for a named cell"; - String cellValue = "TEST Value"; - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(sheetName); - sheet.createRow(0).createCell((short) 0).setCellValue(cellValue); - - // create named range for a single cell using areareference - HSSFName namedCell = wb.createName(); - namedCell.setNameName(cellName); - String reference = sheetName+"!A1:A1"; - namedCell.setReference(reference); - - // retrieve the newly created named range - int namedCellIdx = wb.getNameIndex(cellName); - HSSFName aNamedCell = wb.getNameAt(namedCellIdx); - assertNotNull(aNamedCell); - - // retrieve the cell at the named range and test its contents - AreaReference aref = new AreaReference(aNamedCell.getReference()); - assertTrue("Should be exactly 1 cell in the named cell :'" +cellName+"'", aref.isSingleCell()); - - CellReference cref = aref.getFirstCell(); - assertNotNull(cref); - HSSFSheet s = wb.getSheet(cref.getSheetName()); - assertNotNull(s); - HSSFRow r = sheet.getRow(cref.getRow()); - HSSFCell c = r.getCell(cref.getCol()); - String contents = c.getRichStringCellValue().getString(); - assertEquals("Contents of cell retrieved by its named reference", contents, cellValue); - } - - /** - * Verifies correct functioning for "single cell named range" (aka "named cell") - */ - public void testNamedCell_2() { - - // setup for this testcase - String sname = "TestSheet", cname = "TestName", cvalue = "TestVal"; - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(sname); - sheet.createRow(0).createCell((short) 0).setCellValue(cvalue); - - // create named range for a single cell using cellreference - HSSFName namedCell = wb.createName(); - namedCell.setNameName(cname); - String reference = sname+"!A1"; - namedCell.setReference(reference); - - // retrieve the newly created named range - int namedCellIdx = wb.getNameIndex(cname); - HSSFName aNamedCell = wb.getNameAt(namedCellIdx); - assertNotNull(aNamedCell); - - // retrieve the cell at the named range and test its contents - CellReference cref = new CellReference(aNamedCell.getReference()); - assertNotNull(cref); - HSSFSheet s = wb.getSheet(cref.getSheetName()); - HSSFRow r = sheet.getRow(cref.getRow()); - HSSFCell c = r.getCell(cref.getCol()); - String contents = c.getStringCellValue(); - assertEquals("Contents of cell retrieved by its named reference", contents, cvalue); - } -} + assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); + + workbook.removePrintArea(0); + assertNull("PrintArea was not removed", workbook.getPrintArea(0)); + } + + /** + * Verifies correct functioning for "single cell named range" (aka "named cell") + */ + public void testNamedCell_1() { + + // setup for this testcase + String sheetName = "Test Named Cell"; + String cellName = "A name for a named cell"; + String cellValue = "TEST Value"; + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet(sheetName); + sheet.createRow(0).createCell((short) 0).setCellValue(cellValue); + + // create named range for a single cell using areareference + HSSFName namedCell = wb.createName(); + namedCell.setNameName(cellName); + String reference = sheetName+"!A1:A1"; + namedCell.setReference(reference); + + // retrieve the newly created named range + int namedCellIdx = wb.getNameIndex(cellName); + HSSFName aNamedCell = wb.getNameAt(namedCellIdx); + assertNotNull(aNamedCell); + + // retrieve the cell at the named range and test its contents + AreaReference aref = new AreaReference(aNamedCell.getReference()); + assertTrue("Should be exactly 1 cell in the named cell :'" +cellName+"'", aref.isSingleCell()); + + CellReference cref = aref.getFirstCell(); + assertNotNull(cref); + HSSFSheet s = wb.getSheet(cref.getSheetName()); + assertNotNull(s); + HSSFRow r = sheet.getRow(cref.getRow()); + HSSFCell c = r.getCell(cref.getCol()); + String contents = c.getRichStringCellValue().getString(); + assertEquals("Contents of cell retrieved by its named reference", contents, cellValue); + } + + /** + * Verifies correct functioning for "single cell named range" (aka "named cell") + */ + public void testNamedCell_2() { + // setup for this testcase + String sname = "TestSheet", cname = "TestName", cvalue = "TestVal"; + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet(sname); + sheet.createRow(0).createCell((short) 0).setCellValue(cvalue); + + // create named range for a single cell using cellreference + HSSFName namedCell = wb.createName(); + namedCell.setNameName(cname); + String reference = sname+"!A1"; + namedCell.setReference(reference); + + // retrieve the newly created named range + int namedCellIdx = wb.getNameIndex(cname); + HSSFName aNamedCell = wb.getNameAt(namedCellIdx); + assertNotNull(aNamedCell); + + // retrieve the cell at the named range and test its contents + CellReference cref = new CellReference(aNamedCell.getReference()); + assertNotNull(cref); + HSSFSheet s = wb.getSheet(cref.getSheetName()); + HSSFRow r = sheet.getRow(cref.getRow()); + HSSFCell c = r.getCell(cref.getCol()); + String contents = c.getStringCellValue(); + assertEquals("Contents of cell retrieved by its named reference", contents, cvalue); + } +} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java b/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java index dd57531304..661b1d51f1 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java @@ -17,36 +17,28 @@ package org.apache.poi.hssf.usermodel; -import java.io.File; -import java.io.FileInputStream; import java.util.List; import junit.framework.TestCase; -public class TestOLE2Embeding extends TestCase { - public void testEmbeding() throws Exception { - String dirname = System.getProperty("HSSF.testdata.path"); - String filename = dirname + "/ole2-embedding.xls"; +import org.apache.poi.hssf.HSSFTestDataSamples; - File file = new File(filename); - FileInputStream in = new FileInputStream(file); - HSSFWorkbook workbook; +/** + * + */ +public final class TestOLE2Embeding extends TestCase { + public void testEmbeding() { // This used to break, until bug #43116 was fixed - workbook = new HSSFWorkbook(in); - - in.close(); + HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls"); // Check we can get at the Escher layer still workbook.getAllPictures(); } public void testEmbeddedObjects() throws Exception { - String dirname = System.getProperty("HSSF.testdata.path"); - String filename = dirname + "/ole2-embedding.xls"; + HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls"); - File file = new File(filename); - HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file)); List objects = workbook.getAllEmbeddedObjects(); assertEquals("Wrong number of objects", 2, objects.size()); assertEquals("Wrong name for first object", "MBD06CAB431", @@ -56,6 +48,5 @@ public class TestOLE2Embeding extends TestCase { ((HSSFObjectData) objects.get(1)).getDirectory().getName()); } - } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java index 9fe33ce6c9..98980fe191 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java @@ -17,32 +17,31 @@ package org.apache.poi.hssf.usermodel; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.PropertySetFactory; - -import java.io.FileInputStream; -import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; import junit.framework.TestCase; +import org.apache.poi.hpsf.PropertySetFactory; +import org.apache.poi.hpsf.SummaryInformation; +import org.apache.poi.hssf.HSSFTestDataSamples; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; + /** * Old-style setting of POIFS properties doesn't work with POI 3.0.2 * * @author Yegor Kozlov */ public class TestPOIFSProperties extends TestCase{ - protected String cwd = System.getProperty("HSSF.testdata.path"); - protected String title = "Testing POIFS properties"; + private static final String title = "Testing POIFS properties"; public void testFail() throws Exception { - FileInputStream is = new FileInputStream(new File(cwd, "Simple.xls")); + InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls"); POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); HSSFWorkbook wb = new HSSFWorkbook(fs); @@ -62,19 +61,13 @@ public class TestPOIFSProperties extends TestCase{ POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())); SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); - try { - //failing assertion - assertEquals(title, summary2.getTitle()); - - } catch (AssertionError e){ - assertTrue(true); - } + //failing assertion + assertEquals(title, summary2.getTitle()); } public void testOK() throws Exception { - FileInputStream is = new FileInputStream(new File(cwd, "Simple.xls")); + InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls"); POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); //set POIFS properties before constructing HSSFWorkbook SummaryInformation summary1 = (SummaryInformation)PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java b/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java index 7f2819433b..342f6e26f1 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,47 +14,29 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.usermodel; +import java.util.GregorianCalendar; +import java.util.List; + import junit.framework.TestCase; + +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.model.Sheet; import org.apache.poi.hssf.record.BOFRecord; import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -import java.io.FileInputStream; -import java.util.GregorianCalendar; -import java.util.List; /** * @author Glen Stampoultzis (glens at apache.org) */ - -public class TestReadWriteChart - extends TestCase -{ - public TestReadWriteChart(String s) - { - super(s); - } +public final class TestReadWriteChart extends TestCase { /** * In the presence of a chart we need to make sure BOF/EOF records still exist. */ - - public void testBOFandEOFRecords() - throws Exception - { - //System.out.println("made it in testBOFandEOF"); - String path = System.getProperty("HSSF.testdata.path"); - String filename = path + "/SimpleChart.xls"; - //System.out.println("path is "+path); - POIFSFileSystem fs = - new POIFSFileSystem(new FileInputStream(filename)); - //System.out.println("opened file"); - HSSFWorkbook workbook = new HSSFWorkbook(fs); + public void testBOFandEOFRecords() { + HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleChart.xls"); HSSFSheet sheet = workbook.getSheetAt(0); HSSFRow firstRow = sheet.getRow(0); HSSFCell firstCell = firstRow.getCell(( short ) 0); @@ -77,29 +58,7 @@ public class TestReadWriteChart assertTrue(records.get(records.size() - 1) instanceof EOFRecord); } - public static void main(String [] args) - { - String filename = System.getProperty("HSSF.testdata.path"); - - // assume andy is running this in the debugger - if (filename == null) - { - if (args != null && args[0].length() == 1) { - System.setProperty( - "HSSF.testdata.path", - args[0]); - } else { - System.err.println("Geesh, no HSSF.testdata.path system " + - "property, no command line arg with the path "+ - "what do you expect me to do, guess where teh data " + - "files are? Sorry, I give up!"); - - } - - } - System.out - .println("Testing org.apache.poi.hssf.usermodel.TestReadWriteChart"); + public static void main(String [] args) { junit.textui.TestRunner.run(TestReadWriteChart.class); } - } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java b/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java index 038b6cce55..fc2a24b782 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java @@ -14,40 +14,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.apache.poi.hssf.usermodel; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; import junit.framework.TestCase; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.hssf.HSSFTestDataSamples; /** * Tests for how HSSFWorkbook behaves with XLS files * with a WORKBOOK directory entry (instead of the more * usual, Workbook) */ -public class TestSheetHiding extends TestCase { - private String dirPath; - private String xlsHidden = "TwoSheetsOneHidden.xls"; - private String xlsShown = "TwoSheetsNoneHidden.xls"; +public final class TestSheetHiding extends TestCase { private HSSFWorkbook wbH; private HSSFWorkbook wbU; - protected void setUp() throws Exception { - super.setUp(); - - dirPath = System.getProperty("HSSF.testdata.path"); - FileInputStream isH = new FileInputStream(dirPath + "/" + xlsHidden); - POIFSFileSystem fsH = new POIFSFileSystem(isH); - - FileInputStream isU = new FileInputStream(dirPath + "/" + xlsShown); - POIFSFileSystem fsU = new POIFSFileSystem(isU); - - wbH = new HSSFWorkbook(fsH); - wbU = new HSSFWorkbook(fsU); + protected void setUp() { + wbH = HSSFTestDataSamples.openSampleWorkbook("TwoSheetsOneHidden.xls"); + wbU = HSSFTestDataSamples.openSampleWorkbook("TwoSheetsNoneHidden.xls"); } /** diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetShiftRows.java b/src/testcases/org/apache/poi/hssf/usermodel/TestSheetShiftRows.java index 05eee992e1..03d67cc21c 100755 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetShiftRows.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestSheetShiftRows.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,20 +14,15 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.usermodel; -import junit.framework.TestCase; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.TempFile; - -import java.io.File; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.FileOutputStream; + +import junit.framework.TestCase; + +import org.apache.poi.hssf.HSSFTestDataSamples; /** * Tests row shifting capabilities. @@ -37,16 +31,7 @@ import java.io.FileOutputStream; * @author Shawn Laubach (slaubach at apache dot com) * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) */ - -public class TestSheetShiftRows extends TestCase { - - /** - * Constructor for TestSheetShiftRows. - * @param arg0 - */ - public TestSheetShiftRows(String arg0) { - super(arg0); - } +public final class TestSheetShiftRows extends TestCase { /** * Tests the shiftRows function. Does three different shifts. @@ -59,25 +44,16 @@ public class TestSheetShiftRows extends TestCase { public void testShiftRows() throws Exception { // Read initial file in - String filename = System.getProperty( "HSSF.testdata.path" ); - filename = filename + "/SimpleMultiCell.xls"; - FileInputStream fin = new FileInputStream( filename ); - HSSFWorkbook wb = new HSSFWorkbook( fin ); - fin.close(); + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleMultiCell.xls"); HSSFSheet s = wb.getSheetAt( 0 ); // Shift the second row down 1 and write to temp file s.shiftRows( 1, 1, 1 ); - File tempFile = TempFile.createTempFile( "shift", "test.xls" ); - FileOutputStream fout = new FileOutputStream( tempFile ); - wb.write( fout ); - fout.close(); + + wb = HSSFTestDataSamples.writeOutAndReadBack(wb); // Read from temp file and check the number of cells in each // row (in original file each row was unique) - fin = new FileInputStream( tempFile ); - wb = new HSSFWorkbook( fin ); - fin.close(); s = wb.getSheetAt( 0 ); assertEquals( s.getRow( 0 ).getPhysicalNumberOfCells(), 1 ); @@ -89,15 +65,9 @@ public class TestSheetShiftRows extends TestCase { // Shift rows 1-3 down 3 in the current one. This tests when // 1 row is blank. Write to a another temp file s.shiftRows( 0, 2, 3 ); - tempFile = TempFile.createTempFile( "shift", "test.xls" ); - fout = new FileOutputStream( tempFile ); - wb.write( fout ); - fout.close(); + wb = HSSFTestDataSamples.writeOutAndReadBack(wb); // Read and ensure things are where they should be - fin = new FileInputStream( tempFile ); - wb = new HSSFWorkbook( fin ); - fin.close(); s = wb.getSheetAt( 0 ); assertTrue( s.getRow( 0 ) == null || s.getRow( 0 ).getPhysicalNumberOfCells() == 0 ); assertTrue( s.getRow( 1 ) == null || s.getRow( 1 ).getPhysicalNumberOfCells() == 0 ); @@ -107,22 +77,12 @@ public class TestSheetShiftRows extends TestCase { assertEquals( s.getRow( 5 ).getPhysicalNumberOfCells(), 2 ); // Read the first file again - fin = new FileInputStream( filename ); - wb = new HSSFWorkbook( fin ); - fin.close(); + wb = HSSFTestDataSamples.openSampleWorkbook("SimpleMultiCell.xls"); s = wb.getSheetAt( 0 ); // Shift rows 3 and 4 up and write to temp file s.shiftRows( 2, 3, -2 ); - tempFile = TempFile.createTempFile( "shift", "test.xls" ); - fout = new FileOutputStream( tempFile ); - wb.write( fout ); - fout.close(); - - // Read file and test - fin = new FileInputStream( tempFile ); - wb = new HSSFWorkbook( fin ); - fin.close(); + wb = HSSFTestDataSamples.writeOutAndReadBack(wb); s = wb.getSheetAt( 0 ); assertEquals( s.getRow( 0 ).getPhysicalNumberOfCells(), 3 ); assertEquals( s.getRow( 1 ).getPhysicalNumberOfCells(), 4 ); @@ -137,11 +97,11 @@ public class TestSheetShiftRows extends TestCase { * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) */ public void testShiftRow(){ - HSSFWorkbook b = new HSSFWorkbook(); - HSSFSheet s = b.createSheet(); - s.createRow(0).createCell((short)0).setCellValue("TEST1"); - s.createRow(3).createCell((short)0).setCellValue("TEST2"); - s.shiftRows(0,4,1); + HSSFWorkbook b = new HSSFWorkbook(); + HSSFSheet s = b.createSheet(); + s.createRow(0).createCell((short)0).setCellValue("TEST1"); + s.createRow(3).createCell((short)0).setCellValue("TEST2"); + s.shiftRows(0,4,1); } /** @@ -150,13 +110,13 @@ public class TestSheetShiftRows extends TestCase { * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) */ public void testShiftRow0(){ - HSSFWorkbook b = new HSSFWorkbook(); - HSSFSheet s = b.createSheet(); - s.createRow(0).createCell((short)0).setCellValue("TEST1"); - s.createRow(3).createCell((short)0).setCellValue("TEST2"); - s.shiftRows(0,4,1); + HSSFWorkbook b = new HSSFWorkbook(); + HSSFSheet s = b.createSheet(); + s.createRow(0).createCell((short)0).setCellValue("TEST1"); + s.createRow(3).createCell((short)0).setCellValue("TEST2"); + s.shiftRows(0,4,1); } - + /** * When shifting rows, the page breaks should go with it * @@ -167,29 +127,25 @@ public class TestSheetShiftRows extends TestCase { HSSFRow row = s.createRow(4); row.createCell((short)0).setCellValue("test"); s.setRowBreak(4); - + s.shiftRows(4, 4, 2); assertTrue("Row number 6 should have a pagebreak", s.isRowBroken(6)); - + } public void testShiftWithComments() throws Exception { - String filename = System.getProperty( "HSSF.testdata.path" ); - filename = filename + "/comments.xls"; - FileInputStream fin = new FileInputStream( filename ); - HSSFWorkbook wb = new HSSFWorkbook( fin ); - fin.close(); + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("comments.xls"); HSSFSheet sheet = wb.getSheet("Sheet1"); assertEquals(3, sheet.getLastRowNum()); - + // Verify comments are in the position expected assertNotNull(sheet.getCellComment(0,0)); assertNull(sheet.getCellComment(1,0)); assertNotNull(sheet.getCellComment(2,0)); assertNotNull(sheet.getCellComment(3,0)); - + String comment1 = sheet.getCellComment(0,0).getString().getString(); assertEquals(comment1,"comment top row1 (index0)\n"); String comment3 = sheet.getCellComment(2,0).getString().getString(); @@ -197,7 +153,7 @@ public class TestSheetShiftRows extends TestCase { String comment4 = sheet.getCellComment(3,0).getString().getString(); assertEquals(comment4,"comment top row4 (index3)\n"); - // Shifting all but first line down to test comments shifting + // Shifting all but first line down to test comments shifting sheet.shiftRows(1, sheet.getLastRowNum(), 1, true, true); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); wb.write(outputStream); @@ -216,7 +172,7 @@ public class TestSheetShiftRows extends TestCase { assertEquals(comment3,comment3_shifted); String comment4_shifted = sheet.getCellComment(4,0).getString().getString(); assertEquals(comment4,comment4_shifted); - + // Write out and read back in again // Ensure that the changes were persisted wb = new HSSFWorkbook( new ByteArrayInputStream(outputStream.toByteArray()) ); @@ -235,22 +191,18 @@ public class TestSheetShiftRows extends TestCase { comment3_shifted = sheet.getCellComment(3,0).getString().getString(); assertEquals(comment3,comment3_shifted); comment4_shifted = sheet.getCellComment(4,0).getString().getString(); - assertEquals(comment4,comment4_shifted); + assertEquals(comment4,comment4_shifted); } - + /** * See bug #34023 */ - public void testShiftWithFormulas() throws Exception { - String filename = System.getProperty( "HSSF.testdata.path" ); - filename = filename + "/ForShifting.xls"; - FileInputStream fin = new FileInputStream( filename ); - HSSFWorkbook wb = new HSSFWorkbook( fin ); - fin.close(); + public void testShiftWithFormulas() { + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ForShifting.xls"); HSSFSheet sheet = wb.getSheet("Sheet1"); assertEquals(19, sheet.getLastRowNum()); - + assertEquals("cell B1 (ref)", sheet.getRow(0).getCell((short)3).getRichStringCellValue().toString()); assertEquals("CONCATENATE(B1,\" (ref)\")", sheet.getRow(0).getCell((short)3).getCellFormula()); assertEquals("cell B2 (ref)", sheet.getRow(1).getCell((short)3).getRichStringCellValue().toString()); @@ -259,15 +211,15 @@ public class TestSheetShiftRows extends TestCase { assertEquals("CONCATENATE(B3,\" (ref)\")", sheet.getRow(2).getCell((short)3).getCellFormula()); assertEquals("cell B2 (ref)", sheet.getRow(6).getCell((short)1).getRichStringCellValue().toString()); assertEquals("CONCATENATE(B2,\" (ref)\")", sheet.getRow(6).getCell((short)1).getCellFormula()); - + sheet.shiftRows(1, 1, 10); - + // Row 1 => Row 11 // So strings on row 11 unchanged, but reference in formula is assertEquals("cell B1 (ref)", sheet.getRow(0).getCell((short)3).getRichStringCellValue().toString()); assertEquals("CONCATENATE(B1,\" (ref)\")", sheet.getRow(0).getCell((short)3).getCellFormula()); assertEquals(0, sheet.getRow(1).getPhysicalNumberOfCells()); - + // still save b2 assertEquals("cell B2 (ref)", sheet.getRow(11).getCell((short)3).getRichStringCellValue().toString()); // but points to b12 @@ -275,7 +227,7 @@ public class TestSheetShiftRows extends TestCase { assertEquals("cell B3 (ref)", sheet.getRow(2).getCell((short)3).getRichStringCellValue().toString()); assertEquals("CONCATENATE(B3,\" (ref)\")", sheet.getRow(2).getCell((short)3).getCellFormula()); - + // one on a non-shifted row also updated assertEquals("cell B2 (ref)", sheet.getRow(6).getCell((short)1).getRichStringCellValue().toString()); assertEquals("CONCATENATE(B12,\" (ref)\")", sheet.getRow(6).getCell((short)1).getCellFormula()); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java index 3f876c8663..cd7ae1c7b4 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java @@ -14,43 +14,36 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ -package org.apache.poi.hssf.usermodel; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; +package org.apache.poi.hssf.usermodel; +import junit.framework.AssertionFailedError; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; +import org.apache.poi.hssf.record.RecordFormatException; + /** * @author aviks - * - * This testcase contains tests for bugs that are yet to be fixed. - * Therefore, the standard ant test target does not run these tests. - * Run this testcase with the single-test target. - * The names of the tests usually correspond to the Bugzilla id's - * PLEASE MOVE tests from this class to TestBugs once the bugs are fixed, - * so that they are then run automatically. + * + * This testcase contains tests for bugs that are yet to be fixed. Therefore, + * the standard ant test target does not run these tests. Run this testcase with + * the single-test target. The names of the tests usually correspond to the + * Bugzilla id's PLEASE MOVE tests from this class to TestBugs once the bugs are + * fixed, so that they are then run automatically. */ -public class TestUnfixedBugs extends TestCase { - - - public TestUnfixedBugs(String arg0) { - super(arg0); - +public final class TestUnfixedBugs extends TestCase { + + public void test43493() { + // Has crazy corrupt sub-records on + // a EmbeddedObjectRefSubRecord + try { + HSSFTestDataSamples.openSampleWorkbook("43493.xls"); + } catch (RecordFormatException e) { + if (e.getCause().getCause() instanceof ArrayIndexOutOfBoundsException) { + throw new AssertionFailedError("Identified bug 43493"); + } + throw e; + } } - - protected String cwd = System.getProperty("HSSF.testdata.path"); - - - - public void test43493() throws Exception { - // Has crazy corrup subrecords on - // a EmbeddedObjectRefSubRecord - File f = new File(cwd, "43493.xls"); - HSSFWorkbook wb = new HSSFWorkbook( - new FileInputStream(f) - ); - } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestUppercaseWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestUppercaseWorkbook.java index 951e644015..ad7ae65a08 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestUppercaseWorkbook.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestUppercaseWorkbook.java @@ -14,37 +14,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.apache.poi.hssf.usermodel; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; import java.io.FileNotFoundException; - -import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import java.io.InputStream; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; + /** * Tests for how HSSFWorkbook behaves with XLS files * with a WORKBOOK directory entry (instead of the more * usual, Workbook) */ -public class TestUppercaseWorkbook extends TestCase { - private String dirPath; - private String xlsA = "WORKBOOK_in_capitals.xls"; +public final class TestUppercaseWorkbook extends TestCase { - protected void setUp() throws Exception { - super.setUp(); - - dirPath = System.getProperty("HSSF.testdata.path"); - } + private String xlsA = "WORKBOOK_in_capitals.xls"; /** * Test that we can open a file with WORKBOOK */ public void testOpen() throws Exception { - FileInputStream is = new FileInputStream(dirPath + "/" + xlsA); + InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA); POIFSFileSystem fs = new POIFSFileSystem(is); @@ -68,7 +64,7 @@ public class TestUppercaseWorkbook extends TestCase { * Test that when we write out, we go back to the correct case */ public void testWrite() throws Exception { - FileInputStream is = new FileInputStream(dirPath + "/" + xlsA); + InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA); POIFSFileSystem fs = new POIFSFileSystem(is); // Open the workbook, not preserving nodes @@ -96,7 +92,7 @@ public class TestUppercaseWorkbook extends TestCase { * correct case */ public void testWritePreserve() throws Exception { - FileInputStream is = new FileInputStream(dirPath + "/" + xlsA); + InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA); POIFSFileSystem fs = new POIFSFileSystem(is); // Open the workbook, not preserving nodes diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java index bf6953e785..a5402f64c4 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,11 +14,18 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.usermodel; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Iterator; + import junit.framework.TestCase; + +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.model.Workbook; import org.apache.poi.hssf.record.BackupRecord; import org.apache.poi.hssf.record.LabelSSTRecord; @@ -29,12 +35,6 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.util.Region; import org.apache.poi.util.TempFile; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Iterator; - /** * Class to test Workbook functionality * @@ -42,10 +42,7 @@ import java.util.Iterator; * @author Greg Merrill * @author Siggi Cherem */ - -public class TestWorkbook - extends TestCase -{ +public class TestWorkbook extends TestCase { private static final String LAST_NAME_KEY = "lastName"; private static final String FIRST_NAME_KEY = "firstName"; private static final String SSN_KEY = "ssn"; @@ -58,15 +55,9 @@ public class TestWorkbook private static final String SSN_VALUE = "555555555"; private SanityChecker sanityChecker = new SanityChecker(); - /** - * Constructor TestWorkbook - * - * @param name - */ - public TestWorkbook(String name) - { - super(name); + private static HSSFWorkbook openSample(String sampleFileName) { + return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); } /** @@ -178,21 +169,12 @@ public class TestWorkbook * */ - public void testReadSimple() - throws IOException - { - String filename = System.getProperty("HSSF.testdata.path"); + public void testReadSimple() { + HSSFWorkbook workbook = openSample("Simple.xls"); + HSSFSheet sheet = workbook.getSheetAt(0); - filename = filename + "/Simple.xls"; - FileInputStream stream = new FileInputStream(filename); - POIFSFileSystem fs = new POIFSFileSystem(stream); - HSSFWorkbook workbook = new HSSFWorkbook(fs); - HSSFSheet sheet = workbook.getSheetAt(0); - - assertEquals(REPLACE_ME, - sheet.getRow(( short ) 0).getCell(( short ) 0) - .getStringCellValue()); - stream.close(); + HSSFCell cell = sheet.getRow(0).getCell(0); + assertEquals(REPLACE_ME, cell .getRichStringCellValue().getString()); } /** @@ -204,24 +186,15 @@ public class TestWorkbook * */ - public void testReadSimpleWithDataFormat() - throws IOException - { - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/SimpleWithDataFormat.xls"; - FileInputStream stream = new FileInputStream(filename); - POIFSFileSystem fs = new POIFSFileSystem(stream); - HSSFWorkbook workbook = new HSSFWorkbook(fs); + public void testReadSimpleWithDataFormat() { + HSSFWorkbook workbook = openSample("SimpleWithDataFormat.xls"); HSSFSheet sheet = workbook.getSheetAt(0); HSSFDataFormat format = workbook.createDataFormat(); - HSSFCell cell = - sheet.getRow(( short ) 0).getCell(( short ) 0); + HSSFCell cell = sheet.getRow(0).getCell(0); assertEquals(1.25,cell.getNumericCellValue(), 1e-10); - assertEquals(format.getFormat(cell.getCellStyle().getDataFormat()), "0.0"); - stream.close(); + assertEquals(format.getFormat(cell.getCellStyle().getDataFormat()), "0.0"); } /** @@ -236,23 +209,23 @@ public class TestWorkbook public void testWriteDataFormat() throws IOException { - File file = TempFile.createTempFile("testWriteDataFormat", + File file = TempFile.createTempFile("testWriteDataFormat", ".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; - HSSFDataFormat format = wb.createDataFormat(); - HSSFCellStyle cs = wb.createCellStyle(); - - short df = format.getFormat("0.0"); - cs.setDataFormat(df); - - r = s.createRow((short)0); - c = r.createCell((short)0); - c.setCellStyle(cs); - c.setCellValue(1.25); + HSSFDataFormat format = wb.createDataFormat(); + HSSFCellStyle cs = wb.createCellStyle(); + + short df = format.getFormat("0.0"); + cs.setDataFormat(df); + + r = s.createRow((short)0); + c = r.createCell((short)0); + c.setCellStyle(cs); + c.setCellValue(1.25); wb.write(out); out.close(); @@ -261,16 +234,16 @@ public class TestWorkbook POIFSFileSystem fs = new POIFSFileSystem(stream); HSSFWorkbook workbook = new HSSFWorkbook(fs); HSSFSheet sheet = workbook.getSheetAt(0); - HSSFCell cell = + HSSFCell cell = sheet.getRow(( short ) 0).getCell(( short ) 0); - format = workbook.createDataFormat(); + format = workbook.createDataFormat(); assertEquals(1.25,cell.getNumericCellValue(), 1e-10); - assertEquals(format.getFormat(df), "0.0"); + assertEquals(format.getFormat(df), "0.0"); + + assertEquals(format, workbook.createDataFormat()); - assertEquals(format, workbook.createDataFormat()); - stream.close(); } @@ -283,30 +256,14 @@ public class TestWorkbook * */ - public void testReadEmployeeSimple() - throws IOException - { - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/Employee.xls"; - FileInputStream stream = new FileInputStream(filename); - POIFSFileSystem fs = new POIFSFileSystem(stream); - HSSFWorkbook workbook = new HSSFWorkbook(fs); + public void testReadEmployeeSimple() { + HSSFWorkbook workbook = openSample("Employee.xls"); HSSFSheet sheet = workbook.getSheetAt(0); - assertEquals(EMPLOYEE_INFORMATION, - sheet.getRow(1).getCell(( short ) 1) - .getStringCellValue()); - assertEquals(LAST_NAME_KEY, - sheet.getRow(3).getCell(( short ) 2) - .getStringCellValue()); - assertEquals(FIRST_NAME_KEY, - sheet.getRow(4).getCell(( short ) 2) - .getStringCellValue()); - assertEquals(SSN_KEY, - sheet.getRow(5).getCell(( short ) 2) - .getStringCellValue()); - stream.close(); + assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getStringCellValue()); + assertEquals(LAST_NAME_KEY, sheet.getRow(3).getCell(2).getStringCellValue()); + assertEquals(FIRST_NAME_KEY, sheet.getRow(4).getCell(2).getStringCellValue()); + assertEquals(SSN_KEY, sheet.getRow(5).getCell(2).getStringCellValue()); } /** @@ -322,33 +279,17 @@ public class TestWorkbook * */ - public void testModifySimple() - throws IOException - { - String filename = System.getProperty("HSSF.testdata.path"); + public void testModifySimple() { + HSSFWorkbook workbook = openSample("Simple.xls"); + HSSFSheet sheet = workbook.getSheetAt(0); + HSSFCell cell = sheet.getRow(0).getCell(0); - filename = filename + "/Simple.xls"; - FileInputStream instream = new FileInputStream(filename); - POIFSFileSystem fsin = new POIFSFileSystem(instream); - HSSFWorkbook workbook = new HSSFWorkbook(fsin); - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFCell cell = - sheet.getRow(( short ) 0).getCell(( short ) 0); + cell.setCellValue(new HSSFRichTextString(REPLACED)); - cell.setCellValue(REPLACED); - File destination = TempFile.createTempFile("SimpleResult", - ".xls"); - FileOutputStream outstream = new FileOutputStream(destination); - - workbook.write(outstream); - instream.close(); - outstream.close(); - instream = new FileInputStream(destination); - workbook = new HSSFWorkbook(new POIFSFileSystem(instream)); + workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook); sheet = workbook.getSheetAt(0); - cell = sheet.getRow(( short ) 0).getCell(( short ) 0); - assertEquals(REPLACED, cell.getStringCellValue()); - instream.close(); + cell = sheet.getRow(0).getCell(0); + assertEquals(REPLACED, cell.getRichStringCellValue().getString()); } /** @@ -364,42 +305,26 @@ public class TestWorkbook * or is incorrect.

* */ - - public void testModifySimpleWithSkip() - throws IOException - { - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/SimpleWithSkip.xls"; - FileInputStream instream = new FileInputStream(filename); - POIFSFileSystem fsin = new POIFSFileSystem(instream); - HSSFWorkbook workbook = new HSSFWorkbook(fsin); - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFCell cell = - sheet.getRow(( short ) 0).getCell(( short ) 1); + public void testModifySimpleWithSkip() { + HSSFWorkbook workbook = openSample("SimpleWithSkip.xls"); + HSSFSheet sheet = workbook.getSheetAt(0); + HSSFCell cell = sheet.getRow(0).getCell(1); cell.setCellValue(REPLACED); - cell = sheet.getRow(( short ) 1).getCell(( short ) 0); + cell = sheet.getRow(1).getCell(0); cell.setCellValue(REPLACED); - File destination = - TempFile.createTempFile("SimpleWithSkipResult", ".xls"); - FileOutputStream outstream = new FileOutputStream(destination); - - workbook.write(outstream); - instream.close(); - outstream.close(); - instream = new FileInputStream(destination); - workbook = new HSSFWorkbook(new POIFSFileSystem(instream)); + + workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook); + sheet = workbook.getSheetAt(0); - cell = sheet.getRow(( short ) 0).getCell(( short ) 1); + cell = sheet.getRow(0).getCell(1); assertEquals(REPLACED, cell.getStringCellValue()); - cell = sheet.getRow(( short ) 0).getCell(( short ) 0); + cell = sheet.getRow(0).getCell(0); assertEquals(DO_NOT_REPLACE, cell.getStringCellValue()); - cell = sheet.getRow(( short ) 1).getCell(( short ) 0); + cell = sheet.getRow(1).getCell(0); assertEquals(REPLACED, cell.getStringCellValue()); - cell = sheet.getRow(( short ) 1).getCell(( short ) 1); + cell = sheet.getRow(1).getCell(1); assertEquals(DO_NOT_REPLACE, cell.getStringCellValue()); - instream.close(); } /** @@ -415,41 +340,26 @@ public class TestWorkbook * is incorrect or has not been replaced.

* */ - - public void testModifySimpleWithStyling() - throws IOException - { - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/SimpleWithStyling.xls"; - FileInputStream instream = new FileInputStream(filename); - POIFSFileSystem fsin = new POIFSFileSystem(instream); - HSSFWorkbook workbook = new HSSFWorkbook(fsin); + public void testModifySimpleWithStyling() { + HSSFWorkbook workbook = openSample("SimpleWithStyling.xls"); HSSFSheet sheet = workbook.getSheetAt(0); for (int k = 0; k < 4; k++) { HSSFCell cell = sheet.getRow(( short ) k).getCell(( short ) 0); - cell.setCellValue(REPLACED); + cell.setCellValue(new HSSFRichTextString(REPLACED)); } - File destination = - TempFile.createTempFile("SimpleWithStylingResult", ".xls"); - FileOutputStream outstream = new FileOutputStream(destination); - - workbook.write(outstream); - instream.close(); - outstream.close(); - instream = new FileInputStream(destination); - workbook = new HSSFWorkbook(new POIFSFileSystem(instream)); + + + workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook); sheet = workbook.getSheetAt(0); for (int k = 0; k < 4; k++) { HSSFCell cell = sheet.getRow(( short ) k).getCell(( short ) 0); - assertEquals(REPLACED, cell.getStringCellValue()); + assertEquals(REPLACED, cell.getRichStringCellValue().getString()); } - instream.close(); } /** @@ -465,48 +375,23 @@ public class TestWorkbook * is incorrect or has not been replaced.

* */ - - public void testModifyEmployee() - throws IOException - { - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/Employee.xls"; - FileInputStream instream = new FileInputStream(filename); - POIFSFileSystem fsin = new POIFSFileSystem(instream); - HSSFWorkbook workbook = new HSSFWorkbook(fsin); + public void testModifyEmployee() { + HSSFWorkbook workbook = openSample("Employee.xls"); HSSFSheet sheet = workbook.getSheetAt(0); - HSSFCell cell = - sheet.getRow(( short ) 3).getCell(( short ) 2); + HSSFCell cell = sheet.getRow(3).getCell(2); cell.setCellValue(LAST_NAME_VALUE); - cell = sheet.getRow(( short ) 4).getCell(( short ) 2); + cell = sheet.getRow(4).getCell(2); cell.setCellValue(FIRST_NAME_VALUE); - cell = sheet.getRow(( short ) 5).getCell(( short ) 2); + cell = sheet.getRow(5).getCell(2); cell.setCellValue(SSN_VALUE); - File destination = TempFile.createTempFile("EmployeeResult", - ".xls"); - FileOutputStream outstream = new FileOutputStream(destination); - - workbook.write(outstream); - instream.close(); - outstream.close(); - instream = new FileInputStream(destination); - workbook = new HSSFWorkbook(new POIFSFileSystem(instream)); + + workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook); sheet = workbook.getSheetAt(0); - assertEquals(EMPLOYEE_INFORMATION, - sheet.getRow(1).getCell(( short ) 1) - .getStringCellValue()); - assertEquals(LAST_NAME_VALUE, - sheet.getRow(3).getCell(( short ) 2) - .getStringCellValue()); - assertEquals(FIRST_NAME_VALUE, - sheet.getRow(4).getCell(( short ) 2) - .getStringCellValue()); - assertEquals(SSN_VALUE, - sheet.getRow(5).getCell(( short ) 2) - .getStringCellValue()); - instream.close(); + assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getStringCellValue()); + assertEquals(LAST_NAME_VALUE, sheet.getRow(3).getCell(2).getStringCellValue()); + assertEquals(FIRST_NAME_VALUE, sheet.getRow(4).getCell(2).getStringCellValue()); + assertEquals(SSN_VALUE, sheet.getRow(5).getCell(2).getStringCellValue()); } /** @@ -517,21 +402,10 @@ public class TestWorkbook * FAILURE: HSSF does not read a sheet or excepts. HSSF incorrectly indentifies the cell

* */ - - public void testReadSheetWithRK() - throws IOException - { - String filename = System.getProperty("HSSF.testdata.path"); - - filename = filename + "/rk.xls"; - - // a.xls has a value on position (0,0) - FileInputStream in = new FileInputStream(filename); - POIFSFileSystem fs = new POIFSFileSystem(in); - HSSFWorkbook h = new HSSFWorkbook(fs); + public void testReadSheetWithRK() { + HSSFWorkbook h = openSample("rk.xls"); HSSFSheet s = h.getSheetAt(0); - HSSFRow r = s.getRow(0); - HSSFCell c = r.getCell(( short ) 0); + HSSFCell c = s.getRow(0).getCell(0); int a = c.getCellType(); assertEquals(a, c.CELL_TYPE_NUMERIC); @@ -564,7 +438,6 @@ public class TestWorkbook { r = s.createRow(rownum); - // r.setRowNum(( short ) rownum); for (short cellnum = ( short ) 0; cellnum < 50; cellnum += 2) { c = r.createCell(cellnum); @@ -572,7 +445,7 @@ public class TestWorkbook + ((( double ) rownum / 1000) + (( double ) cellnum / 10000))); c = r.createCell(( short ) (cellnum + 1)); - c.setCellValue("TEST"); + c.setCellValue(new HSSFRichTextString("TEST")); } } s.addMergedRegion(new Region(( short ) 0, ( short ) 0, ( short ) 10, @@ -632,7 +505,7 @@ public class TestWorkbook HSSFRow row = sheet.createRow(( short ) 2); HSSFCell cell = row.createCell(( short ) 1); - cell.setCellValue("Class"); + cell.setCellValue(new HSSFRichTextString("Class")); cell = row.createCell(( short ) 2); // workbook.write(new FileOutputStream("/a2.xls")); @@ -687,49 +560,35 @@ public class TestWorkbook in.close(); file.deleteOnExit(); } - + /** * Generate a file to visually/programmatically verify repeating rows and cols made it */ public void testRepeatingColsRows() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test Print Titles"); - String sheetName = workbook.getSheetName(0); - - HSSFRow row = sheet.createRow(0); - - HSSFCell cell = row.createCell((short)1); - cell.setCellValue("hi"); - - - workbook.setRepeatingRowsAndColumns(0, 0, 1, 0, 0); - - File file = TempFile.createTempFile("testPrintTitles",".xls"); - - FileOutputStream fileOut = new FileOutputStream(file); - workbook.write(fileOut); - fileOut.close(); - - assertTrue("file exists",file.exists()); - - + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet("Test Print Titles"); + + HSSFRow row = sheet.createRow(0); + + HSSFCell cell = row.createCell((short)1); + cell.setCellValue(new HSSFRichTextString("hi")); + + + workbook.setRepeatingRowsAndColumns(0, 0, 1, 0, 0); + + File file = TempFile.createTempFile("testPrintTitles",".xls"); + + FileOutputStream fileOut = new FileOutputStream(file); + workbook.write(fileOut); + fileOut.close(); + + assertTrue("file exists",file.exists()); } - - + + public static void main(String [] ignored_args) { - String filename = System.getProperty("HSSF.testdata.path"); - - // assume this is relative to basedir - if (filename == null) - { - System.setProperty( - "HSSF.testdata.path", - "src/testcases/org/apache/poi/hssf/data"); - } - System.out - .println("Testing org.apache.poi.hssf.usermodel.HSSFWorkbook"); junit.textui.TestRunner.run(TestWorkbook.class); } } diff --git a/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java b/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java index afdda44357..a72c039cb8 100644 --- a/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java +++ b/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java @@ -14,24 +14,29 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.hssf.util; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + import junit.framework.TestCase; -import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.model.Workbook; import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.formula.MemFuncPtg; import org.apache.poi.hssf.record.formula.Area3DPtg; +import org.apache.poi.hssf.record.formula.MemFuncPtg; import org.apache.poi.hssf.record.formula.UnionPtg; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFName; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +/** + * + */ public final class TestAreaReference extends TestCase { public void testAreaRef1() { @@ -99,7 +104,7 @@ public final class TestAreaReference extends TestCase { TestCellReference.confirmCell(allCells[2], "Tabelle1", 6, 1, true, true, "Tabelle1!$B$7"); } - private static class HSSFWB extends HSSFWorkbook { + private static final class HSSFWB extends HSSFWorkbook { public HSSFWB(InputStream in) throws IOException { super(in); } @@ -182,12 +187,9 @@ public final class TestAreaReference extends TestCase { } public void testDiscontinousReference() throws Exception { - String filename = System.getProperty( "HSSF.testdata.path" ); - filename = filename + "/44167.xls"; - FileInputStream fin = new FileInputStream( filename ); - HSSFWB wb = new HSSFWB( fin ); + InputStream is = HSSFTestDataSamples.openSampleFileStream("44167.xls"); + HSSFWB wb = new HSSFWB(is); Workbook workbook = wb.getWorkbook(); - fin.close(); assertEquals(1, wb.getNumberOfNames()); String sheetName = "Tabelle1"; @@ -269,5 +271,4 @@ public final class TestAreaReference extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(TestAreaReference.class); } - } diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestOffice2007XMLException.java b/src/testcases/org/apache/poi/poifs/filesystem/TestOffice2007XMLException.java index 01a0f42d3e..8080b3ec79 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestOffice2007XMLException.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestOffice2007XMLException.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,58 +14,56 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - package org.apache.poi.poifs.filesystem; import junit.framework.TestCase; import java.io.*; +import org.apache.poi.hssf.HSSFTestDataSamples; + /** * Class to test that POIFS complains when given an Office 2007 XML document * * @author Marc Johnson */ +public class TestOffice2007XMLException extends TestCase { -public class TestOffice2007XMLException extends TestCase -{ - public String dirname; - - public void setUp() { - dirname = System.getProperty("HSSF.testdata.path"); + private static final InputStream openSampleStream(String sampleFileName) { + return HSSFTestDataSamples.openSampleFileStream(sampleFileName); } - public void testXMLException() throws IOException { - FileInputStream in = new FileInputStream(dirname + "/sample.xlsx"); + InputStream in = openSampleStream("sample.xlsx"); try { new POIFSFileSystem(in); - fail(); + fail("expected exception was not thrown"); } catch(OfficeXmlFileException e) { - // Good + // expected during successful test + assertTrue(e.getMessage().indexOf("POI only supports OLE2 Office documents") > 0); } } - public void testDetectAsPOIFS() throws IOException { - InputStream in; + public void testDetectAsPOIFS() { // ooxml file isn't - in = new PushbackInputStream( - new FileInputStream(dirname + "/SampleSS.xlsx"), 10 - ); - assertFalse(POIFSFileSystem.hasPOIFSHeader(in)); + confirmIsPOIFS("SampleSS.xlsx", false); // xls file is - in = new PushbackInputStream( - new FileInputStream(dirname + "/SampleSS.xls"), 10 - ); - assertTrue(POIFSFileSystem.hasPOIFSHeader(in)); + confirmIsPOIFS("SampleSS.xls", true); // text file isn't - in = new PushbackInputStream( - new FileInputStream(dirname + "/SampleSS.txt"), 10 - ); - assertFalse(POIFSFileSystem.hasPOIFSHeader(in)); + confirmIsPOIFS("SampleSS.txt", false); + } + private void confirmIsPOIFS(String sampleFileName, boolean expectedResult) { + InputStream in = new PushbackInputStream(openSampleStream(sampleFileName), 10); + boolean actualResult; + try { + actualResult = POIFSFileSystem.hasPOIFSHeader(in); + } catch (IOException e) { + throw new RuntimeException(e); + } + assertEquals(expectedResult, actualResult); } } diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java index dbc5401beb..d792dcf227 100755 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java @@ -17,14 +17,13 @@ package org.apache.poi.poifs.filesystem; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; + /** * Tests for POIFSFileSystem * @@ -32,10 +31,6 @@ import junit.framework.TestCase; */ public final class TestPOIFSFileSystem extends TestCase { - public TestPOIFSFileSystem(String testName) { - super(testName); - } - /** * Mock exception used to ensure correct error handling */ @@ -121,16 +116,7 @@ public final class TestPOIFSFileSystem extends TestCase { } - private static InputStream openSampleStream(String sampleName) { - String dataDirName = System.getProperty("HSSF.testdata.path"); - if(dataDirName == null) { - throw new RuntimeException("Missing system property '" + "HSSF.testdata.path" + "'"); - } - File f = new File(dataDirName + "/" + sampleName); - try { - return new FileInputStream(f); - } catch (FileNotFoundException e) { - throw new RuntimeException("Sample file '" + f.getAbsolutePath() + "' not found"); - } + private static InputStream openSampleStream(String sampleFileName) { + return HSSFTestDataSamples.openSampleFileStream(sampleFileName); } } diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java index f7b9eb7a54..ecff6778a3 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java @@ -18,12 +18,21 @@ package org.apache.poi.poifs.filesystem; -import junit.framework.TestCase; -import junit.framework.ComparisonFailure; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Iterator; -import java.io.*; -import java.util.*; +import junit.framework.ComparisonFailure; +import junit.framework.TestCase; +import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.poifs.property.DirectoryProperty; import org.apache.poi.poifs.property.Property; @@ -36,45 +45,46 @@ import org.apache.poi.poifs.property.Property; * * @author Yegor Kozlov */ -public class TestPropertySorter extends TestCase { +public final class TestPropertySorter extends TestCase { //the correct order of entries in the test file - protected static final String[] _entries = { + private static final String[] _entries = { "dir", "JML", "UTIL", "Loader", "Sheet1", "Sheet2", "Sheet3", "__SRP_0", "__SRP_1", "__SRP_2", "__SRP_3", "__SRP_4", "__SRP_5", "ThisWorkbook", "_VBA_PROJECT", }; - protected File testFile; - - public void setUp(){ - String home = System.getProperty("HSSF.testdata.path"); - testFile = new File(home + "/39234.xls"); + private static POIFSFileSystem openSampleFS() { + InputStream is = HSSFTestDataSamples.openSampleFileStream("39234.xls"); + try { + return new POIFSFileSystem(is); + } catch (IOException e) { + throw new RuntimeException(e); + } } - + /** * Test sorting of properties in DirectoryProperty */ public void testSortProperties() throws IOException { - InputStream is = new FileInputStream(testFile); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); + POIFSFileSystem fs = openSampleFS(); Property[] props = getVBAProperties(fs); assertEquals(_entries.length, props.length); - // (1). See that there is a problem with the old case-sensitive property comparartor - Arrays.sort(props, new CaseSensitivePropertyComparator()); + // (1). See that there is a problem with the old case-sensitive property comparator + Arrays.sort(props, OldCaseSensitivePropertyComparator); try { for (int i = 0; i < props.length; i++) { assertEquals(_entries[i], props[i].getName()); } - fail("case-sensitive property comparator returns properties in wrong order"); + fail("expected old case-sensitive property comparator to return properties in wrong order"); } catch (ComparisonFailure e){ - ; // as expected + // expected during successful test + assertNotNull(e.getMessage()); } - // (2) Verify that the fixed proeprty comparator works right + // (2) Verify that the fixed property comparator works right Arrays.sort(props, new DirectoryProperty.PropertyComparator()); for (int i = 0; i < props.length; i++) { assertEquals(_entries[i], props[i].getName()); @@ -85,14 +95,12 @@ public class TestPropertySorter extends TestCase { * Serialize file system and verify that the order of properties is the same as in the original file. */ public void testSerialization() throws IOException { - InputStream is = new FileInputStream(testFile); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); + POIFSFileSystem fs = openSampleFS(); ByteArrayOutputStream out = new ByteArrayOutputStream(); fs.writeFilesystem(out); out.close(); - is = new ByteArrayInputStream(out.toByteArray()); + InputStream is = new ByteArrayInputStream(out.toByteArray()); fs = new POIFSFileSystem(is); is.close(); Property[] props = getVBAProperties(fs); @@ -128,26 +136,17 @@ public class TestPropertySorter extends TestCase { /** * Old version of case-sensitive PropertyComparator to demonstrate the problem */ - private class CaseSensitivePropertyComparator implements Comparator - { - - public boolean equals(Object o) - { - return this == o; - } + private static final Comparator OldCaseSensitivePropertyComparator = new Comparator() { - public int compare(Object o1, Object o2) - { + public int compare(Object o1, Object o2) { String name1 = (( Property ) o1).getName(); String name2 = (( Property ) o2).getName(); - int result = name1.length() - name2.length(); + int result = name1.length() - name2.length(); - if (result == 0) - { + if (result == 0) { result = name1.compareTo(name2); } return result; } - } - + }; } -- 2.39.5