From 37791e4bdfc706aa5684745594260f243b4be7ee Mon Sep 17 00:00:00 2001 From: Andreas Beeker Date: Sat, 27 Mar 2021 14:03:16 +0000 Subject: 65206 - Migrate ant / maven to gradle build update gradle files and project structure along https://github.com/centic9/poi/tree/gradle_build remove eclipse IDE project files remove obsolete record generator files git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1888111 13f79535-47bb-0310-9956-ffa450edef68 --- src/testcases/org/apache/poi/POIDataSamples.java | 281 -- src/testcases/org/apache/poi/POITestCase.java | 203 -- src/testcases/org/apache/poi/TestJDK12.java | 57 - .../org/apache/poi/TestPOIDocumentMain.java | 200 -- src/testcases/org/apache/poi/TestPOITestCase.java | 87 - .../org/apache/poi/ddf/TestEscherBSERecord.java | 113 - .../org/apache/poi/ddf/TestEscherBlipRecord.java | 165 -- .../org/apache/poi/ddf/TestEscherBoolProperty.java | 39 - .../poi/ddf/TestEscherChildAnchorRecord.java | 94 - .../poi/ddf/TestEscherClientAnchorRecord.java | 112 - .../apache/poi/ddf/TestEscherClientDataRecord.java | 77 - .../apache/poi/ddf/TestEscherContainerRecord.java | 234 -- .../org/apache/poi/ddf/TestEscherDgRecord.java | 83 - .../org/apache/poi/ddf/TestEscherDggRecord.java | 112 - .../org/apache/poi/ddf/TestEscherDump.java | 137 - .../org/apache/poi/ddf/TestEscherOptRecord.java | 320 --- .../org/apache/poi/ddf/TestEscherProperty.java | 55 - .../apache/poi/ddf/TestEscherPropertyFactory.java | 52 - .../org/apache/poi/ddf/TestEscherSpRecord.java | 85 - .../org/apache/poi/ddf/TestEscherSpgrRecord.java | 93 - .../poi/ddf/TestEscherSplitMenuColorsRecord.java | 93 - .../apache/poi/ddf/TestUnknownEscherRecord.java | 165 -- .../org/apache/poi/hpsf/TestVariantSupport.java | 124 - .../org/apache/poi/hpsf/basic/POIFile.java | 93 - .../org/apache/poi/hpsf/basic/TestBasic.java | 206 -- .../org/apache/poi/hpsf/basic/TestClassID.java | 87 - .../apache/poi/hpsf/basic/TestEmptyProperties.java | 155 -- .../org/apache/poi/hpsf/basic/TestHPSFBugs.java | 190 -- .../org/apache/poi/hpsf/basic/TestMetaDataIPI.java | 601 ----- .../apache/poi/hpsf/basic/TestReadAllFiles.java | 213 -- .../org/apache/poi/hpsf/basic/TestUnicode.java | 88 - .../org/apache/poi/hpsf/basic/TestWrite.java | 707 ----- .../apache/poi/hpsf/basic/TestWriteWellKnown.java | 595 ----- src/testcases/org/apache/poi/hpsf/basic/Util.java | 129 - .../extractor/TestHPSFPropertiesExtractor.java | 182 -- .../org/apache/poi/hssf/HSSFITestDataProvider.java | 92 - .../org/apache/poi/hssf/HSSFTestDataSamples.java | 70 - .../apache/poi/hssf/dev/BaseTestIteratingXLS.java | 80 - .../apache/poi/hssf/dev/TestBiffDrawingToXml.java | 58 - .../org/apache/poi/hssf/dev/TestBiffViewer.java | 76 - .../org/apache/poi/hssf/dev/TestEFBiffViewer.java | 75 - .../org/apache/poi/hssf/dev/TestFormulaViewer.java | 79 - .../org/apache/poi/hssf/dev/TestReSave.java | 102 - .../org/apache/poi/hssf/dev/TestRecordLister.java | 68 - .../poi/hssf/eventmodel/TestAbortableListener.java | 108 - .../hssf/eventmodel/TestEventRecordFactory.java | 167 -- .../eventusermodel/TestEventWorkbookBuilder.java | 159 -- .../TestFormatTrackingHSSFListener.java | 116 - .../hssf/eventusermodel/TestHSSFEventFactory.java | 169 -- .../TestMissingRecordAwareHSSFListener.java | 226 -- .../poi/hssf/extractor/TestExcelExtractor.java | 385 --- .../poi/hssf/extractor/TestOldExcelExtractor.java | 381 --- .../poi/hssf/model/TestDrawingAggregate.java | 904 ------- .../apache/poi/hssf/model/TestDrawingManager2.java | 121 - .../apache/poi/hssf/model/TestDrawingShapes.java | 853 ------ .../poi/hssf/model/TestEscherRecordFactory.java | 104 - .../apache/poi/hssf/model/TestFormulaParser.java | 1581 ----------- .../poi/hssf/model/TestFormulaParserEval.java | 99 - .../apache/poi/hssf/model/TestFormulaParserIf.java | 238 -- .../org/apache/poi/hssf/model/TestHSSFAnchor.java | 459 ---- .../org/apache/poi/hssf/model/TestLinkTable.java | 256 -- .../hssf/model/TestOperandClassTransformer.java | 150 -- .../org/apache/poi/hssf/model/TestRVA.java | 132 - .../apache/poi/hssf/model/TestRowBlocksReader.java | 65 - .../org/apache/poi/hssf/model/TestSheet.java | 784 ------ .../apache/poi/hssf/model/TestSheetAdditional.java | 70 - .../org/apache/poi/hssf/model/TestWorkbook.java | 173 -- .../poi/hssf/model/TestWorkbookRecordList.java | 43 - .../apache/poi/hssf/record/TestArrayRecord.java | 81 - .../poi/hssf/record/TestAutoFilterInfoRecord.java | 70 - .../org/apache/poi/hssf/record/TestBOFRecord.java | 41 - .../apache/poi/hssf/record/TestBoolErrRecord.java | 80 - .../poi/hssf/record/TestBoundSheetRecord.java | 123 - .../apache/poi/hssf/record/TestCFHeaderRecord.java | 202 -- .../apache/poi/hssf/record/TestCFRuleRecord.java | 453 ---- .../poi/hssf/record/TestColumnInfoRecord.java | 82 - .../hssf/record/TestCommonObjectDataSubRecord.java | 78 - .../apache/poi/hssf/record/TestDConRefRecord.java | 287 -- .../org/apache/poi/hssf/record/TestDVALRecord.java | 51 - .../poi/hssf/record/TestDrawingGroupRecord.java | 129 - .../apache/poi/hssf/record/TestDrawingRecord.java | 66 - .../record/TestEmbeddedObjectRefSubRecord.java | 154 -- .../apache/poi/hssf/record/TestEndSubRecord.java | 44 - .../poi/hssf/record/TestEscherAggregate.java | 131 - .../apache/poi/hssf/record/TestExtSSTRecord.java | 177 -- .../poi/hssf/record/TestExtendedFormatRecord.java | 162 -- .../poi/hssf/record/TestExternalNameRecord.java | 172 -- .../org/apache/poi/hssf/record/TestFeatRecord.java | 198 -- .../org/apache/poi/hssf/record/TestFontRecord.java | 157 -- .../apache/poi/hssf/record/TestFormulaRecord.java | 200 -- .../poi/hssf/record/TestFtCblsSubRecord.java | 65 - .../poi/hssf/record/TestHyperlinkRecord.java | 545 ---- .../poi/hssf/record/TestInterfaceEndRecord.java | 62 - .../apache/poi/hssf/record/TestLabelRecord.java | 47 - .../poi/hssf/record/TestLbsDataSubRecord.java | 177 -- .../poi/hssf/record/TestMergeCellsRecord.java | 73 - .../poi/hssf/record/TestNameCommentRecord.java | 43 - .../org/apache/poi/hssf/record/TestNameRecord.java | 159 -- .../org/apache/poi/hssf/record/TestNoteRecord.java | 138 - .../hssf/record/TestNoteStructureSubRecord.java | 67 - .../org/apache/poi/hssf/record/TestObjRecord.java | 144 - .../org/apache/poi/hssf/record/TestPLVRecord.java | 59 - .../apache/poi/hssf/record/TestPaletteRecord.java | 56 - .../org/apache/poi/hssf/record/TestPaneRecord.java | 67 - .../apache/poi/hssf/record/TestRecalcIdRecord.java | 68 - .../apache/poi/hssf/record/TestRecordFactory.java | 234 -- .../hssf/record/TestRecordFactoryInputStream.java | 162 -- .../poi/hssf/record/TestRecordInputStream.java | 103 - .../org/apache/poi/hssf/record/TestSCLRecord.java | 55 - .../poi/hssf/record/TestSSTDeserializer.java | 125 - .../org/apache/poi/hssf/record/TestSSTRecord.java | 416 --- .../hssf/record/TestSSTRecordSizeCalculator.java | 137 - .../poi/hssf/record/TestSharedFormulaRecord.java | 245 -- .../apache/poi/hssf/record/TestStringRecord.java | 102 - .../apache/poi/hssf/record/TestStyleRecord.java | 41 - .../org/apache/poi/hssf/record/TestSubRecord.java | 148 -- .../apache/poi/hssf/record/TestSupBookRecord.java | 171 -- .../apache/poi/hssf/record/TestTableRecord.java | 97 - .../poi/hssf/record/TestTextObjectBaseRecord.java | 85 - .../poi/hssf/record/TestTextObjectRecord.java | 201 -- .../poi/hssf/record/TestUnicodeNameRecord.java | 40 - .../poi/hssf/record/TestWriteAccessRecord.java | 96 - .../poi/hssf/record/TestcaseRecordInputStream.java | 101 - .../record/aggregates/TestCFRecordsAggregate.java | 168 -- .../aggregates/TestColumnInfoRecordsAggregate.java | 127 - .../aggregates/TestFormulaRecordAggregate.java | 99 - .../record/aggregates/TestPageSettingsBlock.java | 425 --- .../record/aggregates/TestRowRecordsAggregate.java | 159 -- .../record/aggregates/TestSharedValueManager.java | 163 -- .../aggregates/TestValueRecordsAggregate.java | 411 --- .../apache/poi/hssf/record/cf/TestCellRange.java | 274 -- .../hssf/record/chart/TestAreaFormatRecord.java | 77 - .../poi/hssf/record/chart/TestAreaRecord.java | 62 - .../record/chart/TestAxisLineFormatRecord.java | 54 - .../hssf/record/chart/TestAxisOptionsRecord.java | 92 - .../hssf/record/chart/TestAxisParentRecord.java | 67 - .../poi/hssf/record/chart/TestAxisRecord.java | 66 - .../poi/hssf/record/chart/TestAxisUsedRecord.java | 54 - .../poi/hssf/record/chart/TestBarRecord.java | 69 - .../record/chart/TestCategorySeriesAxisRecord.java | 71 - .../hssf/record/chart/TestChartFormatRecord.java | 58 - .../poi/hssf/record/chart/TestChartRecord.java | 63 - .../record/chart/TestChartTitleFormatRecord.java | 80 - .../poi/hssf/record/chart/TestDatRecord.java | 63 - .../hssf/record/chart/TestDataFormatRecord.java | 67 - .../TestDefaultDataLabelTextPropertiesRecord.java | 55 - .../poi/hssf/record/chart/TestFontBasisRecord.java | 66 - .../poi/hssf/record/chart/TestFontIndexRecord.java | 55 - .../poi/hssf/record/chart/TestFrameRecord.java | 63 - .../poi/hssf/record/chart/TestLegendRecord.java | 87 - .../hssf/record/chart/TestLineFormatRecord.java | 71 - .../hssf/record/chart/TestLinkedDataRecord.java | 194 -- .../record/chart/TestNumberFormatIndexRecord.java | 54 - .../hssf/record/chart/TestObjectLinkRecord.java | 60 - .../poi/hssf/record/chart/TestPlotAreaRecord.java | 50 - .../hssf/record/chart/TestPlotGrowthRecord.java | 58 - .../chart/TestSeriesChartGroupIndexRecord.java | 54 - .../hssf/record/chart/TestSeriesIndexRecord.java | 54 - .../hssf/record/chart/TestSeriesLabelsRecord.java | 67 - .../hssf/record/chart/TestSeriesListRecord.java | 56 - .../poi/hssf/record/chart/TestSeriesRecord.java | 70 - .../hssf/record/chart/TestSeriesTextRecord.java | 95 - .../record/chart/TestSheetPropertiesRecord.java | 74 - .../poi/hssf/record/chart/TestTextRecord.java | 118 - .../poi/hssf/record/chart/TestTickRecord.java | 89 - .../poi/hssf/record/chart/TestUnitsRecord.java | 56 - .../hssf/record/chart/TestValueRangeRecord.java | 89 - .../poi/hssf/record/common/TestUnicodeString.java | 447 ---- .../TestExtendedPivotTableViewFieldsRecord.java | 63 - .../poi/hssf/record/pivot/TestPageItemRecord.java | 61 - .../hssf/record/pivot/TestViewFieldsRecord.java | 63 - .../poi/hssf/usermodel/FormulaExtractor.java | 43 - .../hssf/usermodel/HSSFEvaluationTestHelper.java | 33 - .../apache/poi/hssf/usermodel/HSSFTestHelper.java | 102 - .../apache/poi/hssf/usermodel/SanityChecker.java | 215 -- .../apache/poi/hssf/usermodel/StreamUtility.java | 131 - .../apache/poi/hssf/usermodel/TestBug42464.java | 92 - .../org/apache/poi/hssf/usermodel/TestBugs.java | 2607 ------------------ .../apache/poi/hssf/usermodel/TestCellStyle.java | 504 ---- .../apache/poi/hssf/usermodel/TestCloneSheet.java | 135 - .../apache/poi/hssf/usermodel/TestCryptoAPI.java | 62 - .../poi/hssf/usermodel/TestDataValidation.java | 434 --- .../poi/hssf/usermodel/TestEmbeddedObjects.java | 71 - .../poi/hssf/usermodel/TestEscherGraphics.java | 307 --- .../poi/hssf/usermodel/TestEscherGraphics2d.java | 143 - .../usermodel/TestExternalReferenceChange.java | 67 - .../apache/poi/hssf/usermodel/TestFontDetails.java | 59 - .../hssf/usermodel/TestFormulaEvaluatorBugs.java | 578 ---- .../hssf/usermodel/TestFormulaEvaluatorDocs.java | 128 - .../apache/poi/hssf/usermodel/TestFormulas.java | 950 ------- .../apache/poi/hssf/usermodel/TestHSSFCell.java | 418 --- .../apache/poi/hssf/usermodel/TestHSSFChart.java | 267 -- .../poi/hssf/usermodel/TestHSSFClientAnchor.java | 162 -- .../poi/hssf/usermodel/TestHSSFColumnShifting.java | 34 - .../apache/poi/hssf/usermodel/TestHSSFComment.java | 452 ---- .../usermodel/TestHSSFConditionalFormatting.java | 127 - .../poi/hssf/usermodel/TestHSSFDataFormat.java | 66 - .../poi/hssf/usermodel/TestHSSFDataFormatter.java | 459 ---- .../poi/hssf/usermodel/TestHSSFDateUtil.java | 118 - .../hssf/usermodel/TestHSSFEvaluationSheet.java | 48 - .../hssf/usermodel/TestHSSFExternalFunctions.java | 30 - .../apache/poi/hssf/usermodel/TestHSSFFont.java | 40 - .../hssf/usermodel/TestHSSFFormulaEvaluator.java | 289 -- .../poi/hssf/usermodel/TestHSSFHeaderFooter.java | 195 -- .../poi/hssf/usermodel/TestHSSFHyperlink.java | 287 -- .../apache/poi/hssf/usermodel/TestHSSFName.java | 270 -- .../poi/hssf/usermodel/TestHSSFOptimiser.java | 706 ----- .../apache/poi/hssf/usermodel/TestHSSFPalette.java | 305 --- .../poi/hssf/usermodel/TestHSSFPatriarch.java | 64 - .../apache/poi/hssf/usermodel/TestHSSFPicture.java | 287 -- .../poi/hssf/usermodel/TestHSSFPictureData.java | 129 - .../poi/hssf/usermodel/TestHSSFRangeCopier.java | 42 - .../poi/hssf/usermodel/TestHSSFRichTextString.java | 130 - .../org/apache/poi/hssf/usermodel/TestHSSFRow.java | 146 - .../apache/poi/hssf/usermodel/TestHSSFSheet.java | 1115 -------- .../usermodel/TestHSSFSheetAutosizeColumn.java | 32 - .../hssf/usermodel/TestHSSFSheetShiftColumns.java | 84 - .../poi/hssf/usermodel/TestHSSFSheetShiftRows.java | 31 - .../TestHSSFSheetUpdateArrayFormulas.java | 118 - .../apache/poi/hssf/usermodel/TestHSSFTextbox.java | 71 - .../poi/hssf/usermodel/TestHSSFWorkbook.java | 1189 --------- .../TestMatrixFormulasFromBinarySpreadsheet.java | 223 -- .../TestNonStandardWorkbookStreamNames.java | 134 - .../poi/hssf/usermodel/TestOLE2Embeding.java | 156 -- .../poi/hssf/usermodel/TestPOIFSProperties.java | 115 - .../apache/poi/hssf/usermodel/TestPatriarch.java | 60 - .../org/apache/poi/hssf/usermodel/TestPolygon.java | 283 -- .../poi/hssf/usermodel/TestReadWriteChart.java | 67 - .../apache/poi/hssf/usermodel/TestRowStyle.java | 174 -- .../poi/hssf/usermodel/TestSanityChecker.java | 128 - .../apache/poi/hssf/usermodel/TestShapeGroup.java | 287 -- .../apache/poi/hssf/usermodel/TestSheetHiding.java | 65 - .../org/apache/poi/hssf/usermodel/TestText.java | 214 -- .../apache/poi/hssf/usermodel/TestUnfixedBugs.java | 139 - .../poi/hssf/usermodel/TestUnicodeWorkbook.java | 60 - .../apache/poi/hssf/usermodel/TestWorkbook.java | 632 ----- .../apache/poi/hssf/util/TestAreaReference.java | 309 --- .../apache/poi/hssf/util/TestCellReference.java | 165 -- .../org/apache/poi/hssf/util/TestHSSFColor.java | 59 - .../org/apache/poi/hssf/util/TestRKUtil.java | 50 - .../poi/poifs/crypt/TestBiff8DecryptingStream.java | 211 -- .../poi/poifs/crypt/TestCipherAlgorithm.java | 45 - .../apache/poi/poifs/crypt/TestXorEncryption.java | 93 - .../poi/poifs/crypt/binaryrc4/TestBinaryRC4.java | 100 - .../org/apache/poi/poifs/dev/TestPOIFSDump.java | 192 -- .../apache/poi/poifs/eventfilesystem/Listener.java | 45 - .../eventfilesystem/TestPOIFSReaderRegistry.java | 156 -- .../apache/poi/poifs/filesystem/ReaderWriter.java | 170 -- .../poi/poifs/filesystem/SlowInputStream.java | 41 - .../poi/poifs/filesystem/TestDirectoryNode.java | 208 -- .../apache/poi/poifs/filesystem/TestDocument.java | 147 -- .../poifs/filesystem/TestDocumentDescriptor.java | 110 - .../poifs/filesystem/TestDocumentInputStream.java | 410 --- .../poifs/filesystem/TestDocumentOutputStream.java | 124 - .../poi/poifs/filesystem/TestEmptyDocument.java | 116 - .../poi/poifs/filesystem/TestEntryUtils.java | 211 -- .../apache/poi/poifs/filesystem/TestFileMagic.java | 183 -- .../poi/poifs/filesystem/TestFileSystemBugs.java | 179 -- .../filesystem/TestFilteringDirectoryNode.java | 164 -- .../poi/poifs/filesystem/TestNotOLE2Exception.java | 79 - .../poifs/filesystem/TestOfficeXMLException.java | 126 - .../poi/poifs/filesystem/TestOle10Native.java | 111 - .../poifs/filesystem/TestPOIFSDocumentPath.java | 189 -- .../poi/poifs/filesystem/TestPOIFSFileSystem.java | 350 --- .../poi/poifs/filesystem/TestPOIFSMiniStore.java | 473 ---- .../poi/poifs/filesystem/TestPOIFSStream.java | 2792 -------------------- .../poi/poifs/filesystem/TestPropertySorter.java | 137 - .../poi/poifs/macros/TestVBAMacroReader.java | 320 --- .../org/apache/poi/poifs/nio/TestDataSource.java | 249 -- .../apache/poi/poifs/property/LocalProperty.java | 60 - .../poi/poifs/property/TestDirectoryProperty.java | 273 -- .../poi/poifs/property/TestDocumentProperty.java | 160 -- .../poi/poifs/property/TestPropertyFactory.java | 164 -- .../poi/poifs/property/TestPropertyTable.java | 191 -- .../poi/poifs/property/TestRootProperty.java | 136 - .../apache/poi/poifs/storage/LocalProperty.java | 59 - .../org/apache/poi/poifs/storage/RawDataUtil.java | 73 - .../org/apache/poi/poifs/storage/TestBATBlock.java | 351 --- .../poi/poifs/storage/TestHeaderBlockReading.java | 73 - .../apache/poi/sl/draw/geom/TestFormulaParser.java | 66 - .../poi/sl/draw/geom/TestPresetGeometries.java | 72 - .../apache/poi/sl/usermodel/BaseTestSlideShow.java | 203 -- .../poi/sl/usermodel/BaseTestSlideShowFactory.java | 193 -- .../org/apache/poi/ss/ITestDataProvider.java | 88 - .../org/apache/poi/ss/TestSpreadsheetVersion.java | 52 - .../org/apache/poi/ss/format/TestCellFormat.java | 1029 -------- .../poi/ss/format/TestCellFormatCondition.java | 67 - .../apache/poi/ss/format/TestCellFormatResult.java | 35 - .../poi/ss/formula/BaseTestExternalFunctions.java | 161 -- .../poi/ss/formula/BaseTestMissingWorkbook.java | 146 - .../apache/poi/ss/formula/EvaluationListener.java | 67 - .../SheetRangeAndWorkbookIndexFormatterTest.java | 66 - .../apache/poi/ss/formula/TestCellCacheEntry.java | 43 - .../apache/poi/ss/formula/TestEvaluationCache.java | 712 ----- .../apache/poi/ss/formula/TestFormulaShifter.java | 455 ---- .../poi/ss/formula/TestFunctionRegistry.java | 169 -- .../apache/poi/ss/formula/TestPlainCellCache.java | 64 - .../poi/ss/formula/TestSheetNameFormatter.java | 193 -- .../poi/ss/formula/TestWorkbookEvaluator.java | 646 ----- .../ss/formula/WorkbookEvaluatorTestHelper.java | 37 - .../org/apache/poi/ss/formula/atp/TestIfError.java | 98 - .../org/apache/poi/ss/formula/atp/TestMRound.java | 74 - .../ss/formula/atp/TestNetworkdaysFunction.java | 134 - .../apache/poi/ss/formula/atp/TestPercentile.java | 109 - .../apache/poi/ss/formula/atp/TestRandBetween.java | 196 -- .../poi/ss/formula/atp/TestWorkdayCalculator.java | 154 -- .../poi/ss/formula/atp/TestWorkdayFunction.java | 215 -- .../poi/ss/formula/atp/TestYearFracCalculator.java | 66 - .../atp/TestYearFracCalculatorFromSpreadsheet.java | 115 - .../formula/constant/TestConstantValueParser.java | 78 - .../formula/eval/BaseTestCircularReferences.java | 189 -- .../apache/poi/ss/formula/eval/EvalInstances.java | 53 - .../apache/poi/ss/formula/eval/TestAreaEval.java | 63 - .../apache/poi/ss/formula/eval/TestDivideEval.java | 65 - .../apache/poi/ss/formula/eval/TestEqualEval.java | 160 -- .../poi/ss/formula/eval/TestExternalFunction.java | 83 - .../poi/ss/formula/eval/TestFormulaBugs.java | 261 -- .../formula/eval/TestFormulasFromSpreadsheet.java | 224 -- .../formula/eval/TestHSSFCircularReferences.java | 31 - .../poi/ss/formula/eval/TestMinusZeroResult.java | 150 -- .../poi/ss/formula/eval/TestMissingArgEval.java | 134 - .../poi/ss/formula/eval/TestMultiSheetEval.java | 188 -- .../poi/ss/formula/eval/TestOperandResolver.java | 101 - .../poi/ss/formula/eval/TestPercentEval.java | 82 - .../apache/poi/ss/formula/eval/TestPowerEval.java | 102 - .../apache/poi/ss/formula/eval/TestRangeEval.java | 169 -- .../poi/ss/formula/eval/TestUnaryPlusEval.java | 58 - .../eval/forked/BaseTestForkedEvaluator.java | 117 - .../function/ExcelCetabFunctionExtractor.java | 378 --- .../ExcelFileFormatDocFunctionExtractor.java | 623 ----- .../function/TestFunctionMetadataRegistry.java | 43 - .../function/TestParseMissingBuiltInFuncs.java | 104 - .../function/TestReadMissingBuiltInFuncs.java | 155 -- .../BaseTestFunctionsFromSpreadsheet.java | 244 -- .../poi/ss/formula/functions/BaseTestNumeric.java | 66 - .../poi/ss/formula/functions/EvalFactory.java | 186 -- .../formula/functions/NumericFunctionInvoker.java | 102 - .../formula/functions/RefEvalImplementation.java | 68 - .../poi/ss/formula/functions/TestAddress.java | 81 - .../apache/poi/ss/formula/functions/TestAreas.java | 60 - .../poi/ss/formula/functions/TestAverage.java | 101 - .../poi/ss/formula/functions/TestBin2Dec.java | 111 - .../TestBooleanFunctionsFromSpreadsheet.java | 31 - .../functions/TestCalendarFieldFunction.java | 115 - .../apache/poi/ss/formula/functions/TestClean.java | 68 - .../apache/poi/ss/formula/functions/TestCode.java | 61 - .../TestCodeFunctionsFromSpreadsheet.java | 31 - .../poi/ss/formula/functions/TestComplex.java | 72 - .../TestComplexFunctionsFromSpreadsheet.java | 31 - .../poi/ss/formula/functions/TestCountFuncs.java | 584 ---- .../TestDGetFunctionsFromSpreadsheet.java | 30 - .../TestDStarFunctionsFromSpreadsheet.java | 30 - .../apache/poi/ss/formula/functions/TestDate.java | 94 - .../TestDateTimeToNumberFromSpreadsheet.java | 28 - .../poi/ss/formula/functions/TestDateValue.java | 113 - .../poi/ss/formula/functions/TestDays360.java | 165 -- .../poi/ss/formula/functions/TestDec2Bin.java | 245 -- .../poi/ss/formula/functions/TestDec2Hex.java | 245 -- .../apache/poi/ss/formula/functions/TestDelta.java | 67 - .../TestDeltaFunctionsFromSpreadsheet.java | 30 - .../apache/poi/ss/formula/functions/TestEDate.java | 127 - .../poi/ss/formula/functions/TestEOMonth.java | 152 -- .../TestFactDoubleFunctionsFromSpreadsheet.java | 31 - .../poi/ss/formula/functions/TestFinanceLib.java | 229 -- .../apache/poi/ss/formula/functions/TestFind.java | 81 - .../apache/poi/ss/formula/functions/TestFixed.java | 129 - .../TestFixedFunctionsFromSpreadsheet.java | 31 - .../poi/ss/formula/functions/TestFrequency.java | 96 - .../poi/ss/formula/functions/TestGeomean.java | 134 - .../poi/ss/formula/functions/TestHex2Dec.java | 109 - .../functions/TestIFFunctionFromSpreadsheet.java | 31 - .../apache/poi/ss/formula/functions/TestIPMT.java | 57 - .../TestImRealFunctionsFromSpreadsheet.java | 31 - .../TestImaginaryFunctionsFromSpreadsheet.java | 31 - .../apache/poi/ss/formula/functions/TestIndex.java | 320 --- .../TestIndexFunctionFromSpreadsheet.java | 31 - .../poi/ss/formula/functions/TestIndirect.java | 203 -- .../TestIndirectFunctionFromSpreadsheet.java | 35 - .../poi/ss/formula/functions/TestIntercept.java | 165 -- .../apache/poi/ss/formula/functions/TestIrr.java | 128 - .../poi/ss/formula/functions/TestIsBlank.java | 63 - .../poi/ss/formula/functions/TestLeftRight.java | 62 - .../apache/poi/ss/formula/functions/TestLen.java | 76 - .../ss/formula/functions/TestLogicalFunction.java | 109 - .../TestLogicalFunctionsFromSpreadsheet.java | 31 - .../TestLookupFunctionsFromSpreadsheet.java | 37 - .../apache/poi/ss/formula/functions/TestMatch.java | 288 -- .../TestMatchFunctionsFromSpreadsheet.java | 35 - .../apache/poi/ss/formula/functions/TestMathX.java | 1035 -------- .../apache/poi/ss/formula/functions/TestMid.java | 116 - .../apache/poi/ss/formula/functions/TestMirr.java | 149 -- .../functions/TestMultiOperandNumericFunction.java | 72 - .../apache/poi/ss/formula/functions/TestNper.java | 70 - .../apache/poi/ss/formula/functions/TestNpv.java | 102 - .../poi/ss/formula/functions/TestOct2Dec.java | 67 - .../poi/ss/formula/functions/TestOffset.java | 107 - .../apache/poi/ss/formula/functions/TestPPMT.java | 57 - .../apache/poi/ss/formula/functions/TestPmt.java | 81 - .../poi/ss/formula/functions/TestPoisson.java | 116 - .../poi/ss/formula/functions/TestProduct.java | 71 - .../poi/ss/formula/functions/TestQuotient.java | 68 - .../TestQuotientFunctionsFromSpreadsheet.java | 31 - .../apache/poi/ss/formula/functions/TestRank.java | 71 - .../functions/TestRelationalOperations.java | 196 -- .../TestReptFunctionsFromSpreadsheet.java | 31 - .../TestRomanFunctionsFromSpreadsheet.java | 31 - .../poi/ss/formula/functions/TestRoundFuncs.java | 88 - .../poi/ss/formula/functions/TestRowCol.java | 102 - .../apache/poi/ss/formula/functions/TestSlope.java | 142 - .../poi/ss/formula/functions/TestStatsLib.java | 328 --- .../poi/ss/formula/functions/TestSubstitute.java | 89 - .../poi/ss/formula/functions/TestSubtotal.java | 430 --- .../apache/poi/ss/formula/functions/TestSumif.java | 119 - .../poi/ss/formula/functions/TestSumifs.java | 361 --- .../poi/ss/formula/functions/TestSumproduct.java | 123 - .../apache/poi/ss/formula/functions/TestTFunc.java | 140 - .../apache/poi/ss/formula/functions/TestText.java | 139 - .../apache/poi/ss/formula/functions/TestTime.java | 124 - .../TestTrendFunctionsFromSpreadsheet.java | 30 - .../apache/poi/ss/formula/functions/TestTrim.java | 83 - .../apache/poi/ss/formula/functions/TestTrunc.java | 90 - ...tTwoOperandNumericFunctionsFromSpreadsheet.java | 32 - .../apache/poi/ss/formula/functions/TestValue.java | 97 - .../TestWeekNumFunctionsFromSpreadsheet.java | 31 - .../TestWeekNumFunctionsFromSpreadsheet2013.java | 32 - .../poi/ss/formula/functions/TestWeekdayFunc.java | 93 - .../formula/functions/TestXYNumericFunction.java | 140 - .../org/apache/poi/ss/formula/ptg/BaseTestPtg.java | 47 - .../ss/formula/ptg/TestAbstractFunctionPtg.java | 72 - .../apache/poi/ss/formula/ptg/TestArea3DPtg.java | 53 - .../apache/poi/ss/formula/ptg/TestAreaErrPtg.java | 41 - .../org/apache/poi/ss/formula/ptg/TestAreaPtg.java | 145 - .../apache/poi/ss/formula/ptg/TestArrayPtg.java | 152 -- .../org/apache/poi/ss/formula/ptg/TestAttrPtg.java | 45 - .../org/apache/poi/ss/formula/ptg/TestErrPtg.java | 43 - .../formula/ptg/TestExternalFunctionFormulas.java | 94 - .../ss/formula/ptg/TestExternalNameReference.java | 129 - .../org/apache/poi/ss/formula/ptg/TestFuncPtg.java | 48 - .../apache/poi/ss/formula/ptg/TestFuncVarPtg.java | 58 - .../poi/ss/formula/ptg/TestIntersectionPtg.java | 43 - .../apache/poi/ss/formula/ptg/TestPercentPtg.java | 48 - .../apache/poi/ss/formula/ptg/TestRangePtg.java | 43 - .../apache/poi/ss/formula/ptg/TestRef3DPtg.java | 48 - .../poi/ss/formula/ptg/TestReferencePtg.java | 109 - .../apache/poi/ss/formula/ptg/TestUnionPtg.java | 43 - .../apache/poi/ss/formula/udf/TestUDFFinder.java | 58 - .../poi/ss/usermodel/BaseTestBorderStyle.java | 82 - .../poi/ss/usermodel/BaseTestBugzillaIssues.java | 1849 ------------- .../org/apache/poi/ss/usermodel/BaseTestCell.java | 1417 ---------- .../poi/ss/usermodel/BaseTestCellComment.java | 421 --- .../poi/ss/usermodel/BaseTestCloneSheet.java | 91 - .../poi/ss/usermodel/BaseTestColumnShifting.java | 81 - .../usermodel/BaseTestConditionalFormatting.java | 1385 ---------- .../poi/ss/usermodel/BaseTestDataFormat.java | 262 -- .../poi/ss/usermodel/BaseTestDataValidation.java | 492 ---- .../org/apache/poi/ss/usermodel/BaseTestFont.java | 226 -- .../poi/ss/usermodel/BaseTestFormulaEvaluator.java | 738 ------ .../apache/poi/ss/usermodel/BaseTestHyperlink.java | 148 -- .../poi/ss/usermodel/BaseTestNamedRange.java | 697 ----- .../apache/poi/ss/usermodel/BaseTestPicture.java | 279 -- .../poi/ss/usermodel/BaseTestRangeCopier.java | 174 -- .../org/apache/poi/ss/usermodel/BaseTestRow.java | 537 ---- .../org/apache/poi/ss/usermodel/BaseTestSheet.java | 1367 ---------- .../ss/usermodel/BaseTestSheetAutosizeColumn.java | 380 --- .../poi/ss/usermodel/BaseTestSheetHiding.java | 167 -- .../ss/usermodel/BaseTestSheetShiftColumns.java | 401 --- .../poi/ss/usermodel/BaseTestSheetShiftRows.java | 819 ------ .../BaseTestSheetUpdateArrayFormulas.java | 543 ---- .../apache/poi/ss/usermodel/BaseTestWorkbook.java | 909 ------- .../poi/ss/usermodel/BaseTestXEvaluationSheet.java | 49 - .../apache/poi/ss/usermodel/TestDataFormatter.java | 1060 -------- .../org/apache/poi/ss/usermodel/TestDateUtil.java | 716 ----- .../ss/usermodel/TestExcelStyleDateFormatter.java | 143 - .../poi/ss/usermodel/TestFractionFormat.java | 118 - .../poi/ss/usermodel/TestHSSFBorderStyle.java | 30 - .../apache/poi/ss/usermodel/TestIndexedColors.java | 50 - .../org/apache/poi/ss/util/BaseTestCellUtil.java | 381 --- .../util/NumberComparingSpreadsheetGenerator.java | 146 - .../poi/ss/util/NumberComparisonExamples.java | 165 -- .../util/NumberRenderingSpreadsheetGenerator.java | 248 -- .../ss/util/NumberToTextConversionExamples.java | 278 -- .../org/apache/poi/ss/util/TestAreaReference.java | 88 - .../org/apache/poi/ss/util/TestCellAddress.java | 108 - .../apache/poi/ss/util/TestCellRangeAddress.java | 292 -- .../org/apache/poi/ss/util/TestCellRangeUtil.java | 95 - .../org/apache/poi/ss/util/TestCellReference.java | 476 ---- .../poi/ss/util/TestDateFormatConverter.java | 183 -- .../org/apache/poi/ss/util/TestDateParser.java | 66 - .../org/apache/poi/ss/util/TestExpandedDouble.java | 128 - .../org/apache/poi/ss/util/TestHSSFCellUtil.java | 26 - .../org/apache/poi/ss/util/TestNumberComparer.java | 99 - .../poi/ss/util/TestNumberToTextConverter.java | 95 - .../apache/poi/ss/util/TestPropertyTemplate.java | 949 ------- .../org/apache/poi/ss/util/TestRegionUtil.java | 163 -- .../org/apache/poi/ss/util/TestSheetBuilder.java | 95 - .../org/apache/poi/ss/util/TestSheetUtil.java | 167 -- .../org/apache/poi/ss/util/TestWorkbookUtil.java | 90 - .../apache/poi/ss/util/cellwalk/TestCellWalk.java | 56 - .../org/apache/poi/util/MemoryLeakVerifier.java | 105 - .../org/apache/poi/util/NullOutputStream.java | 41 - .../org/apache/poi/util/NullPrintStream.java | 88 - .../org/apache/poi/util/TestArrayUtil.java | 93 - .../org/apache/poi/util/TestBitField.java | 217 -- .../org/apache/poi/util/TestByteField.java | 138 - src/testcases/org/apache/poi/util/TestHexDump.java | 196 -- src/testcases/org/apache/poi/util/TestIOUtils.java | 579 ---- src/testcases/org/apache/poi/util/TestIntList.java | 515 ---- .../org/apache/poi/util/TestIntegerField.java | 135 - .../org/apache/poi/util/TestLittleEndian.java | 356 --- .../apache/poi/util/TestLittleEndianStreams.java | 118 - .../org/apache/poi/util/TestLocaleUtil.java | 127 - .../org/apache/poi/util/TestLongField.java | 167 -- .../poi/util/TestRLEDecompressingInputStream.java | 172 -- .../org/apache/poi/util/TestShortField.java | 129 - .../poi/util/TestStringCodepointsIterable.java | 46 - .../org/apache/poi/util/TestStringUtil.java | 157 -- .../org/apache/poi/util/TestTempFile.java | 142 - .../org/apache/poi/util/TestXMLHelper.java | 161 -- .../org/apache/poi/util/data/test_properties1 | 26 - .../org/apache/poi/util/data/test_properties2 | 26 - .../org/apache/poi/util/data/test_properties3 | 26 - 521 files changed, 99773 deletions(-) delete mode 100644 src/testcases/org/apache/poi/POIDataSamples.java delete mode 100644 src/testcases/org/apache/poi/POITestCase.java delete mode 100644 src/testcases/org/apache/poi/TestJDK12.java delete mode 100644 src/testcases/org/apache/poi/TestPOIDocumentMain.java delete mode 100644 src/testcases/org/apache/poi/TestPOITestCase.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherBSERecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherBlipRecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherBoolProperty.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherChildAnchorRecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherClientAnchorRecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherClientDataRecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherContainerRecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherDgRecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherDggRecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherDump.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherOptRecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherProperty.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherPropertyFactory.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherSpRecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherSpgrRecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestEscherSplitMenuColorsRecord.java delete mode 100644 src/testcases/org/apache/poi/ddf/TestUnknownEscherRecord.java delete mode 100644 src/testcases/org/apache/poi/hpsf/TestVariantSupport.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/POIFile.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/TestBasic.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/TestClassID.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/TestHPSFBugs.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/TestWrite.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/Util.java delete mode 100644 src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java delete mode 100644 src/testcases/org/apache/poi/hssf/HSSFITestDataProvider.java delete mode 100644 src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java delete mode 100644 src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java delete mode 100644 src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java delete mode 100644 src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java delete mode 100644 src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java delete mode 100644 src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java delete mode 100644 src/testcases/org/apache/poi/hssf/dev/TestReSave.java delete mode 100644 src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java delete mode 100644 src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java delete mode 100644 src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java delete mode 100644 src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java delete mode 100644 src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java delete mode 100644 src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java delete mode 100644 src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java delete mode 100644 src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java delete mode 100644 src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestHSSFAnchor.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestLinkTable.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestOperandClassTransformer.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestRVA.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestSheet.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestWorkbook.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/TestWorkbookRecordList.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestFontRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestNameRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestObjRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestPaneRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestStringRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestSubRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestTableRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/FormulaExtractor.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/HSSFEvaluationTestHelper.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/HSSFTestHelper.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/StreamUtility.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFColumnShifting.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFEvaluationSheet.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFExternalFunctions.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRangeCopier.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetAutosizeColumn.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftColumns.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftRows.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFTextbox.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestMatrixFormulasFromBinarySpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestText.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java delete mode 100644 src/testcases/org/apache/poi/hssf/util/TestAreaReference.java delete mode 100644 src/testcases/org/apache/poi/hssf/util/TestCellReference.java delete mode 100644 src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java delete mode 100644 src/testcases/org/apache/poi/hssf/util/TestRKUtil.java delete mode 100644 src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java delete mode 100644 src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java delete mode 100644 src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java delete mode 100644 src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java delete mode 100644 src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java delete mode 100644 src/testcases/org/apache/poi/poifs/eventfilesystem/Listener.java delete mode 100644 src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/SlowInputStream.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestNotOLE2Exception.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSMiniStore.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java delete mode 100644 src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java delete mode 100644 src/testcases/org/apache/poi/poifs/nio/TestDataSource.java delete mode 100644 src/testcases/org/apache/poi/poifs/property/LocalProperty.java delete mode 100644 src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java delete mode 100644 src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java delete mode 100644 src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java delete mode 100644 src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java delete mode 100644 src/testcases/org/apache/poi/poifs/property/TestRootProperty.java delete mode 100644 src/testcases/org/apache/poi/poifs/storage/LocalProperty.java delete mode 100644 src/testcases/org/apache/poi/poifs/storage/RawDataUtil.java delete mode 100644 src/testcases/org/apache/poi/poifs/storage/TestBATBlock.java delete mode 100644 src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockReading.java delete mode 100644 src/testcases/org/apache/poi/sl/draw/geom/TestFormulaParser.java delete mode 100644 src/testcases/org/apache/poi/sl/draw/geom/TestPresetGeometries.java delete mode 100644 src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShow.java delete mode 100644 src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java delete mode 100644 src/testcases/org/apache/poi/ss/ITestDataProvider.java delete mode 100644 src/testcases/org/apache/poi/ss/TestSpreadsheetVersion.java delete mode 100644 src/testcases/org/apache/poi/ss/format/TestCellFormat.java delete mode 100644 src/testcases/org/apache/poi/ss/format/TestCellFormatCondition.java delete mode 100644 src/testcases/org/apache/poi/ss/format/TestCellFormatResult.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/BaseTestExternalFunctions.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/BaseTestMissingWorkbook.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/EvaluationListener.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/SheetRangeAndWorkbookIndexFormatterTest.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/TestCellCacheEntry.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/TestEvaluationCache.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/TestFormulaShifter.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/TestPlainCellCache.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/TestSheetNameFormatter.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/WorkbookEvaluatorTestHelper.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/atp/TestIfError.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/atp/TestMRound.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/EvalInstances.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestFormulaBugs.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestHSSFCircularReferences.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/forked/BaseTestForkedEvaluator.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/function/ExcelCetabFunctionExtractor.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/BaseTestFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/BaseTestNumeric.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/EvalFactory.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/RefEvalImplementation.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestAddress.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestAreas.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestAverage.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestBin2Dec.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestBooleanFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestClean.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestCode.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestCodeFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestComplex.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestComplexFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestCountFuncs.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestDGetFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestDStarFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestDate.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestDateTimeToNumberFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestDateValue.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestDec2Bin.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestDelta.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestDeltaFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestFactDoubleFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestFinanceLib.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestFind.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestFixedFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestFrequency.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestGeomean.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestHex2Dec.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestIFFunctionFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestIPMT.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestImRealFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestImaginaryFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestIndex.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestIndexFunctionFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestIndirect.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestIndirectFunctionFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestIntercept.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestIrr.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestIsBlank.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestLeftRight.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestLen.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunction.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestLookupFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestMatch.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestMatchFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestMathX.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestMid.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestMirr.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestMultiOperandNumericFunction.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestNper.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestNpv.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestOct2Dec.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestOffset.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestPPMT.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestPmt.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestPoisson.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestProduct.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestQuotient.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestQuotientFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestRank.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestRelationalOperations.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestReptFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestRomanFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestRoundFuncs.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestRowCol.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestSlope.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestSubstitute.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestSubtotal.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestSumif.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestSumifs.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestSumproduct.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestTFunc.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestText.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestTime.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestTrendFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestTrim.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestTrunc.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestTwoOperandNumericFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestValue.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet2013.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestWeekdayFunc.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/TestXYNumericFunction.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/BaseTestPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestAbstractFunctionPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestArea3DPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestAreaErrPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestAreaPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestAttrPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestErrPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestExternalFunctionFormulas.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestExternalNameReference.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestFuncPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestFuncVarPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestIntersectionPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestPercentPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestRangePtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestRef3DPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestReferencePtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/udf/TestUDFFinder.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestBorderStyle.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestCellComment.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestCloneSheet.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestColumnShifting.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestConditionalFormatting.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestDataValidation.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestHyperlink.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestNamedRange.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestRangeCopier.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetHiding.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftColumns.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetUpdateArrayFormulas.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/BaseTestXEvaluationSheet.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/TestExcelStyleDateFormatter.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/TestFractionFormat.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/TestHSSFBorderStyle.java delete mode 100644 src/testcases/org/apache/poi/ss/usermodel/TestIndexedColors.java delete mode 100644 src/testcases/org/apache/poi/ss/util/BaseTestCellUtil.java delete mode 100644 src/testcases/org/apache/poi/ss/util/NumberComparingSpreadsheetGenerator.java delete mode 100644 src/testcases/org/apache/poi/ss/util/NumberComparisonExamples.java delete mode 100644 src/testcases/org/apache/poi/ss/util/NumberRenderingSpreadsheetGenerator.java delete mode 100644 src/testcases/org/apache/poi/ss/util/NumberToTextConversionExamples.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestAreaReference.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestCellAddress.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestCellRangeAddress.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestCellRangeUtil.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestCellReference.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestDateParser.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestExpandedDouble.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestHSSFCellUtil.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestNumberComparer.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestNumberToTextConverter.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestPropertyTemplate.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestRegionUtil.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestSheetBuilder.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestSheetUtil.java delete mode 100644 src/testcases/org/apache/poi/ss/util/TestWorkbookUtil.java delete mode 100644 src/testcases/org/apache/poi/ss/util/cellwalk/TestCellWalk.java delete mode 100644 src/testcases/org/apache/poi/util/MemoryLeakVerifier.java delete mode 100644 src/testcases/org/apache/poi/util/NullOutputStream.java delete mode 100644 src/testcases/org/apache/poi/util/NullPrintStream.java delete mode 100644 src/testcases/org/apache/poi/util/TestArrayUtil.java delete mode 100644 src/testcases/org/apache/poi/util/TestBitField.java delete mode 100644 src/testcases/org/apache/poi/util/TestByteField.java delete mode 100644 src/testcases/org/apache/poi/util/TestHexDump.java delete mode 100644 src/testcases/org/apache/poi/util/TestIOUtils.java delete mode 100644 src/testcases/org/apache/poi/util/TestIntList.java delete mode 100644 src/testcases/org/apache/poi/util/TestIntegerField.java delete mode 100644 src/testcases/org/apache/poi/util/TestLittleEndian.java delete mode 100644 src/testcases/org/apache/poi/util/TestLittleEndianStreams.java delete mode 100644 src/testcases/org/apache/poi/util/TestLocaleUtil.java delete mode 100644 src/testcases/org/apache/poi/util/TestLongField.java delete mode 100644 src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java delete mode 100644 src/testcases/org/apache/poi/util/TestShortField.java delete mode 100644 src/testcases/org/apache/poi/util/TestStringCodepointsIterable.java delete mode 100644 src/testcases/org/apache/poi/util/TestStringUtil.java delete mode 100644 src/testcases/org/apache/poi/util/TestTempFile.java delete mode 100644 src/testcases/org/apache/poi/util/TestXMLHelper.java delete mode 100644 src/testcases/org/apache/poi/util/data/test_properties1 delete mode 100644 src/testcases/org/apache/poi/util/data/test_properties2 delete mode 100644 src/testcases/org/apache/poi/util/data/test_properties3 (limited to 'src/testcases/org/apache') diff --git a/src/testcases/org/apache/poi/POIDataSamples.java b/src/testcases/org/apache/poi/POIDataSamples.java deleted file mode 100644 index ddf66e25bf..0000000000 --- a/src/testcases/org/apache/poi/POIDataSamples.java +++ /dev/null @@ -1,281 +0,0 @@ -/* ==================================================================== - 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; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -/** - * Centralises logic for finding/opening sample files - */ -public final class POIDataSamples { - - /** - * Name of the system property that defined path to the test data. - */ - public static final String TEST_PROPERTY = "POI.testdata.path"; - - private static POIDataSamples _instSlideshow; - private static POIDataSamples _instSpreadsheet; - private static POIDataSamples _instDocument; - private static POIDataSamples _instDiagram; - private static POIDataSamples _instOpenxml4j; - private static POIDataSamples _instPOIFS; - private static POIDataSamples _instDDF; - private static POIDataSamples _instHMEF; - private static POIDataSamples _instHPSF; - private static POIDataSamples _instHPBF; - private static POIDataSamples _instHSMF; - private static POIDataSamples _instXmlDSign; - - private File _resolvedDataDir; - /** true if standard system propery is not set, - * but the data is available on the test runtime classpath */ - private boolean _sampleDataIsAvaliableOnClassPath; - private final String _moduleDir; - - /** - * - * @param moduleDir the name of the directory containing the test files - */ - private POIDataSamples(String moduleDir){ - _moduleDir = moduleDir; - initialise(); - } - - public static POIDataSamples getSpreadSheetInstance(){ - if(_instSpreadsheet == null) _instSpreadsheet = new POIDataSamples("spreadsheet"); - return _instSpreadsheet; - } - - public static POIDataSamples getDocumentInstance(){ - if(_instDocument == null) _instDocument = new POIDataSamples("document"); - return _instDocument; - } - - public static POIDataSamples getSlideShowInstance(){ - if(_instSlideshow == null) _instSlideshow = new POIDataSamples("slideshow"); - return _instSlideshow; - } - - public static POIDataSamples getDiagramInstance(){ - if(_instOpenxml4j == null) _instOpenxml4j = new POIDataSamples("diagram"); - return _instOpenxml4j; - } - - public static POIDataSamples getOpenXML4JInstance(){ - if(_instDiagram == null) _instDiagram = new POIDataSamples("openxml4j"); - return _instDiagram; - } - - public static POIDataSamples getPOIFSInstance(){ - if(_instPOIFS == null) _instPOIFS = new POIDataSamples("poifs"); - return _instPOIFS; - } - - public static POIDataSamples getDDFInstance(){ - if(_instDDF == null) _instDDF = new POIDataSamples("ddf"); - return _instDDF; - } - - public static POIDataSamples getHPSFInstance(){ - if(_instHPSF == null) _instHPSF = new POIDataSamples("hpsf"); - return _instHPSF; - } - - public static POIDataSamples getPublisherInstance(){ - if(_instHPBF == null) _instHPBF = new POIDataSamples("publisher"); - return _instHPBF; - } - - public static POIDataSamples getHMEFInstance(){ - if(_instHMEF == null) _instHMEF = new POIDataSamples("hmef"); - return _instHMEF; - } - - public static POIDataSamples getHSMFInstance(){ - if(_instHSMF == null) _instHSMF = new POIDataSamples("hsmf"); - return _instHSMF; - } - - public static POIDataSamples getXmlDSignInstance() { - if(_instXmlDSign == null) _instXmlDSign = new POIDataSamples("xmldsign"); - return _instXmlDSign; - } - - /** - * Opens a sample file from the test data directory - * - * @param sampleFileName the file to open - * @return an open InputStream for the specified sample file - */ - public InputStream openResourceAsStream(String sampleFileName) { - - if (_sampleDataIsAvaliableOnClassPath) { - InputStream result = sampleFileName == null ? null : - openClasspathResource(sampleFileName); - if(result == null) { - throw new RuntimeException("specified test sample file '" + sampleFileName - + "' not found on the classpath"); - } - // 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_PROPERTY - + "' properly before running tests"); - } - - File f = getFile(sampleFileName); - try { - return new FileInputStream(f); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - } - - /** - * - * @param sampleFileName the name of the test file - * @return Verifies that the file with the given name exists in the test-data directory - * @throws RuntimeException if the file was not found - */ - public File getFile(String sampleFileName) { - File f = new File(_resolvedDataDir, sampleFileName); - if (!f.exists()) { - throw new RuntimeException("Sample file '" + sampleFileName - + "' not found in data dir '" + _resolvedDataDir.getAbsolutePath() + "'"); - } - try { - if(sampleFileName.length() > 0) { - String fn = sampleFileName; - if(fn.indexOf('/') > 0) { - fn = fn.substring(fn.indexOf('/')+1); - } - if(!fn.equals(f.getCanonicalFile().getName())){ - throw new RuntimeException("File name is case-sensitive: requested '" + fn - + "' but actual file is '" + f.getCanonicalFile().getName() + "'"); - } - } - } catch (IOException e){ - throw new RuntimeException(e); - } - return f; - } - - private void initialise() { - String dataDirName = System.getProperty(TEST_PROPERTY); - if (dataDirName == null) { - // check to see if we can just get the resources from the classpath - InputStream is = openClasspathResource(""); - if (is != null) { - try { - is.close(); // be nice - } catch (IOException e) { - throw new RuntimeException(e); - } - _sampleDataIsAvaliableOnClassPath = true; - return; - } - - if(new File("test-data").exists()) { - dataDirName = "test-data"; - } else { - throw new RuntimeException("Must set system property '" + - TEST_PROPERTY + "' before running tests"); - } - } - File dataDir = new File(dataDirName, _moduleDir); - if (!dataDir.exists()) { - throw new RuntimeException("Data dir '" + dataDir + "' 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. - * - * @param sampleFileName the file to open - * @return null if the sample file is not deployed on the classpath. - */ - private InputStream openClasspathResource(String sampleFileName) { - return getClass().getResourceAsStream("/" + _moduleDir + "/" + sampleFileName); - } - - private static final class NonSeekableInputStream extends InputStream { - - private final InputStream _is; - - public NonSeekableInputStream(InputStream is) { - _is = is; - } - - @Override - public int read() throws IOException { - return _is.read(); - } - @Override - public int read(byte[] b, int off, int len) throws IOException { - return _is.read(b, off, len); - } - @Override - public boolean markSupported() { - return false; - } - @Override - public void close() throws IOException { - _is.close(); - } - } - - /** - * @param fileName the file to open - * @return byte array of sample file content from file found in standard test-data directory - */ - public byte[] readFile(String fileName) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - try { - InputStream fis = openResourceAsStream(fileName); - - byte[] buf = new byte[512]; - while (true) { - int bytesRead = fis.read(buf); - if (bytesRead < 1) { - break; - } - bos.write(buf, 0, bytesRead); - } - fis.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - return bos.toByteArray(); - } - -} diff --git a/src/testcases/org/apache/poi/POITestCase.java b/src/testcases/org/apache/poi/POITestCase.java deleted file mode 100644 index dbaae88889..0000000000 --- a/src/testcases/org/apache/poi/POITestCase.java +++ /dev/null @@ -1,203 +0,0 @@ -/* ==================================================================== - 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; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.endsWith; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.lang.reflect.Field; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.SuppressForbidden; -import org.mockito.internal.matchers.apachecommons.ReflectionEquals; - -/** - * Util class for POI JUnit TestCases, which provide additional features - */ -@Internal -public final class POITestCase { - - private POITestCase() { - } - - public static void assertStartsWith(String string, String prefix) { - assertNotNull(string); - assertNotNull(prefix); - assertThat(string, startsWith(prefix)); - } - - public static void assertStartsWith(String message, String string, String prefix) { - assertNotNull(message, string); - assertNotNull(message, prefix); - assertThat(message, string, startsWith(prefix)); - } - - public static void assertEndsWith(String string, String suffix) { - assertNotNull(string); - assertNotNull(suffix); - assertThat(string, endsWith(suffix)); - } - - public static void assertContains(String haystack, String needle) { - assertNotNull(haystack); - assertNotNull(needle); - assertThat(haystack, containsString(needle)); - } - - public static void assertContains(String message, String haystack, String needle) { - assertNotNull(message, haystack); - assertNotNull(message, needle); - assertThat(message, haystack, containsString(needle)); - } - - public static void assertContainsIgnoreCase(String haystack, String needle, Locale locale) { - assertNotNull(haystack); - assertNotNull(needle); - String hay = haystack.toLowerCase(locale); - String n = needle.toLowerCase(locale); - assertTrue(hay.contains(n), "Unable to find expected text '" + needle + "' in text:\n" + haystack); - } - public static void assertContainsIgnoreCase(String haystack, String needle) { - assertContainsIgnoreCase(haystack, needle, Locale.ROOT); - } - - public static void assertNotContained(String haystack, String needle) { - assertNotNull(haystack); - assertNotNull(needle); - assertThat(haystack, not(containsString(needle))); - } - - /** - * @param map haystack - * @param key needle - */ - public static void assertContains(Map map, T key) { - assertTrue(map.containsKey(key), "Unable to find " + key + " in " + map); - } - - public static void assertNotContained(Set set, T element) { - assertThat("Set should not contain " + element, set, not(hasItem(element))); - } - - /** - * Utility method to get the value of a private/protected field. - * Only use this method in test cases!!! - */ - @SuppressWarnings({"unused", "unchecked"}) - @SuppressForbidden("For test usage only") - public static R getFieldValue(final Class clazz, final T instance, final Class fieldType, final String fieldName) { - assertTrue(clazz.getName().startsWith("org.apache.poi."), "Reflection of private fields is only allowed for POI classes."); - try { - return AccessController.doPrivileged((PrivilegedExceptionAction) () -> { - Field f = clazz.getDeclaredField(fieldName); - f.setAccessible(true); - return (R) f.get(instance); - }); - } catch (PrivilegedActionException pae) { - throw new RuntimeException("Cannot access field '" + fieldName + "' of class " + clazz, pae.getException()); - } - } - - /** - * Utility method to shallow compare all fields of the objects - * Only use this method in test cases!!! - */ - public static void assertReflectEquals(final Object expected, Object actual) { - // as long as ReflectionEquals is provided by Mockito, use it ... otherwise use commons.lang for the tests - - // JaCoCo Code Coverage adds its own field, don't look at this one here - assertTrue(new ReflectionEquals(expected, "$jacocoData").matches(actual)); - } - - /** - * Rather than adding {@literal @}Ignore to known-failing tests, - * write the test so that it notifies us if it starts passing. - * This is useful for closing related or forgotten bugs. - * - * An Example: - *
-     * public static int add(int a, int b) {
-     *     // a known bug in behavior that has not been fixed yet
-     *     raise UnsupportedOperationException("add");
-     * }
-     *
-     * {@literal @}Test
-     * void knownFailingUnitTest() {
-     *     try {
-     *         assertEquals(2, add(1,1));
-     *         // this test fails because the assumption that this bug had not been fixed is false
-     *         testPassesNow(12345);
-     *     } catch (UnsupportedOperationException e) {
-     *         // test is skipped because the assumption that this bug had not been fixed is true
-     *         skipTest(e);
-     *     }
-     * }
-     *
-     * Once passing, this unit test can be rewritten as:
-     * {@literal @}Test
-     * void knownPassingUnitTest() {
-     *     assertEquals(2, add(1,1));
-     * }
-     *
-     * If you have a better idea how to simplify test code while still notifying
-     * us when a previous known-failing test now passes, please improve these.
-     * As a bonus, a known-failing test that fails should not be counted as a
-     * passing test.
-     *
-     * One possible alternative is to expect the known exception, but without
-     * a clear message that it is a good thing to no longer get the expected
-     * exception once the test passes.
-     * {@literal @}Test(expected=UnsupportedOperationException.class)
-     * void knownFailingUnitTest() {
-     *     assertEquals(2, add(1,1));
-     * }
-     *
-     * @param e  the exception that was caught that will no longer
-     * be raised when the bug is fixed
-     */
-    public static void skipTest(Throwable e) {
-        assumeTrue(e != null, "This test currently fails with");
-    }
-    /**
-     * @see #skipTest(Throwable)
-     *
-     * @param bug  the bug number corresponding to a known bug in bugzilla
-     */
-    public static void testPassesNow(int bug) {
-        fail("This test passes now. Please update the unit test and bug " + bug + ".");
-    }
-
-    public static void assertBetween(String message, int value, int min, int max) {
-        assertTrue(min <= value, message + ": " + value + " is less than the minimum value of " + min);
-        assertTrue(value <= max, message + ": " + value + " is greater than the maximum value of " + max);
-    }
-}
diff --git a/src/testcases/org/apache/poi/TestJDK12.java b/src/testcases/org/apache/poi/TestJDK12.java
deleted file mode 100644
index 53e272233b..0000000000
--- a/src/testcases/org/apache/poi/TestJDK12.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/* ====================================================================
-   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;
-
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-
-import java.awt.Graphics2D;
-import java.awt.RenderingHints;
-import java.awt.font.TextLayout;
-import java.awt.image.BufferedImage;
-import java.text.AttributedString;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Minimal Test-Class found when running the Apache POI regression tests.
- *
- * This reproduces a crash introduced in JDK 12-ea+28 and JDK 13-ea+4
- *
- * This works in recent JDK 8, JDK 11 and at least up to JDK 12-ea+20
- *
- * https://bugs.openjdk.java.net/browse/JDK-8217768
- *
- * Should be fixed in JDK 12-ea+29 and JDK 13-ea+5
- */
-class TestJDK12 {
-    @Test
-    void test() {
-        assertDoesNotThrow(() -> {
-            BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
-            Graphics2D graphics = img.createGraphics();
-            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
-            graphics.scale(200, 1);
-
-            new TextLayout(new AttributedString("agriculture").getIterator(), graphics.getFontRenderContext());
-
-            graphics.dispose();
-            img.flush();
-        });
-    }
-
-}
diff --git a/src/testcases/org/apache/poi/TestPOIDocumentMain.java b/src/testcases/org/apache/poi/TestPOIDocumentMain.java
deleted file mode 100644
index c2c44529b8..0000000000
--- a/src/testcases/org/apache/poi/TestPOIDocumentMain.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/* ====================================================================
-   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;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
-import org.apache.poi.hpsf.DocumentSummaryInformation;
-import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument;
-import org.apache.poi.hpsf.SummaryInformation;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests that POIDocument correctly loads and saves the common
- *  (hspf) Document Properties.
- *
- * This is part 1 of 2 of the tests - it only does the POIDocuments
- *  which are part of the Main (not scratchpad)
- */
-final class TestPOIDocumentMain {
-    // The POI Documents to work on
-    private POIDocument doc;
-    private POIDocument doc2;
-
-    /**
-     * Set things up, two spreadsheets for our testing
-     */
-    @BeforeEach
-    void setUp() {
-        doc = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls");
-        doc2 = HSSFTestDataSamples.openSampleWorkbook("StringFormulas.xls");
-    }
-
-    @Test
-    void readProperties() {
-        readPropertiesHelper(doc);
-    }
-
-    private void readPropertiesHelper(POIDocument docWB) {
-        // We should have both sets
-        assertNotNull(docWB.getDocumentSummaryInformation());
-        assertNotNull(docWB.getSummaryInformation());
-
-        // Check they are as expected for the test doc
-        assertEquals("Administrator", docWB.getSummaryInformation().getAuthor());
-        assertEquals(0, docWB.getDocumentSummaryInformation().getByteCount());
-    }
-
-    @Test
-    void readProperties2() {
-        // Check again on the word one
-        assertNotNull(doc2.getDocumentSummaryInformation());
-        assertNotNull(doc2.getSummaryInformation());
-
-        assertEquals("Avik Sengupta", doc2.getSummaryInformation().getAuthor());
-        assertNull(doc2.getSummaryInformation().getKeywords());
-        assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount());
-    }
-
-    @Test
-    void writeProperties() throws IOException {
-        // 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(SummaryInformation.DEFAULT_STREAM_NAME)
-        );
-        assertNotNull(
-                outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME)
-        );
-    }
-
-    @Test
-    void WriteReadProperties() throws IOException {
-        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
-        POIDocument doc3 = new HPSFPropertiesOnlyDocument(inFS);
-        doc3.readProperties();
-
-        // Delegate test
-        readPropertiesHelper(doc3);
-        doc3.close();
-    }
-
-    @Test
-    void createNewProperties() throws IOException {
-        POIDocument doc = new HSSFWorkbook();
-
-        // New document won't have them
-        assertNull(doc.getSummaryInformation());
-        assertNull(doc.getDocumentSummaryInformation());
-
-        // Add them in
-        doc.createInformationProperties();
-        assertNotNull(doc.getSummaryInformation());
-        assertNotNull(doc.getDocumentSummaryInformation());
-
-        // Write out and back in again, no change
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        doc.write(baos);
-        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
-
-        doc.close();
-
-        doc = new HSSFWorkbook(bais);
-
-        assertNotNull(doc.getSummaryInformation());
-        assertNotNull(doc.getDocumentSummaryInformation());
-
-        doc.close();
-    }
-
-    @Test
-    void createNewPropertiesOnExistingFile() throws IOException {
-        POIDocument doc = new HSSFWorkbook();
-
-        // New document won't have them
-        assertNull(doc.getSummaryInformation());
-        assertNull(doc.getDocumentSummaryInformation());
-
-        // Write out and back in again, no change
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        doc.write(baos);
-
-        doc.close();
-
-        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
-        doc = new HSSFWorkbook(bais);
-
-        assertNull(doc.getSummaryInformation());
-        assertNull(doc.getDocumentSummaryInformation());
-
-        // Create, and change
-        doc.createInformationProperties();
-        doc.getSummaryInformation().setAuthor("POI Testing");
-        doc.getDocumentSummaryInformation().setCompany("ASF");
-
-        // Save and re-load
-        baos = new ByteArrayOutputStream();
-        doc.write(baos);
-
-        doc.close();
-
-        bais = new ByteArrayInputStream(baos.toByteArray());
-        doc = new HSSFWorkbook(bais);
-
-        // Check
-        assertNotNull(doc.getSummaryInformation());
-        assertNotNull(doc.getDocumentSummaryInformation());
-        assertEquals("POI Testing", doc.getSummaryInformation().getAuthor());
-        assertEquals("ASF", doc.getDocumentSummaryInformation().getCompany());
-
-        // Asking to re-create will make no difference now
-        doc.createInformationProperties();
-        assertNotNull(doc.getSummaryInformation());
-        assertNotNull(doc.getDocumentSummaryInformation());
-        assertEquals("POI Testing", doc.getSummaryInformation().getAuthor());
-        assertEquals("ASF", doc.getDocumentSummaryInformation().getCompany());
-
-        doc.close();
-    }
-}
diff --git a/src/testcases/org/apache/poi/TestPOITestCase.java b/src/testcases/org/apache/poi/TestPOITestCase.java
deleted file mode 100644
index 862d0d7e46..0000000000
--- a/src/testcases/org/apache/poi/TestPOITestCase.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/* ====================================================================
-   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;
-
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.Locale;
-import java.util.Map;
-
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.poifs.property.PropertyTable;
-import org.junit.jupiter.api.Test;
-
-/**
- * A class for testing the POI Junit TestCase utility class
- */
-final class TestPOITestCase {
-    @Test
-    void assertStartsWith() {
-        POITestCase.assertStartsWith("Apache POI", "");
-        POITestCase.assertStartsWith("Apache POI", "Apache");
-        POITestCase.assertStartsWith("Apache POI", "Apache POI");
-    }
-
-    @Test
-    void assertEndsWith() {
-        POITestCase.assertEndsWith("Apache POI", "");
-        POITestCase.assertEndsWith("Apache POI", "POI");
-        POITestCase.assertEndsWith("Apache POI", "Apache POI");
-    }
-
-    @Test
-    void assertContains() {
-        POITestCase.assertContains("There is a needle in this haystack", "needle");
-    }
-
-    @Test
-    void assertContainsIgnoreCase_Locale() {
-        POITestCase.assertContainsIgnoreCase("There is a Needle in this haystack", "needlE", Locale.ROOT);
-    }
-
-    @Test
-    void assertContainsIgnoreCase() {
-        POITestCase.assertContainsIgnoreCase("There is a Needle in this haystack", "needlE");
-    }
-
-    @Test
-    void assertNotContained() {
-        POITestCase.assertNotContained("There is a needle in this haystack", "gold");
-    }
-
-    @Test
-    void assertMapContains() {
-        Map haystack = Collections.singletonMap("needle", "value");
-        POITestCase.assertContains(haystack, "needle");
-    }
-
-
-    /**
-     * Utility method to get the value of a private/protected field.
-     * Only use this method in test cases!!!
-     */
-    @Test
-    void getFieldValue() throws IOException {
-        try (POIFSFileSystem fs = new POIFSFileSystem()) {
-            PropertyTable actual = POITestCase.getFieldValue(POIFSFileSystem.class, fs, PropertyTable.class, "_property_table");
-            assertNotNull(actual);
-        }
-    }
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherBSERecord.java b/src/testcases/org/apache/poi/ddf/TestEscherBSERecord.java
deleted file mode 100644
index 43edb89d0c..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherBSERecord.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.IOException;
-
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.apache.poi.sl.usermodel.PictureData;
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-final class TestEscherBSERecord {
-    @Test
-    void testFillFields() {
-        String data = "01 00 00 00 24 00 00 00 05 05 01 02 03 04 " +
-                " 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00 01 00 00 00 " +
-                " 00 00 02 00 00 00 03 00 00 00 04 05 06 07";
-        EscherBSERecord r = new EscherBSERecord();
-        int bytesWritten = r.fillFields( HexRead.readFromString( data ), 0, new DefaultEscherRecordFactory() );
-        assertEquals( 44, bytesWritten );
-        assertEquals( (short) 0x0001, r.getOptions() );
-        assertEquals( PictureData.PictureType.JPEG.nativeId, r.getBlipTypeWin32() );
-        assertEquals( PictureData.PictureType.JPEG.nativeId, r.getBlipTypeMacOS() );
-        assertEquals( "[01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 00]", HexDump.toHex( r.getUid() ) );
-        assertEquals( (short) 1, r.getTag() );
-        assertEquals( 2, r.getRef() );
-        assertEquals( 3, r.getOffset() );
-        assertEquals( (byte) 4, r.getUsage() );
-        assertEquals( (byte) 5, r.getName() );
-        assertEquals( (byte) 6, r.getUnused2() );
-        assertEquals( (byte) 7, r.getUnused3() );
-        assertEquals( 0, r.getRemainingData().length );
-    }
-
-    @Test
-    void testSerialize() throws IOException {
-        EscherBSERecord r = createRecord();
-        String exp64 = "H4sIAAAAAAAAAGNkYP+gwsDAwMrKyMTMwsrGzsHJxc3Dy8fPwMgAAkxAzAzEICkAgs9OoSwAAAA=";
-        byte[] expected = RawDataUtil.decompress(exp64);
-
-        byte[] data = new byte[8 + 36];
-        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
-        assertEquals(data.length, bytesWritten);
-        assertArrayEquals(expected, data);
-    }
-
-    private EscherBSERecord createRecord() {
-        EscherBSERecord r = new EscherBSERecord();
-        r.setOptions( (short) 0x0001 );
-        r.setBlipTypeWin32( (byte)PictureData.PictureType.JPEG.nativeId );
-        r.setBlipTypeMacOS( (byte)PictureData.PictureType.JPEG.nativeId );
-        r.setUid( HexRead.readFromString( "01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00" ) );
-        r.setTag( (short) 1 );
-        r.setRef( 2 );
-        r.setOffset( 3 );
-        r.setUsage( (byte) 4 );
-        r.setName( (byte) 5 );
-        r.setUnused2( (byte) 6 );
-        r.setUnused3( (byte) 7 );
-        r.setRemainingData( new byte[0] );
-        return r;
-
-    }
-
-    @Test
-    void testToString() {
-        EscherBSERecord record = createRecord();
-        String expected =
-            "{   /* BSE */\n" +
-            "\t  \"recordId\": -4089 /* 0xf007 */\n" +
-            "\t, \"version\": 1\n" +
-            "\t, \"instance\": 0\n" +
-            "\t, \"options\": 1\n" +
-            "\t, \"recordSize\": 44 /* 0x0000002c */\n" +
-            "\t, \"blipTypeWin32\": 5\n" +
-            "\t, \"pictureTypeWin32\": \"JPEG\"\n" +
-            "\t, \"blipTypeMacOS\": 5\n" +
-            "\t, \"pictureTypeMacOS\": \"JPEG\"\n" +
-            "\t, \"suid\": \"AQIDBAUGBwgJCgsMDQ4PAA==\"\n" +
-            "\t, \"tag\": 1\n" +
-            "\t, \"size\": 0\n" +
-            "\t, \"ref\": 2\n" +
-            "\t, \"offset\": 3\n" +
-            "\t, \"usage\": 4\n" +
-            "\t, \"name\": 5\n" +
-            "\t, \"unused2\": 6\n" +
-            "\t, \"unused3\": 7\n" +
-            "\t, \"blipRecord\": null\n" +
-            "\t, \"remainingData\": \"\"\n" +
-            "}";
-        String actual = record.toString().replace("\r", "");
-        assertEquals( expected, actual );
-    }
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherBlipRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherBlipRecord.java
deleted file mode 100644
index a081f61c65..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherBlipRecord.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.sl.usermodel.PictureData;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test read/serialize of escher blip records
-*/
-final class TestEscherBlipRecord {
-    private static final POIDataSamples _samples = POIDataSamples.getDDFInstance();
-
-    //test reading/serializing of a PNG blip
-    @Test
-    void testReadPNG() {
-        //provided in bug-44886
-        byte[] data = _samples.readFile("Container.dat");
-
-        EscherContainerRecord record = new EscherContainerRecord();
-        record.fillFields(data, 0, new DefaultEscherRecordFactory());
-        EscherContainerRecord bstore = (EscherContainerRecord)record.getChild(1);
-        EscherBSERecord bse1 = (EscherBSERecord)bstore.getChild(0);
-        assertEquals(PictureData.PictureType.PNG.nativeId, bse1.getBlipTypeWin32());
-        assertEquals(PictureData.PictureType.PNG.nativeId, bse1.getBlipTypeMacOS());
-        assertArrayEquals(new byte[]{
-            0x65, 0x07, 0x4A, (byte)0x8D, 0x3E, 0x42, (byte)0x8B, (byte)0xAC,
-            0x1D, (byte)0x89, 0x35, 0x4F, 0x48, (byte)0xFA, 0x37, (byte)0xC2
-        }, bse1.getUid());
-        assertEquals(255, bse1.getTag());
-        assertEquals(32308, bse1.getSize());
-
-        EscherBitmapBlip blip1 = (EscherBitmapBlip)bse1.getBlipRecord();
-        assertEquals(0x6E00, blip1.getOptions());
-        assertEquals(EscherBitmapBlip.RECORD_ID_PNG, blip1.getRecordId());
-        assertArrayEquals(new byte[]{
-            0x65, 0x07, 0x4A, (byte)0x8D, 0x3E, 0x42, (byte)0x8B, (byte)0xAC,
-            0x1D, (byte)0x89, 0x35, 0x4F, 0x48, (byte)0xFA, 0x37, (byte)0xC2
-        }, blip1.getUID());
-
-        //serialize and read again
-        byte[] ser = bse1.serialize();
-        EscherBSERecord bse2 = new EscherBSERecord();
-        bse2.fillFields(ser, 0, new DefaultEscherRecordFactory());
-        assertEquals(bse1.getRecordId(), bse2.getRecordId());
-        assertEquals(bse1.getBlipTypeWin32(), bse2.getBlipTypeWin32());
-        assertEquals(bse1.getBlipTypeMacOS(), bse2.getBlipTypeMacOS());
-        assertArrayEquals(bse1.getUid(), bse2.getUid());
-        assertEquals(bse1.getTag(), bse2.getTag());
-        assertEquals(bse1.getSize(), bse2.getSize());
-
-        EscherBitmapBlip blip2 = (EscherBitmapBlip)bse1.getBlipRecord();
-        assertEquals(blip1.getOptions(), blip2.getOptions());
-        assertEquals(blip1.getRecordId(), blip2.getRecordId());
-        assertEquals(blip1.getUID(), blip2.getUID());
-
-        assertArrayEquals(blip1.getPicturedata(), blip1.getPicturedata());
-    }
-
-    //test reading/serializing of a PICT metafile
-    @Test
-    void testReadPICT() {
-        //provided in bug-44886
-        byte[] data = _samples.readFile("Container.dat");
-
-        EscherContainerRecord record = new EscherContainerRecord();
-        record.fillFields(data, 0, new DefaultEscherRecordFactory());
-        EscherContainerRecord bstore = (EscherContainerRecord)record.getChild(1);
-        EscherBSERecord bse1 = (EscherBSERecord)bstore.getChild(1);
-        //System.out.println(bse1);
-        assertEquals(PictureData.PictureType.WMF.nativeId, bse1.getBlipTypeWin32());
-        assertEquals(PictureData.PictureType.PICT.nativeId, bse1.getBlipTypeMacOS());
-        assertArrayEquals(new byte[]{
-            (byte)0xC7, 0x15, 0x69, 0x2D, (byte)0xE5, (byte)0x89, (byte)0xA3, 0x6F,
-            0x66, 0x03, (byte)0xD6, 0x24, (byte)0xF7, (byte)0xDB, 0x1D, 0x13
-        }, bse1.getUid());
-        assertEquals(255, bse1.getTag());
-        assertEquals(1133, bse1.getSize());
-
-        EscherMetafileBlip blip1 = (EscherMetafileBlip)bse1.getBlipRecord();
-        assertEquals(0x5430, blip1.getOptions());
-        assertEquals(EscherMetafileBlip.RECORD_ID_PICT, blip1.getRecordId());
-        assertArrayEquals(new byte[]{
-            0x57, 0x32, 0x7B, (byte)0x91, 0x23, 0x5D, (byte)0xDB, 0x36,
-            0x7A, (byte)0xDB, (byte)0xFF, 0x17, (byte)0xFE, (byte)0xF3, (byte)0xA7, 0x05
-        }, blip1.getUID());
-        assertArrayEquals(new byte[]{
-            (byte)0xC7, 0x15, 0x69, 0x2D, (byte)0xE5, (byte)0x89, (byte)0xA3, 0x6F,
-            0x66, 0x03, (byte)0xD6, 0x24, (byte)0xF7, (byte)0xDB, 0x1D, 0x13
-        }, blip1.getPrimaryUID());
-
-        //serialize and read again
-        byte[] ser = bse1.serialize();
-        EscherBSERecord bse2 = new EscherBSERecord();
-        bse2.fillFields(ser, 0, new DefaultEscherRecordFactory());
-        assertEquals(bse1.getRecordId(), bse2.getRecordId());
-        assertEquals(bse1.getOptions(), bse2.getOptions());
-        assertEquals(bse1.getBlipTypeWin32(), bse2.getBlipTypeWin32());
-        assertEquals(bse1.getBlipTypeMacOS(), bse2.getBlipTypeMacOS());
-        assertArrayEquals(bse1.getUid(), bse2.getUid());
-        assertEquals(bse1.getTag(), bse2.getTag());
-        assertEquals(bse1.getSize(), bse2.getSize());
-
-        EscherMetafileBlip blip2 = (EscherMetafileBlip)bse1.getBlipRecord();
-        assertEquals(blip1.getOptions(), blip2.getOptions());
-        assertEquals(blip1.getRecordId(), blip2.getRecordId());
-        assertEquals(blip1.getUID(), blip2.getUID());
-        assertEquals(blip1.getPrimaryUID(), blip2.getPrimaryUID());
-
-        assertArrayEquals(blip1.getPicturedata(), blip1.getPicturedata());
-    }
-
-    //integral test: check that the read-write-read round trip is consistent
-    @Test
-    void testContainer() {
-        byte[] data = _samples.readFile("Container.dat");
-
-        EscherContainerRecord record = new EscherContainerRecord();
-        record.fillFields(data, 0, new DefaultEscherRecordFactory());
-
-        byte[] ser = record.serialize();
-        assertArrayEquals(data, ser);
-    }
-
-    /**
-     * The test data was created from pl031405.xls attached to Bugzilla #47143
-     */
-    @Test
-    void test47143() {
-        byte[] data = _samples.readFile("47143.dat");
-        EscherBSERecord bse = new EscherBSERecord();
-        bse.fillFields(data, 0, new DefaultEscherRecordFactory());
-        bse.toString(); //assert that toString() works
-        assertTrue(bse.getBlipRecord() instanceof EscherMetafileBlip);
-
-        EscherMetafileBlip blip = (EscherMetafileBlip)bse.getBlipRecord();
-        blip.toString(); //assert that toString() works
-        byte[] remaining = blip.getRemainingData();
-        assertNotNull(remaining);
-
-        byte[] ser = bse.serialize();  //serialize and assert against the source data
-        assertArrayEquals(data, ser);
-    }
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherBoolProperty.java b/src/testcases/org/apache/poi/ddf/TestEscherBoolProperty.java
deleted file mode 100644
index 4957c063d5..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherBoolProperty.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-final class TestEscherBoolProperty {
-    @Test
-    void testToString() {
-        EscherBoolProperty p = new EscherBoolProperty(EscherPropertyTypes.GEOMETRY__FILLOK, 1);
-        String expected =
-            "{   /* GEOMETRY__FILLOK */\n" +
-            "\t  \"id\": 383 /* 0x017f */\n" +
-            "\t, \"name\": \"geometry.fillok\"\n" +
-            "\t, \"propertyNumber\": 383 /* 0x017f */\n" +
-            "\t, \"propertySize\": 6\n" +
-            "\t, \"flags\": 383 /*  */ \n" +
-            "\t, \"value\": 1\n" +
-            "}";
-        assertEquals(expected, p.toString().replace("\r", ""));
-    }
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherChildAnchorRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherChildAnchorRecord.java
deleted file mode 100644
index 9f24b6d18d..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherChildAnchorRecord.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-final class TestEscherChildAnchorRecord {
-    @Test
-    void testSerialize() {
-        EscherChildAnchorRecord r = createRecord();
-
-        byte[] data = new byte[8 + 16];
-        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
-        assertEquals( data.length, bytesWritten );
-        assertEquals( "[01, 00, " +
-                "0F, F0, " +
-                "10, 00, 00, 00, " +
-                "01, 00, 00, 00, " +
-                "02, 00, 00, 00, " +
-                "03, 00, 00, 00, " +
-                "04, 00, 00, 00]", HexDump.toHex( data ) );
-    }
-
-    @Test
-    void testFillFields() {
-        String hexData = "01 00 " +
-                "0F F0 " +
-                "10 00 00 00 " +
-                "01 00 00 00 " +
-                "02 00 00 00 " +
-                "03 00 00 00 " +
-                "04 00 00 00 ";
-
-        byte[] data = HexRead.readFromString( hexData );
-        EscherChildAnchorRecord r = new EscherChildAnchorRecord();
-        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
-
-        assertEquals( 24, bytesWritten );
-        assertEquals( 1, r.getDx1() );
-        assertEquals( 2, r.getDy1() );
-        assertEquals( 3, r.getDx2() );
-        assertEquals( 4, r.getDy2() );
-        assertEquals( (short) 0x0001, r.getOptions() );
-    }
-
-    @Test
-    void testToString(){
-        String expected =
-            "{   /* CHILD_ANCHOR */\n" +
-            "\t  \"recordId\": -4081 /* 0xf00f */\n" +
-            "\t, \"version\": 1\n" +
-            "\t, \"instance\": 0\n" +
-            "\t, \"options\": 1\n" +
-            "\t, \"recordSize\": 24 /* 0x00000018 */\n" +
-            "\t, \"x1\": 1\n" +
-            "\t, \"y1\": 2\n" +
-            "\t, \"x2\": 3\n" +
-            "\t, \"y2\": 4\n" +
-            "}";
-        expected = expected.replace("\n", System.getProperty("line.separator"));
-        assertEquals( expected, createRecord().toString() );
-    }
-
-    private static EscherChildAnchorRecord createRecord() {
-        EscherChildAnchorRecord r = new EscherChildAnchorRecord();
-        r.setRecordId( EscherChildAnchorRecord.RECORD_ID );
-        r.setOptions( (short) 0x0001 );
-        r.setDx1( 1 );
-        r.setDy1( 2 );
-        r.setDx2( 3 );
-        r.setDy2( 4 );
-        return r;
-    }
-}
-
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherClientAnchorRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherClientAnchorRecord.java
deleted file mode 100644
index b931359e54..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherClientAnchorRecord.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-class TestEscherClientAnchorRecord {
-    @Test
-    void testSerialize() {
-        EscherClientAnchorRecord r = createRecord();
-
-        byte[] data = new byte[8 + 18 + 2];
-        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
-        assertEquals( 28, bytesWritten );
-        assertEquals( "[01, 00, " +
-                "10, F0, " +
-                "14, 00, 00, 00, " +
-                "4D, 00, 37, 00, 21, 00, 58, 00, " +
-                "0B, 00, 2C, 00, 16, 00, 63, 00, " +
-                "42, 00, " +
-                "FF, DD]", HexDump.toHex( data ) );
-    }
-
-    @Test
-    void testFillFields() {
-        String hexData = "01 00 " +
-                "10 F0 " +
-                "14 00 00 00 " +
-                "4D 00 37 00 21 00 58 00 " +
-                "0B 00 2C 00 16 00 63 00 " +
-                "42 00 " +
-                "FF DD";
-        byte[] data = HexRead.readFromString( hexData );
-        EscherClientAnchorRecord r = new EscherClientAnchorRecord();
-        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
-
-        assertEquals( 28, bytesWritten );
-        assertEquals( (short) 55, r.getCol1() );
-        assertEquals( (short) 44, r.getCol2() );
-        assertEquals( (short) 33, r.getDx1() );
-        assertEquals( (short) 22, r.getDx2() );
-        assertEquals( (short) 11, r.getDy1() );
-        assertEquals( (short) 66, r.getDy2() );
-        assertEquals( (short) 77, r.getFlag() );
-        assertEquals( (short) 88, r.getRow1() );
-        assertEquals( (short) 99, r.getRow2() );
-        assertEquals( (short) 0x0001, r.getOptions() );
-        assertEquals( (byte) 0xFF, r.getRemainingData()[0] );
-        assertEquals( (byte) 0xDD, r.getRemainingData()[1] );
-    }
-
-    @Test
-    void testToString() {
-        String expected =
-            "{   /* CLIENT_ANCHOR */\n" +
-            "\t  \"recordId\": -4080 /* 0xf010 */\n" +
-            "\t, \"version\": 1\n" +
-            "\t, \"instance\": 0\n" +
-            "\t, \"options\": 1\n" +
-            "\t, \"recordSize\": 28 /* 0x0000001c */\n" +
-            "\t, \"flag\": 77 /* 0x004d */\n" +
-            "\t, \"col1\": 55 /* 0x0037 */\n" +
-            "\t, \"dx1\": 33 /* 0x0021 */\n" +
-            "\t, \"row1\": 88 /* 0x0058 */\n" +
-            "\t, \"dy1\": 11 /* 0x000b */\n" +
-            "\t, \"col2\": 44 /* 0x002c */\n" +
-            "\t, \"dx2\": 22 /* 0x0016 */\n" +
-            "\t, \"row2\": 99 /* 0x0063 */\n" +
-            "\t, \"dy2\": 66 /* 0x0042 */\n" +
-            "\t, \"remainingData\": \"/90=\"\n" +
-            "}";
-        expected = expected.replace("\n", System.getProperty("line.separator"));
-        assertEquals( expected, createRecord().toString() );
-    }
-
-    private EscherClientAnchorRecord createRecord()
-    {
-        EscherClientAnchorRecord r = new EscherClientAnchorRecord();
-        r.setCol1( (short) 55 );
-        r.setCol2( (short) 44 );
-        r.setDx1( (short) 33 );
-        r.setDx2( (short) 22 );
-        r.setDy1( (short) 11 );
-        r.setDy2( (short) 66 );
-        r.setFlag( (short) 77 );
-        r.setRow1( (short) 88 );
-        r.setRow2( (short) 99 );
-        r.setOptions( (short) 0x0001 );
-        r.setRemainingData( new byte[]{(byte) 0xFF, (byte) 0xDD} );
-        return r;
-    }
-
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherClientDataRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherClientDataRecord.java
deleted file mode 100644
index f9ee5eaca1..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherClientDataRecord.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-class TestEscherClientDataRecord {
-    @Test
-    void testSerialize() {
-        EscherClientDataRecord r = createRecord();
-
-        byte[] data = new byte[8];
-        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
-        assertEquals( 8, bytesWritten );
-        assertEquals( "[02, 00, " +
-                "11, F0, " +
-                "00, 00, 00, 00]",
-                HexDump.toHex( data ) );
-    }
-
-    @Test
-    void testFillFields() {
-        String hexData = "02 00 " +
-                "11 F0 " +
-                "00 00 00 00 ";
-        byte[] data = HexRead.readFromString( hexData );
-        EscherClientDataRecord r = new EscherClientDataRecord();
-        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
-
-        assertEquals( 8, bytesWritten );
-        assertEquals( (short)0xF011, r.getRecordId() );
-        assertEquals( "[]", HexDump.toHex(r.getRemainingData()) );
-    }
-
-    @Test
-    void testToString() {
-        String expected =
-            "{   /* CLIENT_DATA */\n" +
-            "\t  \"recordId\": -4079 /* 0xf011 */\n" +
-            "\t, \"version\": 2\n" +
-            "\t, \"instance\": 0\n" +
-            "\t, \"options\": 2\n" +
-            "\t, \"recordSize\": 8\n" +
-            "\t, \"remainingData\": \"\"\n" +
-            "}";
-        expected = expected.replace("\n", System.getProperty("line.separator"));
-        assertEquals( expected, createRecord().toString() );
-    }
-
-    private static EscherClientDataRecord createRecord()
-    {
-        EscherClientDataRecord r = new EscherClientDataRecord();
-        r.setOptions( (short) 0x0002 );
-        r.setRecordId( EscherClientDataRecord.RECORD_ID );
-        r.setRemainingData( new byte[] {} );
-        return r;
-    }
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherContainerRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherContainerRecord.java
deleted file mode 100644
index df13975197..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherContainerRecord.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotSame;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.List;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link EscherContainerRecord}
- */
-final class TestEscherContainerRecord {
-    private static final POIDataSamples _samples = POIDataSamples.getDDFInstance();
-
-    @Test
-	void testFillFields() {
-		EscherRecordFactory f = new DefaultEscherRecordFactory();
-		byte[] data = HexRead.readFromString("0F 02 11 F1 00 00 00 00");
-		EscherRecord r = f.createRecord(data, 0);
-		r.fillFields(data, 0, f);
-		assertTrue(r instanceof EscherContainerRecord);
-		assertEquals((short) 0x020F, r.getOptions());
-		assertEquals((short) 0xF111, r.getRecordId());
-
-		data = HexRead.readFromString("0F 02 11 F1 08 00 00 00" +
-				" 02 00 22 F2 00 00 00 00");
-		r = f.createRecord(data, 0);
-		r.fillFields(data, 0, f);
-		EscherRecord c = r.getChild(0);
-		assertFalse(c instanceof EscherContainerRecord);
-		assertEquals((short) 0x0002, c.getOptions());
-		assertEquals((short) 0xF222, c.getRecordId());
-	}
-
-    @Test
-	void testSerialize() {
-		UnknownEscherRecord r = new UnknownEscherRecord();
-		r.setOptions((short) 0x123F);
-		r.setRecordId((short) 0xF112);
-		byte[] data = new byte[8];
-		r.serialize(0, data, new NullEscherSerializationListener());
-
-		assertEquals("[3F, 12, 12, F1, 00, 00, 00, 00]", HexDump.toHex(data));
-
-		EscherRecord childRecord = new UnknownEscherRecord();
-		childRecord.setOptions((short) 0x9999);
-		childRecord.setRecordId((short) 0xFF01);
-		r.addChildRecord(childRecord);
-		data = new byte[16];
-		r.serialize(0, data, new NullEscherSerializationListener());
-
-		assertEquals("[3F, 12, 12, F1, 08, 00, 00, 00, 99, 99, 01, FF, 00, 00, 00, 00]", HexDump.toHex(data));
-
-	}
-
-    @Test
-	void testToString() {
-		EscherContainerRecord r = new EscherContainerRecord();
-		r.setRecordId(EscherContainerRecord.SP_CONTAINER);
-		r.setOptions((short) 0x000F);
-        String expected =
-            "{   /* SP_CONTAINER */\n" +
-			"\t  \"recordId\": -4092 /* 0xf004 */\n" +
-			"\t, \"version\": 15 /* 0x000f */\n" +
-			"\t, \"instance\": 0\n" +
-			"\t, \"options\": 15 /* 0x000f */\n" +
-			"\t, \"recordSize\": 8\n" +
-			"\t, \"isContainer\": true\n" +
-			"}";
-		expected = expected.replace("\n", System.getProperty("line.separator"));
-		assertEquals(expected, r.toString());
-
-		EscherOptRecord r2 = new EscherOptRecord();
-		// don't try to shoot in foot, please -- vlsergey
-		// r2.setOptions((short) 0x9876);
-		r2.setRecordId(EscherOptRecord.RECORD_ID);
-
-		r.addChildRecord(r2);
-		expected =
-	        "{   /* SP_CONTAINER */\n" +
-			"\t  \"recordId\": -4092 /* 0xf004 */\n" +
-			"\t, \"version\": 15 /* 0x000f */\n" +
-			"\t, \"instance\": 0\n" +
-			"\t, \"options\": 15 /* 0x000f */\n" +
-			"\t, \"recordSize\": 16 /* 0x00000010 */\n" +
-			"\t, \"isContainer\": true\n" +
-			"\t, \"children\": [\n" +
-			"\t\t{   /* OPT */\n" +
-			"\t\t\t  \"recordId\": -4085 /* 0xf00b */\n" +
-			"\t\t\t, \"version\": 3\n" +
-			"\t\t\t, \"instance\": 0\n" +
-			"\t\t\t, \"options\": 3\n" +
-			"\t\t\t, \"recordSize\": 8\n" +
-			"\t\t\t, \"isContainer\": false\n" +
-			"\t\t\t, \"properties\": [\n" +
-			"\t\t\t]\n" +
-			"\t\t}\n" +
-			"\t]\n" +
-			"}";
-		expected = expected.replace("\n", System.getProperty("line.separator"));
-		assertEquals(expected, r.toString());
-
-		r.addChildRecord(r2);
-		expected =
-	        "{   /* SP_CONTAINER */\n" +
-			"\t  \"recordId\": -4092 /* 0xf004 */\n" +
-			"\t, \"version\": 15 /* 0x000f */\n" +
-			"\t, \"instance\": 0\n" +
-			"\t, \"options\": 15 /* 0x000f */\n" +
-			"\t, \"recordSize\": 24 /* 0x00000018 */\n" +
-			"\t, \"isContainer\": true\n" +
-			"\t, \"children\": [\n" +
-			"\t\t{   /* OPT */\n" +
-			"\t\t\t  \"recordId\": -4085 /* 0xf00b */\n" +
-			"\t\t\t, \"version\": 3\n" +
-			"\t\t\t, \"instance\": 0\n" +
-			"\t\t\t, \"options\": 3\n" +
-			"\t\t\t, \"recordSize\": 8\n" +
-			"\t\t\t, \"isContainer\": false\n" +
-			"\t\t\t, \"properties\": [\n" +
-			"\t\t\t]\n" +
-			"\t\t},\t\t{   /* OPT - index: 1 */\n" +
-			"\t\t\t  \"recordId\": -4085 /* 0xf00b */\n" +
-			"\t\t\t, \"version\": 3\n" +
-			"\t\t\t, \"instance\": 0\n" +
-			"\t\t\t, \"options\": 3\n" +
-			"\t\t\t, \"recordSize\": 8\n" +
-			"\t\t\t, \"isContainer\": false\n" +
-			"\t\t\t, \"properties\": [\n" +
-			"\t\t\t]\n" +
-			"\t\t}\n" +
-			"\t]\n" +
-			"}";
-		expected = expected.replace("\n", System.getProperty("line.separator"));
-		assertEquals(expected, r.toString());
-    }
-
-	private static final class DummyEscherRecord extends EscherRecord {
-		public DummyEscherRecord() { }
-		@Override
-        public int fillFields(byte[] data, int offset, EscherRecordFactory recordFactory) { return 0; }
-		@Override
-        public int serialize(int offset, byte[] data, EscherSerializationListener listener) { return 0; }
-		@Override
-        public int getRecordSize() { return 10; }
-		@Override
-        public String getRecordName() { return ""; }
-		@Override
-		public Enum getGenericRecordType() { return EscherRecordTypes.UNKNOWN; }
-		@Override
-		public DummyEscherRecord copy() { return null; }
-	}
-
-    @Test
-	void testGetRecordSize() {
-		EscherContainerRecord r = new EscherContainerRecord();
-		r.addChildRecord(new DummyEscherRecord());
-		assertEquals(18, r.getRecordSize());
-	}
-
-	/**
-	 * We were having problems with reading too much data on an UnknownEscherRecord,
-	 *  but hopefully we now read the correct size.
-	 */
-    @Test
-	void testBug44857() {
-		byte[] data = _samples.readFile("Container.dat");
-
-		// This used to fail with an OutOfMemory
-		EscherContainerRecord record = new EscherContainerRecord();
-		record.fillFields(data, 0, new DefaultEscherRecordFactory());
-
-		Class[] exp = { EscherDggRecord.class, EscherContainerRecord.class, EscherOptRecord.class, EscherSplitMenuColorsRecord.class };
-		Class[] act = record.getChildRecords().stream().map(Object::getClass).toArray(Class[]::new);
-		assertArrayEquals(exp, act);
-	}
-
-	/**
-	 * Ensure {@link EscherContainerRecord} doesn't spill its guts everywhere
-	 */
-    @Test
-	void testChildren() {
-		EscherContainerRecord ecr = new EscherContainerRecord();
-		List children0 = ecr.getChildRecords();
-		assertEquals(0, children0.size());
-
-		EscherRecord chA = new DummyEscherRecord();
-		EscherRecord chB = new DummyEscherRecord();
-		EscherRecord chC = new DummyEscherRecord();
-
-		ecr.addChildRecord(chA);
-		ecr.addChildRecord(chB);
-		children0.add(chC);
-
-		List children1 = ecr.getChildRecords();
-		assertNotSame(children0, children1);
-		assertEquals(2, children1.size());
-		assertEquals(chA, children1.get(0));
-		assertEquals(chB, children1.get(1));
-
-		assertEquals(1, children0.size()); // first copy unchanged
-
-		ecr.setChildRecords(children0);
-		ecr.addChildRecord(chA);
-		List children2 = ecr.getChildRecords();
-		assertEquals(2, children2.size());
-		assertEquals(chC, children2.get(0));
-		assertEquals(chA, children2.get(1));
-	}
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherDgRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherDgRecord.java
deleted file mode 100644
index ad84a54585..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherDgRecord.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-final class TestEscherDgRecord {
-    @Test
-    void testSerialize() {
-        EscherDgRecord r = createRecord();
-
-        byte[] data = new byte[16];
-        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
-        assertEquals( 16, bytesWritten );
-        assertEquals( "[10, 00, " +
-                "08, F0, " +
-                "08, 00, 00, 00, " +
-                "02, 00, 00, 00, " +     // num shapes in drawing
-                "01, 04, 00, 00]",     // The last MSOSPID given to an SP in this DG
-                HexDump.toHex( data ) );
-    }
-
-    @Test
-    void testFillFields() {
-        String hexData = "10 00 " +
-                "08 F0 " +
-                "08 00 00 00 " +
-                "02 00 00 00 " +
-                "01 04 00 00 ";
-        byte[] data = HexRead.readFromString( hexData );
-        EscherDgRecord r = new EscherDgRecord();
-        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
-
-        assertEquals( 16, bytesWritten );
-        assertEquals( 2, r.getNumShapes() );
-        assertEquals( 1025, r.getLastMSOSPID() );
-    }
-
-    @Test
-    void testToString() {
-        String expected =
-            "{   /* DG */\n" +
-            "\t  \"recordId\": -4088 /* 0xf008 */\n" +
-            "\t, \"version\": 0\n" +
-            "\t, \"instance\": 1\n" +
-            "\t, \"options\": 16 /* 0x0010 */\n" +
-            "\t, \"recordSize\": 16 /* 0x00000010 */\n" +
-            "\t, \"numShapes\": 2\n" +
-            "\t, \"lastMSOSPID\": 1025 /* 0x00000401 */\n" +
-            "\t, \"drawingGroupId\": 1\n" +
-            "}";
-        assertEquals( expected, createRecord().toString().replace("\r", "") );
-    }
-
-    private static EscherDgRecord createRecord()
-    {
-        EscherDgRecord r = new EscherDgRecord();
-        r.setOptions( (short) 0x0010 );
-        r.setRecordId( EscherDgRecord.RECORD_ID );
-        r.setNumShapes(2);
-        r.setLastMSOSPID(1025);
-        return r;
-    }
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherDggRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherDggRecord.java
deleted file mode 100644
index f8f8b58115..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherDggRecord.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-final class TestEscherDggRecord {
-    @Test
-    void testSerialize() {
-        EscherDggRecord r = createRecord();
-
-        byte[] data = new byte[32];
-        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
-        assertEquals( 32, bytesWritten );
-        assertEquals( "[00, 00, " +
-                "06, F0, " +
-                "18, 00, 00, 00, " +
-                "02, 04, 00, 00, " +
-                "02, 00, 00, 00, " +
-                "02, 00, 00, 00, " +
-                "01, 00, 00, 00, " +
-                "01, 00, 00, 00, 02, 00, 00, 00]",
-                HexDump.toHex( data ) );
-    }
-
-    @Test
-    void testFillFields() {
-        String hexData = "00 00 " +
-                "06 F0 " +
-                "18 00 00 00 " +
-                "02 04 00 00 " +
-                "02 00 00 00 " +
-                "02 00 00 00 " +
-                "01 00 00 00 " +
-                "01 00 00 00 02 00 00 00";
-        byte[] data = HexRead.readFromString( hexData );
-        EscherDggRecord r = new EscherDggRecord();
-        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
-
-        assertEquals( 32, bytesWritten );
-        assertEquals( 0x402, r.getShapeIdMax() );
-        assertEquals( 0x02, r.getNumIdClusters() );
-        assertEquals( 0x02, r.getNumShapesSaved() );
-        assertEquals( 0x01, r.getDrawingsSaved() );
-        assertEquals( 1, r.getFileIdClusters().length );
-        assertEquals( 0x01, r.getFileIdClusters()[0].getDrawingGroupId());
-        assertEquals( 0x02, r.getFileIdClusters()[0].getNumShapeIdsUsed());
-    }
-
-    @Test
-    void testToString() {
-        String expected =
-            "{   /* DGG */\n" +
-            "\t  \"recordId\": -4090 /* 0xf006 */\n" +
-            "\t, \"version\": 0\n" +
-            "\t, \"instance\": 0\n" +
-            "\t, \"options\": 0\n" +
-            "\t, \"recordSize\": 32 /* 0x00000020 */\n" +
-            "\t, \"fileIdClusters\": [\n" +
-            "\t{   /* FileIdCluster */\n" +
-            "\t\t  \"drawingGroupId\": 1\n" +
-            "\t\t, \"numShapeIdUsed\": 2\n" +
-            "\t}\t]\n" +
-            "\t, \"shapeIdMax\": 1026 /* 0x00000402 */\n" +
-            "\t, \"numIdClusters\": 2\n" +
-            "\t, \"numShapesSaved\": 2\n" +
-            "\t, \"drawingsSaved\": 1\n" +
-            "}";
-        expected = expected.replace("\n", System.getProperty("line.separator"));
-        assertEquals( expected, createRecord().toString() );
-    }
-
-    private static EscherDggRecord createRecord()
-    {
-        EscherDggRecord r = new EscherDggRecord();
-        r.setOptions( (short) 0x0000 );
-        r.setRecordId( EscherDggRecord.RECORD_ID );
-        r.setShapeIdMax( 0x402 );
-        r.setNumShapesSaved( 0x02 );
-        r.setDrawingsSaved( 0x01 );
-        r.setFileIdClusters(new EscherDggRecord.FileIdCluster[] {
-            new EscherDggRecord.FileIdCluster( 1, 2 )
-        });
-        return r;
-    }
-
-    @Test
-    void testGetRecordSize() {
-        EscherDggRecord r = new EscherDggRecord();
-        r.setFileIdClusters(new EscherDggRecord.FileIdCluster[] { new EscherDggRecord.FileIdCluster(0,0) } );
-        assertEquals(32,r.getRecordSize());
-    }
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherDump.java b/src/testcases/org/apache/poi/ddf/TestEscherDump.java
deleted file mode 100644
index 088d346bae..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherDump.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.StandardCharsets;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.apache.poi.util.IOUtils;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-class TestEscherDump {
-    private static final String recordData =
-        "H4sIAAAAAAAAAL2UaVCSWxjHX0SBChABLRXM1FxSEzXTzHK7dpVIcMmwxXCP9KaGTaWlGYLrtGmGmYEmYmqF2qIt4ppmjNG+" +
-        "2dWulUtOUdq1NHjva8v90HT7eM+Z5znP/M9/zpk5v3mONgAoc5AANBDKeVDW0gQAjZkVCti3mKnpAExpB/m8AKTyEiTCNd2J" +
-        "Z+O0o6W+srDCyH3DhzkgUAD76v86QNA4mKTMg4QfnUew/5qA29CZz6ALqGcSgNzOICB05gD1rhODJR2AZu3Ox3YOKAfVUPhH" +
-        "ULtbpdVJ0ccdijw0pY1A56M3Jup7U15jp7X4PPTTecx92/MT9eZwtUICrLJvsB6z0fHG5qbw7mRpFRaOnPYJ6SqXd5AQMSKM" +
-        "jceyMD4NsULkj1OwHncz5cO3pPvCXXPTMNdNa+kDfwku4q0RnFL8YGBI6N+oXHlgzCkGWGRdONJPK1PbusJrhBltylPBMm3e" +
-        "G0kw6DGdLhoU3pmgJ6n1maC1fXrs0uUL6cWG/kGVm3MWHh3pALq4+PH55k7Uu3d+x85u9zxwIzfQuU+3TIG5SkOgrS1tCJb3" +
-        "3nqHrxcx3XlJA6vZJ6Oi1ctaXppQyBQLbLLrPJaKKq+zIexFLrVdZM+r34pJJpNN1hSrWbM/lIyRmKpYRIi7CybTTUzBWt49" +
-        "11HRM/VbCiZ6Gyt9TZmhGXPS75xYjpH366vhgLJu4ZoZfM+/4FvGaBZIE9aZ2SduMrUT4mJA4NpP8F2AhB+dT+D/jY/7DZ84" +
-        "ULbaK4C4crJvZ4qej2+em2+Vni4mPluh2e5xyoGUWYRaoFnWubHcaX+L09Ya0ta4KrP13C2ozMyicr4ovY0fNhT2wfMF7ip8" +
-        "/tD0u96myXcn92gtTnEuGfBJxY0lFG0mJxPWpknjNxmzWvzKj18rpjO4hhQXAtaRVSmJu+D8egI3RdQVXYxzRhs1+HE2iNvM" +
-        "fVe2DsSjqJQbBdUajcaECC3/58MP97Q0Eo+GNTdKbhk1r7UJadrVj0rLplmAqU/BlGeXDObGLtl69vITp9tD25vVY9vUT17u" +
-        "WTGW8idcxUDMMX2PHa8X6xzG0C5cGJcVth40m3ycwCpcfuP4OClu6IpysV/9QuvrdW/Yb3Qj6Ul7e3nybqemdkvLXsXG2N3v" +
-        "qeVE0woXb06pLduuFWUv7NxY8jq1k63fcD5jvG/w/IE8eUNh0Pohz0WRx6tdOlf4XhlbF5pgfYYzn8w6cjYx/8rBXvtWNz8L" +
-        "6uu+ig35t+dgOc4jOpLirmFPtjQdKHovGZ4Bff4LaIPLnx6cbnKFo8JHDoGpJ1+BwKGfgM6GhB+d+F/0acj3PiVEABoProzN" +
-        "1dcsVo9TPoPIF+r9EQI0qtveV4WEI1YhFjfmLxDsyFJptHvx/0BD3bfKJY/XqlFTReyIko4tQSzFFRyGRbkyg7MyuCqTmsiA" +
-        "mAgs3FGB0BOR7LzNuUYMC9QWaXyUTcxELLOFQvaRIQZ1HlgkJtE25Ohym/xzkqxqbFI1fWKsGgKq0m/q9kwkVDJAvdKM+7c8" +
-        "wj8GVPdneU0GVaeLVO6Kd3T2lMQFRNeCRwUyx5LSIxI5RmIFNc2RnuSIfYOeOZ+0CwzE7BFTJO+5cVeUz2nDN7mMYUSYOZyv" +
-        "SyyaRRydLKPYMmqFbS5K8RJ6vQNIGtiuI8AKCEgXsqV9Vz1tgvzovKiD2FPtpNgRlb0keoprdS+hnsP6ICwLBrE9dz26g2YP" +
-        "DszibWNE7zW5xndwlsoqFRh87XTFw8BXiFdv0SDsGBnfNcOu/Qu7y7SLppfzLJq714byzYQ590BA+BN2xyDhR+fZX7CL/s5u" +
-        "Q9f/8ccWX28U3BaGw9qTiSqDfOtHmXXZq8XiHXAYoz901c5V2lVulTXZEMqwnLq8+8ds95s0FFrdl73saRntr/UuUxFHY0WU" +
-        "z5b333qXTe/NagSRrmqkqypoNG12Oz3nE5Yzyt7d05eY66Ci2oTR+rNS3K4OiClGK+07HWtFFLvAqv6sNkpFsLs4Wp8XfRp/" +
-        "11oPk3uTQB0ftHg1C16KRTBl+AbCzVaYfx6VFlJ7GL7Jme8bVOku8FKZL0eGgMVk4qhEnpZogNrtFU5yEyswJ+LbHOKsOPCn" +
-        "cT19LR+PfTgjN4CKCS5Es4LS+7nLt9hQ7ejwGQnEyxebOgJzlHjotWUACpoZsFkAgGqBeUDZAzB6h4N2MFCNhmIuFJMAgPsH" +
-        "eJr+iZEHAAA=";
-
-    private EscherDump dumper = new EscherDump();
-    private ByteArrayOutputStream baos = new ByteArrayOutputStream();
-    private PrintStream stream;
-
-    @BeforeEach
-    void setup() throws UnsupportedEncodingException {
-        stream = new PrintStream(baos, true, StandardCharsets.UTF_8.name());
-    }
-
-    // simple test to at least cover some parts of the class
-    @Test
-    void testSimple() throws Exception {
-        // Decode the stream to bytes
-        byte[] bytes = RawDataUtil.decompress(recordData);
-        // Dump the contents of escher to stream.
-        dumper.dump(bytes, 0, bytes.length, stream);
-        assertEquals(216, countProperties());
-
-        baos.reset();
-        dumper.dump(0, new byte[0], stream);
-        assertEquals(0, countProperties());
-
-        baos.reset();
-        dumper.dump(new byte[0], 0, 0, stream);
-        assertEquals(0, countProperties());
-    }
-
-    @Test
-    void testWithData() {
-        dumper.dump(8, new byte[] {0, 0, 0, 0, 0, 0, 0, 0}, stream);
-        assertEquals(6, countProperties());
-    }
-
-    @Test
-    void testWithSamplefile() throws Exception {
-        //InputStream stream = HSSFTestDataSamples.openSampleFileStream(")
-        byte[] data = POIDataSamples.getDDFInstance().readFile("Container.dat");
-        dumper.dump(data.length, data, stream);
-        assertEquals(127, countProperties());
-
-        data = new byte[2586114];
-        try (InputStream is = HSSFTestDataSamples.openSampleFileStream("44593.xls")) {
-            int bytes = IOUtils.readFully(is, data);
-            assertNotEquals(-1, bytes);
-            dumper.dump(data, 0, bytes, stream);
-            assertEquals(163, countProperties());
-        }
-    }
-
-    @Test
-    void testCopy() throws Exception {
-        byte[] data1 = RawDataUtil.decompress(recordData);
-
-        EscherRecordFactory recordFactory = new DefaultEscherRecordFactory();
-        EscherRecord r = recordFactory.createRecord(data1, 0);
-        r.fillFields(data1, recordFactory);
-        EscherRecord r2 = r.copy();
-        byte[] data2 = r2.serialize();
-
-        assertArrayEquals(data1, data2);
-    }
-
-    private int countProperties() {
-        String data = new String(baos.toByteArray(), StandardCharsets.UTF_8);
-        Matcher matcher = Pattern.compile(",? \"[^\"]+\": ").matcher(data);
-        int count = 0;
-        while (matcher.find()) {
-            count++;
-        }
-        return count;
-    }
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherOptRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherOptRecord.java
deleted file mode 100644
index c09dc223c2..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherOptRecord.java
+++ /dev/null
@@ -1,320 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.IOException;
-
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-final class TestEscherOptRecord {
-
-    @Test
-    void testFillFields() {
-        checkFillFieldsSimple();
-        checkFillFieldsComplex();
-    }
-
-    private void checkFillFieldsComplex() {
-        String dataStr = "33 00 " +
-                "0B F0 " +
-                "14 00 00 00 " +
-                "BF 00 01 00 00 00 " +
-                "01 80 02 00 00 00 " +
-                "BF 00 01 00 00 00 " +
-                "01 02";
-
-        EscherOptRecord r = new EscherOptRecord();
-        r.fillFields( HexRead.readFromString( dataStr ), new DefaultEscherRecordFactory() );
-        assertEquals( (short) 0x0033, r.getOptions() );
-        assertEquals( (short) 0xF00B, r.getRecordId() );
-        assertEquals( 3, r.getEscherProperties().size() );
-        EscherBoolProperty prop1 = new EscherBoolProperty( EscherPropertyTypes.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 1 );
-        EscherComplexProperty prop2 = new EscherComplexProperty( EscherPropertyTypes.TEXT__SIZE_TEXT_TO_FIT_SHAPE, false, 2);
-        prop2.setComplexData(new byte[] { 0x01, 0x02 });
-        EscherBoolProperty prop3 = new EscherBoolProperty( EscherPropertyTypes.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 1 );
-        assertEquals( prop1, r.getEscherProperty( 0 ) );
-        assertEquals( prop2, r.getEscherProperty( 1 ) );
-        assertEquals( prop3, r.getEscherProperty( 2 ) );
-
-    }
-
-    private void checkFillFieldsSimple() {
-        String dataStr = "33 00 " + // options
-                        "0B F0 " + // recordid
-                        "12 00 00 00 " + // remaining bytes
-                        "BF 00 08 00 08 00 " +
-                        "81 01 09 00 00 08 " +
-                        "C0 01 40 00 00 08";
-
-        EscherOptRecord r = new EscherOptRecord();
-        r.fillFields( HexRead.readFromString( dataStr ), new DefaultEscherRecordFactory() );
-        assertEquals( (short) 0x0033, r.getOptions() );
-        assertEquals( (short) 0xF00B, r.getRecordId() );
-        assertEquals( 3, r.getEscherProperties().size() );
-        EscherBoolProperty prop1 = new EscherBoolProperty( EscherPropertyTypes.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 524296 );
-        EscherRGBProperty prop2 = new EscherRGBProperty( EscherPropertyTypes.FILL__FILLCOLOR, 0x08000009 );
-        EscherRGBProperty prop3 = new EscherRGBProperty( EscherPropertyTypes.LINESTYLE__COLOR, 0x08000040 );
-        assertEquals( prop1, r.getEscherProperty( 0 ) );
-        assertEquals( prop2, r.getEscherProperty( 1 ) );
-        assertEquals( prop3, r.getEscherProperty( 2 ) );
-    }
-
-    @Test
-    void testSerialize() {
-        checkSerializeSimple();
-        checkSerializeComplex();
-    }
-
-    private void checkSerializeComplex()
-    {
-        //Complex escher record
-        EscherOptRecord r = new EscherOptRecord();
-        r.setOptions( (short) 0x0033 );
-        r.setRecordId( (short) 0xF00B );
-        EscherBoolProperty prop1 = new EscherBoolProperty( EscherPropertyTypes.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 1 );
-        EscherComplexProperty prop2 = new EscherComplexProperty( EscherPropertyTypes.TEXT__SIZE_TEXT_TO_FIT_SHAPE, false, 2);
-        prop2.setComplexData(new byte[] { 0x01, 0x02 });
-        EscherBoolProperty prop3 = new EscherBoolProperty( EscherPropertyTypes.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 1 );
-        r.addEscherProperty( prop1 );
-        r.addEscherProperty( prop2 );
-        r.addEscherProperty( prop3 );
-
-        byte[] data = new byte[28];
-        int bytesWritten = r.serialize(0, data, new NullEscherSerializationListener() );
-        assertEquals( 28, bytesWritten );
-        String dataStr = "[33, 00, " +
-                "0B, F0, " +
-                "14, 00, 00, 00, " +
-                "BF, 00, 01, 00, 00, 00, " +
-                "BF, 80, 02, 00, 00, 00, " +
-                "BF, 00, 01, 00, 00, 00, " +
-                "01, 02]";
-        assertEquals( dataStr, HexDump.toHex(data) );
-
-    }
-
-    private void checkSerializeSimple()
-    {
-        EscherOptRecord r = new EscherOptRecord();
-        r.setOptions( (short) 0x0033 );
-        r.setRecordId( (short) 0xF00B );
-        EscherBoolProperty prop1 = new EscherBoolProperty( EscherPropertyTypes.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 1 );
-        EscherRGBProperty prop2 = new EscherRGBProperty( EscherPropertyTypes.FILL__FILLCOLOR, 0x08000009 );
-        EscherRGBProperty prop3 = new EscherRGBProperty( EscherPropertyTypes.LINESTYLE__COLOR, 0x08000040 );
-        r.addEscherProperty( prop1 );
-        r.addEscherProperty( prop2 );
-        r.addEscherProperty( prop3 );
-
-        byte[] data = new byte[26];
-        int bytesWritten = r.serialize(0, data, new NullEscherSerializationListener() );
-        String dataStr = "[33, 00, " +
-                "0B, F0, " +
-                "12, 00, 00, 00, " +
-                "BF, 00, 01, 00, 00, 00, " +
-                "81, 01, 09, 00, 00, 08, " +
-                "C0, 01, 40, 00, 00, 08]";
-        assertEquals( dataStr, HexDump.toHex(data) );
-        assertEquals( 26, bytesWritten );
-    }
-
-    @Test
-    void testToString() {
-        EscherOptRecord r = new EscherOptRecord();
-        // don't try to shoot in foot, please -- vlsergey
-        // r.setOptions((short)0x000F);
-        r.setRecordId(EscherOptRecord.RECORD_ID);
-        EscherProperty prop1 = new EscherBoolProperty(EscherPropertyTypes.GEOMETRY__FILLOK, 1);
-        r.addEscherProperty(prop1);
-        String expected =
-            "{   /* OPT */\n" +
-            "\t  \"recordId\": -4085 /* 0xf00b */\n" +
-            "\t, \"version\": 3\n" +
-            "\t, \"instance\": 1\n" +
-            "\t, \"options\": 19 /* 0x0013 */\n" +
-            "\t, \"recordSize\": 14 /* 0x0000000e */\n" +
-            "\t, \"isContainer\": false\n" +
-            "\t, \"properties\": [\n" +
-            "\t{   /* GEOMETRY__FILLOK */\n" +
-            "\t\t  \"id\": 383 /* 0x017f */\n" +
-            "\t\t, \"name\": \"geometry.fillok\"\n" +
-            "\t\t, \"propertyNumber\": 383 /* 0x017f */\n" +
-            "\t\t, \"propertySize\": 6\n" +
-            "\t\t, \"flags\": 383 /*  */ \n" +
-            "\t\t, \"value\": 1\n" +
-            "\t}\t]\n" +
-            "}";
-        expected = expected.replace("\n", System.getProperty("line.separator"));
-        assertEquals( expected, r.toString());
-    }
-
-    /**
-     * Test serialization of a particularly complex example
-     * This test is currently broken!
-     */
-    @Test
-    void testComplexSerialise() {
-    	byte[] data = {
-    		0x53, 0x01, 0x0B, 0xF0-256, 0x9C-256, 0x01, 0x00, 0x00,
-    		// Simple data follows
-    		0x42, 0x01,	0x49, 0x00, 0x00, 0x00,          // SP @ 8
-    		0x43, 0x01, 0x85-256, 0x00, 0x00, 0x00,      // SP @ 14
-    		0x44, 0x01, 0x04, 0x00, 0x00, 0x00,          // SP @ 20
-    		0x45, 0xC1-256, 0x88-256, 0x00, 0x00, 0x00,  // SP @ 26
-    		0x46, 0xC1-256, 0x90-256, 0x00, 0x00, 0x00,  // SP @ 32
-    		0x7F, 0x01, 0x01, 0x00, 0x01, 0x00,
-    		0x80-256, 0x01, 0x00, 0x00, 0x00, 0x00,
-    		0x81-256, 0x01, 0x02, 0x00, 0x00, 0x08,
-    		0xBF-256, 0x01,	0x10, 0x00, 0x10, 0x00,
-    		0xC0-256, 0x01, 0x01, 0x00, 0x00, 0x08,      // SP 10
-    		0xC1-256, 0x01, 0x00, 0x00, 0x01, 0x00,
-    		0xC4-256, 0x01, 0x00, 0x00, 0x00, 0x00,
-    		0xCB-256, 0x01, 0x38, 0x63, 0x00, 0x00,
-    		0xCD-256, 0x01, 0x00, 0x00,	0x00, 0x00,
-    		0xCE-256, 0x01, 0x00, 0x00, 0x00, 0x00,      // SP 15
-    		0xD0-256, 0x01, 0x00, 0x00, 0x00, 0x00,
-    		0xD1-256, 0x01, 0x00, 0x00, 0x00, 0x00,
-    		0xD7-256, 0x01, 0x00, 0x00, 0x00, 0x00,
-    		0xFF-256, 0x01, 0x18, 0x00, 0x18, 0x00,
-    		0x01, 0x02, 0x02, 0x00, 0x00, 0x08,
-    		0x3F, 0x02, 0x00, 0x00,	0x02, 0x00,          // SP 21
-
-    		// Complex data follows
-
-    		// Complex data for Array #325
-    		// Array header
-    		0x22, 0x00, 0x22, 0x00, 0xF0-256, 0xFF-256,
-    		// Array data
-    		0x18, 0x00, 0x28, 0x00, 0x04, 0x00, 0x34,
-    		0x00, 0x04, 0x00, 0x28, 0x00, 0x04, 0x00,
-    		0x1C, 0x00, 0x04, 0x00, 0x10, 0x00, 0x04, 0x00, 0x04, 0x00, 0x10,
-    		0x00, 0x00, 0x00, 0x1C, 0x00,
-    		0x04, 0x00, 0x28, 0x00, 0x10, 0x00, 0x34, 0x00, 0x18, 0x00, 0x3C,
-    		0x00, 0x24, 0x00, 0x44, 0x00,
-    		0x30, 0x00, 0x48, 0x00, 0x3C, 0x00, 0x44, 0x00, 0x48, 0x00, 0x3C,
-    		0x00, 0x54, 0x00, 0x38, 0x00,
-    		0x60, 0x00, 0x2C, 0x00, 0x70, 0x00, 0x20, 0x00, 0x78, 0x00,
-    		0x14, 0x00, 0x80-256, 0x00, 0x08, 0x00,
-    		0x84-256, 0x00, 0x04, 0x00, 0x78, 0x00, 0x04, 0x00, 0x6C, 0x00,
-    		0x04, 0x00, 0x60, 0x00, 0x04, 0x00,
-    		0x54, 0x00, 0x08, 0x00, 0x48, 0x00, 0x0C, 0x00, 0x3C, 0x00, 0x0C,
-    		0x00, 0x30, 0x00, 0x08, 0x00,
-    		0x3C, 0x00, 0x08, 0x00, 0x48, 0x00, 0x08, 0x00, 0x54, 0x00, 0x00,
-    		0x00, 0x48, 0x00, 0x00, 0x00,
-    		0x3C, 0x00, 0x00, 0x00, 0x30, 0x00, 0x04, 0x00, 0x24, 0x00,
-    		// Complex data for Array #326
-    		// Array header
-    		0x45, 0x00, 0x48, 0x00, 0x02, 0x00,
-    		// Array data
-    		0x00, 0x40, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
-    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
-    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
-    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
-    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
-    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
-    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
-    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
-    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
-    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
-    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
-    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
-    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
-    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
-    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
-    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
-    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x00, 0x80-256
-    	};
-
-    	// Create the record
-        EscherOptRecord r = new EscherOptRecord();
-        int filled = r.fillFields( data, new DefaultEscherRecordFactory() );
-
-        // Check it's the right length
-        assertEquals(data.length, filled);
-        assertEquals(data.length, r.getRecordSize());
-
-        // Serialize it
-        byte[] dest = new byte[data.length];
-        int written = r.serialize(0, dest);
-
-        // Check it serialised it back to the same data
-        assertEquals(data.length, written);
-        assertArrayEquals(data, dest);
-    }
-
-    /**
-     * Test read/write against an OPT record from a real ppt file.
-     * In PowerPoint it is legal to have array properties with empty complex part.
-     * In Glen's original implementation complex part is always 6 bytes which resulted
-     * in +6 extra bytes when writing back out. As the result the ppt becomes unreadable.
-     *
-     * Make sure we write back the original empty complex part.
-     *
-     * See Bug 41946 for details.
-     */
-    @Test
-    void test41946() throws IOException {
-        String data64 =
-            "H4sIAAAAAAAAAB3SuW5TQRjF8TPfOOZCHMeARAluEKIzSEgUSCQsLaLgDYCehgIJCe8L+xIgQB6"+
-            "AEvEAOI6zOwlhX54BpBRIiGqY+Vvy7x6d+3k8nmufje/ISzVVrjrVNftWapCb5JbSqyMX7ZJ72I"+
-            "/vSRXcH6k0kW6Wi1hNquZyUlaP2amRmqxJbjHTnmbNQbLLfA9v4x28i/fwPj7Ah/gIH+MTnMGn+"+
-            "Ayfs/4s+QW+xFc45+KPnuq7gg5q3sUqG7DDBRdC0JB9LjK5xG6XWW2FZhXXcB1H7sRhaSMto02a"+
-            "LXzPp745iwaXV1FKUc7iJTMbjUbyqSnnLH37mJ28LOVxF5MZ7ubuHvI4FmgmyEWctPSQSuS9eDr"+
-            "qVSXXmK/bWMwNmzsmNelbtvMvrza5Y3/jAl320zcXn+88/QAX7Ep0SF7EJVzGFVzFNVy3yvV4Mr"+
-            "a9b782rPL7V9i0qUs9bZmq8WSiIWzHyRvhgx2P8x+tfEH6ZBeH0mdW+GKlI9JXuzYTz9DenArhO"+
-            "/0P+p/0wQ7okHI+Hfe0f33U6YxPM2d9upzzN985nae55dM/tknTommTO+T/V9IPpAgDAAA=";
-
-        EscherOptRecord r = new EscherOptRecord();
-        byte[] data = RawDataUtil.decompress(data64);
-        r.fillFields( data, 0, new DefaultEscherRecordFactory() );
-        assertEquals( (short) 0xF00B, r.getRecordId() );
-
-        byte[] data1 = r.serialize();
-        EscherOptRecord opt2 = new EscherOptRecord();
-        opt2.fillFields( data1, new DefaultEscherRecordFactory() );
-
-        byte[] data2 = opt2.serialize();
-        assertArrayEquals(data1, data2);
-    }
-
-    /**
-     * Test that EscherOptRecord can properly read/write array properties
-     * with empty complex part.
-     */
-    @Test
-    void testEmptyArrayProperty() {
-        EscherOptRecord r = new EscherOptRecord();
-        EscherArrayProperty p = new EscherArrayProperty(EscherPropertyTypes.FILL__SHADECOLORS, false, 0);
-        assertEquals(0, p.getNumberOfElementsInArray());
-        r.addEscherProperty(p);
-
-        byte[] data1 = r.serialize();
-        EscherOptRecord opt2 = new EscherOptRecord();
-        opt2.fillFields( data1, new DefaultEscherRecordFactory() );
-        p = (EscherArrayProperty)opt2.getEscherProperties().get(0);
-        assertEquals(0, p.getNumberOfElementsInArray());
-
-        byte[] data2 = opt2.serialize();
-        assertArrayEquals(data1, data2);
-    }
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherProperty.java b/src/testcases/org/apache/poi/ddf/TestEscherProperty.java
deleted file mode 100644
index 99f508224f..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherProperty.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import org.junit.jupiter.api.Test;
-
-
-class TestEscherProperty {
-    /**
-     * assure that EscherProperty.getName() returns correct name for complex properties
-     * See Bugzilla 50401
-     */
-    @Test
-    void testPropertyNames() throws Exception {
-        EscherProperty p1 = new EscherSimpleProperty( EscherPropertyTypes.GROUPSHAPE__SHAPENAME, 0);
-        assertEquals("groupshape.shapename", p1.getName());
-        assertEquals(EscherPropertyTypes.GROUPSHAPE__SHAPENAME.propNumber, p1.getPropertyNumber());
-        assertFalse(p1.isComplex());
-
-        EscherComplexProperty p2 = new EscherComplexProperty(
-                EscherPropertyTypes.GROUPSHAPE__SHAPENAME, false, 10);
-        p2.setComplexData(new byte[10]);
-        assertEquals("groupshape.shapename", p2.getName());
-        assertEquals(EscherPropertyTypes.GROUPSHAPE__SHAPENAME.propNumber, p2.getPropertyNumber());
-        assertTrue(p2.isComplex());
-        assertFalse(p2.isBlipId());
-
-        EscherComplexProperty p3 = new EscherComplexProperty(
-                EscherPropertyTypes.GROUPSHAPE__SHAPENAME, true, 10);
-        p2.setComplexData(new byte[10]);
-        assertEquals("groupshape.shapename", p3.getName());
-        assertEquals(EscherPropertyTypes.GROUPSHAPE__SHAPENAME.propNumber, p3.getPropertyNumber());
-        assertTrue(p3.isComplex());
-        assertTrue(p3.isBlipId());
-    }
-}
\ No newline at end of file
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherPropertyFactory.java b/src/testcases/org/apache/poi/ddf/TestEscherPropertyFactory.java
deleted file mode 100644
index ec94ba15d4..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherPropertyFactory.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.util.List;
-
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-class TestEscherPropertyFactory {
-    @Test
-    void testCreateProperties() {
-        String dataStr = "41 C1 " +     // propid, complex ind
-                "03 00 00 00 " +         // size of complex property
-                "01 00 " +              // propid, complex ind
-                "00 00 00 00 " +         // value
-                "41 C1 " +              // propid, complex ind
-                "03 00 00 00 " +         // size of complex property
-                "01 02 03 " +
-                "01 02 03 "
-                ;
-        byte[] data = HexRead.readFromString( dataStr );
-        EscherPropertyFactory f = new EscherPropertyFactory();
-        List props = f.createProperties( data, 0, (short)3 );
-        EscherComplexProperty p1 = (EscherComplexProperty) props.get( 0 );
-        assertEquals( (short)0xC141, p1.getId() );
-        assertEquals( "[01, 02, 03]", HexDump.toHex( p1.getComplexData() ) );
-
-        EscherComplexProperty p3 = (EscherComplexProperty) props.get( 2 );
-        assertEquals( (short)0xC141, p3.getId() );
-        assertEquals( "[01, 02, 03]", HexDump.toHex( p3.getComplexData() ) );
-    }
-}
-
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherSpRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherSpRecord.java
deleted file mode 100644
index 4e18b641d3..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherSpRecord.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-class TestEscherSpRecord {
-    @Test
-    void testSerialize() {
-        EscherSpRecord r = createRecord();
-
-        byte[] data = new byte[16];
-        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
-        assertEquals( 16, bytesWritten );
-        assertEquals( "[02, 00, " +
-                "0A, F0, " +
-                "08, 00, 00, 00, " +
-                "00, 04, 00, 00, " +
-                "05, 00, 00, 00]",
-                HexDump.toHex( data ) );
-    }
-
-    @Test
-    void testFillFields() {
-        String hexData = "02 00 " +
-                "0A F0 " +
-                "08 00 00 00 " +
-                "00 04 00 00 " +
-                "05 00 00 00 ";
-        byte[] data = HexRead.readFromString( hexData );
-        EscherSpRecord r = new EscherSpRecord();
-        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
-
-        assertEquals( 16, bytesWritten );
-        assertEquals( 0x0400, r.getShapeId() );
-        assertEquals( 0x05, r.getFlags() );
-    }
-
-    @Test
-    void testToString() {
-        String expected =
-            "{   /* SP */\n" +
-            "\t  \"recordId\": -4086 /* 0xf00a */\n" +
-            "\t, \"version\": 2\n" +
-            "\t, \"instance\": 0\n" +
-            "\t, \"options\": 2\n" +
-            "\t, \"recordSize\": 16 /* 0x00000010 */\n" +
-            "\t, \"shapeType\": 0\n" +
-            "\t, \"shapeId\": 1024 /* 0x00000400 */\n" +
-            "\t, \"flags\": 5 /* GROUP | PATRIARCH */ \n" +
-            "}";
-        expected = expected.replace("\n", System.getProperty("line.separator"));
-        assertEquals( expected, createRecord().toString() );
-    }
-
-    private static EscherSpRecord createRecord()
-    {
-        EscherSpRecord r = new EscherSpRecord();
-        r.setOptions( (short) 0x0002 );
-        r.setRecordId( EscherSpRecord.RECORD_ID );
-        r.setShapeId(0x0400);
-        r.setFlags(0x05);
-        return r;
-    }
-
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherSpgrRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherSpgrRecord.java
deleted file mode 100644
index 8aa7aa86d9..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherSpgrRecord.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-final class TestEscherSpgrRecord {
-    @Test
-    void testSerialize() {
-        EscherSpgrRecord r = createRecord();
-
-        byte[] data = new byte[24];
-        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
-        assertEquals( 24, bytesWritten );
-        assertEquals( "[10, 00, " +
-                "09, F0, " +
-                "10, 00, 00, 00, " +
-                "01, 00, 00, 00, " +     // x
-                "02, 00, 00, 00, " +     // y
-                "03, 00, 00, 00, " +     // width
-                "04, 00, 00, 00]",     // height
-                HexDump.toHex( data ) );
-    }
-
-    @Test
-    void testFillFields() {
-        String hexData = "10 00 " +
-                "09 F0 " +
-                "10 00 00 00 " +
-                "01 00 00 00 " +
-                "02 00 00 00 " +
-                "03 00 00 00 " +
-                "04 00 00 00 ";
-        byte[] data = HexRead.readFromString( hexData );
-        EscherSpgrRecord r = new EscherSpgrRecord();
-        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
-
-        assertEquals( 24, bytesWritten );
-        assertEquals( 1, r.getRectX1() );
-        assertEquals( 2, r.getRectY1() );
-        assertEquals( 3, r.getRectX2() );
-        assertEquals( 4, r.getRectY2() );
-    }
-
-    @Test
-    void testToString() {
-        String expected =
-            "{   /* SPGR */\n" +
-            "\t  \"recordId\": -4087 /* 0xf009 */\n" +
-            "\t, \"version\": 0\n" +
-            "\t, \"instance\": 1\n" +
-            "\t, \"options\": 16 /* 0x0010 */\n" +
-            "\t, \"recordSize\": 24 /* 0x00000018 */\n" +
-            "\t, \"rectX1\": 1\n" +
-            "\t, \"rectY1\": 2\n" +
-            "\t, \"rectX2\": 3\n" +
-            "\t, \"rectY2\": 4\n" +
-            "}";
-        expected = expected.replace("\n", System.getProperty("line.separator"));
-        assertEquals( expected, createRecord().toString() );
-    }
-
-    private static EscherSpgrRecord createRecord()
-    {
-        EscherSpgrRecord r = new EscherSpgrRecord();
-        r.setOptions( (short) 0x0010 );
-        r.setRecordId( EscherSpgrRecord.RECORD_ID );
-        r.setRectX1(1);
-        r.setRectY1(2);
-        r.setRectX2(3);
-        r.setRectY2(4);
-        return r;
-    }
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestEscherSplitMenuColorsRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherSplitMenuColorsRecord.java
deleted file mode 100644
index 1aa96edc5c..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestEscherSplitMenuColorsRecord.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-final class TestEscherSplitMenuColorsRecord {
-    @Test
-    void testSerialize() {
-        EscherSplitMenuColorsRecord r = createRecord();
-
-        byte[] data = new byte[24];
-        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
-        assertEquals( 24, bytesWritten );
-        assertEquals( "[40, 00, " +
-                "1E, F1, " +
-                "10, 00, 00, 00, " +
-                "02, 04, 00, 00, " +
-                "02, 00, 00, 00, " +
-                "02, 00, 00, 00, " +
-                "01, 00, 00, 00]",
-                HexDump.toHex( data ) );
-    }
-
-    @Test
-    void testFillFields() {
-        String hexData = "40 00 " +
-                "1E F1 " +
-                "10 00 00 00 " +
-                "02 04 00 00 " +
-                "02 00 00 00 " +
-                "02 00 00 00 " +
-                "01 00 00 00 ";
-        byte[] data = HexRead.readFromString( hexData );
-        EscherSplitMenuColorsRecord r = new EscherSplitMenuColorsRecord();
-        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
-
-        assertEquals( 24, bytesWritten );
-        assertEquals( 0x0402, r.getColor1() );
-        assertEquals( 0x02, r.getColor2() );
-        assertEquals( 0x02, r.getColor3() );
-        assertEquals( 0x01, r.getColor4() );
-    }
-
-    @Test
-    void testToString() {
-        String expected =
-            "{   /* SPLIT_MENU_COLORS */\n" +
-            "\t  \"recordId\": -3810 /* 0xf11e */\n" +
-            "\t, \"version\": 0\n" +
-            "\t, \"instance\": 4\n" +
-            "\t, \"options\": 64 /* 0x0040 */\n" +
-            "\t, \"recordSize\": 24 /* 0x00000018 */\n" +
-            "\t, \"color1\": 1026 /* 0x00000402 */\n" +
-            "\t, \"color2\": 2\n" +
-            "\t, \"color3\": 2\n" +
-            "\t, \"color4\": 1\n" +
-            "}";
-        expected = expected.replace("\n", System.getProperty("line.separator"));
-        assertEquals( expected, createRecord().toString() );
-    }
-
-    private static EscherSplitMenuColorsRecord createRecord()
-    {
-        EscherSplitMenuColorsRecord r = new EscherSplitMenuColorsRecord();
-        r.setOptions( (short) 0x0040 );
-        r.setRecordId( EscherSplitMenuColorsRecord.RECORD_ID );
-        r.setColor1( 0x402  );
-        r.setColor2( 0x2 );
-        r.setColor3( 0x2 );
-        r.setColor4( 0x1 );
-        return r;
-    }
-}
diff --git a/src/testcases/org/apache/poi/ddf/TestUnknownEscherRecord.java b/src/testcases/org/apache/poi/ddf/TestUnknownEscherRecord.java
deleted file mode 100644
index d84f8bccee..0000000000
--- a/src/testcases/org/apache/poi/ddf/TestUnknownEscherRecord.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/* ====================================================================
-   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.ddf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-final class TestUnknownEscherRecord {
-    @Test
-    void testFillFields() {
-        String testData =
-                "0F 02 " + // options
-                "11 F1 " + // record id
-                "00 00 00 00";      // remaining bytes
-
-        UnknownEscherRecord r = new UnknownEscherRecord();
-        EscherRecordFactory factory = new DefaultEscherRecordFactory();
-        r.fillFields( HexRead.readFromString( testData ), factory );
-
-        assertEquals( 0x020F, r.getOptions() );
-        assertEquals( (short) 0xF111, r.getRecordId() );
-        assertTrue( r.isContainerRecord() );
-        assertEquals( 8, r.getRecordSize() );
-        assertEquals( 0, r.getChildRecords().size() );
-        assertEquals( 0, r.getData().length );
-
-        testData =
-                "00 02 " + // options
-                "11 F1 " + // record id
-                "04 00 00 00 " + // remaining bytes
-                "01 02 03 04";
-
-        r = new UnknownEscherRecord();
-        r.fillFields( HexRead.readFromString( testData ), factory );
-
-        assertEquals( 0x0200, r.getOptions() );
-        assertEquals( (short) 0xF111, r.getRecordId() );
-        assertEquals( 12, r.getRecordSize() );
-        assertFalse( r.isContainerRecord() );
-        assertEquals( 0, r.getChildRecords().size() );
-        assertEquals( 4, r.getData().length );
-        assertEquals( 1, r.getData()[0] );
-        assertEquals( 2, r.getData()[1] );
-        assertEquals( 3, r.getData()[2] );
-        assertEquals( 4, r.getData()[3] );
-
-        testData =
-                "0F 02 " + // options
-                "11 F1 " + // record id
-                "08 00 00 00 " + // remaining bytes
-                "00 02 " + // options
-                "FF FF " + // record id
-                "00 00 00 00";      // remaining bytes
-
-        r = new UnknownEscherRecord();
-        r.fillFields( HexRead.readFromString( testData ), factory );
-
-        assertEquals( 0x020F, r.getOptions() );
-        assertEquals( (short) 0xF111, r.getRecordId() );
-        assertEquals( 8, r.getRecordSize() );
-        assertTrue( r.isContainerRecord() );
-        assertEquals( 1, r.getChildRecords().size() );
-        assertEquals( (short) 0xFFFF, r.getChild( 0 ).getRecordId() );
-
-        //Add by Zhang Zhang test error situation when remaining bytes > avalible bytes
-        testData =
-            "00 02 " + // options
-            "11 F1 " + // record id
-            "05 00 00 00 " + // remaining bytes
-            "01 02 03 04";
-
-	    r = new UnknownEscherRecord();
-	    r.fillFields( HexRead.readFromString( testData ), factory );
-
-	    assertEquals( 0x0200, r.getOptions() );
-	    assertEquals( (short) 0xF111, r.getRecordId() );
-	    assertEquals( 12, r.getRecordSize() );
-	    assertFalse( r.isContainerRecord() );
-	    assertEquals( 0, r.getChildRecords().size() );
-	    assertEquals( 4, r.getData().length );
-	    assertEquals( 1, r.getData()[0] );
-	    assertEquals( 2, r.getData()[1] );
-	    assertEquals( 3, r.getData()[2] );
-	    assertEquals( 4, r.getData()[3] );
-
-        testData =
-            "0F 02 " + // options
-            "11 F1 " + // record id
-            "09 00 00 00 " + // remaining bytes
-            "00 02 " + // options
-            "FF FF " + // record id
-            "00 00 00 00";      // remaining bytes
-
-	    r = new UnknownEscherRecord();
-	    r.fillFields( HexRead.readFromString( testData ), factory );
-
-	    assertEquals( 0x020F, r.getOptions() );
-	    assertEquals( (short) 0xF111, r.getRecordId() );
-	    assertEquals( 8, r.getRecordSize() );
-	    assertTrue( r.isContainerRecord() );
-	    assertEquals( 1, r.getChildRecords().size() );
-	    assertEquals( (short) 0xFFFF, r.getChild( 0 ).getRecordId() );
-    }
-
-    @Test
-    void testSerialize() {
-        UnknownEscherRecord r = new UnknownEscherRecord();
-        r.setOptions( (short) 0x1234 );
-        r.setRecordId( (short) 0xF112 );
-        byte[] data = new byte[8];
-        r.serialize( 0, data, new NullEscherSerializationListener() );
-
-        assertEquals( "[34, 12, 12, F1, 00, 00, 00, 00]", HexDump.toHex( data ) );
-
-        EscherRecord childRecord = new UnknownEscherRecord();
-        childRecord.setOptions( (short) 0x9999 );
-        childRecord.setRecordId( (short) 0xFF01 );
-        r.addChildRecord( childRecord );
-        r.setOptions( (short) 0x123F );
-        data = new byte[16];
-        r.serialize( 0, data, new NullEscherSerializationListener() );
-
-        assertEquals( "[3F, 12, 12, F1, 08, 00, 00, 00, 99, 99, 01, FF, 00, 00, 00, 00]", HexDump.toHex( data ) );
-    }
-
-    @Test
-    void testToString() {
-        UnknownEscherRecord r = new UnknownEscherRecord();
-        r.setOptions( (short) 0x1234 );
-        r.setRecordId( (short) 0xF112 );
-        byte[] data = new byte[8];
-        r.serialize( 0, data, new NullEscherSerializationListener() );
-        String expected =
-            "{   /* UNKNOWN */\n" +
-            "\t  \"recordId\": -3822 /* 0xf112 */\n" +
-            "\t, \"version\": 4\n" +
-            "\t, \"instance\": 291 /* 0x0123 */\n" +
-            "\t, \"options\": 4660 /* 0x1234 */\n" +
-            "\t, \"recordSize\": 8\n" +
-            "\t, \"data\": \"\"\n" +
-            "}";
-        expected = expected.replace("\n", System.getProperty("line.separator"));
-        assertEquals(expected, r.toString() );
-    }
-}
diff --git a/src/testcases/org/apache/poi/hpsf/TestVariantSupport.java b/src/testcases/org/apache/poi/hpsf/TestVariantSupport.java
deleted file mode 100644
index 1cea118353..0000000000
--- a/src/testcases/org/apache/poi/hpsf/TestVariantSupport.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- *  ====================================================================
- *    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.hpsf;
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.math.BigInteger;
-
-import org.apache.poi.hpsf.wellknown.PropertyIDMap;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.apache.poi.util.LittleEndianByteArrayInputStream;
-import org.junit.jupiter.api.Test;
-
-class TestVariantSupport {
-    @Test
-    void test52337() throws Exception {
-        // document summary stream   from test1-excel.doc attached to Bugzilla 52337
-        String documentSummaryEnc =
-            "H4sIAAAAAAAAAG2RsUvDQBjFXxsraiuNKDoI8ZwclIJOjhYCGpQitINbzXChgTQtyQ3+Hw52cHB0E"+
-            "kdHRxfBpeAf4H/g5KK+M59Firn8eNx3d+++x31+AZVSGdOfrZTHz+Prxrp7eTWH7Z2PO5+1ylTtrA"+
-            "SskBrXKOiROhnavWREZskNWSK3ZI3ckyp5IC55JMvkiaySF7JIXlF4v0tPbzOAR1XE18MwM32dGjW"+
-            "IVJAanaVhoppRFMZZDjjSgyO9WT10Cq1vVX/uh/Txn3pucc7m6fTiXPEPldG5Qc0t2vEkXic2iZ5c"+
-            "JDkd8VFS3pcMBzIvS7buaeB3j06C1nF7krFJPRdz62M4rM7/8f3NtyE+LQyQoY8QCfbQwAU1l/UF0"+
-            "ubraA6DXWzC5x7gG6xzLtsAAgAA";
-        byte[] bytes = RawDataUtil.decompress(documentSummaryEnc);
-
-        PropertySet ps = PropertySetFactory.create(new ByteArrayInputStream(bytes));
-        DocumentSummaryInformation dsi = (DocumentSummaryInformation) ps;
-        Section s = dsi.getSections().get(0);
-
-        Object hdrs =  s.getProperty(PropertyIDMap.PID_HEADINGPAIR);
-        assertNotNull(hdrs);
-        assertEquals(byte[].class, hdrs.getClass());
-
-        // parse the value
-        Vector v = new Vector((short)Variant.VT_VARIANT);
-        LittleEndianByteArrayInputStream lei = new LittleEndianByteArrayInputStream((byte[])hdrs, 0);
-        v.read(lei);
-
-        TypedPropertyValue[] items = v.getValues();
-        assertEquals(2, items.length);
-
-        Object cp = items[0].getValue();
-        assertNotNull(cp);
-        assertEquals(CodePageString.class, cp.getClass());
-        Object i = items[1].getValue();
-        assertNotNull(i);
-        assertEquals(Integer.class, i.getClass());
-        assertEquals(1, i);
-
-    }
-
-    @Test
-    void newNumberTypes() throws Exception {
-        ClipboardData cd = new ClipboardData();
-        cd.setValue(new byte[10]);
-
-        Object[][] exp = {
-                {Variant.VT_CF, cd.toByteArray()},
-                {Variant.VT_BOOL, true},
-                {Variant.VT_LPSTR, "codepagestring"},
-                {Variant.VT_LPWSTR, "widestring"},
-                {Variant.VT_I2, -1}, // int, not short ... :(
-                {Variant.VT_UI2, 0xFFFF},
-                {Variant.VT_I4, -1},
-                {Variant.VT_UI4, 0xFFFFFFFFL},
-                {Variant.VT_I8, -1L},
-                {Variant.VT_UI8, BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.TEN)},
-                {Variant.VT_R4, -999.99f},
-                {Variant.VT_R8, -999.99d},
-        };
-
-        POIFSFileSystem poifs = new POIFSFileSystem();
-        DocumentSummaryInformation dsi = PropertySetFactory.newDocumentSummaryInformation();
-        CustomProperties cpList = new CustomProperties();
-        for (Object[] o : exp) {
-            int type = (Integer)o[0];
-            Property p = new Property(PropertyIDMap.PID_MAX+type, type, o[1]);
-            cpList.put("testprop"+type, new CustomProperty(p, "testprop"+type));
-
-        }
-        dsi.setCustomProperties(cpList);
-        dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        poifs.writeFilesystem(bos);
-        poifs.close();
-        poifs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
-        dsi = (DocumentSummaryInformation)PropertySetFactory.create(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
-        assertNotNull(dsi);
-        cpList = dsi.getCustomProperties();
-        int i=0;
-        for (Object[] o : exp) {
-            Object obj = cpList.get("testprop"+o[0]);
-            if (o[1] instanceof byte[]) {
-                assertArrayEquals((byte[])o[1], (byte[])obj, "property "+i);
-            } else {
-                assertEquals(o[1], obj, "property "+i);
-            }
-            i++;
-        }
-        poifs.close();
-    }
-}
diff --git a/src/testcases/org/apache/poi/hpsf/basic/POIFile.java b/src/testcases/org/apache/poi/hpsf/basic/POIFile.java
deleted file mode 100644
index 1420e35bab..0000000000
--- a/src/testcases/org/apache/poi/hpsf/basic/POIFile.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/* ====================================================================
-   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.hpsf.basic;
-
-import org.apache.poi.poifs.filesystem.POIFSDocumentPath;
-
-/**
- * 

A POI file just for testing.

- */ -public class POIFile -{ - - private String name; - private POIFSDocumentPath path; - private byte[] bytes; - - - /** - *

Sets the POI file's name.

- * - * @param name The POI file's name. - */ - void setName(final String name) - { - this.name = name; - } - - /** - *

Returns the POI file's name.

- * - * @return The POI file's name. - */ - public String getName() - { - return name; - } - - /** - *

Sets the POI file's path.

- * - * @param path The POI file's path. - */ - void setPath(final POIFSDocumentPath path) - { - this.path = path; - } - - /** - *

Returns the POI file's path.

- * - * @return The POI file's path. - */ - public POIFSDocumentPath getPath() - { - return path; - } - - /** - *

Sets the POI file's content bytes.

- * - * @param bytes The POI file's content bytes. - */ - void setBytes(final byte[] bytes) - { - this.bytes = bytes; - } - - /** - *

Returns the POI file's content bytes.

- * - * @return The POI file's content bytes. - */ - public byte[] getBytes() - { - return bytes; - } - -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestBasic.java b/src/testcases/org/apache/poi/hpsf/basic/TestBasic.java deleted file mode 100644 index 6d95b38450..0000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestBasic.java +++ /dev/null @@ -1,206 +0,0 @@ -/* ==================================================================== - 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.hpsf.basic; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.Date; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.ClassID; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.Filetime; -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.Section; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.wellknown.PropertyIDMap; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - *

Tests the basic HPSF functionality.

- */ -final class TestBasic { - - private static final POIDataSamples samples = POIDataSamples.getHPSFInstance(); - - private static final String[] POI_FILES = { - SummaryInformation.DEFAULT_STREAM_NAME, - DocumentSummaryInformation.DEFAULT_STREAM_NAME, - "WordDocument", - "\001CompObj", - "1Table" - }; - private static final int BYTE_ORDER = 0xfffe; - private static final int FORMAT = 0x0000; - private static final int OS_VERSION = 0x00020A04; - private static final ClassID CLASS_ID = new ClassID("{00000000-0000-0000-0000-000000000000}"); - private static final int[] SECTION_COUNT = {1, 2}; - private static final boolean[] IS_SUMMARY_INFORMATION = {true, false}; - private static final boolean[] IS_DOCUMENT_SUMMARY_INFORMATION = {false, true}; - - private List poiFiles; - - - /** - *

Read a the test file from the "data" directory.

- * - * @exception FileNotFoundException if the file to be read does not exist. - * @exception IOException if any other I/O exception occurs. - */ - @BeforeEach - void setUp() throws IOException { - final File data = samples.getFile("TestGermanWord90.doc"); - poiFiles = Util.readPOIFiles(data); - } - - /** - *

Checks the names of the files in the POI filesystem. They - * are expected to be in a certain order.

- */ - @Test - void testReadFiles() { - String[] expected = POI_FILES; - for (int i = 0; i < expected.length; i++) { - assertEquals(poiFiles.get(i).getName(), expected[i]); - } - } - - /** - *

Tests whether property sets can be created from the POI - * files in the POI file system. This test case expects the first - * file to be a {@link SummaryInformation}, the second file to be - * a {@link DocumentSummaryInformation} and the rest to be no - * property sets. In the latter cases a {@link - * NoPropertySetStreamException} will be thrown when trying to - * create a {@link PropertySet}.

- * - * @exception IOException if an I/O exception occurs. - * - * @exception UnsupportedEncodingException if a character encoding is not - * supported. - */ - @Test - void testCreatePropertySets() - throws UnsupportedEncodingException, IOException { - Class[] expected = { - SummaryInformation.class, - DocumentSummaryInformation.class, - NoPropertySetStreamException.class, - NoPropertySetStreamException.class, - NoPropertySetStreamException.class - }; - for (int i = 0; i < expected.length; i++) { - InputStream in = new ByteArrayInputStream(poiFiles.get(i).getBytes()); - Object o; - try { - o = PropertySetFactory.create(in); - } catch (NoPropertySetStreamException | MarkUnsupportedException ex) { - o = ex; - } - in.close(); - assertEquals(expected[i], o.getClass()); - } - } - - /** - *

Tests the {@link PropertySet} methods. The test file has two - * property sets: the first one is a {@link SummaryInformation}, - * the second one is a {@link DocumentSummaryInformation}.

- * - * @exception IOException if an I/O exception occurs - * @exception HPSFException if any HPSF exception occurs - */ - @Test - void testPropertySetMethods() throws IOException, HPSFException { - /* Loop over the two property sets. */ - for (int i = 0; i < 2; i++) { - byte[] b = poiFiles.get(i).getBytes(); - PropertySet ps = PropertySetFactory.create(new ByteArrayInputStream(b)); - assertEquals(BYTE_ORDER, ps.getByteOrder()); - assertEquals(FORMAT, ps.getFormat()); - assertEquals(OS_VERSION, ps.getOSVersion()); - assertEquals(CLASS_ID, ps.getClassID()); - assertEquals(SECTION_COUNT[i], ps.getSectionCount()); - assertEquals(IS_SUMMARY_INFORMATION[i], ps.isSummaryInformation()); - assertEquals(IS_DOCUMENT_SUMMARY_INFORMATION[i], ps.isDocumentSummaryInformation()); - } - } - - /** - *

Tests the {@link Section} methods. The test file has two - * property sets: the first one is a {@link SummaryInformation}, - * the second one is a {@link DocumentSummaryInformation}.

- * - * @exception IOException if an I/O exception occurs - * @exception HPSFException if any HPSF exception occurs - */ - @Test - void testSectionMethods() throws IOException, HPSFException { - InputStream is = new ByteArrayInputStream(poiFiles.get(0).getBytes()); - final SummaryInformation si = (SummaryInformation)PropertySetFactory.create(is); - final List
sections = si.getSections(); - final Section s = sections.get(0); - assertEquals(s.getFormatID(), SummaryInformation.FORMAT_ID); - assertNotNull(s.getProperties()); - assertEquals(17, s.getPropertyCount()); - assertEquals("Titel", s.getProperty(PropertyIDMap.PID_TITLE)); - assertEquals(1764, s.getSize()); - } - - @Test - void bug52117LastPrinted() throws IOException, HPSFException { - File f = samples.getFile("TestBug52117.doc"); - POIFile poiFile = Util.readPOIFiles(f, new String[]{POI_FILES[0]}).get(0); - InputStream in = new ByteArrayInputStream(poiFile.getBytes()); - SummaryInformation si = (SummaryInformation)PropertySetFactory.create(in); - Date lastPrinted = si.getLastPrinted(); - long editTime = si.getEditTime(); - assertTrue(Filetime.isUndefined(lastPrinted)); - assertEquals(1800000000L, editTime); - } - - @Test - void bug61809() throws IOException, HPSFException { - InputStream is_si = new ByteArrayInputStream(poiFiles.get(0).getBytes()); - final SummaryInformation si = (SummaryInformation)PropertySetFactory.create(is_si); - final Section s_si = si.getSections().get(0); - - assertEquals("PID_TITLE", s_si.getPIDString(PropertyIDMap.PID_TITLE)); - assertEquals(PropertyIDMap.UNDEFINED, s_si.getPIDString(4711)); - - InputStream is_dsi = new ByteArrayInputStream(poiFiles.get(1).getBytes()); - final DocumentSummaryInformation dsi = (DocumentSummaryInformation)PropertySetFactory.create(is_dsi); - final Section s_dsi = dsi.getSections().get(0); - - assertEquals("PID_MANAGER", s_dsi.getPIDString(PropertyIDMap.PID_MANAGER)); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestClassID.java b/src/testcases/org/apache/poi/hpsf/basic/TestClassID.java deleted file mode 100644 index ac50ec591d..0000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestClassID.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - 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.hpsf.basic; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.Locale; - -import org.apache.poi.hpsf.ClassID; -import org.apache.poi.hpsf.ClassIDPredefined; -import org.junit.jupiter.api.Test; - -/** - * Tests ClassID structure. - */ -final class TestClassID { - - private static final byte[] BUF16 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; - - /** - * Various tests of overridden .equals() - */ - @Test - void testEquals() { - ClassID clsidTest1 = new ClassID(BUF16, 0); - ClassID clsidTest2 = new ClassID(BUF16, 0); - byte[] buf2 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,17}; - ClassID clsidTest3 = new ClassID(buf2, 0); - assertEquals(clsidTest1, clsidTest1); - assertEquals(clsidTest1, clsidTest2); - assertNotEquals(clsidTest1, clsidTest3); - assertNotEquals(null, clsidTest1); - } - - /** - * Try to write to a buffer that is too small. This should - * throw an Exception - */ - @Test - void testWriteArrayStoreException1() { - assertThrows(ArrayStoreException.class, () -> new ClassID(BUF16, 0).write(new byte[15], 0)); - } - - @Test - void testWriteArrayStoreException2() { - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ClassID(BUF16, 0).write(new byte[16], 1)); - } - - @Test - void testWriteArrayStoreException3() { - ClassID clsidTest = new ClassID(BUF16, 0); - assertDoesNotThrow(() -> clsidTest.write(new byte[16], 0)); - assertDoesNotThrow(() -> clsidTest.write(new byte[17], 1)); - } - - @Test - void testClassID() { - ClassID clsidTest = new ClassID(BUF16, 0); - assertEquals("{04030201-0605-0807-090A-0B0C0D0E0F10}", clsidTest.toString()); - } - - @Test - void checkUUIDConversion() { - String exp = "EABCECDB-CC1C-4A6F-B4E3-7F888A5ADFC8"; - ClassID clsId = ClassIDPredefined.EXCEL_V14_ODS.getClassID(); - assertEquals(exp, clsId.toUUIDString()); - assertEquals(exp, clsId.toUUID().toString().toUpperCase(Locale.ROOT)); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java b/src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java deleted file mode 100644 index 9ef1289461..0000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java +++ /dev/null @@ -1,155 +0,0 @@ -/* ==================================================================== - 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.hpsf.basic; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.Variant; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Test case for OLE2 files with empty properties. - * An empty property's type is {@link Variant#VT_EMPTY}. - */ -final class TestEmptyProperties { - - private static final POIDataSamples samples = POIDataSamples.getHPSFInstance(); - - /** - * This test file's summary information stream contains some empty properties. - */ - private static final String POI_FS = "TestCorel.shw"; - - private static final String[] POI_FILES = { - "PerfectOffice_MAIN", - SummaryInformation.DEFAULT_STREAM_NAME, - "Main" - }; - - private List poiFiles; - - /** - *

Read a the test file from the "data" directory.

- * - * @exception FileNotFoundException if the file containing the test data - * does not exist - * @exception IOException if an I/O exception occurs - */ - @BeforeEach - void setUp() throws IOException { - final File data = samples.getFile(POI_FS); - poiFiles = Util.readPOIFiles(data); - } - - /** - * Checks the names of the files in the POI filesystem. They - * are expected to be in a certain order. - */ - @Test - void testReadFiles() { - String[] expected = POI_FILES; - for (int i = 0; i < expected.length; i++) - assertEquals(poiFiles.get(i).getName(), expected[i]); - } - - /** - *

Tests whether property sets can be created from the POI - * files in the POI file system. This test case expects the first - * file to be a {@link SummaryInformation}, the second file to be - * a {@link DocumentSummaryInformation} and the rest to be no - * property sets. In the latter cases a {@link - * NoPropertySetStreamException} will be thrown when trying to - * create a {@link PropertySet}.

- * - * @exception IOException if an I/O exception occurs. - * - * @exception UnsupportedEncodingException if a character encoding is not - * supported. - */ - @Test - void testCreatePropertySets() - throws UnsupportedEncodingException, IOException { - Class[] expected = { - NoPropertySetStreamException.class, - SummaryInformation.class, - NoPropertySetStreamException.class - }; - for (int i = 0; i < expected.length; i++) { - InputStream in = new ByteArrayInputStream(poiFiles.get(i).getBytes()); - Object o; - try { - o = PropertySetFactory.create(in); - } catch (NoPropertySetStreamException | MarkUnsupportedException ex) { - o = ex; - } - in.close(); - assertEquals(o.getClass(), expected[i]); - } - } - - /** - *

Tests the {@link PropertySet} methods. The test file has two - * property sets: the first one is a {@link SummaryInformation}, - * the second one is a {@link DocumentSummaryInformation}.

- * - * @exception IOException if an I/O exception occurs - * @exception HPSFException if an HPSF operation fails - */ - @Test - void testPropertySetMethods() throws IOException, HPSFException { - byte[] b = poiFiles.get(1).getBytes(); - PropertySet ps = PropertySetFactory.create(new ByteArrayInputStream(b)); - SummaryInformation s = (SummaryInformation) ps; - assertNull(s.getTitle()); - assertNull(s.getSubject()); - assertNotNull(s.getAuthor()); - assertNull(s.getKeywords()); - assertNull(s.getComments()); - assertNotNull(s.getTemplate()); - assertNotNull(s.getLastAuthor()); - assertNotNull(s.getRevNumber()); - assertEquals(s.getEditTime(), 0); - assertNull(s.getLastPrinted()); - assertNull(s.getCreateDateTime()); - assertNull(s.getLastSaveDateTime()); - assertEquals(s.getPageCount(), 0); - assertEquals(s.getWordCount(), 0); - assertEquals(s.getCharCount(), 0); - assertNull(s.getThumbnail()); - assertNull(s.getApplicationName()); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestHPSFBugs.java b/src/testcases/org/apache/poi/hpsf/basic/TestHPSFBugs.java deleted file mode 100644 index 6205713fa3..0000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestHPSFBugs.java +++ /dev/null @@ -1,190 +0,0 @@ -/* ==================================================================== - 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.hpsf.basic; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Date; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POIDocument; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.Test; - -/** - * Tests various bugs have been fixed - */ -final class TestHPSFBugs { - private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - - /** - * Ensure that we can create a new HSSF Workbook, - * then add some properties to it, save + - * reload, and still access & change them. - */ - @Test - void test48832() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - - // Starts empty - assertNull(wb1.getDocumentSummaryInformation()); - assertNull(wb1.getSummaryInformation()); - - // Add new properties - wb1.createInformationProperties(); - - assertNotNull(wb1.getDocumentSummaryInformation()); - assertNotNull(wb1.getSummaryInformation()); - - // Set initial values - wb1.getSummaryInformation().setAuthor("Apache POI"); - wb1.getSummaryInformation().setKeywords("Testing POI"); - wb1.getSummaryInformation().setCreateDateTime(new Date(12345)); - - wb1.getDocumentSummaryInformation().setCompany("Apache"); - - - // Save and reload - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - - // Ensure changes were taken - assertNotNull(wb2.getDocumentSummaryInformation()); - assertNotNull(wb2.getSummaryInformation()); - - assertEquals("Apache POI", wb2.getSummaryInformation().getAuthor()); - assertEquals("Testing POI", wb2.getSummaryInformation().getKeywords()); - assertEquals(12345, wb2.getSummaryInformation().getCreateDateTime().getTime()); - assertEquals("Apache", wb2.getDocumentSummaryInformation().getCompany()); - - - // Set some more, save + reload - wb2.getSummaryInformation().setComments("Resaved"); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - - // Check again - assertNotNull(wb3.getDocumentSummaryInformation()); - assertNotNull(wb3.getSummaryInformation()); - - assertEquals("Apache POI", wb3.getSummaryInformation().getAuthor()); - assertEquals("Testing POI", wb3.getSummaryInformation().getKeywords()); - assertEquals("Resaved", wb3.getSummaryInformation().getComments()); - assertEquals(12345, wb3.getSummaryInformation().getCreateDateTime().getTime()); - assertEquals("Apache", wb3.getDocumentSummaryInformation().getCompany()); - wb3.close(); - } - - /** - * Some files seem to want the length and data to be on a 4-byte boundary, - * and without that you'll hit an ArrayIndexOutOfBoundsException after - * reading junk - */ - @Test - void test54233() throws IOException, NoPropertySetStreamException, MarkUnsupportedException { - InputStream is = _samples.openResourceAsStream("TestNon4ByteBoundary.doc"); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - - SummaryInformation si = (SummaryInformation) - PropertySetFactory.create(fs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - DocumentSummaryInformation dsi = (DocumentSummaryInformation) - PropertySetFactory.create(fs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - // Test - assertEquals("Microsoft Word 10.0", si.getApplicationName()); - assertEquals("", si.getTitle()); - assertEquals("", si.getAuthor()); - assertEquals("Cour de Justice", dsi.getCompany()); - - - // Write out and read back, should still be valid - POIDocument doc = new HPSFPropertiesOnlyDocument(fs); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - doc.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - doc = new HPSFPropertiesOnlyDocument(new POIFSFileSystem(bais)); - - // Check properties are still there - assertEquals("Microsoft Word 10.0", si.getApplicationName()); - assertEquals("", si.getTitle()); - assertEquals("", si.getAuthor()); - assertEquals("Cour de Justice", dsi.getCompany()); - - doc.close(); - fs.close(); - } - - /** - * CodePage Strings can be zero length - */ - @Test - void test56138() throws IOException, NoPropertySetStreamException { - InputStream is = _samples.openResourceAsStream("TestZeroLengthCodePage.mpp"); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - - SummaryInformation si = (SummaryInformation) - PropertySetFactory.create(fs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - DocumentSummaryInformation dsi = (DocumentSummaryInformation) - PropertySetFactory.create(fs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - // Test - assertEquals("MSProject", si.getApplicationName()); - assertEquals("project1", si.getTitle()); - assertEquals("Jon Iles", si.getAuthor()); - - assertEquals("", dsi.getCompany()); - assertEquals(2, dsi.getSectionCount()); - - fs.close(); - } - - @Test - void bug62451() throws IOException { - final long millis = 920355314183864L; - try (HSSFWorkbook wb = new HSSFWorkbook()) { - wb.createSheet().createRow(0).createCell(0).setCellValue("foo"); - wb.createInformationProperties(); - SummaryInformation si = wb.getSummaryInformation(); - si.setLastPrinted(new Date(millis)); - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb)) { - SummaryInformation si2 = wb2.getSummaryInformation(); - Date d = si2.getLastPrinted(); - assertNotNull(d); - assertEquals(millis, d.getTime()); - } - } - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java b/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java deleted file mode 100644 index f8fb0aad13..0000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java +++ /dev/null @@ -1,601 +0,0 @@ -/* ==================================================================== - 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.hpsf.basic; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Date; -import java.util.Random; - -import org.apache.poi.hpsf.CustomProperties; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Basing on: src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java - * This class tests reading and writing of meta data. No actual document is created. All information - * is stored in a virtual document in a ByteArrayOutputStream - */ -final class TestMetaDataIPI { - - private POIFSFileSystem poifs ; - private DocumentSummaryInformation dsi; - private SummaryInformation si; - - @AfterEach - void tearDown() throws Exception { - poifs.close(); - } - - /** - * Setup is used to get the document ready. Gets the DocumentSummaryInformation and the - * SummaryInformation to reasonable values - */ - @BeforeEach - void setUp() throws Exception { - poifs = new POIFSFileSystem(); - dsi = PropertySetFactory.newDocumentSummaryInformation(); - si = PropertySetFactory.newSummaryInformation(); - dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - } - - /** - * Sets the most important information in DocumentSummaryInformation and Summary Information and rereads it - */ - @Test - void testOne() throws Exception { - - // DocumentSummaryInformation - dsi.setCompany("xxxCompanyxxx"); - dsi.setManager("xxxManagerxxx"); - dsi.setCategory("xxxCategoryxxx"); - - // SummaryInformation - si.setTitle("xxxTitlexxx"); - si.setAuthor("xxxAuthorxxx"); - si.setComments("xxxCommentsxxx"); - si.setKeywords("xxxKeyWordsxxx"); - si.setSubject("xxxSubjectxxx"); - - // Custom Properties (in DocumentSummaryInformation - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - customProperties = new CustomProperties(); - } - - /* Insert some custom properties into the container. */ - customProperties.put("Key1", "Value1"); - customProperties.put("Schl\u00fcssel2", "Wert2"); - customProperties.put("Sample Integer", 12345); - customProperties.put("Sample Boolean", true); - Date date = new Date(); - customProperties.put("Sample Date", date); - customProperties.put("Sample Double", -1.0001); - customProperties.put("Sample Negative Integer", -100000); - - dsi.setCustomProperties(customProperties); - - // start reading - closeAndReOpen(); - - // testing - assertNotNull(dsi); - assertNotNull(si); - - assertEquals("xxxCategoryxxx", dsi.getCategory(), "Category"); - assertEquals("xxxCompanyxxx", dsi.getCompany(), "Company"); - assertEquals("xxxManagerxxx", dsi.getManager(), "Manager"); - - assertEquals("xxxAuthorxxx", si.getAuthor()); - assertEquals("xxxTitlexxx", si.getTitle()); - assertEquals("xxxCommentsxxx", si.getComments()); - assertEquals("xxxKeyWordsxxx", si.getKeywords()); - assertEquals("xxxSubjectxxx", si.getSubject()); - - /* - * Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. - */ - customProperties = dsi.getCustomProperties(); - assertNotNull(customProperties); - - /* Insert some custom properties into the container. */ - String a1 = (String) customProperties.get("Key1"); - assertEquals("Value1", a1, "Key1"); - String a2 = (String) customProperties.get("Schl\u00fcssel2"); - assertEquals("Wert2", a2, "Schl\u00fcssel2"); - Integer a3 = (Integer) customProperties.get("Sample Integer"); - assertEquals(12345, (int)a3, "Sample Number"); - Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertTrue(a4, "Sample Boolean"); - Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals(date, a5, "Custom Date:"); - - Double a6 = (Double) customProperties.get("Sample Double"); - assertEquals(-1.0001, a6, 0, "Custom Float"); - - Integer a7 = (Integer) customProperties.get("Sample Negative Integer"); - assertEquals(-100000, (int)a7, "Neg"); - } - - /** - * Test very long input in each of the fields (approx 30-60KB each) - */ - @Test - void testTwo() throws Exception { - - String company = elongate("company"); - String manager = elongate("manager"); - String category = elongate("category"); - String title = elongate("title"); - String author = elongate("author"); - String comments = elongate("comments"); - String keywords = elongate("keywords"); - String subject = elongate("subject"); - String p1 = elongate("p1"); - String p2 = elongate("p2"); - String k1 = elongate("k1"); - String k2 = elongate("k2"); - - dsi.setCompany(company); - dsi.setManager(manager); - dsi.setCategory(category); - - si.setTitle(title); - si.setAuthor(author); - si.setComments(comments); - si.setKeywords(keywords); - si.setSubject(subject); - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - customProperties = new CustomProperties(); - } - - /* Insert some custom properties into the container. */ - customProperties.put(k1, p1); - customProperties.put(k2, p2); - customProperties.put("Sample Number", 12345); - customProperties.put("Sample Boolean", Boolean.TRUE); - Date date = new Date(); - customProperties.put("Sample Date", date); - - dsi.setCustomProperties(customProperties); - - closeAndReOpen(); - - assertNotNull(dsi); - assertNotNull(si); - /* - * Change the category to "POI example". Any former category value will - * be lost. If there has been no category yet, it will be created. - */ - assertEquals(category, dsi.getCategory(), "Category"); - assertEquals(company, dsi.getCompany(), "Company"); - assertEquals(manager, dsi.getManager(), "Manager"); - - assertEquals(author, si.getAuthor()); - assertEquals(title, si.getTitle()); - assertEquals(comments, si.getComments()); - assertEquals(keywords, si.getKeywords()); - assertEquals(subject, si.getSubject()); - - /* - * Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. - */ - customProperties = dsi.getCustomProperties(); - assertNotNull(customProperties); - - /* Insert some custom properties into the container. */ - String a1 = (String) customProperties.get(k1); - assertEquals(p1, a1, "Key1"); - String a2 = (String) customProperties.get(k2); - assertEquals(p2, a2, "Schl\u00fcssel2"); - Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals(12345, (int)a3, "Sample Number"); - Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertTrue(a4, "Sample Boolean"); - Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals(date, a5, "Custom Date:"); - - } - - - /** - * Tests with strange characters in keys and data (Umlaute etc.) - */ - @Test - void testThree() throws Exception { - - String company = strangize("company"); - String manager = strangize("manager"); - String category = strangize("category"); - String title = strangize("title"); - String author = strangize("author"); - String comments = strangize("comments"); - String keywords = strangize("keywords"); - String subject = strangize("subject"); - String p1 = strangize("p1"); - String p2 = strangize("p2"); - String k1 = strangize("k1"); - String k2 = strangize("k2"); - - dsi.setCompany(company); - dsi.setManager(manager); - dsi.setCategory(category); - - si.setTitle(title); - si.setAuthor(author); - si.setComments(comments); - si.setKeywords(keywords); - si.setSubject(subject); - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - customProperties = new CustomProperties(); - } - - /* Insert some custom properties into the container. */ - customProperties.put(k1, p1); - customProperties.put(k2, p2); - customProperties.put("Sample Number", 12345); - customProperties.put("Sample Boolean", false); - Date date = new Date(0); - customProperties.put("Sample Date", date); - - dsi.setCustomProperties(customProperties); - - closeAndReOpen(); - - assertNotNull(dsi); - assertNotNull(si); - /* - * Change the category to "POI example". Any former category value will - * be lost. If there has been no category yet, it will be created. - */ - assertEquals(category, dsi.getCategory(), "Category"); - assertEquals(company, dsi.getCompany(), "Company"); - assertEquals(manager, dsi.getManager(), "Manager"); - - assertEquals(author, si.getAuthor()); - assertEquals(title, si.getTitle()); - assertEquals(comments, si.getComments()); - assertEquals(keywords, si.getKeywords()); - assertEquals(subject, si.getSubject()); - - /* - * Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. - */ - customProperties = dsi.getCustomProperties(); - assertNotNull(customProperties); - - /* Insert some custom properties into the container. */ - // System.out.println(k1); - String a1 = (String) customProperties.get(k1); - assertEquals(p1, a1, "Key1"); - String a2 = (String) customProperties.get(k2); - assertEquals(p2, a2, "Schl\u00fcssel2"); - Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals(12345, (int)a3, "Sample Number"); - Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertFalse(a4, "Sample Boolean"); - Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals(date, a5, "Custom Date:"); - - } - - /** - * Iterative testing: writing, reading etc. - */ - @Test - void testFour() throws Exception { - for (int i = 1; i < 100; i++) { - testThree(); - closeAndReOpen(); - } - } - - /** - * Unicode test - */ - @Test - void testUnicode() throws Exception { - String company = strangizeU("company"); - String manager = strangizeU("manager"); - String category = strangizeU("category"); - String title = strangizeU("title"); - String author = strangizeU("author"); - String comments = strangizeU("comments"); - String keywords = strangizeU("keywords"); - String subject = strangizeU("subject"); - String p1 = strangizeU("p1"); - String p2 = strangizeU("p2"); - String k1 = strangizeU("k1"); - String k2 = strangizeU("k2"); - - dsi.setCompany(company); - dsi.setManager(manager); - dsi.setCategory(category); - - si.setTitle(title); - si.setAuthor(author); - si.setComments(comments); - si.setKeywords(keywords); - si.setSubject(subject); - - CustomProperties customProperties = new CustomProperties(); - /* Insert some custom properties into the container. */ - customProperties.put(k1, p1); - customProperties.put(k2, p2); - customProperties.put("Sample Number", 12345); - customProperties.put("Sample Boolean", true); - Date date = new Date(); - customProperties.put("Sample Date", date); - - dsi.setCustomProperties(customProperties); - - closeAndReOpen(); - - assertNotNull(dsi); - assertNotNull(si); - /* - * Change the category to "POI example". Any former category value will - * be lost. If there has been no category yet, it will be created. - */ - assertEquals(category, dsi.getCategory(), "Category"); - assertEquals(company, dsi.getCompany(), "Company"); - assertEquals(manager, dsi.getManager(), "Manager"); - - assertEquals(author, si.getAuthor()); - assertEquals(title, si.getTitle()); - assertEquals(comments, si.getComments()); - assertEquals(keywords, si.getKeywords()); - assertEquals(subject, si.getSubject()); - - /* - * Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. - */ - customProperties = dsi.getCustomProperties(); - assertNotNull(customProperties); - - /* Insert some custom properties into the container. */ - // System.out.println(k1); - String a1 = (String) customProperties.get(k1); - assertEquals(p1, a1, "Key1"); - String a2 = (String) customProperties.get(k2); - assertEquals(p2, a2, "Schl\u00fcssel2"); - Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals(12345, (int)a3, "Sample Number"); - Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertTrue(a4, "Sample Boolean"); - Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals(date, a5, "Custom Date:"); - } - - - /** - * Iterative testing of the unicode test - * - */ - @Test - void testSix() throws Exception { - for (int i = 1; i < 100; i++) { - testUnicode(); - closeAndReOpen(); - } - } - - - /** - * Tests conversion in custom fields and errors - */ - @Test - void testConvAndExistence() throws Exception { - - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - customProperties = new CustomProperties(); - } - - /* Insert some custom properties into the container. */ - customProperties.put("int", 12345); - customProperties.put("negint", -12345); - customProperties.put("long", 12345L); - customProperties.put("neglong", -12345L); - customProperties.put("boolean", true); - customProperties.put("string", "a String"); - // customProperties.put("float", new Float(12345.0)); is not valid - // customProperties.put("negfloat", new Float(-12345.1)); is not valid - customProperties.put("double", 12345.2); - customProperties.put("negdouble", -12345.3); - // customProperties.put("char", new Character('a')); is not valid - - Date date = new Date(); - customProperties.put("date", date); - - dsi.setCustomProperties(customProperties); - - closeAndReOpen(); - - assertNotNull(dsi); - assertNotNull(si); - /* - * Change the category to "POI example". Any former category value will - * be lost. If there has been no category yet, it will be created. - */ - assertNull(dsi.getCategory()); - assertNull(dsi.getCompany()); - assertNull(dsi.getManager()); - - assertNull(si.getAuthor()); - assertNull(si.getTitle()); - assertNull(si.getComments()); - assertNull(si.getKeywords()); - assertNull(si.getSubject()); - - /* - * Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. - */ - customProperties = dsi.getCustomProperties(); - assertNotNull(customProperties); - - /* Insert some custom properties into the container. */ - - Integer a3 = (Integer) customProperties.get("int"); - assertEquals(12345, (int)a3, "int"); - - a3 = (Integer) customProperties.get("negint"); - assertEquals(-12345, (int)a3, "negint"); - - Long al = (Long) customProperties.get("neglong"); - assertEquals(-12345L, (long)al, "neglong"); - - al = (Long) customProperties.get("long"); - assertEquals(12345L, (long)al, "long"); - - Boolean a4 = (Boolean) customProperties.get("boolean"); - assertTrue(a4, "boolean"); - - Date a5 = (Date) customProperties.get("date"); - assertEquals(date, a5, "Custom Date:"); - - Double d = (Double) customProperties.get("double"); - assertEquals(12345.2, d, 0, "int"); - - d = (Double) customProperties.get("negdouble"); - assertEquals(-12345.3, d, 0, "string"); - - String s = (String) customProperties.get("string"); - assertEquals("a String", s, "string"); - - - assertTrue(customProperties.get("string") instanceof String); - assertTrue(customProperties.get("boolean") instanceof Boolean); - assertTrue(customProperties.get("int") instanceof Integer); - assertTrue(customProperties.get("negint") instanceof Integer); - assertTrue(customProperties.get("long") instanceof Long); - assertTrue(customProperties.get("neglong") instanceof Long); - assertTrue(customProperties.get("double") instanceof Double); - assertTrue(customProperties.get("negdouble") instanceof Double); - assertTrue(customProperties.get("date") instanceof Date); - } - - - /** - * Closes the ByteArrayOutputStream and reads it into a ByteArrayInputStream. - * When finished writing information this method is used in the tests to - * start reading from the created document and then the see if the results match. - */ - private void closeAndReOpen() throws IOException, HPSFException { - dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - poifs.writeFilesystem(bout); - poifs.close(); - - InputStream is = new ByteArrayInputStream(bout.toByteArray()); - poifs = new POIFSFileSystem(is); - is.close(); - - /* Read the document summary information. */ - DirectoryEntry dir = poifs.getRoot(); - - dsi = (DocumentSummaryInformation)PropertySetFactory.create(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME); - si = (SummaryInformation)PropertySetFactory.create(dir, SummaryInformation.DEFAULT_STREAM_NAME); - } - - /** - * multiplies a string - * @param s Input String - * @return the multiplied String - */ - private static String elongate(String s) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < 10000; i++) { - sb.append(s); - sb.append(" "); - } - return sb.toString(); - } - - /** - * adds strange characters to the string - * @param s Input String - * @return the multiplied String - */ - private static String strangize(String s) { - StringBuilder sb = strangizeInit(s); - - return sb.toString(); - } - - /** - * adds strange characters to the string with the adding of unicode characters - * @param s Input String - * @return the multiplied String - */ - private static String strangizeU(String s) { - - StringBuilder sb = strangizeInit(s); - sb.append("\u00e4\u00f6\u00fc\uD840\uDC00"); - return sb.toString(); - } - - private static StringBuilder strangizeInit(String s) { - StringBuilder sb = new StringBuilder(); - String[] umlaute = { "\u00e4", "\u00fc", "\u00f6", "\u00dc", "$", "\u00d6", "\u00dc", - "\u00c9", "\u00d6", "@", "\u00e7", "&" }; - Random rand = new Random(0); // TODO - no Random - tests should be completely deterministic - for (int i = 0; i < 5; i++) { - sb.append(s); - sb.append(" "); - char j = (char) rand.nextInt(220); - j += 33; - sb.append(">"); - sb.append(Character.valueOf(j)); - sb.append("="); - sb.append(umlaute[rand.nextInt(umlaute.length)]); - sb.append("<"); - } - return sb; - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java b/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java deleted file mode 100644 index 13eb537fe2..0000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java +++ /dev/null @@ -1,213 +0,0 @@ -/* ==================================================================== - 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.hpsf.basic; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Stream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.CustomProperties; -import org.apache.poi.hpsf.CustomProperty; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Tests some HPSF functionality by reading all property sets from all files - * in the "data" directory. If you want to ensure HPSF can deal with a certain - * OLE2 file, just add it to the "data" directory and run this test case. - */ -class TestReadAllFiles { - private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - - public static Stream files() { - File hpsfTestDir = _samples.getFile(""); - - File[] files = hpsfTestDir.listFiles(f -> true); - Objects.requireNonNull(files, "Could not find directory " + hpsfTestDir.getAbsolutePath()); - - // convert to list of object-arrays for @Parameterized - return Arrays.stream(files).map(Arguments::of); - } - - /** - * This test methods reads all property set streams from all POI - * filesystems in the "data" directory. - */ - @ParameterizedTest - @MethodSource("files") - void read(File file) throws IOException, NoPropertySetStreamException, MarkUnsupportedException { - /* Read the POI filesystem's property set streams: */ - for (POIFile pf : Util.readPropertySets(file)) { - try (InputStream in = new ByteArrayInputStream(pf.getBytes())) { - PropertySet ps = PropertySetFactory.create(in); - assertNotNull(ps); - } - } - } - - - /** - * This test method does a write and read back test with all POI - * filesystems in the "data" directory by performing the following - * actions for each file:

- * - *

    - *
  • Read its property set streams. - *
  • Create a new POI filesystem containing the origin file's property set streams. - *
  • Read the property set streams from the POI filesystem just created. - *
  • Compare each property set stream with the corresponding one from - * the origin file and check whether they are equal. - *
- */ - @ParameterizedTest - @MethodSource("files") - void recreate(File file) throws IOException, HPSFException { - /* Read the POI filesystem's property set streams: */ - Map psMap = new HashMap<>(); - - /* Create a new POI filesystem containing the origin file's - * property set streams: */ - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - final POIFSFileSystem poiFs = new POIFSFileSystem(); - for (POIFile poifile : Util.readPropertySets(file)) { - final InputStream in = new ByteArrayInputStream(poifile.getBytes()); - final PropertySet psIn = PropertySetFactory.create(in); - psMap.put(poifile.getName(), psIn); - bos.reset(); - psIn.write(bos); - poiFs.createDocument(new ByteArrayInputStream(bos.toByteArray()), poifile.getName()); - } - - /* Read the property set streams from the POI filesystem just - * created. */ - for (Map.Entry me : psMap.entrySet()) { - final PropertySet ps1 = me.getValue(); - final PropertySet ps2 = PropertySetFactory.create(poiFs.getRoot(), me.getKey()); - assertNotNull(ps2); - - /* Compare the property set stream with the corresponding one - * from the origin file and check whether they are equal. */ - - // Because of missing 0-paddings in the original input files, the bytes might differ. - // This fixes the comparison - String ps1str = ps1.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)",""); - String ps2str = ps2.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)",""); - - assertEquals(ps1str, ps2str, "Equality for file " + file.getName()); - } - poiFs.close(); - } - - /** - * This test method checks whether DocumentSummary information streams - * can be read. This is done by opening all "Test*" files in the 'poifs' directrory - * pointed to by the "POI.testdata.path" system property, trying to extract - * the document summary information stream in the root directory and calling - * its get... methods. - */ - @ParameterizedTest - @MethodSource("files") - void readDocumentSummaryInformation(File file) throws Exception { - /* Read a test document doc into a POI filesystem. */ - try (POIFSFileSystem poifs = new POIFSFileSystem(file, true)) { - final DirectoryEntry dir = poifs.getRoot(); - /* - * If there is a document summry information stream, read it from - * the POI filesystem. - */ - if (dir.hasEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)) { - final DocumentSummaryInformation dsi = TestWriteWellKnown.getDocumentSummaryInformation(poifs); - assertNotNull(dsi); - - /* Execute the get... methods. */ - dsi.getByteCount(); - //noinspection ResultOfMethodCallIgnored - dsi.getByteOrder(); - dsi.getCategory(); - dsi.getCompany(); - dsi.getCustomProperties(); - // FIXME dsi.getDocparts(); - // FIXME dsi.getHeadingPair(); - dsi.getHiddenCount(); - dsi.getLineCount(); - dsi.getLinksDirty(); - dsi.getManager(); - dsi.getMMClipCount(); - dsi.getNoteCount(); - dsi.getParCount(); - dsi.getPresentationFormat(); - dsi.getScale(); - dsi.getSlideCount(); - } - } - } - - /** - * Tests the simplified custom properties by reading them from the - * available test files. - * - * @throws Exception if anything goes wrong. - */ - @ParameterizedTest - @MethodSource("files") - void readCustomPropertiesFromFiles(File file) throws Exception { - /* Read a test document doc into a POI filesystem. */ - try (POIFSFileSystem poifs = new POIFSFileSystem(file)) { - /* - * If there is a document summry information stream, read it from - * the POI filesystem, else create a new one. - */ - DocumentSummaryInformation dsi = TestWriteWellKnown.getDocumentSummaryInformation(poifs); - if (dsi == null) { - dsi = PropertySetFactory.newDocumentSummaryInformation(); - } - final CustomProperties cps = dsi.getCustomProperties(); - - if (cps == null) { - /* The document does not have custom properties. */ - return; - } - - for (CustomProperty cp : cps.properties()) { - assertNotNull(cp.getName()); - assertNotNull(cp.getValue()); - } - } - } - -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java b/src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java deleted file mode 100644 index 4abf73547f..0000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - 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.hpsf.basic; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.Section; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.util.CodePageUtil; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Tests whether Unicode string can be read from a DocumentSummaryInformation. - */ -class TestUnicode { - - static final String POI_FS = "TestUnicode.xls"; - static final String[] POI_FILES = { - DocumentSummaryInformation.DEFAULT_STREAM_NAME, - }; - File data; - POIFile[] poiFiles; - - - /** - * Read a the test file from the "data" directory. - * - * @exception FileNotFoundException if the file to be read does not exist. - * @exception IOException if any other I/O exception occurs - */ - @BeforeEach - void setUp() { - POIDataSamples samples = POIDataSamples.getHPSFInstance(); - data = samples.getFile(POI_FS); - } - - - - /** - * Tests the {@link PropertySet} methods. The test file has two - * property set: the first one is a {@link SummaryInformation}, - * the second one is a {@link DocumentSummaryInformation}. - * - * @exception IOException if an I/O exception occurs - * @exception HPSFException if an HPSF exception occurs - */ - @Test - void testPropertySetMethods() throws IOException, HPSFException { - POIFile poiFile = Util.readPOIFiles(data, POI_FILES).get(0); - byte[] b = poiFile.getBytes(); - PropertySet ps = PropertySetFactory.create(new ByteArrayInputStream(b)); - assertTrue(ps.isDocumentSummaryInformation()); - assertEquals(ps.getSectionCount(), 2); - Section s = ps.getSections().get(1); - assertEquals(s.getProperty(1), CodePageUtil.CP_UTF16); - assertEquals(s.getProperty(2), -96070278); - assertEquals(s.getProperty(3), "MCon_Info zu Office bei Schreiner"); - assertEquals(s.getProperty(4), "petrovitsch@schreiner-online.de"); - assertEquals(s.getProperty(5), "Petrovitsch, Wilhelm"); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java b/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java deleted file mode 100644 index 85ae090206..0000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java +++ /dev/null @@ -1,707 +0,0 @@ -/* ==================================================================== - 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.hpsf.basic; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.ClassID; -import org.apache.poi.hpsf.ClassIDPredefined; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.NoFormatIDException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.Property; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.Section; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.UnsupportedVariantTypeException; -import org.apache.poi.hpsf.Variant; -import org.apache.poi.hpsf.VariantSupport; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.hpsf.wellknown.PropertyIDMap; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.DocumentNode; -import org.apache.poi.poifs.filesystem.DocumentOutputStream; -import org.apache.poi.poifs.filesystem.POIFSDocument; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.CodePageUtil; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndianConsts; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.Test; - -/** - * Tests HPSF's writing functionality - */ -class TestWrite { - private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - private static final int CODEPAGE_DEFAULT = -1; - - private static final String POI_FS = "TestHPSFWritingFunctionality.doc"; - - private static final String IMPROPER_DEFAULT_CHARSET_MESSAGE = - "Your default character set is " + getDefaultCharsetName() + - ". However, this testcase must be run in an environment " + - "with a default character set supporting at least " + - "8-bit-characters. You can achieve this by setting the " + - "LANG environment variable to a proper value, e.g. " + - "\"de_DE\"."; - - /* - @BeforeClass - public static void setUpClass() { - VariantSupport.setLogUnsupportedTypes(false); - } - */ - - /** - * Writes an empty property set to a POIFS and reads it back in. - * - * @exception IOException if an I/O exception occurs - */ - @Test - void withoutAFormatID() throws Exception { - final File filename = TempFile.createTempFile(POI_FS, ".doc"); - - /* Create a mutable property set with a section that does not have the - * formatID set: */ - final PropertySet ps = new PropertySet(); - ps.clearSections(); - ps.addSection(new Section()); - - /* Write it to a POIFS and the latter to disk: */ - try (OutputStream out = new FileOutputStream(filename); - POIFSFileSystem poiFs = new POIFSFileSystem(); - ByteArrayOutputStream psStream = new ByteArrayOutputStream()) { - assertThrows(NoFormatIDException.class, () -> ps.write(psStream)); - poiFs.createDocument(new ByteArrayInputStream(psStream.toByteArray()), SummaryInformation.DEFAULT_STREAM_NAME); - poiFs.writeFilesystem(out); - } - } - - /** - * Writes an empty property set to a POIFS and reads it back in. - * - * @exception IOException if an I/O exception occurs - * @exception UnsupportedVariantTypeException if HPSF does not yet support - * a variant type to be written - */ - @Test - void writeEmptyPropertySet() - throws IOException, UnsupportedVariantTypeException { - final File dataDir = _samples.getFile(""); - final File filename = new File(dataDir, POI_FS); - filename.deleteOnExit(); - - /* Create a mutable property set and write it to a POIFS: */ - try (OutputStream out = new FileOutputStream(filename); - POIFSFileSystem poiFs = new POIFSFileSystem(); - ByteArrayOutputStream psStream = new ByteArrayOutputStream()) { - final PropertySet ps = new PropertySet(); - final Section s = ps.getSections().get(0); - s.setFormatID(SummaryInformation.FORMAT_ID); - ps.write(psStream); - poiFs.createDocument(new ByteArrayInputStream(psStream.toByteArray()), SummaryInformation.DEFAULT_STREAM_NAME); - poiFs.writeFilesystem(out); - } - - /* Read the POIFS: */ - final POIFSReader r = new POIFSReader(); - final List psa = new ArrayList<>(); - - r.registerListener(getListener(psa), SummaryInformation.DEFAULT_STREAM_NAME); - r.read(filename); - assertEquals(1, psa.size()); - } - - /** - *

Writes a simple property set with a SummaryInformation section to a - * POIFS and reads it back in.

- * - * @exception IOException if an I/O exception occurs - * @exception UnsupportedVariantTypeException if HPSF does not yet support - * a variant type to be written - */ - @Test - void writeSimplePropertySet() - throws IOException, UnsupportedVariantTypeException { - final String AUTHOR = "Rainer Klute"; - final String TITLE = "Test Document"; - final File dataDir = _samples.getFile(""); - final File filename = new File(dataDir, POI_FS); - filename.deleteOnExit(); - try (OutputStream out = new FileOutputStream(filename); - POIFSFileSystem poiFs = new POIFSFileSystem()) { - - final PropertySet ps = new PropertySet(); - final Section si = new Section(); - si.setFormatID(SummaryInformation.FORMAT_ID); - ps.clearSections(); - ps.addSection(si); - - final Property p = new Property(); - p.setID(PropertyIDMap.PID_AUTHOR); - p.setType(Variant.VT_LPWSTR); - p.setValue(AUTHOR); - si.setProperty(p); - si.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPSTR, TITLE); - - poiFs.createDocument(ps.toInputStream(), SummaryInformation.DEFAULT_STREAM_NAME); - poiFs.writeFilesystem(out); - } - - /* Read the POIFS: */ - final List psa = new ArrayList<>(); - final POIFSReader r = new POIFSReader(); - r.registerListener(getListener(psa), SummaryInformation.DEFAULT_STREAM_NAME); - r.read(filename); - assertEquals(1, psa.size()); - assertTrue(psa.get(0).isSummaryInformation()); - - final Section s = psa.get(0).getSections().get(0); - Object p1 = s.getProperty(PropertyIDMap.PID_AUTHOR); - Object p2 = s.getProperty(PropertyIDMap.PID_TITLE); - assertEquals(AUTHOR, p1); - assertEquals(TITLE, p2); - } - - - - /** - * Writes a simple property set with two sections to a POIFS and reads it - * back in. - * - * @exception IOException if an I/O exception occurs - * @exception WritingNotSupportedException if HPSF does not yet support - * a variant type to be written - */ - @Test - void writeTwoSections() throws WritingNotSupportedException, IOException { - final String STREAM_NAME = "PropertySetStream"; - final String SECTION1 = "Section 1"; - final String SECTION2 = "Section 2"; - final ClassID FORMATID = ClassIDPredefined.EXCEL_V12.getClassID(); - - final File dataDir = _samples.getFile(""); - final File filename = new File(dataDir, POI_FS); - filename.deleteOnExit(); - - try (OutputStream out = new FileOutputStream(filename); - POIFSFileSystem poiFs = new POIFSFileSystem()) { - final PropertySet ps = new PropertySet(); - ps.clearSections(); - - final Section s1 = new Section(); - s1.setFormatID(FORMATID); - s1.setProperty(2, SECTION1); - ps.addSection(s1); - - final Section s2 = new Section(); - s2.setFormatID(FORMATID); - s2.setProperty(2, SECTION2); - ps.addSection(s2); - - poiFs.createDocument(ps.toInputStream(), STREAM_NAME); - poiFs.writeFilesystem(out); - } - - /* Read the POIFS: */ - final PropertySet[] psa = new PropertySet[1]; - final POIFSReader r = new POIFSReader(); - final POIFSReaderListener listener = (event) -> { - assertDoesNotThrow(() -> psa[0] = PropertySetFactory.create(event.getStream())); - }; - - r.registerListener(listener,STREAM_NAME); - r.read(filename); - - assertNotNull(psa[0]); - Section s = (psa[0].getSections().get(0)); - assertEquals(s.getFormatID(), FORMATID); - Object p = s.getProperty(2); - assertEquals(SECTION1, p); - s = (psa[0].getSections().get(1)); - p = s.getProperty(2); - assertEquals(SECTION2, p); - } - - private static POIFSReaderListener getListener(List psa) { - return event -> assertDoesNotThrow(() -> psa.add(PropertySetFactory.create(event.getStream()))); - } - - /** - * Writes and reads back various variant types and checks whether the - * stuff that has been read back equals the stuff that was written. - */ - @Test - void variantTypes() throws Exception { - final int codepage = CODEPAGE_DEFAULT; - Assumptions.assumeTrue(hasProperDefaultCharset(), IMPROPER_DEFAULT_CHARSET_MESSAGE); - - check(Variant.VT_EMPTY, null, codepage); - check(Variant.VT_BOOL, Boolean.TRUE, codepage); - check(Variant.VT_BOOL, Boolean.FALSE, codepage); - check( Variant.VT_CF, new byte[] { 8, 0, 0, 0, 1, 0, 0, 0, 1, 2, 3, 4 }, codepage ); - check(Variant.VT_I4, 27, codepage); - check(Variant.VT_I8, 28L, codepage); - check(Variant.VT_R8, 29.0d, codepage); - check(Variant.VT_I4, -27, codepage); - check(Variant.VT_I8, -28L, codepage); - check(Variant.VT_R8, -29.0d, codepage); - check(Variant.VT_FILETIME, new Date(), codepage); - check(Variant.VT_I4, Integer.MAX_VALUE, codepage); - check(Variant.VT_I4, Integer.MIN_VALUE, codepage); - check(Variant.VT_I8, Long.MAX_VALUE, codepage); - check(Variant.VT_I8, Long.MIN_VALUE, codepage); - check(Variant.VT_R8, Double.MAX_VALUE, codepage); - check(Variant.VT_R8, Double.MIN_VALUE, codepage); - checkString(Variant.VT_LPSTR, "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc", codepage); - checkString(Variant.VT_LPWSTR, "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc", codepage); - } - - - - /** - * Writes and reads back strings using several different codepages and - * checks whether the stuff that has been read back equals the stuff that - * was written. - */ - @Test - void codepages() throws UnsupportedVariantTypeException, IOException - { - final int[] validCodepages = {CODEPAGE_DEFAULT, CodePageUtil.CP_UTF8, CodePageUtil.CP_UNICODE, CodePageUtil.CP_WINDOWS_1252}; - for (final int cp : validCodepages) { - if (cp == -1 && !hasProperDefaultCharset()) - { - System.err.println(IMPROPER_DEFAULT_CHARSET_MESSAGE + - " This testcase is skipped for the default codepage."); - continue; - } - - final long t = (cp == CodePageUtil.CP_UNICODE) ? Variant.VT_LPWSTR : Variant.VT_LPSTR; - checkString(t, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp); - if (cp == CodePageUtil.CP_UTF16 || cp == CodePageUtil.CP_UTF8) { - check(t, "\u79D1\u5B78", cp); - } - } - - final int[] invalidCodepages = new int[] {0, 1, 2, 4711, 815}; - for (int cp : invalidCodepages) { - assertThrows(UnsupportedEncodingException.class, - () -> checkString(Variant.VT_LPSTR, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp), - "UnsupportedEncodingException for codepage " + cp + " expected."); - } - - } - - - - /** - * Tests whether writing 8-bit characters to a Unicode property succeeds. - */ - @Test - void unicodeWrite8Bit() throws WritingNotSupportedException, IOException, NoPropertySetStreamException { - final String TITLE = "This is a sample title"; - final PropertySet mps = new PropertySet(); - final Section ms = mps.getSections().get(0); - ms.setFormatID(SummaryInformation.FORMAT_ID); - final Property p = new Property(); - p.setID(PropertyIDMap.PID_TITLE); - p.setType(Variant.VT_LPSTR); - p.setValue(TITLE); - ms.setProperty(p); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - mps.write(out); - out.close(); - byte[] bytes = out.toByteArray(); - - PropertySet psr = new PropertySet(bytes); - assertTrue(psr.isSummaryInformation()); - Section sr = psr.getSections().get(0); - String title = (String) sr.getProperty(PropertyIDMap.PID_TITLE); - assertEquals(TITLE, title); - } - - private void checkString(final long variantType, final String value, final int codepage) - throws UnsupportedVariantTypeException, IOException { - for (int i=0; iTests writing and reading back a proper dictionary.

- */ - @Test - void dictionary() throws IOException, HPSFException { - final File copy = TempFile.createTempFile("Test-HPSF", "ole2"); - copy.deleteOnExit(); - - /* Write: */ - final OutputStream out = new FileOutputStream(copy); - final POIFSFileSystem poiFs = new POIFSFileSystem(); - final PropertySet ps1 = new PropertySet(); - final Section s = ps1.getSections().get(0); - final Map m = new HashMap<>(3, 1.0f); - m.put(1L, "String 1"); - m.put(2L, "String 2"); - m.put(3L, "String 3"); - s.setDictionary(m); - s.setFormatID(DocumentSummaryInformation.FORMAT_ID[0]); - int codepage = CodePageUtil.CP_UNICODE; - s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, codepage); - poiFs.createDocument(ps1.toInputStream(), "Test"); - poiFs.writeFilesystem(out); - poiFs.close(); - out.close(); - - /* Read back: */ - final List psf = Util.readPropertySets(copy); - assertEquals(1, psf.size()); - final byte[] bytes = psf.get(0).getBytes(); - final InputStream in = new ByteArrayInputStream(bytes); - final PropertySet ps2 = PropertySetFactory.create(in); - - /* Check if the result is a DocumentSummaryInformation stream, as - * specified. */ - assertTrue(ps2.isDocumentSummaryInformation()); - - /* Compare the property set stream with the corresponding one - * from the origin file and check whether they are equal. */ - assertEquals(ps1, ps2); - } - - /** - * Tests that when using POIFS, we can do an in-place write - * without needing to stream in + out the whole kitchen sink - */ - @Test - void inPlacePOIFSWrite() throws Exception { - // We need to work on a File for in-place changes, so create a temp one - final File copy = TempFile.createTempFile("Test-HPSF", "ole2"); - copy.deleteOnExit(); - - // Copy a test file over to our temp location - try (FileOutputStream out = new FileOutputStream(copy); - InputStream inp = _samples.openResourceAsStream("TestShiftJIS.doc")) { - IOUtils.copy(inp, out); - } - - // Open the copy in read/write mode - try (POIFSFileSystem fs = new POIFSFileSystem(copy, false)) { - DirectoryEntry root = fs.getRoot(); - - // Read the properties in there - DocumentNode sinfDoc = (DocumentNode) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - DocumentNode dinfDoc = (DocumentNode) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - InputStream sinfStream = new DocumentInputStream(sinfDoc); - SummaryInformation sinf = (SummaryInformation) PropertySetFactory.create(sinfStream); - sinfStream.close(); - assertEquals(131077, sinf.getOSVersion()); - - InputStream dinfStream = new DocumentInputStream(dinfDoc); - DocumentSummaryInformation dinf = (DocumentSummaryInformation) PropertySetFactory.create(dinfStream); - dinfStream.close(); - assertEquals(131077, dinf.getOSVersion()); - - - // Check they start as we expect - assertEquals("Reiichiro Hori", sinf.getAuthor()); - assertEquals("Microsoft Word 9.0", sinf.getApplicationName()); - assertEquals("\u7b2c1\u7ae0", sinf.getTitle()); - - assertEquals("", dinf.getCompany()); - assertNull(dinf.getManager()); - - - // Do an in-place replace via an InputStream - assertNotNull(sinfDoc); - assertNotNull(dinfDoc); - - new POIFSDocument(sinfDoc).replaceContents(sinf.toInputStream()); - new POIFSDocument(dinfDoc).replaceContents(dinf.toInputStream()); - - - // Check it didn't get changed - sinfDoc = (DocumentNode) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - dinfDoc = (DocumentNode) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - InputStream sinfStream2 = new DocumentInputStream(sinfDoc); - sinf = (SummaryInformation) PropertySetFactory.create(sinfStream2); - sinfStream2.close(); - assertEquals(131077, sinf.getOSVersion()); - - InputStream dinfStream2 = new DocumentInputStream(dinfDoc); - dinf = (DocumentSummaryInformation) PropertySetFactory.create(dinfStream2); - dinfStream2.close(); - assertEquals(131077, dinf.getOSVersion()); - } - - // Start again! - try (FileOutputStream out = new FileOutputStream(copy); - InputStream inp = _samples.openResourceAsStream("TestShiftJIS.doc")) { - IOUtils.copy(inp, out); - } - - try (POIFSFileSystem fs = new POIFSFileSystem(copy, false)) { - DirectoryEntry root = fs.getRoot(); - - // Read the properties in once more - DocumentNode sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - DocumentNode dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - InputStream sinfStream3 = new DocumentInputStream(sinfDoc); - SummaryInformation sinf = (SummaryInformation)PropertySetFactory.create(sinfStream3); - sinfStream3.close(); - assertEquals(131077, sinf.getOSVersion()); - - InputStream dinfStream3 = new DocumentInputStream(dinfDoc); - DocumentSummaryInformation dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream3); - dinfStream3.close(); - assertEquals(131077, dinf.getOSVersion()); - - - // Have them write themselves in-place with no changes, as an OutputStream - OutputStream soufStream = new DocumentOutputStream(sinfDoc); - sinf.write(soufStream); - soufStream.close(); - OutputStream doufStream = new DocumentOutputStream(dinfDoc); - dinf.write(doufStream); - doufStream.close(); - - // And also write to some bytes for checking - ByteArrayOutputStream sinfBytes = new ByteArrayOutputStream(); - sinf.write(sinfBytes); - ByteArrayOutputStream dinfBytes = new ByteArrayOutputStream(); - dinf.write(dinfBytes); - - - // Check that the filesystem can give us back the same bytes - sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - InputStream sinfStream4 = new DocumentInputStream(sinfDoc); - byte[] sinfData = IOUtils.toByteArray(sinfStream4); - sinfStream4.close(); - InputStream dinfStream4 = new DocumentInputStream(dinfDoc); - byte[] dinfData = IOUtils.toByteArray(dinfStream4); - dinfStream4.close(); - assertThat(sinfBytes.toByteArray(), equalTo(sinfData)); - assertThat(dinfBytes.toByteArray(), equalTo(dinfData)); - - - // Read back in as-is - InputStream sinfStream5 = new DocumentInputStream(sinfDoc); - sinf = (SummaryInformation)PropertySetFactory.create(sinfStream5); - sinfStream5.close(); - assertEquals(131077, sinf.getOSVersion()); - - InputStream dinfStream5 = new DocumentInputStream(dinfDoc); - dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream5); - dinfStream5.close(); - assertEquals(131077, dinf.getOSVersion()); - - assertEquals("Reiichiro Hori", sinf.getAuthor()); - assertEquals("Microsoft Word 9.0", sinf.getApplicationName()); - assertEquals("\u7b2c1\u7ae0", sinf.getTitle()); - - assertEquals("", dinf.getCompany()); - assertNull(dinf.getManager()); - - - // Now alter a few of them - sinf.setAuthor("Changed Author"); - sinf.setTitle("Le titre \u00e9tait chang\u00e9"); - dinf.setManager("Changed Manager"); - - - // Save this into the filesystem - OutputStream soufStream2 = new DocumentOutputStream(sinfDoc); - sinf.write(soufStream2); - soufStream2.close(); - OutputStream doufStream2 = new DocumentOutputStream(dinfDoc); - dinf.write(doufStream2); - doufStream2.close(); - - - // Read them back in again - sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - InputStream sinfStream6 = new DocumentInputStream(sinfDoc); - sinf = (SummaryInformation)PropertySetFactory.create(sinfStream6); - sinfStream6.close(); - assertEquals(131077, sinf.getOSVersion()); - - dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - InputStream dinfStream6 = new DocumentInputStream(dinfDoc); - dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream6); - dinfStream6.close(); - assertEquals(131077, dinf.getOSVersion()); - - assertEquals("Changed Author", sinf.getAuthor()); - assertEquals("Microsoft Word 9.0", sinf.getApplicationName()); - assertEquals("Le titre \u00e9tait chang\u00e9", sinf.getTitle()); - - assertEquals("", dinf.getCompany()); - assertEquals("Changed Manager", dinf.getManager()); - - - // Close the whole filesystem, and open it once more - fs.writeFilesystem(); - } - - try (POIFSFileSystem fs = new POIFSFileSystem(copy)) { - DirectoryEntry root = fs.getRoot(); - - // Re-check on load - DocumentNode sinfDoc = (DocumentNode) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - InputStream sinfStream7 = new DocumentInputStream(sinfDoc); - SummaryInformation sinf = (SummaryInformation) PropertySetFactory.create(sinfStream7); - sinfStream7.close(); - assertEquals(131077, sinf.getOSVersion()); - - DocumentNode dinfDoc = (DocumentNode) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - InputStream dinfStream7 = new DocumentInputStream(dinfDoc); - DocumentSummaryInformation dinf = (DocumentSummaryInformation) PropertySetFactory.create(dinfStream7); - dinfStream7.close(); - assertEquals(131077, dinf.getOSVersion()); - - assertEquals("Changed Author", sinf.getAuthor()); - assertEquals("Microsoft Word 9.0", sinf.getApplicationName()); - assertEquals("Le titre \u00e9tait chang\u00e9", sinf.getTitle()); - - assertEquals("", dinf.getCompany()); - assertEquals("Changed Manager", dinf.getManager()); - } - - // Tidy up - assertTrue(copy.delete()); - } - - - /** - * Tests writing and reading back a proper dictionary with an invalid - * codepage. (HPSF writes Unicode dictionaries only.) - */ - @Test - void dictionaryWithInvalidCodepage() throws IOException, HPSFException { - final File copy = TempFile.createTempFile("Test-HPSF", "ole2"); - copy.deleteOnExit(); - - /* Write: */ - - final PropertySet ps1 = new PropertySet(); - final Section s = ps1.getSections().get(0); - final Map m = new HashMap<>(3, 1.0f); - m.put(1L, "String 1"); - m.put(2L, "String 2"); - m.put(3L, "String 3"); - - try (OutputStream out = new FileOutputStream(copy); - POIFSFileSystem poiFs = new POIFSFileSystem()) { - s.setDictionary(m); - s.setFormatID(DocumentSummaryInformation.FORMAT_ID[0]); - int codepage = 12345; - s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, codepage); - assertThrows(UnsupportedEncodingException.class, () -> poiFs.createDocument(ps1.toInputStream(), "Test")); - poiFs.writeFilesystem(out); - } - } - - /** - *

Returns the display name of the default character set.

- * - * @return the display name of the default character set. - */ - private static String getDefaultCharsetName() { - final String charSetName = System.getProperty("file.encoding"); - final Charset charSet = Charset.forName(charSetName); - return charSet.displayName(Locale.ROOT); - } - - /** - *

In order to execute tests with characters beyond US-ASCII, this - * method checks whether the application is runing in an environment - * where the default character set is 16-bit-capable.

- * - * @return true if the default character set is 16-bit-capable, - * else false. - */ - private boolean hasProperDefaultCharset() { - final String charSetName = System.getProperty("file.encoding"); - final Charset charSet = Charset.forName(charSetName); - return charSet.newEncoder().canEncode('\u00e4'); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java b/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java deleted file mode 100644 index 06cf09cf3f..0000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java +++ /dev/null @@ -1,595 +0,0 @@ -/* ==================================================================== - 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.hpsf.basic; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.CustomProperties; -import org.apache.poi.hpsf.CustomProperty; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.Property; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.Section; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.UnexpectedPropertySetTypeException; -import org.apache.poi.hpsf.Variant; -import org.apache.poi.hpsf.VariantSupport; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - *

Tests HPSF's high-level writing functionality for the well-known property - * set "SummaryInformation" and "DocumentSummaryInformation".

- */ -class TestWriteWellKnown { - - private static final String POI_FS = "TestWriteWellKnown.doc"; - - @BeforeAll - public static void setUp() { - VariantSupport.setLogUnsupportedTypes(false); - } - - private static final String P_APPLICATION_NAME = "ApplicationName"; - private static final String P_AUTHOR = "Author"; - private static final int P_CHAR_COUNT = 4712; - private static final String P_COMMENTS = "Comments"; - private static final Date P_CREATE_DATE_TIME; - private static final long P_EDIT_TIME = 4713 * 1000 * 10; - private static final String P_KEYWORDS = "Keywords"; - private static final String P_LAST_AUTHOR = "LastAuthor"; - private static final Date P_LAST_PRINTED; - private static final Date P_LAST_SAVE_DATE_TIME; - private static final int P_PAGE_COUNT = 4714; - private static final String P_REV_NUMBER = "RevNumber"; - private static final int P_SECURITY = 1; - private static final String P_SUBJECT = "Subject"; - private static final String P_TEMPLATE = "Template"; - // FIXME (byte array properties not yet implemented): static final byte[] P_THUMBNAIL = new byte[123]; - private static final String P_TITLE = "Title"; - private static final int P_WORD_COUNT = 4715; - - private static final int P_BYTE_COUNT = 4716; - private static final String P_CATEGORY = "Category"; - private static final String P_COMPANY = "Company"; - // FIXME (byte array properties not yet implemented): static final byte[] P_DOCPARTS = new byte[123]; - // FIXME (byte array properties not yet implemented): static final byte[] P_HEADING_PAIR = new byte[123]; - private static final int P_HIDDEN_COUNT = 4717; - private static final int P_LINE_COUNT = 4718; - private static final boolean P_LINKS_DIRTY = true; - private static final String P_MANAGER = "Manager"; - private static final int P_MM_CLIP_COUNT = 4719; - private static final int P_NOTE_COUNT = 4720; - private static final int P_PAR_COUNT = 4721; - private static final String P_PRESENTATION_FORMAT = "PresentationFormat"; - private static final boolean P_SCALE = false; - private static final int P_SLIDE_COUNT = 4722; - private static final Date now = new Date(); - - private static final Integer POSITIVE_INTEGER = 2222; - private static final Long POSITIVE_LONG = 3333L; - private static final Double POSITIVE_DOUBLE = 4444d; - private static final Integer NEGATIVE_INTEGER = 2222; - private static final Long NEGATIVE_LONG = 3333L; - private static final Double NEGATIVE_DOUBLE = 4444d; - - private static final Integer MAX_INTEGER = Integer.MAX_VALUE; - private static final Integer MIN_INTEGER = Integer.MIN_VALUE; - private static final Long MAX_LONG = Long.MAX_VALUE; - private static final Long MIN_LONG = Long.MIN_VALUE; - private static final Double MAX_DOUBLE = Double.MAX_VALUE; - private static final Double MIN_DOUBLE = Double.MIN_VALUE; - - static { - Calendar cal = LocaleUtil.getLocaleCalendar(2000, 6, 6, 6, 6, 6); - P_CREATE_DATE_TIME = cal.getTime(); - cal.set(2001, 7, 7, 7, 7, 7); - P_LAST_PRINTED = cal.getTime(); - cal.set(2002, 8, 8, 8, 8, 8); - P_LAST_SAVE_DATE_TIME = cal.getTime(); - } - - /** - *

This test method test the writing of properties in the well-known - * property set streams "SummaryInformation" and - * "DocumentSummaryInformation" by performing the following steps:

- * - *
    - * - *
  1. Read a test document doc1 into a POI filesystem.

  2. - * - *
  3. Read the summary information stream and the document summary - * information stream from the POI filesystem.

  4. - * - *
  5. Write all properties supported by HPSF to the summary - * information (e.g. author, edit date, application name) and to the - * document summary information (e.g. company, manager).

  6. - * - *
  7. Write the summary information stream and the document summary - * information stream to the POI filesystem.

  8. - * - *
  9. Write the POI filesystem to a (temporary) file doc2 - * and close the latter.

  10. - * - *
  11. Open doc2 for reading and check summary information - * and document summary information. All properties written before must be - * found in the property streams of doc2 and have the correct - * values.

  12. - * - *
  13. Remove all properties supported by HPSF from the summary - * information (e.g. author, edit date, application name) and from the - * document summary information (e.g. company, manager).

  14. - * - *
  15. Write the summary information stream and the document summary - * information stream to the POI filesystem.

  16. - * - *
  17. Write the POI filesystem to a (temporary) file doc3 - * and close the latter.

  18. - * - *
  19. Open doc3 for reading and check summary information - * and document summary information. All properties removed before must not - * be found in the property streams of doc3.

- * - * @throws IOException if some I/O error occurred. - */ - @Test - void testWriteWellKnown() throws Exception { - POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - - final File doc1 = TempFile.createTempFile("POI_HPSF_Test1.", ".tmp"); - final File doc2 = TempFile.createTempFile("POI_HPSF_Test2.", ".tmp"); - final File doc3 = TempFile.createTempFile("POI_HPSF_Test3.", ".tmp"); - - FileInputStream fis = new FileInputStream(_samples.getFile(POI_FS)); - FileOutputStream fos = new FileOutputStream(doc1); - IOUtils.copy(fis, fos); - fos.close(); - fis.close(); - - CustomProperties cps1 = write1stFile(doc1, doc2); - CustomProperties cps2 = write2ndFile(doc2, doc3); - write3rdFile(doc3); - - assertEquals(cps1, cps2); - } - - /* - * Write all properties supported by HPSF to the summary information - * (e.g. author, edit date, application name) and to the document - * summary information (e.g. company, manager). - */ - private static CustomProperties write1stFile(File fileIn, File fileOut) throws Exception { - /* Read a test document doc1 into a POI filesystem. */ - POIFSFileSystem poifs = new POIFSFileSystem(fileIn, false); - - /* - * Read the summary information stream and the document summary - * information stream from the POI filesystem. - * - * Please note that the result consists of SummaryInformation and - * DocumentSummaryInformation instances which are in memory only. To - * make them permanent they have to be written to a POI filesystem - * explicitly (overwriting the former contents). Then the POI filesystem - * should be saved to a file. - */ - SummaryInformation si = getSummaryInformation(poifs); - DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); - - si.setApplicationName(P_APPLICATION_NAME); - si.setAuthor(P_AUTHOR); - si.setCharCount(P_CHAR_COUNT); - si.setComments(P_COMMENTS); - si.setCreateDateTime(P_CREATE_DATE_TIME); - si.setEditTime(P_EDIT_TIME); - si.setKeywords(P_KEYWORDS); - si.setLastAuthor(P_LAST_AUTHOR); - si.setLastPrinted(P_LAST_PRINTED); - si.setLastSaveDateTime(P_LAST_SAVE_DATE_TIME); - si.setPageCount(P_PAGE_COUNT); - si.setRevNumber(P_REV_NUMBER); - si.setSecurity(P_SECURITY); - si.setSubject(P_SUBJECT); - si.setTemplate(P_TEMPLATE); - // FIXME (byte array properties not yet implemented): si.setThumbnail(P_THUMBNAIL); - si.setTitle(P_TITLE); - si.setWordCount(P_WORD_COUNT); - - dsi.setByteCount(P_BYTE_COUNT); - dsi.setCategory(P_CATEGORY); - dsi.setCompany(P_COMPANY); - // FIXME (byte array properties not yet implemented): dsi.setDocparts(P_DOCPARTS); - // FIXME (byte array properties not yet implemented): dsi.setHeadingPair(P_HEADING_PAIR); - dsi.setHiddenCount(P_HIDDEN_COUNT); - dsi.setLineCount(P_LINE_COUNT); - dsi.setLinksDirty(P_LINKS_DIRTY); - dsi.setManager(P_MANAGER); - dsi.setMMClipCount(P_MM_CLIP_COUNT); - dsi.setNoteCount(P_NOTE_COUNT); - dsi.setParCount(P_PAR_COUNT); - dsi.setPresentationFormat(P_PRESENTATION_FORMAT); - dsi.setScale(P_SCALE); - dsi.setSlideCount(P_SLIDE_COUNT); - - CustomProperties cps = dsi.getCustomProperties(); - assertNull(cps); - cps = new CustomProperties(); - cps.put("Schl\u00fcssel \u00e4", "Wert \u00e4"); - cps.put("Schl\u00fcssel \u00e4\u00f6", "Wert \u00e4\u00f6"); - cps.put("Schl\u00fcssel \u00e4\u00f6\u00fc", "Wert \u00e4\u00f6\u00fc"); - cps.put("Schl\u00fcssel \u00e4\u00f6\u00fc\u00d6", "Wert \u00e4\u00f6\u00fc\u00d6"); - cps.put("positive_Integer", POSITIVE_INTEGER); - cps.put("positive_Long", POSITIVE_LONG); - cps.put("positive_Double", POSITIVE_DOUBLE); - cps.put("negative_Integer", NEGATIVE_INTEGER); - cps.put("negative_Long", NEGATIVE_LONG); - cps.put("negative_Double", NEGATIVE_DOUBLE); - cps.put("Boolean", Boolean.TRUE); - cps.put("Date", now); - cps.put("max_Integer", MAX_INTEGER); - cps.put("min_Integer", MIN_INTEGER); - cps.put("max_Long", MAX_LONG); - cps.put("min_Long", MIN_LONG); - cps.put("max_Double", MAX_DOUBLE); - cps.put("min_Double", MIN_DOUBLE); - - // Check the keys went in - assertTrue(cps.containsKey("Schl\u00fcssel \u00e4")); - assertTrue(cps.containsKey("Boolean")); - - // Check the values went in - assertEquals("Wert \u00e4", cps.get("Schl\u00fcssel \u00e4")); - assertEquals(Boolean.TRUE, cps.get("Boolean")); - assertTrue(cps.containsValue(Boolean.TRUE)); - assertTrue(cps.containsValue("Wert \u00e4")); - - // Check that things that aren't in aren't in - assertFalse(cps.containsKey("False Boolean")); - assertFalse(cps.containsValue(Boolean.FALSE)); - - // Save as our custom properties - dsi.setCustomProperties(cps); - - - /* Write the summary information stream and the document summary - * information stream to the POI filesystem. */ - si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - /* Write the POI filesystem to a (temporary) file doc2 - * and close the latter. */ - OutputStream out = new FileOutputStream(fileOut); - poifs.writeFilesystem(out); - out.close(); - poifs.close(); - - return cps; - } - - /* - * Open doc2 for reading and check summary information and - * document summary information. All properties written before must be - * found in the property streams of doc2 and have the correct - * values. - */ - private static CustomProperties write2ndFile(File fileIn, File fileOut) throws Exception { - POIFSFileSystem poifs = new POIFSFileSystem(fileIn, false); - SummaryInformation si = getSummaryInformation(poifs); - DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); - - assertEquals(P_APPLICATION_NAME, si.getApplicationName()); - assertEquals(P_AUTHOR, si.getAuthor()); - assertEquals(P_CHAR_COUNT, si.getCharCount()); - assertEquals(P_COMMENTS, si.getComments()); - assertEquals(P_CREATE_DATE_TIME, si.getCreateDateTime()); - assertEquals(P_EDIT_TIME, si.getEditTime()); - assertEquals(P_KEYWORDS, si.getKeywords()); - assertEquals(P_LAST_AUTHOR, si.getLastAuthor()); - assertEquals(P_LAST_PRINTED, si.getLastPrinted()); - assertEquals(P_LAST_SAVE_DATE_TIME, si.getLastSaveDateTime()); - assertEquals(P_PAGE_COUNT, si.getPageCount()); - assertEquals(P_REV_NUMBER, si.getRevNumber()); - assertEquals(P_SECURITY, si.getSecurity()); - assertEquals(P_SUBJECT, si.getSubject()); - assertEquals(P_TEMPLATE, si.getTemplate()); - // FIXME (byte array properties not yet implemented): assertEquals(P_THUMBNAIL, si.getThumbnail()); - assertEquals(P_TITLE, si.getTitle()); - assertEquals(P_WORD_COUNT, si.getWordCount()); - - assertEquals(P_BYTE_COUNT, dsi.getByteCount()); - assertEquals(P_CATEGORY, dsi.getCategory()); - assertEquals(P_COMPANY, dsi.getCompany()); - // FIXME (byte array properties not yet implemented): assertEquals(P_, dsi.getDocparts()); - // FIXME (byte array properties not yet implemented): assertEquals(P_, dsi.getHeadingPair()); - assertEquals(P_HIDDEN_COUNT, dsi.getHiddenCount()); - assertEquals(P_LINE_COUNT, dsi.getLineCount()); - assertEquals(P_LINKS_DIRTY, dsi.getLinksDirty()); - assertEquals(P_MANAGER, dsi.getManager()); - assertEquals(P_MM_CLIP_COUNT, dsi.getMMClipCount()); - assertEquals(P_NOTE_COUNT, dsi.getNoteCount()); - assertEquals(P_PAR_COUNT, dsi.getParCount()); - assertEquals(P_PRESENTATION_FORMAT, dsi.getPresentationFormat()); - assertEquals(P_SCALE, dsi.getScale()); - assertEquals(P_SLIDE_COUNT, dsi.getSlideCount()); - - final CustomProperties cps = dsi.getCustomProperties(); - assertNotNull(cps); - assertNull(cps.get("No value available")); - assertEquals("Wert \u00e4", cps.get("Schl\u00fcssel \u00e4")); - assertEquals("Wert \u00e4\u00f6", cps.get("Schl\u00fcssel \u00e4\u00f6")); - assertEquals("Wert \u00e4\u00f6\u00fc", cps.get("Schl\u00fcssel \u00e4\u00f6\u00fc")); - assertEquals("Wert \u00e4\u00f6\u00fc\u00d6", cps.get("Schl\u00fcssel \u00e4\u00f6\u00fc\u00d6")); - assertEquals(POSITIVE_INTEGER, cps.get("positive_Integer")); - assertEquals(POSITIVE_LONG, cps.get("positive_Long")); - assertEquals(POSITIVE_DOUBLE, cps.get("positive_Double")); - assertEquals(NEGATIVE_INTEGER, cps.get("negative_Integer")); - assertEquals(NEGATIVE_LONG, cps.get("negative_Long")); - assertEquals(NEGATIVE_DOUBLE, cps.get("negative_Double")); - assertEquals(Boolean.TRUE, cps.get("Boolean")); - assertEquals(now, cps.get("Date")); - assertEquals(MAX_INTEGER, cps.get("max_Integer")); - assertEquals(MIN_INTEGER, cps.get("min_Integer")); - assertEquals(MAX_LONG, cps.get("max_Long")); - assertEquals(MIN_LONG, cps.get("min_Long")); - assertEquals(MAX_DOUBLE, cps.get("max_Double")); - assertEquals(MIN_DOUBLE, cps.get("min_Double")); - - /* Remove all properties supported by HPSF from the summary - * information (e.g. author, edit date, application name) and from the - * document summary information (e.g. company, manager). */ - si.removeApplicationName(); - si.removeAuthor(); - si.removeCharCount(); - si.removeComments(); - si.removeCreateDateTime(); - si.removeEditTime(); - si.removeKeywords(); - si.removeLastAuthor(); - si.removeLastPrinted(); - si.removeLastSaveDateTime(); - si.removePageCount(); - si.removeRevNumber(); - si.removeSecurity(); - si.removeSubject(); - si.removeTemplate(); - si.removeThumbnail(); - si.removeTitle(); - si.removeWordCount(); - - dsi.removeByteCount(); - dsi.removeCategory(); - dsi.removeCompany(); - dsi.removeCustomProperties(); - dsi.removeDocparts(); - dsi.removeHeadingPair(); - dsi.removeHiddenCount(); - dsi.removeLineCount(); - dsi.removeLinksDirty(); - dsi.removeManager(); - dsi.removeMMClipCount(); - dsi.removeNoteCount(); - dsi.removeParCount(); - dsi.removePresentationFormat(); - dsi.removeScale(); - dsi.removeSlideCount(); - - // Write the summary information stream and the document summary - // information stream to the POI filesystem. - si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - // Write the POI filesystem to a (temporary) file doc3 and close the latter. - FileOutputStream out = new FileOutputStream(fileOut); - poifs.writeFilesystem(out); - out.close(); - poifs.close(); - - return cps; - } - - /* - * Open {@code doc3} for reading and check summary information - * and document summary information. All properties removed before must not - * be found in the property streams of {@code doc3}. - */ - private static void write3rdFile(File fileIn) throws Exception { - POIFSFileSystem poifs = new POIFSFileSystem(fileIn, false); - SummaryInformation si = getSummaryInformation(poifs); - DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); - - assertNull(si.getApplicationName()); - assertNull(si.getAuthor()); - assertEquals(0, si.getCharCount()); - assertTrue(si.wasNull()); - assertNull(si.getComments()); - assertNull(si.getCreateDateTime()); - assertEquals(0, si.getEditTime()); - assertTrue(si.wasNull()); - assertNull(si.getKeywords()); - assertNull(si.getLastAuthor()); - assertNull(si.getLastPrinted()); - assertNull(si.getLastSaveDateTime()); - assertEquals(0, si.getPageCount()); - assertTrue(si.wasNull()); - assertNull(si.getRevNumber()); - assertEquals(0, si.getSecurity()); - assertTrue(si.wasNull()); - assertNull(si.getSubject()); - assertNull(si.getTemplate()); - assertNull(si.getThumbnail()); - assertNull(si.getTitle()); - assertEquals(0, si.getWordCount()); - assertTrue(si.wasNull()); - - assertEquals(0, dsi.getByteCount()); - assertTrue(dsi.wasNull()); - assertNull(dsi.getCategory()); - assertNull(dsi.getCustomProperties()); - // FIXME (byte array properties not yet implemented): assertNull(dsi.getDocparts()); - // FIXME (byte array properties not yet implemented): assertNull(dsi.getHeadingPair()); - assertEquals(0, dsi.getHiddenCount()); - assertTrue(dsi.wasNull()); - assertEquals(0, dsi.getLineCount()); - assertTrue(dsi.wasNull()); - assertFalse(dsi.getLinksDirty()); - assertTrue(dsi.wasNull()); - assertNull(dsi.getManager()); - assertEquals(0, dsi.getMMClipCount()); - assertTrue(dsi.wasNull()); - assertEquals(0, dsi.getNoteCount()); - assertTrue(dsi.wasNull()); - assertEquals(0, dsi.getParCount()); - assertTrue(dsi.wasNull()); - assertNull(dsi.getPresentationFormat()); - assertFalse(dsi.getScale()); - assertTrue(dsi.wasNull()); - assertEquals(0, dsi.getSlideCount()); - assertTrue(dsi.wasNull()); - poifs.close(); - } - - private static SummaryInformation getSummaryInformation(POIFSFileSystem poifs) throws Exception { - DocumentInputStream dis = poifs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME); - PropertySet ps = new PropertySet(dis); - SummaryInformation si = new SummaryInformation(ps); - dis.close(); - return si; - } - - static DocumentSummaryInformation getDocumentSummaryInformation(POIFSFileSystem poifs) - throws IOException, NoPropertySetStreamException, UnexpectedPropertySetTypeException { - if (!poifs.getRoot().hasEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)) { - return null; - } - - DocumentInputStream dis = poifs.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - PropertySet ps = new PropertySet(dis); - DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps); - dis.close(); - return dsi; - } - - /** - * Tests basic custom property features. - */ - @Test - void testCustomerProperties() - { - final String KEY = "Schl\u00fcssel \u00e4"; - final String VALUE_1 = "Wert 1"; - final String VALUE_2 = "Wert 2"; - - CustomProperty cp; - CustomProperties cps = new CustomProperties(); - assertEquals(0, cps.size()); - - /* After adding a custom property the size must be 1 and it must be - * possible to extract the custom property from the map. */ - cps.put(KEY, VALUE_1); - assertEquals(1, cps.size()); - Object v1 = cps.get(KEY); - assertEquals(VALUE_1, v1); - - /* After adding a custom property with the same name the size must still - * be one. */ - cps.put(KEY, VALUE_2); - assertEquals(1, cps.size()); - Object v2 = cps.get(KEY); - assertEquals(VALUE_2, v2); - - /* Removing the custom property must return the remove property and - * reduce the size to 0. */ - cp = cps.remove(KEY); - assertEquals(KEY, cp.getName()); - assertEquals(VALUE_2, cp.getValue()); - assertEquals(0, cps.size()); - } - - - - /** - * Tests reading custom properties from a section including reading - * custom properties which are not pure. - */ - @Test - void testGetCustomerProperties() - { - final int ID_1 = 2; - final int ID_2 = 3; - final String NAME_1 = "Schl\u00fcssel \u00e4"; - final String VALUE_1 = "Wert 1"; - final Map dictionary = new HashMap<>(); - - DocumentSummaryInformation dsi = PropertySetFactory.newDocumentSummaryInformation(); - CustomProperties cps; - Section s; - - /* A document summary information set stream by default does have custom properties. */ - cps = dsi.getCustomProperties(); - assertNull(cps); - - /* Test an empty custom properties set. */ - s = new Section(); - s.setFormatID(DocumentSummaryInformation.FORMAT_ID[1]); - // s.setCodepage(CodePageUtil.CP_UNICODE); - dsi.addSection(s); - cps = dsi.getCustomProperties(); - assertEquals(0, cps.size()); - - /* Add a custom property. */ - Property p = new Property(); - p.setID(ID_1); - p.setType(Variant.VT_LPWSTR); - p.setValue(VALUE_1); - s.setProperty(p); - dictionary.put((long) ID_1, NAME_1); - s.setDictionary(dictionary); - cps = dsi.getCustomProperties(); - assertEquals(1, cps.size()); - assertTrue(cps.isPure()); - - /* Add another custom property. */ - s.setProperty(ID_2, Variant.VT_LPWSTR, VALUE_1); - dictionary.put((long) ID_2, NAME_1); - s.setDictionary(dictionary); - cps = dsi.getCustomProperties(); - assertEquals(1, cps.size()); - assertFalse(cps.isPure()); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/Util.java b/src/testcases/org/apache/poi/hpsf/basic/Util.java deleted file mode 100644 index c6ef7ae6c7..0000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/Util.java +++ /dev/null @@ -1,129 +0,0 @@ - -/* ==================================================================== - 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.hpsf.basic; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.util.IOUtils; - - - -/** - *

Static utility methods needed by the HPSF test cases.

- */ -final class Util { - - private Util() { - } - - /** - *

Reads a set of files from a POI filesystem and returns them - * as an array of {@link POIFile} instances. This method loads all - * files into memory and thus does not cope well with large POI - * filessystems.

- * - * @param poiFs The name of the POI filesystem as seen by the - * operating system. (This is the "filename".) - * - * @param poiFiles The names of the POI files to be read. - * - * @return The POI files. The elements are ordered in the same way - * as the files in the POI filesystem. - * - * @exception FileNotFoundException if the file containing the POI - * filesystem does not exist - * - * @exception IOException if an I/O exception occurs - */ - static List readPOIFiles(final File poiFs, final String... poiFiles) throws IOException { - final List files = new ArrayList<>(); - POIFSReader r = new POIFSReader(); - POIFSReaderListener pfl = event -> assertDoesNotThrow(() -> { - final POIFile f = new POIFile(); - f.setName(event.getName()); - f.setPath(event.getPath()); - final InputStream in = event.getStream(); - f.setBytes(IOUtils.toByteArray(in)); - in.close(); - files.add(f); - }); - if (poiFiles.length == 0) { - /* Register the listener for all POI files. */ - r.registerListener(pfl); - } else { - for (String poiFile : poiFiles) { - r.registerListener(pfl, poiFile); - } - } - - /* Read the POI filesystem. */ - r.read(poiFs); - - return files; - } - - - - /** - *

Read all files from a POI filesystem which are property set streams - * and returns them as an array of {@link org.apache.poi.hpsf.PropertySet} - * instances.

- * - * @param poiFs The name of the POI filesystem as seen by the - * operating system. (This is the "filename".) - * - * @return The property sets. The elements are ordered in the same way - * as the files in the POI filesystem. - * - * @exception IOException if an I/O exception occurs - */ - static List readPropertySets(final File poiFs) throws IOException { - final List files = new ArrayList<>(7); - final POIFSReader r = new POIFSReader(); - final POIFSReaderListener pfl = event -> assertDoesNotThrow(() -> { - final POIFile f = new POIFile(); - f.setName(event.getName()); - f.setPath(event.getPath()); - final InputStream in = event.getStream(); - if (PropertySet.isPropertySetStream(in)) { - f.setBytes(IOUtils.toByteArray(in)); - files.add(f); - } - }); - - /* Register the listener for all POI files. */ - r.registerListener(pfl); - - /* Read the POI filesystem. */ - r.read(poiFs); - - return files; - } -} diff --git a/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java b/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java deleted file mode 100644 index 85d7d02b89..0000000000 --- a/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java +++ /dev/null @@ -1,182 +0,0 @@ -/* ==================================================================== - 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.hpsf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.Thumbnail; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.Test; - -final class TestHPSFPropertiesExtractor { - private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - - @Test - void testNormalProperties() throws Exception { - try (InputStream is = _samples.openResourceAsStream("TestMickey.doc"); - POIFSFileSystem fs = new POIFSFileSystem(is); - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs)) { - // Check each bit in turn - String summary = ext.getSummaryInformationText(); - String docSummary = ext.getDocumentSummaryInformationText(); - - assertContains(summary, "TEMPLATE = Normal"); - assertContains(summary, "SUBJECT = sample subject"); - assertContains(docSummary, "MANAGER = sample manager"); - assertContains(docSummary, "COMPANY = sample company"); - - // Now overall - String text = ext.getText(); - assertContains(text, "TEMPLATE = Normal"); - assertContains(text, "SUBJECT = sample subject"); - assertContains(text, "MANAGER = sample manager"); - assertContains(text, "COMPANY = sample company"); - } - } - - @Test - void testNormalUnicodeProperties() throws Exception { - - try (InputStream is = _samples.openResourceAsStream("TestUnicode.xls"); - POIFSFileSystem fs = new POIFSFileSystem(is); - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs)) { - // Check each bit in turn - String summary = ext.getSummaryInformationText(); - String docSummary = ext.getDocumentSummaryInformationText(); - - assertContains(summary, "AUTHOR = marshall"); - assertContains(summary, "TITLE = Titel: \u00c4h"); - assertContains(docSummary, "COMPANY = Schreiner"); - assertContains(docSummary, "SCALE = false"); - - // Now overall - String text = ext.getText(); - assertContains(text, "AUTHOR = marshall"); - assertContains(text, "TITLE = Titel: \u00c4h"); - assertContains(text, "COMPANY = Schreiner"); - assertContains(text, "SCALE = false"); - } - } - - @Test - void testCustomProperties() throws Exception { - try (InputStream is = _samples.openResourceAsStream("TestMickey.doc"); - POIFSFileSystem fs = new POIFSFileSystem(is); - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs)) { - - // Custom properties are part of the document info stream - String dinfText = ext.getDocumentSummaryInformationText(); - assertContains(dinfText, "Client = sample client"); - assertContains(dinfText, "Division = sample division"); - - String text = ext.getText(); - assertContains(text, "Client = sample client"); - assertContains(text, "Division = sample division"); - } - } - - @Test - void testConstructors() throws IOException { - final String fsText; - final String hwText; - final String eeText; - - try (POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream("TestUnicode.xls")); - HSSFWorkbook wb = new HSSFWorkbook(fs); - ExcelExtractor excelExt = new ExcelExtractor(wb)) { - - try (HPSFPropertiesExtractor fsExt = new HPSFPropertiesExtractor(fs)) { - // Don't close re-used test resources! - fsExt.setCloseFilesystem(false); - fsText = fsExt.getText(); - } - - try (HPSFPropertiesExtractor hwExt = new HPSFPropertiesExtractor(wb)) { - // Don't close re-used test resources! - hwExt.setCloseFilesystem(false); - hwText = hwExt.getText(); - } - - try (HPSFPropertiesExtractor eeExt = new HPSFPropertiesExtractor(excelExt)) { - // Don't close re-used test resources! - eeExt.setCloseFilesystem(false); - eeText = eeExt.getText(); - } - } - - assertEquals(fsText, hwText); - assertEquals(fsText, eeText); - - assertContains(fsText, "AUTHOR = marshall"); - assertContains(fsText, "TITLE = Titel: \u00c4h"); - } - - @Test - void test42726() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42726.xls"); - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(wb)) { - String txt = ext.getText(); - assertContains(txt, "PID_AUTHOR"); - assertContains(txt, "PID_EDITTIME"); - assertContains(txt, "PID_REVNUMBER"); - assertContains(txt, "PID_THUMBNAIL"); - } - } - - @Test - void testThumbnail() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream("TestThumbnail.xls")); - HSSFWorkbook wb = new HSSFWorkbook(fs); - Thumbnail thumbnail = new Thumbnail(wb.getSummaryInformation().getThumbnail()); - assertEquals(-1, thumbnail.getClipboardFormatTag()); - assertEquals(3, thumbnail.getClipboardFormat()); - assertNotNull(thumbnail.getThumbnailAsWMF()); - wb.close(); - } - - @Test - void test52258() throws Exception { - try (InputStream is = _samples.openResourceAsStream("TestVisioWithCodepage.vsd"); - POIFSFileSystem fs = new POIFSFileSystem(is); - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs)) { - assertNotNull(ext.getDocSummaryInformation()); - assertNotNull(ext.getDocumentSummaryInformationText()); - assertNotNull(ext.getSummaryInformation()); - assertNotNull(ext.getSummaryInformationText()); - assertNotNull(ext.getText()); - } - } - - @Test - void test61300Extractor() throws IOException { - try (POIFSFileSystem poifs = new POIFSFileSystem( - POIDataSamples.getPOIFSInstance().getFile("61300.bin"))) { - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(poifs); - assertContains(ext.getText(), "PID_CODEPAGE = 1252"); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/HSSFITestDataProvider.java b/src/testcases/org/apache/poi/hssf/HSSFITestDataProvider.java deleted file mode 100644 index 5d80a26d53..0000000000 --- a/src/testcases/org/apache/poi/hssf/HSSFITestDataProvider.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ==================================================================== - 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.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * @author Yegor Kozlov - */ -public final class HSSFITestDataProvider implements ITestDataProvider { - public static final HSSFITestDataProvider instance = new HSSFITestDataProvider(); - - private HSSFITestDataProvider(){ - // enforce singleton - } - - @Override - public HSSFWorkbook openSampleWorkbook(String sampleFileName) { - return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - public InputStream openWorkbookStream(String sampleFileName) { - return HSSFTestDataSamples.openSampleFileStream(sampleFileName); - } - - @Override - public HSSFWorkbook writeOutAndReadBack(Workbook original) { - if(!(original instanceof HSSFWorkbook)) { - throw new IllegalArgumentException("Expected an instance of HSSFWorkbook"); - } - return HSSFTestDataSamples.writeOutAndReadBack((HSSFWorkbook)original); - } - - @Override - public HSSFWorkbook createWorkbook(){ - return new HSSFWorkbook(); - } - - //************ SXSSF-specific methods ***************// - @Override - public HSSFWorkbook createWorkbook(int rowAccessWindowSize) { - return createWorkbook(); - } - - @Override - public void trackAllColumnsForAutosizing(Sheet sheet) {} - //************ End SXSSF-specific methods ***************// - - @Override - public FormulaEvaluator createFormulaEvaluator(Workbook wb) { - return new HSSFFormulaEvaluator((HSSFWorkbook) wb); - } - - @Override - public byte[] getTestDataFileContent(String fileName) { - return POIDataSamples.getSpreadSheetInstance().readFile(fileName); - } - - @Override - public SpreadsheetVersion getSpreadsheetVersion(){ - return SpreadsheetVersion.EXCEL97; - } - - @Override - public String getStandardFileNameExtension() { - return "xls"; - } -} diff --git a/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java b/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java deleted file mode 100644 index 2fe3359d4d..0000000000 --- a/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - 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.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -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 POIDataSamples _inst = POIDataSamples.getSpreadSheetInstance(); - - public static InputStream openSampleFileStream(String sampleFileName) { - return _inst.openResourceAsStream(sampleFileName); - } - public static File getSampleFile(String sampleFileName) { - return _inst.getFile(sampleFileName); - } - public static byte[] getTestDataFileContent(String fileName) { - return _inst.readFile(fileName); - } - - public static HSSFWorkbook openSampleWorkbook(String sampleFileName) { - try { - return new HSSFWorkbook(_inst.openResourceAsStream(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/dev/BaseTestIteratingXLS.java b/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java deleted file mode 100644 index 91481c80ec..0000000000 --- a/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - 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.dev; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.stream.Stream; - -import org.apache.poi.POIDataSamples; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Base class for integration-style tests which iterate over all test-files - * and execute the same action to find out if any change breaks these applications. - */ -public abstract class BaseTestIteratingXLS { - protected static final Map> EXCLUDED = new HashMap<>(); - - private static Stream files() { - String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY); - if(dataDirName == null) { - dataDirName = "test-data"; - } - - List files = new ArrayList<>(); - findFile(files, dataDirName + "/spreadsheet"); - findFile(files, dataDirName + "/hpsf"); - - return files.stream(); - } - - private static void findFile(List list, String dir) { - String[] files = new File(dir).list((arg0, arg1) -> arg1.toLowerCase(Locale.ROOT).endsWith(".xls")); - assertNotNull(files, "Did not find any xls files in directory " + dir); - - for(String file : files) { - list.add(Arguments.of(new File(dir, file))); - } - } - - @ParameterizedTest - @MethodSource("files") - void testMain(File file) throws Exception { - String fileName = file.getName(); - - Class t = EXCLUDED.get(fileName); - - if (t == null) { - runOneFile(file); - } else { - assertThrows(t, () -> runOneFile(file)); - } - - } - - abstract void runOneFile(File pFile) throws Exception; -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java deleted file mode 100644 index ee06b7d101..0000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - 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.dev; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.util.NullOutputStream; -import org.apache.poi.util.RecordFormatException; -import org.junit.jupiter.api.BeforeAll; - -class TestBiffDrawingToXml extends BaseTestIteratingXLS { - @BeforeAll - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header - EXCLUDED.put("51832.xls", EncryptedDocumentException.class); - EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class); - EXCLUDED.put("password.xls", EncryptedDocumentException.class); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well - EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); - EXCLUDED.put("61300.xls", RecordFormatException.class); - EXCLUDED.put("64130.xls", OldExcelFormatException.class); // BIFF 5 - } - - @Override - void runOneFile(File pFile) throws Exception { - try (InputStream wb = new FileInputStream(pFile)) { - BiffDrawingToXml.writeToFile(new NullOutputStream(), wb, false, new String[0]); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java deleted file mode 100644 index 7c6cf1b1f5..0000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - 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.dev; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; - -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.NullOutputStream; -import org.apache.poi.util.RecordFormatException; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -@Execution(ExecutionMode.CONCURRENT) -class TestBiffViewer extends BaseTestIteratingXLS { - @BeforeAll - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("35897-type4.xls", IllegalArgumentException.class); // unsupported crypto api header - EXCLUDED.put("51832.xls", IllegalArgumentException.class); - EXCLUDED.put("xor-encryption-abc.xls", RecordFormatException.class); - EXCLUDED.put("password.xls", IllegalArgumentException.class); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("43493.xls", RecordFormatException.class); // HSSFWorkbook cannot open it as well - // EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); - EXCLUDED.put("50833.xls", IllegalArgumentException.class); // "Name is too long" when setting username - EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun" - EXCLUDED.put("61300.xls", IndexOutOfBoundsException.class); - EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5 - } - - @Override - void runOneFile(File fileIn) throws IOException { - try (POIFSFileSystem fs = new POIFSFileSystem(fileIn, true); - InputStream is = BiffViewer.getPOIFSInputStream(fs)) { - // use a NullOutputStream to not write the bytes anywhere for best runtime - PrintWriter dummy = new PrintWriter(new OutputStreamWriter(new NullOutputStream(), LocaleUtil.CHARSET_1252)); - BiffViewer.runBiffViewer(dummy, is, true, true, true, false); - } - } - -// @Test -// @Disabled("only used for manual tests") -// @SuppressWarnings("java:S2699") -// void testOneFile() throws Exception { -// POIDataSamples samples = POIDataSamples.getSpreadSheetInstance(); -// runOneFile(samples.getFile("43493.xls")); -// } -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java deleted file mode 100644 index 56be2c87af..0000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - 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.dev; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.util.NullPrintStream; -import org.apache.poi.util.RecordFormatException; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.parallel.ResourceLock; -import org.junit.jupiter.api.parallel.Resources; - -@ResourceLock(Resources.SYSTEM_OUT) -class TestEFBiffViewer extends BaseTestIteratingXLS { - @BeforeAll - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header - EXCLUDED.put("51832.xls", EncryptedDocumentException.class); - EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class); - EXCLUDED.put("password.xls", EncryptedDocumentException.class); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well - EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); - // EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun" - EXCLUDED.put("61300.xls", RecordFormatException.class); - EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5 - } - - @Override - void runOneFile(File fileIn) throws IOException { - PrintStream save = System.out; - try { - // redirect standard out during the test to avoid spamming the console with output - System.setOut(new NullPrintStream()); - - EFBiffViewer.main(new String[] { fileIn.getAbsolutePath() }); - } finally { - System.setOut(save); - } - } - - //@Test - void testFile() throws IOException { - EFBiffViewer viewer = new EFBiffViewer(); - viewer.setFile(new File("test-data/spreadsheet/59074.xls").getAbsolutePath()); - viewer.run(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java deleted file mode 100644 index a0cdaddcd2..0000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - 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.dev; - -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.File; -import java.io.PrintStream; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.util.NullPrintStream; -import org.apache.poi.util.RecordFormatException; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.parallel.ResourceLock; -import org.junit.jupiter.api.parallel.Resources; - -@ResourceLock(Resources.SYSTEM_OUT) -class TestFormulaViewer extends BaseTestIteratingXLS { - @BeforeAll - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header - EXCLUDED.put("51832.xls", EncryptedDocumentException.class); - EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class); - EXCLUDED.put("password.xls", EncryptedDocumentException.class); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well - EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); - EXCLUDED.put("61300.xls", RecordFormatException.class); - EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5 - } - - @Override - void runOneFile(File fileIn) throws Exception { - PrintStream save = System.out; - try { - // redirect standard out during the test to avoid spamming the console with output - System.setOut(new NullPrintStream()); - - FormulaViewer viewer = new FormulaViewer(); - viewer.setFile(fileIn.getAbsolutePath()); - viewer.setList(true); - viewer.run(); - } catch (RuntimeException re) { - String m = re.getMessage(); - if (m.startsWith("toFormulaString") || m.startsWith("3D references")) { - // TODO: fix those cases, but ignore them for now ... - assumeTrue(true); - } else { - throw re; - } - } finally { - System.setOut(save); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestReSave.java b/src/testcases/org/apache/poi/hssf/dev/TestReSave.java deleted file mode 100644 index 868561df21..0000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestReSave.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - 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.dev; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.PrintStream; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.util.NullPrintStream; -import org.apache.poi.util.RecordFormatException; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Isolated; -import org.junit.jupiter.api.parallel.ResourceLock; -import org.junit.jupiter.api.parallel.Resources; - -@Isolated("Modifies the test data directory") -@ResourceLock(Resources.SYSTEM_OUT) -class TestReSave extends BaseTestIteratingXLS { - @BeforeAll - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header - EXCLUDED.put("51832.xls", EncryptedDocumentException.class); - EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class); - EXCLUDED.put("password.xls", EncryptedDocumentException.class); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well - EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); - EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun" - EXCLUDED.put("61300.xls", RecordFormatException.class); - EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5 - } - - @Override - void runOneFile(File fileIn) throws Exception { - // avoid running on files leftover from previous failed runs - if(fileIn.getName().endsWith("-saved.xls")) { - return; - } - - PrintStream save = System.out; - try { - // redirect standard out during the test to avoid spamming the console with output - System.setOut(new NullPrintStream()); - - File reSavedFile = new File(fileIn.getParentFile(), fileIn.getName().replace(".xls", "-saved.xls")); - try { - ReSave.main(new String[] { fileIn.getAbsolutePath() }); - - // also try BiffViewer on the saved file - new TestBiffViewer().runOneFile(reSavedFile); - - // had one case where the re-saved could not be re-saved! - ReSave.main(new String[] { "-bos", reSavedFile.getAbsolutePath() }); - } finally { - // clean up the re-saved file - assertTrue(!reSavedFile.exists() || reSavedFile.delete()); - } - } finally { - System.setOut(save); - } - } - - @Disabled("Only used for local testing") - @Test - void testOneFile() throws Exception { - String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY); - if(dataDirName == null) { - dataDirName = "test-data"; - } - - runOneFile(new File(dataDirName + "/spreadsheet", "49931.xls")); - } -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java b/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java deleted file mode 100644 index 9eb6ebc255..0000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - 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.dev; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; - -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.util.NullPrintStream; -import org.apache.poi.util.RecordFormatException; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.parallel.ResourceLock; -import org.junit.jupiter.api.parallel.Resources; - -@ResourceLock(Resources.SYSTEM_OUT) -class TestRecordLister extends BaseTestIteratingXLS { - @BeforeAll - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("61300.xls", RecordFormatException.class); - EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5 - } - - @Override - void runOneFile(File fileIn) throws IOException { - PrintStream save = System.out; - try { - // redirect standard out during the test to avoid spamming the console with output - System.setOut(new NullPrintStream()); - - RecordLister viewer = new RecordLister(); - viewer.setFile(fileIn.getAbsolutePath()); - viewer.run(); - } finally { - System.setOut(save); - } - } - - //@Test - void testFile() throws IOException { - RecordLister viewer = new RecordLister(); - viewer.setFile(new File("test-data/spreadsheet/testEXCEL_95.xls").getAbsolutePath()); - viewer.run(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java b/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java deleted file mode 100644 index 058e1eda09..0000000000 --- a/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java +++ /dev/null @@ -1,108 +0,0 @@ -/* ==================================================================== - 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.eventmodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.eventusermodel.AbortableHSSFListener; -import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; -import org.apache.poi.hssf.eventusermodel.HSSFRequest; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link AbortableHSSFListener} - */ -final class TestAbortableListener { - - private POIFSFileSystem openSample() throws IOException { - ByteArrayInputStream is = new ByteArrayInputStream(HSSFITestDataProvider.instance - .getTestDataFileContent("SimpleWithColours.xls")); - return new POIFSFileSystem(is); - } - - @Test - void testAbortingBasics() throws Exception { - AbortableCountingListener l = new AbortableCountingListener(1000); - - HSSFRequest req = new HSSFRequest(); - req.addListenerForAllRecords(l); - - HSSFEventFactory f = new HSSFEventFactory(); - - assertEquals(0, l.countSeen); - assertNull(l.lastRecordSeen); - - POIFSFileSystem fs = openSample(); - short res = f.abortableProcessWorkbookEvents(req, fs); - - assertEquals(0, res); - assertEquals(175, l.countSeen); - assertEquals(EOFRecord.sid, l.lastRecordSeen.getSid()); - } - - @Test - void testAbortStops() throws Exception { - AbortableCountingListener l = new AbortableCountingListener(1); - - HSSFRequest req = new HSSFRequest(); - req.addListenerForAllRecords(l); - - HSSFEventFactory f = new HSSFEventFactory(); - - assertEquals(0, l.countSeen); - assertNull(l.lastRecordSeen); - - POIFSFileSystem fs = openSample(); - short res = f.abortableProcessWorkbookEvents(req, fs); - - assertEquals(1234, res); - assertEquals(1, l.countSeen); - assertEquals(BOFRecord.sid, l.lastRecordSeen.getSid()); - } - - private static final class AbortableCountingListener extends AbortableHSSFListener { - private final int abortAfterIndex; - public int countSeen; - public Record lastRecordSeen; - - public AbortableCountingListener(int abortAfter) { - abortAfterIndex = abortAfter; - countSeen = 0; - lastRecordSeen = null; - } - @Override - public short abortableProcessRecord(org.apache.poi.hssf.record.Record record) { - countSeen++; - lastRecordSeen = record; - - if (countSeen == abortAfterIndex) { - return 1234; - } - return 0; - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java b/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java deleted file mode 100644 index 8bb1b6771c..0000000000 --- a/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - 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.eventmodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.SequenceInputStream; -import java.util.Iterator; -import java.util.stream.Stream; - -import org.apache.commons.collections4.IteratorUtils; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.ContinueRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordFactory; -import org.apache.poi.hssf.record.StandardRecord; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.record.UnknownRecord; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * enclosing_type describe the purpose here - */ -final class TestEventRecordFactory { - private static final byte[][] CONTINUE_DATA = { - // an unknown record with 0 length - {0, -1, 0, 0,}, - // a continuation record with 3 bytes of data - {0x3C, 0, 3, 0, 1, 2, 3,}, - // one more continuation record with 1 byte of data - {0x3C, 0, 1, 0, 4} - }; - - /** - * tests that the records can be processed and properly return values. - */ - @Test - void testProcessRecords() { - final boolean[] wascalled = { false }; // hack to pass boolean by ref into inner class - - ERFListener listener = rec -> { - wascalled[0] = true; - assertEquals(rec.getSid(), BOFRecord.sid, "must be BOFRecord got SID=" + rec.getSid()); - return true; - }; - EventRecordFactory factory = new EventRecordFactory(listener, new short[] {BOFRecord.sid}); - - BOFRecord bof = new BOFRecord(); - bof.setBuild((short)0); - bof.setBuildYear((short)1999); - bof.setRequiredVersion(123); - bof.setType(BOFRecord.TYPE_WORKBOOK); - bof.setVersion((short)0x06); - bof.setHistoryBitMask(BOFRecord.HISTORY_MASK); - - EOFRecord eof = EOFRecord.instance; - byte[] bytes = new byte[bof.getRecordSize() + eof.getRecordSize()]; - int offset = 0; - offset = bof.serialize(offset,bytes); - eof.serialize(offset,bytes); - - factory.processRecords(new ByteArrayInputStream(bytes)); - assertTrue(wascalled[0], "The record listener must be called"); - } - - - /** - * tests that the create record function returns a properly - * constructed record in the simple case. - */ - @Test - void testCreateRecord() { - BOFRecord bof = new BOFRecord(); - bof.setBuild((short)0); - bof.setBuildYear((short)1999); - bof.setRequiredVersion(123); - bof.setType(BOFRecord.TYPE_WORKBOOK); - bof.setVersion((short)0x06); - bof.setHistoryBitMask(BOFRecord.HISTORY_MASK); - - byte[] bytes = bof.serialize(); - - Record[] records = RecordFactory.createRecord(TestcaseRecordInputStream.create(bytes)); - - assertEquals(1, records.length, "record.length must be 1, was =" + records.length); - - byte[] rec1 = bof.serialize(); - byte[] rec2 = records[0].serialize(); - assertArrayEquals(rec1, rec2); - } - - /* - * tests that the create record function returns a properly - * constructed record in the case of a continued record. - * TODO - need a real world example to put in a unit test - */ - // @NotImplemented - // @Test - // @Disabled - // void testCreateContinuedRecord() { - // } - - - /** - * TEST NAME: Test Creating ContinueRecords After Unknown Records From An InputStream

- * OBJECTIVE: Test that the RecordFactory given an InputStream - * constructs the expected records.

- * SUCCESS: Record factory creates the expected records.

- * FAILURE: The wrong records are created or contain the wrong values

- * - */ - @Test - void testContinuedUnknownRecord() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - for (byte[] b : CONTINUE_DATA) { - bos.write(b); - } - continueHelper(new ByteArrayInputStream(bos.toByteArray())); - } - - @Test - @Disabled("same as testContinuedUnknownRecord but with SequenceInputStream which causes the available() bug 59893") - void bug59893() { - Iterator iter = Stream.of(CONTINUE_DATA).map(ByteArrayInputStream::new).iterator(); - SequenceInputStream sis = new SequenceInputStream(IteratorUtils.asEnumeration(iter)); - continueHelper(sis); - } - - private void continueHelper(InputStream data) { - Iterator> expectedType = - Stream.of(UnknownRecord.class, ContinueRecord.class, ContinueRecord.class).iterator(); - Iterator expectedData = Stream.of(CONTINUE_DATA).iterator(); - - ERFListener listener = rec -> { - assertEquals(expectedType.next(), rec.getClass()); - assertArrayEquals(expectedData.next(), rec.serialize()); - return true; - }; - EventRecordFactory factory = new EventRecordFactory(listener, new short[] {-256, 0x3C}); - factory.processRecords(data); - assertFalse(expectedData.hasNext(), "left over input data"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java deleted file mode 100644 index fcd9d81dbc..0000000000 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java +++ /dev/null @@ -1,159 +0,0 @@ -/* ==================================================================== - 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.eventusermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.Ref3DPtg; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link EventWorkbookBuilder} - */ -final class TestEventWorkbookBuilder { - private final List fRecs = new ArrayList<>(); - private SheetRecordCollectingListener listener; - - @BeforeEach - void setUp() throws IOException { - HSSFRequest req = new HSSFRequest(); - fRecs.clear(); - listener = new SheetRecordCollectingListener(this::addFormulaRecord); - req.addListenerForAllRecords(listener); - - HSSFEventFactory factory = new HSSFEventFactory(); - try (InputStream is = HSSFTestDataSamples.openSampleFileStream("3dFormulas.xls"); - POIFSFileSystem fs = new POIFSFileSystem(is)) { - factory.processWorkbookEvents(req, fs); - } - } - - private void addFormulaRecord(org.apache.poi.hssf.record.Record r) { - if (r instanceof FormulaRecord) { - fRecs.add((FormulaRecord)r); - } - } - - @Test - void testBasics() { - assertNotNull(listener.getSSTRecord()); - assertNotNull(listener.getBoundSheetRecords()); - assertNotNull(listener.getExternSheetRecords()); - } - - @Test - void testGetStubWorkbooks() { - assertNotNull(listener.getStubWorkbook()); - assertNotNull(listener.getStubHSSFWorkbook()); - } - - @Test - void testContents() { - assertEquals(2, listener.getSSTRecord().getNumStrings()); - assertEquals(3, listener.getBoundSheetRecords().length); - assertEquals(1, listener.getExternSheetRecords().length); - - assertEquals(3, listener.getStubWorkbook().getNumSheets()); - - InternalWorkbook ref = listener.getStubWorkbook(); - assertEquals("Sh3", ref.findSheetFirstNameFromExternSheet(0)); - assertEquals("Sheet1", ref.findSheetFirstNameFromExternSheet(1)); - assertEquals("S2", ref.findSheetFirstNameFromExternSheet(2)); - } - - @Test - void testFormulas() { - - // Check our formula records - assertEquals(6, fRecs.size()); - - InternalWorkbook stubWB = listener.getStubWorkbook(); - assertNotNull(stubWB); - HSSFWorkbook stubHSSF = listener.getStubHSSFWorkbook(); - assertNotNull(stubHSSF); - - // Check these stubs have the right stuff on them - assertEquals("Sheet1", stubWB.getSheetName(0)); - assertEquals("Sheet1", stubHSSF.getSheetName(0)); - assertEquals("S2", stubWB.getSheetName(1)); - assertEquals("S2", stubHSSF.getSheetName(1)); - assertEquals("Sh3", stubWB.getSheetName(2)); - assertEquals("Sh3", stubHSSF.getSheetName(2)); - - // Check we can get the formula without breaking - for (FormulaRecord fRec : fRecs) { - HSSFFormulaParser.toFormulaString(stubHSSF, fRec.getParsedExpression()); - } - - // Peer into just one formula, and check that - // all the ptgs give back the right things - Ptg[] ptgs = fRecs.get(0).getParsedExpression(); - assertEquals(1, ptgs.length); - assertTrue(ptgs[0] instanceof Ref3DPtg); - - Ref3DPtg ptg = (Ref3DPtg)ptgs[0]; - HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(stubHSSF); - assertEquals("Sheet1!A1", ptg.toFormulaString(book)); - - - // Now check we get the right formula back for - // a few sample ones - FormulaRecord fr; - - // Sheet 1 A2 is on same sheet - fr = fRecs.get(0); - assertEquals(1, fr.getRow()); - assertEquals(0, fr.getColumn()); - assertEquals("Sheet1!A1", HSSFFormulaParser.toFormulaString(stubHSSF, fr.getParsedExpression())); - - // Sheet 1 A5 is to another sheet - fr = fRecs.get(3); - assertEquals(4, fr.getRow()); - assertEquals(0, fr.getColumn()); - assertEquals("'S2'!A1", HSSFFormulaParser.toFormulaString(stubHSSF, fr.getParsedExpression())); - - // Sheet 1 A7 is to another sheet, range - fr = fRecs.get(5); - assertEquals(6, fr.getRow()); - assertEquals(0, fr.getColumn()); - assertEquals("SUM(Sh3!A1:A4)", HSSFFormulaParser.toFormulaString(stubHSSF, fr.getParsedExpression())); - - - // Now, load via Usermodel and re-check - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("3dFormulas.xls"); - assertEquals("Sheet1!A1", wb.getSheetAt(0).getRow(1).getCell(0).getCellFormula()); - assertEquals("SUM(Sh3!A1:A4)", wb.getSheetAt(0).getRow(6).getCell(0).getCellFormula()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java deleted file mode 100644 index 74ac31845d..0000000000 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - 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.eventusermodel; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.CellValueRecordInterface; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.Test; - -/** - * Tests for FormatTrackingHSSFListener - */ -final class TestFormatTrackingHSSFListener { - private FormatTrackingHSSFListener listener; - private MockHSSFListener mockListen; - - private void processFile(String filename) throws Exception { - HSSFRequest req = new HSSFRequest(); - mockListen = new MockHSSFListener(); - listener = new FormatTrackingHSSFListener(mockListen); - req.addListenerForAllRecords(listener); - - File file = HSSFTestDataSamples.getSampleFile(filename); - HSSFEventFactory factory = new HSSFEventFactory(); - POIFSFileSystem fs = new POIFSFileSystem(file); - factory.processWorkbookEvents(req, fs); - fs.close(); - } - - @Test - void testFormats() throws Exception { - processFile("MissingBits.xls"); - - assertEquals("_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)", listener.getFormatString(41)); - assertEquals("_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)", listener.getFormatString(42)); - assertEquals("_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)", listener.getFormatString(43)); - assertEquals("_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)", listener.getFormatString(44)); - } - - /** - * Ensure that all number and formula records can be - * turned into strings without problems. - * For now, we're just looking to get text back, no - * exceptions thrown, but in future we might also - * want to check the exact strings! - */ - @Test - void testTurnToString() throws Exception { - String[] files = new String[] { - "45365.xls", "45365-2.xls", "MissingBits.xls" - }; - for (String file : files) { - processFile(file); - - // Check we found our formats - assertTrue(listener.getNumberOfCustomFormats() > 5); - assertTrue(listener.getNumberOfExtendedFormats() > 5); - - // Now check we can turn all the numeric - // cells into strings without error - for(org.apache.poi.hssf.record.Record r : mockListen._records) { - CellValueRecordInterface cvr = null; - - if(r instanceof NumberRecord) { - cvr = (CellValueRecordInterface)r; - } - if(r instanceof FormulaRecord) { - cvr = (CellValueRecordInterface)r; - } - - if(cvr != null) { - // Should always give us a string - String s = listener.formatNumberDateCell(cvr); - assertNotNull(s); - assertTrue(s.length() > 0); - } - } - - // TODO - test some specific format strings - } - } - - private static final class MockHSSFListener implements HSSFListener { - public MockHSSFListener() {} - private final List _records = new ArrayList<>(); - - @Override - public void processRecord(org.apache.poi.hssf.record.Record record) { - _records.add(record); - } - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java deleted file mode 100644 index 24fba3e492..0000000000 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ==================================================================== - 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.eventusermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.BoundSheetRecord; -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.FeatHdrRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.SelectionRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.Test; - -/** - * Testing for {@link HSSFEventFactory} - */ -final class TestHSSFEventFactory { - private final List records = new ArrayList<>(); - - private void openSample(String sampleFileName) throws IOException { - records.clear(); - HSSFRequest req = new HSSFRequest(); - req.addListenerForAllRecords(records::add); - try (InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName); - POIFSFileSystem fs = new POIFSFileSystem(is)) { - HSSFEventFactory factory = new HSSFEventFactory(); - factory.processWorkbookEvents(req, fs); - } - } - - @Test - void testWithMissingRecords() throws Exception { - - openSample("SimpleWithSkip.xls"); - - int numRec = records.size(); - - // Check we got the records - assertTrue( numRec > 100 ); - - // Check that the last few records are as we expect - // (Makes sure we don't accidently skip the end ones) - Class[] exp = { WindowTwoRecord.class, SelectionRecord.class, EOFRecord.class }; - Class[] act = records.subList(numRec - 3, numRec).stream().map(Object::getClass).toArray(Class[]::new); - assertArrayEquals(exp, act); - } - - @Test - void testWithCrazyContinueRecords() throws Exception { - // Some files have crazy ordering of their continue records - // Check that we don't break on them (bug #42844) - - openSample("ContinueRecordProblem.xls"); - - int numRec = records.size(); - // Check we got the records - assertTrue( numRec > 100 ); - - // And none of them are continue ones - assertFalse(records.stream().anyMatch(r -> r instanceof ContinueRecord)); - - // Check that the last few records are as we expect - // (Makes sure we don't accidentally skip the end ones) - Class[] exp = { DVALRecord.class, DVRecord.class, FeatHdrRecord.class, EOFRecord.class }; - Class[] act = records.subList(numRec-4, numRec).stream().map(Object::getClass).toArray(Class[]::new); - assertArrayEquals(exp, act); - } - - /** - * Unknown records can be continued. - * Check that HSSFEventFactory doesn't break on them. - * (the test file was provided in a reopen of bug #42844) - */ - @Test - @SuppressWarnings("java:S2699") - void testUnknownContinueRecords() throws Exception { - openSample("42844.xls"); - } - - @Test - @SuppressWarnings("java:S2699") - void testWithDifferentWorkbookName() throws Exception { - openSample("BOOK_in_capitals.xls"); - openSample("WORKBOOK_in_capitals.xls"); - } - - @Test - @SuppressWarnings("java:S2699") - void testWithPasswordProtectedWorkbooksNoPass() { - // Without a password, can't be read - assertThrows(EncryptedDocumentException.class, () -> openSample("xor-encryption-abc.xls")); - } - - @Test - void testWithPasswordProtectedWorkbooks() throws Exception { - // With the password, is properly processed - Biff8EncryptionKey.setCurrentUserPassword("abc"); - try { - openSample("xor-encryption-abc.xls"); - - // Check we got the sheet and the contents - assertTrue(records.size() > 50); - - // Has one sheet, with values 1,2,3 in column A rows 1-3 - boolean hasSheet = false, hasA1 = false, hasA2 = false, hasA3 = false; - for (org.apache.poi.hssf.record.Record r : records) { - if (r instanceof BoundSheetRecord) { - BoundSheetRecord bsr = (BoundSheetRecord) r; - assertEquals("Sheet1", bsr.getSheetname()); - hasSheet = true; - } - if (r instanceof NumberRecord) { - NumberRecord nr = (NumberRecord) r; - if (nr.getColumn() == 0 && nr.getRow() == 0) { - assertEquals(1, (int) nr.getValue()); - hasA1 = true; - } - if (nr.getColumn() == 0 && nr.getRow() == 1) { - assertEquals(2, (int) nr.getValue()); - hasA2 = true; - } - if (nr.getColumn() == 0 && nr.getRow() == 2) { - assertEquals(3, (int) nr.getValue()); - hasA3 = true; - } - } - } - - assertTrue(hasSheet, "Sheet record not found"); - assertTrue(hasA1, "Numeric record for A1 not found"); - assertTrue(hasA2, "Numeric record for A2 not found"); - assertTrue(hasA3, "Numeric record for A3 not found"); - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java deleted file mode 100644 index 852f07e9de..0000000000 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java +++ /dev/null @@ -1,226 +0,0 @@ -/* ==================================================================== - 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.eventusermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Predicate; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord; -import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord; -import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingRowDummyRecord; -import org.apache.poi.hssf.record.BlankRecord; -import org.apache.poi.hssf.record.CellValueRecordInterface; -import org.apache.poi.hssf.record.DimensionsRecord; -import org.apache.poi.hssf.record.LabelSSTRecord; -import org.apache.poi.hssf.record.MulBlankRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.RowRecord; -import org.apache.poi.hssf.record.SharedFormulaRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.Test; - -/** - * Tests for MissingRecordAwareHSSFListener - */ -final class TestMissingRecordAwareHSSFListener { - - private final List _records = new ArrayList<>(); - - private void readRecords(String sampleFileName) throws IOException { - _records.clear(); - HSSFRequest req = new HSSFRequest(); - req.addListenerForAllRecords(new MissingRecordAwareHSSFListener(_records::add)); - - HSSFEventFactory factory = new HSSFEventFactory(); - try (InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName); - POIFSFileSystem fs = new POIFSFileSystem(is)) { - factory.processWorkbookEvents(req, fs); - } - - assertTrue(_records.size() > 100); - } - - @Test - void testMissingRowRecords() throws IOException { - readRecords("MissingBits.xls"); - - // We have rows 0, 1, 2, 20 and 21 - int row0 = lastIndexOf(r -> r instanceof RowRecord && ((RowRecord)r).getRowNumber() == 0); - assertTrue(row0 > -1); - - // Records: row 0: column 1, 2), then missing rows, rows 20,21,22 each 1 column - String exp1 = - "0:rr,1:rr,2:rr,3:mr,4:mr,5:mr,6:mr,7:mr,8:mr,9:mr,10:mr,11:mr,12:mr,13:mr,14:mr," + - "15:mr,16:mr,17:mr,18:mr,19:mr,20:rr,21:rr,22:rr"; - String act1 = digest(row0, 22); - assertEquals(exp1, act1); - - - // Find the cell at 0,0 - int cell00 = lastIndexOf(r -> r instanceof LabelSSTRecord && ((LabelSSTRecord)r).getRow() == 0 && ((LabelSSTRecord)r).getColumn() == 0); - - String exp2 = - "0:ls0lc0," + - "1:nr0/11mc1mc2nr3/23lc3," + - "2:nr0/45mc1mc2mc3mc4nr5/22lc5," + - "3:lc,4:lc,5:lc,6:lc,7:lc,8:lc,9:lc,10:lc,11:lc,12:lc,13:lc,14:lc,15:lc,16:lc,17:lc,18:lc,19:lc," + - "20:nr0/50nr1/51nr2/52nr3/53nr4/54lc4," + - "21:ls0ls1mc2nr3/12mc4nr5/23nr6/42lc6," + - "22:ls0mc1mc2ls3ls4mc5mc6mc7mc8mc9mc10ls11lc11"; - String act2 = digest(cell00, 57); - assertEquals(exp2, act2); - } - - // Make sure we don't put in any extra new lines that aren't already there - @Test - void testNoExtraNewLines() throws IOException { - // Load a different file - // This file has has something in lines 1-33 - readRecords("MRExtraLines.xls"); - - int rowCount=0; - for (org.apache.poi.hssf.record.Record rec : _records) { - if (rec instanceof LastCellOfRowDummyRecord) { - LastCellOfRowDummyRecord eor = (LastCellOfRowDummyRecord) rec; - assertEquals(rowCount, eor.getRow()); - rowCount++; - } - } - // Check we got the 33 rows - assertEquals(33, rowCount); - } - - /** - * Make sure that the presence of shared formulas does not cause extra end-of-row records. - */ - @Test - void testEndOfRow_bug45672() throws IOException { - readRecords("ex45672.xls"); - assertEquals(1, matches(r -> r instanceof SharedFormulaRecord)); - assertEquals(1, matches(r -> r instanceof LastCellOfRowDummyRecord)); - } - - /** - * MulBlank records hold multiple blank cells. - * Check that we don't have any MulBlankRecords, but do have lots of BlankRecords - */ - @Test - void testMulBlankHandling() throws IOException { - readRecords("45672.xls"); - assertEquals(20, matches(r -> r instanceof BlankRecord)); - assertEquals(2, matches(r -> r instanceof LastCellOfRowDummyRecord)); - assertEquals(0, matches(r -> r instanceof MulBlankRecord)); - } - - @Test - void testStringRecordHandling() throws IOException { - readRecords("53588.xls"); - assertEquals(1, matches(r -> r instanceof MissingCellDummyRecord)); - assertEquals(1, matches(r -> r instanceof LastCellOfRowDummyRecord)); - } - - @Test - void testFormulasWithStringResultsHandling() throws IOException { - readRecords("53433.xls"); - - String exp = - "dr0:mr,1:mr,2:mr,3:rr,4:rr,5:rr,6:rr,7:rr,8:rr,9:rr,10:mr,11:mr,12:mr,13:mr,14:mr,15:rr,16:rr,17:mr,18:rr," + - "0:lc,1:lc,2:lc,3:mc0ls1ls2ls3ls4lc4,4:mc0ls1cv2urnr3/12cv4urlc4," + - "5:mc0cv1urnr2/23nr3/23cv4urlc4,6:mc0mc1nr2/25nr3/45nr4/32815lc4," + - "7:mc0ls1cv2cv3urcv4lc4,8:mc0mc1mc2mc3cv4lc4,9:mc0mc1mc2ls3lc3," + - "10:lc,11:lc,12:lc,13:lc,14:lc,15:mc0ls1lc1,16:mc0mc1mc2ls3lc3," + - "17:lc,18:mc0mc1mc2mc3ls4lc4wr"; - String act = digest(95, 89); - assertEquals(exp, act); - } - - private int lastIndexOf(Predicate pre) { - int found = -1; - int i = 0; - for (org.apache.poi.hssf.record.Record r : _records) { - if (pre.test(r)) { - found = i; - } - i++; - } - return found; - } - - private String digest(int start, int len) { - StringBuilder sb = new StringBuilder(len*10); - int lastRow = -1; - for (org.apache.poi.hssf.record.Record r : _records.subList(start, start+len+1)) { - String dig = null; - int row = -1; - if (r instanceof RowRecord) { - RowRecord rr = (RowRecord)r; - row = rr.getRowNumber(); - dig = "rr"; - } else if (r instanceof MissingRowDummyRecord) { - MissingRowDummyRecord mr = (MissingRowDummyRecord)r; - row = mr.getRowNumber(); - dig = "mr"; - } else if (r instanceof MissingCellDummyRecord) { - MissingCellDummyRecord mc = (MissingCellDummyRecord)r; - row = mc.getRow(); - dig = "mc" + mc.getColumn(); - } else if (r instanceof LastCellOfRowDummyRecord) { - LastCellOfRowDummyRecord lc = (LastCellOfRowDummyRecord)r; - row = lc.getRow(); - dig = "lc" + (lc.getLastColumnNumber() > -1 ? lc.getLastColumnNumber() : ""); - } else if (r instanceof NumberRecord) { - NumberRecord nr = (NumberRecord)r; - row = nr.getRow(); - dig = "nr" + nr.getColumn() + "/" + (int)nr.getValue(); - } else if (r instanceof LabelSSTRecord) { - LabelSSTRecord ls = (LabelSSTRecord) r; - row = ls.getRow(); - dig = "ls" + ls.getColumn(); - } else if (r instanceof WindowTwoRecord) { - dig = "wr"; - } else if (r instanceof DimensionsRecord) { - dig = "dr"; - } else if (r instanceof CellValueRecordInterface) { - CellValueRecordInterface cv = (CellValueRecordInterface) r; - row = cv.getRow(); - dig = "cv" + cv.getColumn(); - } else { - // unhandled record - dig = "ur"; - } - if (lastRow != row && row > -1) { - sb.append((lastRow > -1 ? "," : "") + row + ":"); - lastRow = row; - } - sb.append(dig); - } - return sb.toString(); - } - - private long matches(Predicate r) { - return _records.stream().filter(r).count(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java b/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java deleted file mode 100644 index 7a5ceef5f1..0000000000 --- a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java +++ /dev/null @@ -1,385 +0,0 @@ -/* ==================================================================== - 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.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.POITestCase.assertStartsWith; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.util.Locale; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * - */ -final class TestExcelExtractor { - private static ExcelExtractor createExtractor(String sampleFileName) throws IOException { - File file = HSSFTestDataSamples.getSampleFile(sampleFileName); - POIFSFileSystem fs = new POIFSFileSystem(file); - return new ExcelExtractor(fs); - } - - @Test - void testSimple() throws IOException { - try (ExcelExtractor extractor = createExtractor("Simple.xls")) { - assertEquals("Sheet1\nreplaceMe\nSheet2\nSheet3\n", extractor.getText()); - - // Now turn off sheet names - extractor.setIncludeSheetNames(false); - assertEquals("replaceMe\n", extractor.getText()); - } - } - - @Test - void testNumericFormula() throws IOException { - try (ExcelExtractor extractor = createExtractor("sumifformula.xls")) { - assertEquals( - "Sheet1\n" + - "1000\t1\t5\n" + - "2000\t2\n" + - "3000\t3\n" + - "4000\t4\n" + - "5000\t5\n" + - "Sheet2\nSheet3\n", - extractor.getText() - ); - - extractor.setFormulasNotResults(true); - - assertEquals( - "Sheet1\n" + - "1000\t1\tSUMIF(A1:A5,\">4000\",B1:B5)\n" + - "2000\t2\n" + - "3000\t3\n" + - "4000\t4\n" + - "5000\t5\n" + - "Sheet2\nSheet3\n", - extractor.getText() - ); - } - } - - @Test - void testWithContinueRecords() throws IOException { - try (ExcelExtractor extractor = createExtractor("StringContinueRecords.xls")) { - // Has masses of text - // Until we fixed bug #41064, this would've - // failed by now - assertTrue(extractor.getText().length() > 40960); - } - } - - @Test - void testStringConcat() throws IOException { - try (ExcelExtractor extractor = createExtractor("SimpleWithFormula.xls")) { - // Comes out as NaN if treated as a number - // And as XYZ if treated as a string - assertEquals("Sheet1\nreplaceme\nreplaceme\nreplacemereplaceme\nSheet2\nSheet3\n", extractor.getText()); - - extractor.setFormulasNotResults(true); - - assertEquals("Sheet1\nreplaceme\nreplaceme\nCONCATENATE(A1,A2)\nSheet2\nSheet3\n", extractor.getText()); - } - } - - @Test - void testStringFormula() throws IOException { - try (ExcelExtractor extractor = createExtractor("StringFormulas.xls")) { - // Comes out as NaN if treated as a number - // And as XYZ if treated as a string - assertEquals("Sheet1\nXYZ\nSheet2\nSheet3\n", extractor.getText()); - - extractor.setFormulasNotResults(true); - - assertEquals("Sheet1\nUPPER(\"xyz\")\nSheet2\nSheet3\n", extractor.getText()); - } - } - - - @Test - void testEventExtractor() throws Exception { - // First up, a simple file with string - // based formulas in it - try (EventBasedExcelExtractor extractor1 = new EventBasedExcelExtractor( - new POIFSFileSystem( - HSSFTestDataSamples.openSampleFileStream("SimpleWithFormula.xls") - ) - )) { - extractor1.setIncludeSheetNames(true); - - String text = extractor1.getText(); - assertEquals("Sheet1\nreplaceme\nreplaceme\nreplacemereplaceme\nSheet2\nSheet3\n", text); - - extractor1.setIncludeSheetNames(false); - extractor1.setFormulasNotResults(true); - - text = extractor1.getText(); - assertEquals("replaceme\nreplaceme\nCONCATENATE(A1,A2)\n", text); - } - - // Now, a slightly longer file with numeric formulas - try (EventBasedExcelExtractor extractor2 = new EventBasedExcelExtractor( - new POIFSFileSystem( - HSSFTestDataSamples.openSampleFileStream("sumifformula.xls") - ) - )) { - - extractor2.setIncludeSheetNames(false); - extractor2.setFormulasNotResults(true); - - String text = extractor2.getText(); - assertEquals( - "1000\t1\tSUMIF(A1:A5,\">4000\",B1:B5)\n" + - "2000\t2\n" + - "3000\t3\n" + - "4000\t4\n" + - "5000\t5\n", - text - ); - } - } - - @Test - void testWithComments() throws IOException { - try (ExcelExtractor extractor = createExtractor("SimpleWithComments.xls")) { - extractor.setIncludeSheetNames(false); - - // Check without comments - assertEquals( - "1\tone\n" + - "2\ttwo\n" + - "3\tthree\n", - extractor.getText() - ); - - // Now with - extractor.setIncludeCellComments(true); - assertEquals( - "1\tone Comment by Yegor Kozlov: Yegor Kozlov: first cell\n" + - "2\ttwo Comment by Yegor Kozlov: Yegor Kozlov: second cell\n" + - "3\tthree Comment by Yegor Kozlov: Yegor Kozlov: third cell\n", - extractor.getText() - ); - } - } - - @Test - void testWithBlank() throws IOException { - try (ExcelExtractor extractor = createExtractor("MissingBits.xls")) { - String def = extractor.getText(); - extractor.setIncludeBlankCells(true); - String padded = extractor.getText(); - - assertStartsWith(def, - "Sheet1\n" + - "&[TAB]\t\n" + - "Hello\n" + - "11\t23\n" - ); - - assertStartsWith(padded, - "Sheet1\n" + - "&[TAB]\t\n" + - "Hello\n" + - "11\t\t\t23\n" - ); - } - } - - @Test - void testFormatting() throws Exception { - Locale userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.ROOT); - try (ExcelExtractor extractor = createExtractor("Formatting.xls")) { - extractor.setIncludeBlankCells(false); - extractor.setIncludeSheetNames(false); - String text = extractor.getText(); - - // Note - not all the formats in the file - // actually quite match what they claim to - // be, as some are auto-local builtins... - - assertStartsWith(text, "Dates, all 24th November 2006\n"); - assertContains(text, "yyyy/mm/dd\t2006/11/24\n"); - assertContains(text, "yyyy-mm-dd\t2006-11-24\n"); - assertContains(text, "dd-mm-yy\t24-11-06\n"); - - assertContains(text, "nn.nn\t10.52\n"); - assertContains(text, "nn.nnn\t10.520\n"); - assertContains(text, "\u00a3nn.nn\t\u00a310.52\n"); - } finally { - LocaleUtil.setUserLocale(userLocale); - } - } - - /** - * Embeded in a non-excel file - */ - @Test - void testWithEmbeded() throws Exception { - POIFSFileSystem fs = null; - - HSSFWorkbook wbA = null, wbB = null; - ExcelExtractor exA = null, exB = null; - - try { - fs = new POIFSFileSystem(POIDataSamples.getDocumentInstance().getFile("word_with_embeded.doc")); - - DirectoryNode objPool = (DirectoryNode) fs.getRoot().getEntry("ObjectPool"); - DirectoryNode dirA = (DirectoryNode) objPool.getEntry("_1269427460"); - DirectoryNode dirB = (DirectoryNode) objPool.getEntry("_1269427461"); - - wbA = new HSSFWorkbook(dirA, fs, true); - exA = new ExcelExtractor(wbA); - wbB = new HSSFWorkbook(dirB, fs, true); - exB = new ExcelExtractor(wbB); - - assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", exA.getText()); - assertEquals("Sample Excel", exA.getSummaryInformation().getTitle()); - assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", exB.getText()); - assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle()); - } finally { - if (exB != null) exB.close(); - if (wbB != null) wbB.close(); - if (exA != null) exA.close(); - if (wbA != null) wbA.close(); - if (fs != null) fs.close(); - } - } - - /** - * Excel embeded in excel - */ - @Test - void testWithEmbededInOwn() throws Exception { - POIDataSamples ssSamples = POIDataSamples.getSpreadSheetInstance(); - POIFSFileSystem fs = null; - HSSFWorkbook wbA = null, wbB = null; - ExcelExtractor exA = null, exB = null, ex = null; - - try { - fs = new POIFSFileSystem(ssSamples.getFile("excel_with_embeded.xls")); - - DirectoryNode dirA = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B5"); - DirectoryNode dirB = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B4"); - - wbA = new HSSFWorkbook(dirA, fs, true); - wbB = new HSSFWorkbook(dirB, fs, true); - - exA = new ExcelExtractor(wbA); - exB = new ExcelExtractor(wbB); - assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", exA.getText()); - assertEquals("Sample Excel", exA.getSummaryInformation().getTitle()); - - assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", exB.getText()); - assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle()); - - // And the base file too - ex = new ExcelExtractor(fs); - assertEquals("Sheet1\nI have lots of embeded files in me\nSheet2\nSheet3\n", ex.getText()); - assertEquals("Excel With Embeded", ex.getSummaryInformation().getTitle()); - } finally { - if (ex != null) ex.close(); - if (exB != null) exB.close(); - if (exA != null) exA.close(); - if (wbB != null) wbB.close(); - if (wbA != null) wbA.close(); - if (fs != null) fs.close(); - } - } - - /** - * Test that we get text from headers and footers - */ - @Test - void test45538() throws IOException { - String[] files = { - "45538_classic_Footer.xls", "45538_form_Footer.xls", - "45538_classic_Header.xls", "45538_form_Header.xls" - }; - for (String file : files) { - try (ExcelExtractor extractor = createExtractor(file)) { - String text = extractor.getText(); - assertContains(file, text, "testdoc"); - assertContains(file, text, "test phrase"); - } - } - } - - @Test - void testPassword() throws IOException { - Biff8EncryptionKey.setCurrentUserPassword("password"); - try (ExcelExtractor extractor = createExtractor("password.xls")) { - String text = extractor.getText(); - assertContains(text, "ZIP"); - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - - } - } - - @Test - void testNullPointerException() throws IOException { - try (ExcelExtractor extractor = createExtractor("ar.org.apsme.www_Form%20Inscripcion%20Curso%20NO%20Socios.xls")) { - assertNotNull(extractor); - assertNotNull(extractor.getText()); - } - } - - @Test - void test61045() throws IOException { - //bug 61045. File is govdocs1 626534 - try (ExcelExtractor extractor = createExtractor("61045_govdocs1_626534.xls")) { - String txt = extractor.getText(); - assertContains(txt, "NONBUSINESS"); - } - } - - @Test - void test60405a() throws IOException { - //bug 61045. File is govdocs1 626534 - try (ExcelExtractor extractor = createExtractor("60405.xls")) { - String txt = extractor.getText(); - assertContains(txt, "Macro1"); - assertContains(txt, "Macro2"); - } - } - - @Test - void test60405b() throws IOException { - //bug 61045. File is govdocs1 626534 - try (ExcelExtractor extractor = createExtractor("60405.xls")) { - extractor.setFormulasNotResults(true); - String txt = extractor.getText(); - assertContains(txt, "Macro1"); - assertContains(txt, "Macro2"); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java b/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java deleted file mode 100644 index 3fb037c93e..0000000000 --- a/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java +++ /dev/null @@ -1,381 +0,0 @@ -/* ==================================================================== - 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.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -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 java.io.PrintStream; -import java.security.Permission; - -import org.apache.poi.EmptyFileException; -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.OfficeXmlFileException; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.NullPrintStream; -import org.apache.poi.util.RecordFormatException; -import org.junit.jupiter.api.Test; - -/** - * Unit tests for the Excel 5/95 and Excel 4 (and older) text - * extractor - */ -final class TestOldExcelExtractor { - private static OldExcelExtractor createExtractor(String sampleFileName) throws IOException { - File file = HSSFTestDataSamples.getSampleFile(sampleFileName); - return new OldExcelExtractor(file); - } - - @Test - void testSimpleExcel3() throws IOException { - try (OldExcelExtractor extractor = createExtractor("testEXCEL_3.xls")) { - - // Check we can call getText without error - String text = extractor.getText(); - - // Check we find a few words we expect in there - assertContains(text, "Season beginning August"); - assertContains(text, "USDA"); - - // Check we find a few numbers we expect in there - assertContains(text, "347"); - assertContains(text, "228"); - - // Check we find a few string-literal dates in there - assertContains(text, "1981/82"); - - // Check the type - assertEquals(3, extractor.getBiffVersion()); - assertEquals(0x10, extractor.getFileType()); - - } - } - - - @Test - void testSimpleExcel3NoReading() throws IOException { - try (OldExcelExtractor extractor = createExtractor("testEXCEL_3.xls")) { - assertNotNull(extractor); - } - } - - @Test - void testSimpleExcel4() throws IOException { - try (OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls")) { - - // Check we can call getText without error - String text = extractor.getText(); - - // Check we find a few words we expect in there - assertContains(text, "Size"); - assertContains(text, "Returns"); - - // Check we find a few numbers we expect in there - assertContains(text, "11"); - assertContains(text, "784"); - - // Check the type - assertEquals(4, extractor.getBiffVersion()); - assertEquals(0x10, extractor.getFileType()); - - } - } - - @Test - void testSimpleExcel5() throws IOException { - for (String ver : new String[] {"5", "95"}) { - try (OldExcelExtractor extractor = createExtractor("testEXCEL_"+ver+".xls")) { - - // Check we can call getText without error - String text = extractor.getText(); - - // Check we find a few words we expect in there - assertContains(text, "Sample Excel"); - assertContains(text, "Written and saved"); - - // Check we find a few numbers we expect in there - assertContains(text, "15"); - assertContains(text, "169"); - - // Check we got the sheet names (new formats only) - assertContains(text, "Sheet: Feuil3"); - - // Check the type - assertEquals(5, extractor.getBiffVersion()); - assertEquals(0x05, extractor.getFileType()); - - } - } - } - - @Test - void testStrings() throws IOException { - try (OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls")) { - String text = extractor.getText(); - - // Simple strings - assertContains(text, "Table 10 -- Examination Coverage:"); - assertContains(text, "Recommended and Average Recommended Additional Tax After"); - assertContains(text, "Individual income tax returns, total"); - - // More complicated strings - assertContains(text, "$100,000 or more"); - assertContains(text, "S corporation returns, Form 1120S [10,15]"); - assertContains(text, "individual income tax return \u201Cshort forms.\u201D"); - - // Formula based strings - // TODO Find some then test - } - } - - @Test - void testFormattedNumbersExcel4() throws IOException { - try (OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls")) { - String text = extractor.getText(); - - // Simple numbers - assertContains(text, "151"); - assertContains(text, "784"); - - // Numbers which come from formulas - assertContains(text, "0.398"); // TODO Rounding - assertContains(text, "624"); - - // Formatted numbers - // TODO - // assertContains(text, "55,624"); - // assertContains(text, "11,743,477"); - } - } - - @Test - void testFormattedNumbersExcel5() throws IOException { - for (String ver : new String[] {"5", "95"}) { - try (OldExcelExtractor extractor = createExtractor("testEXCEL_"+ver+".xls")) { - String text = extractor.getText(); - - // Simple numbers - assertContains(text, "1"); - - // Numbers which come from formulas - assertContains(text, "13"); - assertContains(text, "169"); - - // Formatted numbers - // TODO - // assertContains(text, "100.00%"); - // assertContains(text, "155.00%"); - // assertContains(text, "1,125"); - // assertContains(text, "189,945"); - // assertContains(text, "1,234,500"); - // assertContains(text, "$169.00"); - // assertContains(text, "$1,253.82"); - } - } - } - - @Test - void testFromFile() throws IOException { - for (String ver : new String[] {"4", "5", "95"}) { - String filename = "testEXCEL_"+ver+".xls"; - File f = HSSFTestDataSamples.getSampleFile(filename); - - try (OldExcelExtractor extractor = new OldExcelExtractor(f)) { - String text = extractor.getText(); - assertNotNull(text); - assertTrue(text.length() > 100); - } - } - } - - @Test - void testFromInputStream() throws IOException { - for (String ver : new String[] {"4", "5", "95"}) { - String filename = "testEXCEL_"+ver+".xls"; - File f = HSSFTestDataSamples.getSampleFile(filename); - - try (InputStream stream = new FileInputStream(f); - OldExcelExtractor extractor = new OldExcelExtractor(stream)) { - String text = extractor.getText(); - assertNotNull(text); - assertTrue(text.length() > 100); - } - } - } - - @Test - void testOpenInvalidFile1() throws IOException { - // a file that exists, but is a different format - assertThrows(OfficeXmlFileException.class, () -> createExtractor("WithVariousData.xlsx").close()); - - // a completely different type of file - assertThrows(RecordFormatException.class, () -> createExtractor("48936-strings.txt").close()); - - // a POIFS file which is not a Workbook - try (InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream("47304.doc")) { - assertThrows(FileNotFoundException.class, () -> new OldExcelExtractor(is).close()); - } - } - - @Test - void testOpenNonExistingFile() { - // a file that exists, but is a different format - assertThrows(EmptyFileException.class, () -> new OldExcelExtractor(new File("notexistingfile.xls")).close()); - } - - @Test - void testInputStream() throws IOException { - File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls"); - try (InputStream stream = new FileInputStream(file); - OldExcelExtractor extractor = new OldExcelExtractor(stream)) { - String text = extractor.getText(); - assertNotNull(text); - } - } - - @Test - void testInputStreamNPOIHeader() throws IOException { - //TODO: the worksheet names are currently mangled. They're treated - //as if UTF-16, but they're just ascii. Need to fix this. - //Is it possible that the leading 0 byte in the worksheet name is a signal - //that these worksheet names should be interpreted as ascii/1252? - File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls"); - try (InputStream stream = new FileInputStream(file); - OldExcelExtractor extractor = new OldExcelExtractor(stream)) { - String text = extractor.getText(); - assertNotNull(text); - } - } - - @Test - void testPOIFSFileSystem() throws IOException { - File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls"); - try (POIFSFileSystem fs = new POIFSFileSystem(file); - OldExcelExtractor extractor = new OldExcelExtractor(fs)){ - String text = extractor.getText(); - assertNotNull(text); - } - } - - @Test - void testDirectoryNode() throws IOException { - File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls"); - try (POIFSFileSystem fs = new POIFSFileSystem(file); - OldExcelExtractor extractor = new OldExcelExtractor(fs.getRoot())) { - String text = extractor.getText(); - assertNotNull(text); - } - } - - @Test - void testDirectoryNodeInvalidFile() throws IOException { - File file = POIDataSamples.getDocumentInstance().getFile("test.doc"); - try (POIFSFileSystem fs = new POIFSFileSystem(file)) { - assertThrows(FileNotFoundException.class, () -> new OldExcelExtractor(fs.getRoot())); - } - } - - @Test - void testMainUsage() { - PrintStream save = System.err; - SecurityManager sm = System.getSecurityManager(); - System.setSecurityManager(new NoExitSecurityManager()); - try { - System.setErr(new NullPrintStream()); - // calls System.exit() - assertThrows(ExitException.class, () -> OldExcelExtractor.main(new String[]{})); - } finally { - System.setSecurityManager(sm); - System.setErr(save); - } - } - - @Test - void testMain() throws IOException { - File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls"); - PrintStream save = System.out; - try { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - PrintStream str = new PrintStream(out, false, "UTF-8"); - System.setOut(str); - OldExcelExtractor.main(new String[] {file.getAbsolutePath()}); - String string = out.toString("UTF-8"); - assertTrue(string.contains("Table C-13--Lemons"), "Had: " + string); - } finally { - System.setOut(save); - } - } - - @Test - void testEncryptionException() throws IOException { - //test file derives from Common Crawl - File file = HSSFTestDataSamples.getSampleFile("60284.xls"); - - try (OldExcelExtractor ex = new OldExcelExtractor(file)) { - assertEquals(5, ex.getBiffVersion()); - assertEquals(5, ex.getFileType()); - assertThrows(EncryptedDocumentException.class, ex::getText); - } - } - - @Test - void testSheetWithNoName() throws IOException { - File file = HSSFTestDataSamples.getSampleFile("64130.xls"); - - try (OldExcelExtractor ex = new OldExcelExtractor(file)) { - assertEquals(5, ex.getBiffVersion()); - assertEquals(5, ex.getFileType()); - assertContains(ex.getText(), "Dawn"); - } - } - - private static class NoExitSecurityManager extends SecurityManager { - @Override - public void checkPermission(Permission perm) { - // allow anything. - } - @Override - public void checkPermission(Permission perm, Object context) { - // allow anything. - } - @Override - public void checkExit(int status) { - super.checkExit(status); - throw new ExitException(status); - } - } - - private static class ExitException extends SecurityException { - public final int status; - public ExitException(int status) { - super("There is no escape!"); - this.status = status; - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java deleted file mode 100644 index 18138de8ed..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java +++ /dev/null @@ -1,904 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; - -import org.apache.poi.ddf.DefaultEscherRecordFactory; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherDggRecord; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherRecordFactory; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.ContinueRecord; -import org.apache.poi.hssf.record.DrawingRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.hssf.record.NoteRecord; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.hssf.record.RecordFactory; -import org.apache.poi.hssf.record.TextObjectRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.aggregates.RowRecordsAggregate; -import org.apache.poi.hssf.usermodel.HSSFPatriarch; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFTestHelper; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -class TestDrawingAggregate { - /** - * information about drawing aggregate in a worksheet - */ - private static class DrawingAggregateInfo { - /** - * start and end indices of the aggregate in the worksheet stream - */ - private int startRecordIndex, endRecordIndex; - /** - * the records being aggregated - */ - private List aggRecords; - - /** - * @return aggregate info or null if the sheet does not contain drawing objects - */ - static DrawingAggregateInfo get(HSSFSheet sheet){ - DrawingAggregateInfo info = null; - InternalSheet isheet = HSSFTestHelper.getSheetForTest(sheet); - List records = isheet.getRecords(); - for(int i = 0; i < records.size(); i++){ - RecordBase rb = records.get(i); - if((rb instanceof DrawingRecord) && info == null) { - info = new DrawingAggregateInfo(); - info.startRecordIndex = i; - info.endRecordIndex = i; - } else if (info != null && ( - rb instanceof DrawingRecord - || rb instanceof ObjRecord - || rb instanceof TextObjectRecord - || rb instanceof ContinueRecord - || rb instanceof NoteRecord - )){ - info.endRecordIndex = i; - } else { - if(rb instanceof EscherAggregate) - throw new IllegalStateException("Drawing data already aggregated. " + - "You should cal this method before the first invocation of HSSFSheet#getDrawingPatriarch()"); - if (info != null) break; - } - } - if(info != null){ - info.aggRecords = new ArrayList<>( - records.subList(info.startRecordIndex, info.endRecordIndex + 1)); - } - return info; - } - - /** - * @return the raw data being aggregated - */ - byte[] getRawBytes(){ - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for (RecordBase rb : aggRecords) { - Record r = (org.apache.poi.hssf.record.Record) rb; - try { - out.write(r.serialize()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - return out.toByteArray(); - } - } - - public static Stream samples() { - File testData = new File(System.getProperty("POI.testdata.path"), "spreadsheet"); - File[] files = testData.listFiles((dir, name) -> name.endsWith(".xls")); - assertNotNull(files, "Need to find files in test-data path, had path: " + testData); - return Stream.of(files).map(Arguments::of); - } - - /** - * test that we correctly read and write drawing aggregates in all .xls files in POI test samples. - * iterate over all sheets, aggregate drawing records (if there are any) - * and remember information about the aggregated data. - * Then serialize the workbook, read back and assert that the aggregated data is preserved. - * - * The assertion is strict meaning that the drawing data before and after save must be equal. - */ - @ParameterizedTest - @MethodSource("samples") - void testAllTestSamples(File file) throws IOException { - boolean ignoreParse = true; - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(file.getName())) { - ignoreParse = false; - - // map aggregate info by sheet index - Map aggs = new HashMap<>(); - for (int i = 0; i < wb.getNumberOfSheets(); i++){ - HSSFSheet sheet = wb.getSheetAt(i); - DrawingAggregateInfo info = DrawingAggregateInfo.get(sheet); - if(info != null) { - aggs.put(i, info); - HSSFPatriarch p = sheet.getDrawingPatriarch(); - - // compare aggregate.serialize() with raw bytes from the record stream - EscherAggregate agg = HSSFTestHelper.getEscherAggregate(p); - - byte[] dgBytes1 = info.getRawBytes(); - byte[] dgBytes2 = agg.serialize(); - - assertEquals(dgBytes1.length, dgBytes2.length, "different size of raw data ande aggregate.serialize()"); - assertArrayEquals(dgBytes1, dgBytes2, "raw drawing data (" + dgBytes1.length + " bytes) and aggregate.serialize() are different."); - } - } - - if(aggs.size() != 0){ - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb)) { - for (int i = 0; i < wb2.getNumberOfSheets(); i++) { - DrawingAggregateInfo info1 = aggs.get(i); - if (info1 != null) { - HSSFSheet sheet2 = wb2.getSheetAt(i); - DrawingAggregateInfo info2 = DrawingAggregateInfo.get(sheet2); - byte[] dgBytes1 = info1.getRawBytes(); - byte[] dgBytes2 = info2.getRawBytes(); - assertEquals(dgBytes1.length, dgBytes2.length, "different size of drawing data before and after save"); - assertArrayEquals(dgBytes1, dgBytes2, "drawing data (" + dgBytes1.length + " bytes) before and after save is different."); - } - } - } - } - - } catch (Throwable e) { - // don't bother about files we cannot read - they are different bugs - if (!ignoreParse) { - throw e; - } - } - } - - /** - * when reading incomplete data ensure that the serialized bytes match the source - */ - @Test - void testIncompleteData() throws IOException { - //EscherDgContainer and EscherSpgrContainer length exceeds the actual length of the data - String data = - "H4sIAAAAAAAAAGWOOw7CQAxE32YTsSRIWSgQJSUloqSm5g4ICURBg+iBK3APGi6wBWeh9xGYbEps2WON"+ - "P+OWwpYeIsECMFC8S2jxNvMdlrYQ5xha5N8K6ryHdir6+avwOer5l3hq2NPYWuWN0n1dIsgfbgshuSj1"+ - "+2eqbvLdxQ0ndhy5KJ/lc1ZZK9okY5X/gSbrHZTH1vE/ozagTcwAAAA="; - byte[] dgBytes = decompress(data); - - List records = new ArrayList<>(); - EscherRecordFactory recordFactory = new DefaultEscherRecordFactory(); - int pos = 0; - while (pos < dgBytes.length) { - EscherRecord r = recordFactory.createRecord(dgBytes, pos); - int bytesRead = r.fillFields(dgBytes, pos, recordFactory); - records.add(r); - pos += bytesRead; - } - assertEquals(dgBytes.length, pos, "data was not fully read"); - - // serialize to byte array - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for(EscherRecord r : records) { - out.write(r.serialize()); - } - assertArrayEquals(dgBytes, out.toByteArray()); - } - - /** - * TODO: figure out why it fails with "RecordFormatException: 0 bytes written but getRecordSize() reports 80" - */ - @Test - void testFailing() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("15573.xls")) { - HSSFSheet sh = wb.getSheetAt(0); - HSSFPatriarch dp = sh.getDrawingPatriarch(); - assertNotNull(dp); - - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb)) { - HSSFSheet sh2 = wb2.getSheetAt(0); - HSSFPatriarch dp2 = sh2.getDrawingPatriarch(); - assertNotNull(dp2); - } - } - } - - private static byte[] toByteArray(List records) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for (RecordBase rb : records) { - Record r = (org.apache.poi.hssf.record.Record) rb; - try { - out.write(r.serialize()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - return out.toByteArray(); - } - - @Test - void testSolverContainerMustBeSavedDuringSerialization() throws IOException{ - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("SolverContainerAfterSPGR.xls")) { - HSSFSheet sh = wb1.getSheetAt(0); - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - List records = ish.getRecords(); - // records to be aggregated - List dgRecords = records.subList(19, 22); - byte[] dgBytes = toByteArray(dgRecords); - sh.getDrawingPatriarch(); - EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - assertNotNull(agg); - assertEquals(agg.getEscherRecords().get(0).getChildRecords().size(), 3); - assertEquals(agg.getEscherRecords().get(0).getChild(2).getRecordId(), EscherContainerRecord.SOLVER_CONTAINER); - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - sh = wb2.getSheetAt(0); - sh.getDrawingPatriarch(); - ish = HSSFTestHelper.getSheetForTest(sh); - agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - assertNotNull(agg); - assertEquals(agg.getEscherRecords().get(0).getChildRecords().size(), 3); - assertEquals(agg.getEscherRecords().get(0).getChild(2).getRecordId(), EscherContainerRecord.SOLVER_CONTAINER); - - - // collect drawing records into a byte buffer. - agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - assertNotNull(agg); - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save"); - assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different"); - } - } - } - - @Test - void testFileWithTextbox() throws IOException{ - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("text.xls")) { - HSSFSheet sh = wb.getSheetAt(0); - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - List records = ish.getRecords(); - // records to be aggregated - List dgRecords = records.subList(19, 23); - byte[] dgBytes = toByteArray(dgRecords); - sh.getDrawingPatriarch(); - - // collect drawing records into a byte buffer. - EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - assertNotNull(agg); - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save"); - assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different"); - } - } - - @Test - void testFileWithCharts() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49581.xls")) { - HSSFSheet sh = wb.getSheetAt(0); - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - List records = ish.getRecords(); - // records to be aggregated - List dgRecords = records.subList(19, 21); - byte[] dgBytes = toByteArray(dgRecords); - sh.getDrawingPatriarch(); - - // collect drawing records into a byte buffer. - EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - assertNotNull(agg); - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save"); - for (int i = 0; i < dgBytes.length; i++) { - if (dgBytes[i] != dgBytesAfterSave[i]) { - System.out.println("pos = " + i); - } - } - assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different"); - } - } - - /** - * test reading drawing aggregate from a test file from Bugzilla 45129 - */ - @Test - void test45129() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("45129.xls")) { - HSSFSheet sh = wb.getSheetAt(0); - - InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb); - InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh); - - List records = isheet.getRecords(); - - // the sheet's drawing is not aggregated - assertEquals(394, records.size(), "wrong size of sheet records stream"); - // the last record before the drawing block - assertTrue(records.get(18) instanceof RowRecordsAggregate, - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName()); - - // records to be aggregated - List dgRecords = records.subList(19, 389); - // collect drawing records into a byte buffer. - byte[] dgBytes = toByteArray(dgRecords); - - for (RecordBase rb : dgRecords) { - Record r = (org.apache.poi.hssf.record.Record) rb; - short sid = r.getSid(); - // we expect that drawing block consists of either - // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord - assertTrue( - sid == DrawingRecord.sid || - sid == ContinueRecord.sid || - sid == ObjRecord.sid || - sid == TextObjectRecord.sid); - } - - // the first record after the drawing block - assertTrue(records.get(389) instanceof WindowTwoRecord, "records.get(389) is expected to be Window2"); - - // aggregate drawing records. - // The subrange [19, 388] is expected to be replaced with a EscherAggregate object - DrawingManager2 drawingManager = iworkbook.findDrawingGroup(); - int loc = isheet.aggregateDrawingRecords(drawingManager, false); - EscherAggregate agg = (EscherAggregate) records.get(loc); - - assertEquals(25, records.size(), "wrong size of the aggregated sheet records stream"); - assertTrue(records.get(18) instanceof RowRecordsAggregate, - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName()); - assertTrue(records.get(19) instanceof EscherAggregate, - "records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName()); - assertTrue(records.get(20) instanceof WindowTwoRecord, - "records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName()); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save"); - assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different"); - } - } - - /** - * Try to check file with such record sequence - * ... - * DrawingRecord - * ContinueRecord - * ObjRecord | TextObjRecord - * ... - */ - @Test - void testSerializeDrawingBigger8k() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DrawingContinue.xls")) { - InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb); - HSSFSheet sh = wb.getSheetAt(0); - InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh); - - - List records = isheet.getRecords(); - - // the sheet's drawing is not aggregated - assertEquals(32, records.size(), "wrong size of sheet records stream"); - // the last record before the drawing block - assertTrue(records.get(18) instanceof RowRecordsAggregate, - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName()); - - // records to be aggregated - List dgRecords = records.subList(19, 26); - for (RecordBase rb : dgRecords) { - Record r = (org.apache.poi.hssf.record.Record) rb; - short sid = r.getSid(); - // we expect that drawing block consists of either - // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord - assertTrue( - sid == DrawingRecord.sid || - sid == ContinueRecord.sid || - sid == ObjRecord.sid || - sid == NoteRecord.sid || - sid == TextObjectRecord.sid); - } - // collect drawing records into a byte buffer. - byte[] dgBytes = toByteArray(dgRecords); - - // the first record after the drawing block - assertTrue(records.get(26) instanceof WindowTwoRecord, "records.get(26) is expected to be Window2"); - - // aggregate drawing records. - // The subrange [19, 38] is expected to be replaced with a EscherAggregate object - DrawingManager2 drawingManager = iworkbook.findDrawingGroup(); - int loc = isheet.aggregateDrawingRecords(drawingManager, false); - EscherAggregate agg = (EscherAggregate) records.get(loc); - - assertEquals(26, records.size(), "wrong size of the aggregated sheet records stream"); - assertTrue(records.get(18) instanceof RowRecordsAggregate, - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName()); - assertTrue(records.get(19) instanceof EscherAggregate, - "records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName()); - assertTrue(records.get(20) instanceof WindowTwoRecord, - "records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName()); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save"); - assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different"); - } - } - - - @Test - void testSerializeDrawingBigger8k_noAggregation() throws IOException { - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("DrawingContinue.xls")) { - InternalSheet isheet = HSSFTestHelper.getSheetForTest(wb1.getSheetAt(0)); - List records = isheet.getRecords(); - - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - InternalSheet isheet2 = HSSFTestHelper.getSheetForTest(wb2.getSheetAt(0)); - List records2 = isheet2.getRecords(); - - assertEquals(records.size(), records2.size()); - for (int i = 0; i < records.size(); i++) { - RecordBase r1 = records.get(i); - RecordBase r2 = records2.get(i); - assertSame(r1.getClass(), r2.getClass()); - assertEquals(r1.getRecordSize(), r2.getRecordSize()); - if (r1 instanceof Record) { - assertEquals(((org.apache.poi.hssf.record.Record) r1).getSid(), ((org.apache.poi.hssf.record.Record) r2).getSid()); - assertArrayEquals(((org.apache.poi.hssf.record.Record) r1).serialize(), ((org.apache.poi.hssf.record.Record) r2).serialize()); - } - } - } - } - } - - @Test - void testSerializeDrawingWithComments() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DrawingAndComments.xls")) { - HSSFSheet sh = wb.getSheetAt(0); - InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb); - InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh); - - List records = isheet.getRecords(); - - // the sheet's drawing is not aggregated - assertEquals(46, records.size(), "wrong size of sheet records stream"); - // the last record before the drawing block - assertTrue(records.get(18) instanceof RowRecordsAggregate, - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName()); - - // records to be aggregated - List dgRecords = records.subList(19, 39); - for (RecordBase rb : dgRecords) { - Record r = (org.apache.poi.hssf.record.Record) rb; - short sid = r.getSid(); - // we expect that drawing block consists of either - // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord - assertTrue( - sid == DrawingRecord.sid || - sid == ContinueRecord.sid || - sid == ObjRecord.sid || - sid == NoteRecord.sid || - sid == TextObjectRecord.sid); - } - // collect drawing records into a byte buffer. - byte[] dgBytes = toByteArray(dgRecords); - - // the first record after the drawing block - assertTrue(records.get(39) instanceof WindowTwoRecord, "records.get(39) is expected to be Window2"); - - // aggregate drawing records. - // The subrange [19, 38] is expected to be replaced with a EscherAggregate object - DrawingManager2 drawingManager = iworkbook.findDrawingGroup(); - int loc = isheet.aggregateDrawingRecords(drawingManager, false); - EscherAggregate agg = (EscherAggregate) records.get(loc); - - assertEquals(27, records.size(), "wrong size of the aggregated sheet records stream"); - assertTrue(records.get(18) instanceof RowRecordsAggregate, - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName()); - assertTrue(records.get(19) instanceof EscherAggregate, - "records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName()); - assertTrue(records.get(20) instanceof WindowTwoRecord, - "records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName()); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save"); - assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different"); - } - } - - - @Test - void testFileWithPictures() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ContinueRecordProblem.xls")) { - HSSFSheet sh = wb.getSheetAt(0); - - InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb); - InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh); - - List records = isheet.getRecords(); - - // the sheet's drawing is not aggregated - assertEquals(315, records.size(), "wrong size of sheet records stream"); - // the last record before the drawing block - assertTrue(records.get(21) instanceof RowRecordsAggregate, - "records.get(21) is expected to be RowRecordsAggregate but was " + records.get(21).getClass().getSimpleName()); - - // records to be aggregated - List dgRecords = records.subList(22, 300); - for (RecordBase rb : dgRecords) { - Record r = (org.apache.poi.hssf.record.Record) rb; - short sid = r.getSid(); - // we expect that drawing block consists of either - // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord - assertTrue( - sid == DrawingRecord.sid || - sid == ContinueRecord.sid || - sid == ObjRecord.sid || - sid == TextObjectRecord.sid); - } - // collect drawing records into a byte buffer. - byte[] dgBytes = toByteArray(dgRecords); - - // the first record after the drawing block - assertTrue(records.get(300) instanceof WindowTwoRecord, "records.get(300) is expected to be Window2"); - - // aggregate drawing records. - // The subrange [19, 299] is expected to be replaced with a EscherAggregate object - DrawingManager2 drawingManager = iworkbook.findDrawingGroup(); - int loc = isheet.aggregateDrawingRecords(drawingManager, false); - EscherAggregate agg = (EscherAggregate) records.get(loc); - - assertEquals(38, records.size(), "wrong size of the aggregated sheet records stream"); - assertTrue(records.get(21) instanceof RowRecordsAggregate, - "records.get(21) is expected to be RowRecordsAggregate but was " + records.get(21).getClass().getSimpleName()); - assertTrue(records.get(22) instanceof EscherAggregate, - "records.get(22) is expected to be EscherAggregate but was " + records.get(22).getClass().getSimpleName()); - assertTrue(records.get(23) instanceof WindowTwoRecord, - "records.get(23) is expected to be Window2 but was " + records.get(23).getClass().getSimpleName()); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save"); - assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different"); - } - } - - @Test - void testUnhandledContinue() throws IOException { - String data = - "H4sIAAAAAAAAAO3adVRU2/4A8EPHAEOnlEooNaSUdCNIg4CUDCEtQ6gwlITSjYiSkoKA0ikg0i1IyCjS"+ - "QwpSEr8B73v3PS6+9+67vz/eH+615pyz9tn71PqevT/rfGcJOIcLBtDXrNgAgBjAXcMFAAAb9SPDBAAw"+ - "gLGmzna8xlxjR9WhAXhrxMAfCzqAf9IPQPXBAn6078IBgAyCH/VgVD2ADwCxAGhNBbXpc9LUF2h8n4we"+ - "iOoNAKEnywaAFmAEGtDQABLgCA0AcAHfZvLjeozjc+gAUMATgAEygBNqzQTwHl8lcH5dGHWmvGY+1FJD"+ - "FQOTHHX1x+dkBta2H9UcoLam0I7bAYCRrJMjDOoIM9W56wx1vcnt6WAfF92t0gIhfrfqv0o8e9khH4fE"+ - "thqnQJHiJqOZUrbDByG8xwYeiEmYJPcUPoP17NH6hTz9cVtyfvnyyUuV3BzE06+vDH/Dlxi+/pYeV32e"+ - "IGIy2p+e90VyZ+i9OlDL+Rp6Dmot/G2tUgYbGW5vpkSep5Fk2eKtJthDdEvKkzrvC4cmWe7kKaliC7ip"+ - "0sMjlMUdN/akSG0ticE4nweeA7LUha1xyjNLXZEJUx80rOZMmgMIveJ5pQ7Hio17qM558+zaZgheNOHN"+ - "tk7hCxKIZgFTs9t1NGhTdj0EIdz0tEcV4KZebLmun1t9qpQ2fF6N29/P3I3j3pYc8kI9zaMjjFNPi/ej"+ - "qfkAaisS9bRAqLXpHai9Kw/38TIr6s3tZghB0GpAXUB/ncuYLE2mulOgiSpODb6R8rVbnQasDoj6bIiB"+ - "gpPYItWexPrqVgUk73GpZwT2sBroUQZ07ovZJ6SXgbdvjH//55ZoggllM0Rdw7K6gHmeIt/exXytDGpq"+ - "VeVUw1D6S2kCKezDar0iZnm3GGAy99/4bWY7VIgeWUlVmOVn8kdFOmIsel1/vx9MX9vNOZHYeqdvYnuy"+ - "PuP2uxHPjCotCFiHoJKzFzI4MTQn1bBVdLQQT0LmrX8os3+t4Nu7F1SC7mDgrFsvKsHS80DFHx3O8SsA"+ - "AJZ3XHlcbcydoagIOY6SWl1Vp3EIQT34gw8x7PqBwdNgkpp5LViiOWHMLE5uaQp1LIusFllOAzxrOusm"+ - "WExAlgdfVmW/LRLc67SnF1MHKe/PT2vXvfZQw1g/fIwStuEpmaxlQa9NEWv40J8h8PmVmRGejXo+EW2v"+ - "HEI0qo7ZNPb5niruyPOdHhnQLRUPGb+y4Wwo0WGygw6NOzBXGDYgzKBYzu+v6872oAZEaXgP4VtOrDV5"+ - "LyQtP9wxoKWMM/buA960eUbfNY0RKG1vKafEuMZMtwJjh5N0+JRy8JYlbS/r6OhsqifipW+Gx4NtrO4B"+ - "znA/UjinjWh9TytvuD/PeHSCSyZI5WEAslSzQZpIoczUQ5XM8tCuQSArrxGN5VGZ1OKFiaOi+zEpKW/o"+ - "vaSMwbfZQYveck70N1ZjZrwdxtKxlzAobG5kMl1LQFazAkJqVsrYDgCNeunmvRhm4c6jbinypsbQpyUr"+ - "wX1UwXJ9mtLhn3qC321JFsoymDATqy98V+hQ3ZBcpxN+W1+6wo6FrlRGKhW2ug7eAH3Dvn0rNWTG6vvr"+ - "qKDGWqAXYu0s8ZmmdMM3xFjWIjXsqtT56ly7tMPY9d40CZ/CQ0b4OLsD9qG5CB5n47N2/2qJMKo1+rUg"+ - "TTpa4D7au2JRC6XrayDXu7ZXGpvcwM5DWoz4HdBBTfQnmzN1K2YG+hpYNVGkX6ZlZGv7OM1XZeaZU1e2"+ - "Rt+QEzSTyLSYPXezW5pSbf62gbi5iHWB7xBAZ2leDdXI7Kat5+Epnor5sC3ZefMh0hUTSQ8VP+BIz2fh"+ - "t3eD2z9TLOhGRLoIErwXi+9yUgMZHhVGhWusRIi4J297mNL4iBUbHaKdFaRyobYMnKg9BWjH4+uPILV0"+ - "8nC8A3U/jlFjjX71Jgi595V1xmS7qScwAiEcrTYLmRbMfuaHL6EOo1NjPeWNa8hlBYLWd64rInOTrmyv"+ - "FPTmG8O5ys73rWL5VnYIcryPaJz1hicCpRGXFTgKhf3IKiBPTEzV5pMWMjt2zJfd24LZxbIx8ecWeVuF"+ - "eCqzynPsivav2VzI2+hbgvBvzjdDA5uZQkqynn+lwzfceOc/l4qsu1hsOTVzy6AnNW9HhaqZ8yHRS87z"+ - "01vZyoyAyGRlaOVkgW6lsSNCaOFlWqgRBJ2ZaR02lhwDHRJ1xN2B1xc64WubpudpxVONMUW7GMG/w61N"+ - "qLmi+xXRMaSqigzr33Iwc3owsLyZl1hUaNChDstgByZaRb2FUik+0vh0uZw72thqliZVKKQydVxsnHk3"+ - "yPj3tx8NnQv4+UTxz+WMaeP0AU6Pnb8XbrR/GklPdzw98vxeLqH/cRw63ft0SPxeejD/ECAaqljYP6Zo"+ - "TOAbas2G/aMp8RrpyQyOBpihYQAbqK0+1BxuiKojWTvefxM1J1MApKiTggESs9MPZ+nkUghPWpajkQKk"+ - "6H/bg/3bDYkDqHuDQT1hXLziJ1WUv+3+2wE6cY650PkPXCD+CRcAqPZf4ALfb1y4csIF3l9c+MWF/44L"+ - "j9ungt3+JRe6HacgxPUvhzyKvXJ2F/yZmvIM81egZfIaDI0XieSQH6KXZeYHV8Oe9jmC77MXmJyzbuVH"+ - "7Dxh7HWqUYgJgJQPP+qfFs2Wy5VJLBvjrb4LP6d2qSSiIEa1EDOTzXzBAf7NYTKe9Uv+BzvZxsBSGlzq"+ - "j2IjVpqWoXU2lXXDhRppha9tKwNMX4WqNEd+qo3WpH0X21ausDawEugMlpZ1XaXro5TpEAOTyMX3q32g"+ - "MJxtF2+idkYSmm3o6N6l7W39svNCNlqfzruLTTpsXDpob1SYnlNqhqsWeUW8X0QLFtb0RgBb4RFZ5sL0"+ - "d0/SQfbKUi5bT3OBzDhhYW67b3Rb0nlESHfbpvodNwNarcSwSY0MT4wUiebd+x+jYc7Y1n2+lUQtURRx"+ - "30MmxUonWXqrOwS88XfYSPvWDKWTxAd15QH75K4YXh20CYiyU3YjQcbGEoJcjplI/AMtEo7r7XINk573"+ - "ttxnL6/9tUHRi1OE6J/j4C+e18b5+n2Sujwc78Z2iVgqPx6w8gr3STZTEnam+x76oWmpHGSLuwkiJvTG"+ - "RlKOOIuBQ9oojJdCS+4ryVHpYg358B7SDCFMC46CEUMqT575UKujkzl/itEcCTxEr8cwQdh5o5lxmTEm"+ - "sBHYgkxtulQL0LCL7vs/j9lrs2FGJpAmZb1khCo2GylQdMmohMWCCNdlSh5UgdKDv7/24CGqTnOKID6P"+ - "zVFodIvClLZo9WhLi4c6eh1EzC5SzyMTLmTnaWpiPnzRRdLGOGLDNc4iUwyxMqmSe6ed0PRpeHenTdnu"+ - "OLWibGodMxRubxi1VyEzLFOFs7LTt8poQuMjWvzk6Ews6D2wxOX6F1iIMr2OwsJbhNo+Ubfgulo5Ravk"+ - "JUteZgv/qaiWkdJy++ryV4WQnU13JuY9z566hsH7oslDpXJGjvbpFH65FOhTlwdfaNChF1Qs3GSMctPh"+ - "Nbz9Fm+pKrB9Z++2XPC1VZ2OCtUKaQm5UWaWKDF9woBGK5HEoXLY2/hUPIeLbibJao0EH3edb2ALE9T4"+ - "ZQV+5Zl+PQUW6ZVIRMQ0pjyc21bn9c6Y4njsNgCvvVmcFDX+RLQKZ9pzmbtT97CkcWN3zy0+hSrChV8h"+ - "jVBJfGUk2+xSWQQden2qE/JJ0wf93E45aJWQUtYEJQ5idRqUycJ3TzENxD4I/XJlTx63k95POuxW6jSb"+ - "NU5wwAcj6djFzYfLB6U7YLpvGT2Swk3LEhF0wpUTMPJESYaj/zktnB54/pwWTsfE76Xr32uB9QwtYKOm"+ - "5GMt4ACzZ2iB+C9qge8/1QLJz7TQ/1e0wP9LC7+08P+hBWVCae5j4tP+VAtqruNMxHUe2Ud+n1fmLyTQ"+ - "2YXx5fEvPB/0XNrBMcMbTT7fB5TM7O+t+C9liWwSe9yRtqHauspQ07lU7sQyCrpFV0itVmSh8uCy2/tc"+ - "rkxkTnA/Icuwi65LXrzZJjtnHVc9/PG3+Paqyx5jxLjp9kTYCh49bnfJR++wGTq+hLGRe9o5GK58GrHP"+ - "7FjDwHSCxrWuXyx9SlJbKsY84b3W1/QO+3VV1NceWUxtBxid1fMEeb7QKAz1A+wk8WG36NZBztBeCYG7"+ - "Ff3BFrRdwldH+yS7B5aW1um8pvWF+8W0tsKaqgWwpTsuZC5YpqhZ0AYqlV/g4gm3iiPF6YRmwpvFhd/D"+ - "33NdS0ps2ALJJj/q52V5VMG0QPbiqOj+HW98bDtnDJerSZ+1+lZo6ggtvZWebZfZBtN9YuxrmAlHTxYf"+ - "cVMDllgfs9JcREuB7CZEfBGQhT07MvJnX2sM/PFxwfU8dYjmBZW53fWD60iNEH3cB9p76dFftdDU0XE0"+ - "eQtfiKn4AVpcWOxftPeb0ZsDA8pLJEO4ut35E4Okqnz7NKwgjs4EOccfF5rfSNDc95WDaY4wHbB9SZU+"+ - "2C3b89lxyHxNsxk8eXENfcuYb3FPwzTNo5HutoMS0IX1onkxJE5oLbCpVoAuDVGtSH07DxyWULrA7qew"+ - "93XSHVJ7S0eaI6tFWGSkkSqG5fXNNIaewY9XxXL904XR5S+itGBOaaoyMuLjYUtuabkPoKtE9IZqZH7D"+ - "f5ZINS+ovLSROlfUeChS3SrjUT9xwJ2ej3XF6+6k/TPFzm+IJyWCBBUe1XwIIS6DA21muvSJqx77Oqur"+ - "DDQNorlG+2d64a68eyEHak/+z7ygeeyFQJQXwMdeEGV970demkTM+/g3L7g4WBuZ7yC5LjyY/yKyDZ/b"+ - "gok76IaXN1V32OAfmGAqzTetqTixv5i0voLHNPd49oWQocYHEM5g+8zbpPDK0QVj+0R4gEyI+wWF9M16"+ - "GvOlR1rss/eySUS7skoe7TItY7t2ujMbvxeOyBB7YfC8OTBGcKqE/O3cVyPNtkqvXWqdV9asDQO7TNfb"+ - "3N/gPR/Rd9gD2kKHUxPpOKhcEgoRegu26aFPXPExpL7aNpRT9D7eaNLCPZAZ7yNnTZcxyqlmD5fnoyra"+ - "wzuIqH+twGznTh7ki6/NuB8Ajx/AYzQmjXV05puyUVLC3CFe7CZZDjaipzsyJ7tzBF55V6FcjB7We32x"+ - "ZTeUreF/TgunB54/p4XTEfF7+Q++LZylBTyA8EQL+IDrGVog+Yta4D9bC104p1MRpD/TgtBfSUUIAL9S"+ - "Eb+08P+gBSMhtMnjl5b+51rQHoecaEE6837xU9bHUW+s2AnqYPixjWDi8hTPy6oMyheJGuqdWNg0iK5G"+ - "EVHdMLHdXq4/6HsLRVwujx8WVJgTF1MVia0W0M0cEfHxqqTvFnE1mVdhz4T2bA+sd04hE0PrS0HpneEl"+ - "BKyvjaSiNsK3P55XNq6KLnS2zo6lzSkrKVzbKUNmlVrgfClUabUVVTW2fp47oaDiQ3bdk8QeY9nwshsF"+ - "U0ZueXZ4zUDu+RqlNpwxbCz7lcVq6py5Qdt74hc0hcut9C0DiJbBMtVR0FinhbSAV2lkYQ3nOyZflfbu"+ - "wsTpcz5lTcx5iT+5Zn3pegbXSIle3PB0Cn8kMr+/oSQy+F7N4orDRGJD+XaCIEWYS7Y8SI/R+ahmYXTa"+ - "jMBDyW+XwWI6cPpNZkWQMeQSpbfDODPeFMYlG/nMz9kGSdVWwBPruVFyNykS/+67tDLkoT7aUXKSberW"+ - "T4+Yu9slePniXDlUGffJxlN7yEheEmPmdDtkDuVhnsONyNKCijToxwBxJioQsvz9ZswLnz8JEfpVDhSl"+ - "FsVD56mJw9Wb9+TswrgB0jvhjcdeuAi7MXKcjIhMY4ZnHjHCx21u4RzyPrvIYsah0+PN+B3kpVibPhKE"+ - "nmaYJvFia3qArN6mS7sA7cIIwjwvfnSmVkftHY3VQuf90Z5H3HO0g1H8yPdlfg3sCcJ3P98Ly6m5tzXv"+ - "ny6SETr94g5cXtcrv4ZddXMiT68thBCEq+NvQp2nGMlRC+FJchk179vxn52zkQlfka3B4coruG/+9muu"+ - "fapi57uGeFsBglGxLM4wNRxbTy6dC2UNJCbn9g4+ipE5KrqHSp4ZpOM9XLvH352LfpaKuHn9RypCUmCk"+ - "5coC9RBwkoqwhBMoe3HZdVKOuJe7EfjU0ctAJD6muK6ILFcN3i24PISLVMm8tHmfhCndtVm17nkx3Ggi"+ - "DBDpFbCO7/dvMhFO6uXmybZv6la3zrixy4XPPKZGHdj0/Z5/SScoPQn52HA+TfkWxQbaGNdswrJMZb7z"+ - "OfkKgxKtYCp8vdDvMtOMBTzyzDNfF7wNuBke719LaLaXS6ZSZ6+rvx0rJmXy+rDW+IpQ+CBso1pdHRRc"+ - "yZIjBbQHH7QmiN/qAakyb4IcZLWTAvEd4udrIZTt1yq/im1+n3kuiH/jFagSzH5Flw3W8ipOfSeCgSgj"+ - "iiKLjELxlsz5xptFVxQ9vGDBuyNXI9okPSQZwiwGqtZ3jXCcJTaWcP7XuHB65PlzXDgdEn+KC2elIkBA"+ - "8gkXCI7/dfAHLpD+RS4InMUFcaDthAtt/8AFsp9wwZf/r3BB8DcuCJxwgfsXF35x4b/jQouTZIA7Kv7O"+ - "/YtUxI9/LojhVueUB4iqhbfJJ2bUENhFCYDT2u5YXEsgUFZLkThQaleuYHC3CTKxTCbd1WT0EahBGslv"+ - "DVS32ii8KogjzQvMo62Dwg72hZO1psRHKPQVVBUiB/prviITb5iO+tuV8Cf4gpbxNSDVG/UcMS0Pn9pX"+ - "1fA9HSo2ohu/A25wf6KTwNh4tyDGJVmddORGO0dF7IBkC70hNsJXKFHlI05Ibn6hbebFsMuvbvjzplET"+ - "SHnmI++kTM7evTcpq/uhfFbDakQz8qsyjX32rhp8Ep/1zTZd2tJVkquZu8KMOVIPhflEnxnPxcax9scj"+ - "lToDBcO0pj5X3t7kifqSPfmyOjC8dKfK1GBAJ0ydvb8WSyv18/6Vwdj9aYKeNLT1q7nMXLlgkoOFNqzE"+ - "2nm7cSKRT4xtUp10hOZfm4YE0Ypt3Z/MaGB/DmqcUQt5RHWUzfTQJS21R/ToZnLorfPzIZocgeD19QPw"+ - "XHTIFdwHg7Mlmota6OqYilolxSmSlx8CKjwsELJHKCrINvmNCxi34NV87Ipn6YNICQjQvqAz/rKMznR+"+ - "xLnkeisDE8nNYUGNo/Yd6z5nn79bwVxU+VrjMw6FYyvsRHjKviTE8i3z9Tag580i9Ern5SnETqo8xEsw"+ - "fIyRKSNIzwJRMUUgiRI8wm5TB8UZvJzFngq0eBhAJRO5vbBiKg5703eOV45AT6Sh6XK9gDG76nyVal0a"+ - "GR0lk4aLl1kWQ6H+WmNtU1jngMZR7RpLTy8JgWWcC6Gelj7Icfervb2pQuc3RKswbdDSUy3K1mwMB09O"+ - "lBZ8Pj1LRWmBn0xd0b0TcWaMvhRwTruEejUL/yMtjCZxXMuKevsgpH2fOmbNcDiBq2jZnuNYC7lyjL3W"+ - "qwueYx20DlUl8XqYe3XExPqBVvFjxAb1PUWkUsOab20KKdiK5yizYzde8dLz1mmLILgnsHdJoYpxUgvG"+ - "/PjoRnHGWuODhPomZGNKi+ICT3xpqjdmSokyIOcwY/Q6GjQGghDxtZ5GXkroNGSRBZXJVzXWn/V8EX8z"+ - "bh2EV1VrM2gkFVGxYum4qEsJHd2DPj6kJnJzVTADlCZWR7ItRI7zEPBUU2RiU8t1G6QOxXMhpekJvVQ4"+ - "IppKQdVys+cLtUY6Un0+hI2Z0wMzAxO8Lr0LbaILk8WtNsxpaFYMrTjC22723OH5GFkUi+ux8An2Hi0F"+ - "fvcr1v8aFU6POn+OCqfj4ffS/e+pcOEMKhABrCdUAAPhwB+pQHYGFcT/BBUEz6LC/wGpc+eRNSkAAA=="; - - byte[] dgBytes = decompress(data); - List dgRecords = RecordFactory.createRecords(new ByteArrayInputStream(dgBytes)); - assertEquals(20, dgRecords.size()); - - int[] expectedSids = { - DrawingRecord.sid, ObjRecord.sid, - DrawingRecord.sid, TextObjectRecord.sid, - DrawingRecord.sid, ObjRecord.sid, - DrawingRecord.sid, TextObjectRecord.sid, - DrawingRecord.sid, ObjRecord.sid, - DrawingRecord.sid, TextObjectRecord.sid, - DrawingRecord.sid, ObjRecord.sid, - DrawingRecord.sid, TextObjectRecord.sid, - ContinueRecord.sid, ObjRecord.sid, - ContinueRecord.sid, TextObjectRecord.sid - }; - - int[] actualSids = dgRecords.stream().mapToInt(Record::getSid).toArray(); - assertArrayEquals(expectedSids, actualSids, "unexpected record.sid"); - - DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord()); - - // create a dummy sheet consisting of our test data - InternalSheet sheet = InternalSheet.createSheet(); - List records = sheet.getRecords(); - records.clear(); - records.addAll(dgRecords); - records.add(EOFRecord.instance); - - - sheet.aggregateDrawingRecords(drawingManager, false); - assertEquals(2, records.size(), "drawing was not fully aggregated"); - assertTrue(records.get(0) instanceof EscherAggregate, "expected EscherAggregate"); - assertTrue(records.get(1) instanceof EOFRecord, "expected EOFRecord"); - EscherAggregate agg = (EscherAggregate) records.get(0); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save"); - assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different"); - } - - @Test - void testUnhandledContinue2() throws IOException { - String data = - "H4sIAAAAAAAAAO3bdVRUW9sA8AGGrqFHSlpAhSEcQAkJ6UYQyaFBmiEFpCVEOiREGikJSekGlRJQuiQl"+ - "FQFB4ptBvxvIvd+97/fete4f7rWYc9aZc4aZw7P3/s3zbFYB/FiEANTNeD4AAATA2sQCAADIH0wgAEAI"+ - "QNv04kNugZusiGMoAOxNEODHhgrAObkOgLgGHfDt/GlMAID4+3EUxHEADgDgB8DdVEbsNgDAgPMAHxQl"+ - "nzpAAwoI8XsbUfh1QwCvUPiNAIBjFCzEO/BuoUOeiYZ89fPA60AloCBQGCgO5EE8XgPKA4WA/MCrQDoA"+ - "F+IsRgDDR0VM5JUAwHVAbosYYl9ZDg1ICsA4+Sz0gM3dkJpDxN4s4gwSxFZb3NbG0cTGUf+mm50JXJfD"+ - "1doqJrJbthUC6tjw3QAtsFvnYRJZvMDMlyLTPQ+TzrYehmInaLpMTTqKcMzi0JotHH9kzL01ZkHKc6Ni"+ - "kq2K4yJorozv7TaO8FulNhosxSW8sMlIXxqugsRXD+7W4bYy1NBcBKvi7KqW0pqLcXjSxXM+DifJFmzX"+ - "wxikWpWZvDlUODjJ7JArLYfB6yRHcy9MRtBma/86sYUxiBBz5k0WQBxc2B4jM7/6OjxudljZdFGvxQ/f"+ - "I5br+tFosU4PBbUn555F+hUmPa5ss2Tu+7yRzIRgVsuXDWrkr4Nxp5w01EYk7+l7XHgKn2n3qpbe8no+"+ - "ZuWesRfDsSsy6IG4v8fHaKfuFteEvsEbxF444m7hIrb6DiZWcE4O5GNmRNOdFgje/Q2/Or/+OvtR8XMZ"+ - "irYBenKYNTjaMvJGrzRZrKfqsyGakrbXPlDsC3/c2KmE5CaUuoZhvFXADUk3WXwPm17x0PT0jvLtn2mN"+ - "xBuXgU3VNawp8hrkSnHvM+WppoPBcjJPtB7QsKXyJrO+VegVgOUa0TqKuTf5fM62rrx6bHq9EpaXwRMR"+ - "boP2wUNp6CCQprb70nh8u0Pf+O5kffqdjneu6dWqEMKbeFWXeiED44OL1xt2nh0vxxKReN46EjuQz9/u"+ - "KKC44kwIOOujl5871I5HBQAOMJDdAQAwdoBzws0N7EwQEYKMkgJ1GZsxCOkExRIN1joJfgWxVDFpGcGo"+ - "Qj9YEQ7QSLdKI2WLKLhspp46hiokRtiv0E9vFmE7qKSqOuqo2bojlj1JcezuxZCzqNDWlyirjpMyPT3c"+ - "EfRJfo5Zn+XL/tDzDGxJWZIUEhZ+hc04do8U4Xu81g7nSFIK/SWmffPB3sCismdGvWojIRoSNA8SHYrJ"+ - "xTQkWvJ17lYzUdnpcXF+PiRRGoqK0ilkHaLo8VVb0bZtDeXeaVXlfxqR7pAvX8ybfFfS7/YofnHVpRBH"+ - "0lApA95hPONuVas3kX7dpR2hQkHNJRuE0Jq2/XrGQUM6mQ6/LRQe7XSZ6eMH/Eutk2bCD/ZpYNXv10Zu"+ - "PmSPkomEhfJa817co9K8plVfn7dYGr3pIBT/9DUJtWGrDHrAHZG1yTXhiqmxsYmvO3D3sXtjnuZeZfqj"+ - "RayNk8XdX7z5qNaLaGO3FWazI9RvwT55f9LInEuNb01nVUbDJ38oCeKRHAM+uZ/BM8WnJY3XlPZ6uCO6"+ - "05vVj9B3iZffJ/yhcE6rh5Zc1hO1kkp2Y2pmzTfy2gHGh2IWUkNqjm721ZDu7M9xKoy+H9EDvK3ei/Bz"+ - "KkOwBMpWnQ2XQmXKWC41Mb1ifefDUyitSEO9t7nyiWu1eKTEN7Q03XgVNnoVxTTxeHDBYejjCAM5OtMW"+ - "bO7omPh9p0WvOSPFgd2celfAQRIAQ32ZwcXDM7rqLUQ3PSmHYYpSpmjmPAZ8Sthn67Z+cwbMMHo6NPaK"+ - "pN3m5HhHpikPygTa1vuwBaAln7788kVGO302kID8dL1eAUknroFcleOjaGk34QtRlwBmrePCn9b6Zylt"+ - "nlDxY/umra1wTHlGrXVlAcrjUS4aWHEEsWRLVJA36DOSw6tlvFDPCuKXAuvz1Ii+G4aCHIu/BbGxrYuN"+ - "g4kzMoblI14ptkBAN3alD/yuSFuBnFJYY66qi4qZqEmMlsLMiBfpDa+VKkQfCUXH5U3s9Yzz8Lx7vken"+ - "XUrSDtXi2rxAC0pz0OXNMyyeqJ28cL3gfd50oYZvk57mo5x3t3iELzsWcZdo14RMg0xykkXXdPiyBhfK"+ - "I8YVHS+Q7shaM7mwKtzAbXGn5tCmdJ1Ei61VqUpbeOyae+Po+VFs1Zz4PZtt+KfydJcxYW2bKBYCknYb"+ - "2/ttJKALGC7Q4wFbdD+AdPW4V1J2Z5VTM6SRH0zgJxpCQbgmNl8OfV/Dq0Wc4Y5BH6FTiUm57X5bayYi"+ - "yK9TnFo7R3VJygCERmOfE14cfo3QEWg0Y+wZ2u/a1R68QXP7rhtmyBZfttcvowEK6mXAH08cv29nTCOn"+ - "X+D0WPpr40D53ch6+sLTI9GvjQ31x3Hp9NWnQ+DXtg78ISCU5dAxvk3fQMA2YsuH8e1U0Cbx9/kdhIoG"+ - "6EY824eGB8BHHCHaRB7XBVACyBCzPCpCBkSw0zdnFbCEeVoCqP+gBLh/SuCnBP57ErjpXBiC7H9HfyiB"+ - "7rABCKie8SNB3EbNnkXSZZVoMkd0ilYN3R0U+dkyojCakWwRd7HZkLLwRnE70YNVnkzb1mFFVZhPS4VQ"+ - "Zo+84BTf1Ovh6C0EBUK+UWDwOwWYvuxvb0VznabAyBw3i6A2TjAd8BYXmLh28EWYkJKJnBaRE/udl03a"+ - "WLeJ8IscZuajCuhd22r7dhlPKHCZDUEBPzUq7aK2GO6dQTF+Nfob8xoJMAv+j3iYz8uoYPa3SZchIT3N"+ - "Khs8LCtxho8JHo9cupb0EbPJbvprXa9NScmut9ZnumVhV9vnKs1NX/QbReV2aB1IBZd3vG3Dx2dyKdWZ"+ - "ohmawBYv+gvmbA3WvPc+5KV0xbXmD8mncyttAhgV2VnVtyx277mMediuO59P7O3W3bLeLdnr97CoTwe5"+ - "H0JJ0Catmhskb0KhwXwBBaPE0ZikVQzMmPVM5Dd8oH2G/a5AAaMyhc0vl1Bn8CmIxR1YeY7ovzQFcX+h"+ - "Az9GJ/Kw+iLAsjCgxX7oG+J3m56EtSnKdJSbKT9e9tpTgvShNguDUYXlyxn3ge/hONgjb72KOZQh0gJl"+ - "S86mSzEyZQzfJQC/LKP42G2upWgoY8pgqMQf7zlCAubjWqimKRtwuFa5a0XQDRRDWvzx4ycQgmTnICi8"+ - "KRxTL1ans4EIphwLhQe+uxJsiT/AfHdLfk5bfBn/oAVGO3rBTmxFzpVUvoAkuaS0HStsMknEWvV5rve6"+ - "z559INy3PIkz+3MsvSsrWSc1y2YfKxRrSWwY9RnNAqtqSm8QE7yYx3D9/N668T383V78ZKDo1I5TvsuF"+ - "UqFqUs01p0ZZcBJuejBbZGHbBkVwuYD1mydnBnFQfewychqIOFsCNyMUlE76sPRBYKe0DkhO5K3qy1IL"+ - "ujR7lJJC6qoAFt2LiZmyzaOH7oIYo1V75YfD94QS8POYtS10jXj97EgBkS940/upMNr2P15FmxV851sp"+ - "KYdxbRkGFRJJ2tR5pMc57zzPBww0j4djlO/qKuZetMytokpQvFOg3s6+rjKKTxa3y69TzovjG8M+aT6u"+ - "vKUoPFh6oOPJpvMpbxIH/qROZCA/XZ/j7e3o1nNG8RQtBwRB8X4i0OM3Sr6ieJlaq8JWjHHjbhbnUml4"+ - "A9thSAnoxJeXfK0qlSSyvIthRJdlcU6i+B2n+nymFAN1B8qs5r7cw4HPLLLe6/a2BHZBg4SPD3IGNsm1"+ - "lRA94DmaghKnqL3H3Geqf5sETo9Ef08Cp0Pg/ysBNCAgEfEtvw+ABxg9QwKoZ0rg/YkExn4jAbR/UAI8"+ - "3yUg8xsJCP2UwE8J/GcSKAnuIYz+05yAnM0YBPQ9J+BJPRICYzOnKUtK50peABRIjIixqdLd9ipl77P2"+ - "oU0LXMpeuoDMCdCzVT/8ert1p5m2126hbi/y/QOn7r4oWXXslNkTCOiQkj3J+bIw9DwazJiFzYlFkpzt"+ - "Kk5W30krQlmEmwBK4fSXAPnmA0nZ9MwnmFJyPqEXBl8lw5+HXQ4oCL7f4LBOFlVA59qNgEBgyh0m5gAt"+ - "5TzOx+hm0Aq9YGyT1eAAuzzVkFGZatgIbPUcgWQZAZ1OrIkzbUB/jyHpW9Y29pVByVWndmFKVKJFFJYV"+ - "A7RjsQHDwD7MESl8+pcNdn5hy8J2IILZyUVah/AcypvROiGkRpnLWs9DGlBGImderZiyXzPkjFcLzmNo"+ - "MwPbq4o/GVUacxkLX9vdsflafzg+WT5VcX70/Fr8zkVKmO2iqWEjYr7YIIp9qBDlxLbyrGEOZaJQps2H"+ - "U0bidvqV17cEgzAN/PsxjEVCpeptOyOApeLVAnbkUoupEtUCRA996ZOhQBoyeFmkrEjOLEyrEyhbklld"+ - "Qdr1KeANQV7gEs77EIP7Csv4SATw4JwbafKyM0g1inAw719r78OONpfRDJFJUXuGZqYV4XvVaa4lJ7+j"+ - "p0Wjg5j79cuQkgz7FaxH1kfRSfnqgWZJmnHKrzN8vh5fDEXLEUrv1tl87/OOjOKTLRDsmPVqfGZbfFay"+ - "RT5YT4SsrV35Ln5DcUJgD/Z47z5OvSyLBlvP7SEYkGJjrV7xDpQIIlQssn5HscT5a1tMPRRImIWa0IJB"+ - "S9mG4fMCBA2UChQIiaFQY+jC+xz66J1UvVDCROMKHJdPtJjqa3a+i76xuxNb32iHt3oxNF6CZIBh7MHX"+ - "3qCh6lFjEZSzAlh6X2qcCvHMw7+YD4iKIhZ7nEeXVooSCb00nNDqFjQcZjWQ6dWbmXXHpb4evi648EC0"+ - "wvhiqHWZ4bSSIJ3Y/Avzm210Y7Xjkr/kAxQ1NZniKeC0FC9u5Q4/070BkRh5xPP08YqhrLUebteahItY"+ - "2q07jNXiFuxa4EmjKiuLaTcedreMYvHuax91HhyYHV4s6Qo8eP1Z7fO2pG2psK51OkuyZKiuPv4rKTpF"+ - "vPWbB0oN5Hjr3jH5E5UWITHaF/DQdDDjW9romoIDnXM/aSV91KW8HNwv5AeSfqaNoQY+SQiAx3vt6uvg"+ - "B25YfqClzquedJ4SO6ySyWn3IA+LHcvCrLztMRNTwn1mHdvmCP9tCDg9CP09BJyOgF/bh/8bAdynEICG"+ - "eAPoAFMkAlDwAdlnIADtL6YDgP8gAngBP9MBPxHwX0PA6+aBzkeInnb4lxAgEzbf6ZuV6tRnE9Jul4hW"+ - "TGyCmyXtY3zYlXe9Ev2uP216UvqTZNF6lcBMJr7Dy4buBgM8c7V8tqadXW3ZhuY3stjRlezsPhhJuLF8"+ - "iuIk9tj6MCLjH/nGf9EfW5GkNgtHPzP8vAK0OhS7N06MAatJHe8+kLP8pDIQpSHxOCTRYfOkMqBfvekg"+ - "8xZUazjZuCuVksfMXK2lilAAZg5CAQ/YThSQLRbyspC76c3zYDP+R1lCgAf56dJ+KhBa/7reRwXaIU5X"+ - "HUyfr1q1e5Gj10/VrGJT3Q3PuREeuW60C4Ub8wdJHjfj3/f87N6o4jpJg6LoPk2gOPSUIYEUu1164KEp"+ - "sxeaJYVf0bOVBCuBWp1uJvYtYCACA6JpiUo1LjXh3bsLNrv1e+PjV6aczyee745fuEhpWCRygoGNIiQG"+ - "ZhXo8ysa51DmC6W7fDiDb6ik4vMOu66K94CtDWgkULAQFgCXiieMQEKbucAqps7+iyhBd5xdw0JGTkoD"+ - "9pDLxqgnpYEQ420xC8wh0bJmfi75SrY6k8EImIciPePYHiE5BjsGG+GlFzTnrpoQF2LJQbq4XzpN68hF"+ - "qZkReH4pu/v5QsHVuAgDjZhQmofaco2hW0/GkzUup1w2VPF+JIW2e3wBQQGabxS4xXxCgZtZ3eMzTgqz"+ - "Wi2OwZOCZHtvkRSAJATuYOv0ISiAw/IWu0fzthGQb2NtA5o7cvP6buNBVY1A02g3hdr+KEgwBseYgMTV"+ - "nJQK6EhvhVJEACdl6zWTiBIYPsfVG+7hzt3gs7j4dpzMc+xd4eTjzp0PqrDyopPKQPBJZWB3isgSPpp5"+ - "tgRy7xoJUP1ZZaAbKQH/Delav3JpHZDTG2iT/wt1UbE1dIlRu2lT4kWpVmeTJBZPd+gdFfct192xkZGR"+ - "9FuXR+RWKDME/DMAQYPVbJS69p0VRbt4QVtiFOlXtBz4pTEf7G0PyTMFLDuy71LpE1Gn6zLwD05uEMvq"+ - "6skxj3euZrZrWRQQ02YVmhvcCGxRl+sQBakxUz4kKB/uitdaEEnSD2A5/4GHp3d15eGkie6L0VKWREiP"+ - "re3+PAmI093LRrh/xVccmKlDU2+tltnsZiEAo8YLbIKFUe2uqS6Wl7TUlEkSWV4l4IoYL6NmgSztljq+"+ - "yTA08ObVOPJq5veglrqOOZrESKWoBNHSb7x0t7FHzvWq6Uei7Hj3VP4n9keY/zYJnB6J/p4ETkfAr23j"+ - "76cDEBJAwUB83UZIAJUAAD9DAsAzJCAImD+RwMRvJID+D0rgyncJyP1GAiI/JfBTAv+ZBPoZnjfFIXra"+ - "3l+TQNx81R9KwOF3EqhcNiNyN1LjSXYLR0pg7ywJHO7vdSHzAb3YJMksrnJkwkrnRRKtkGsELgdIRPjm"+ - "g/Gw9e7odqTklDIXBl0luzI/fdm/IOi+0okEIk5JIBkhgcoTCeT+KgG72XMEphZoyMKABRivRXTwa2jX"+ - "iyzNHLMeq7jH3V8OJ61cxsrcL13eP1gWtrXloe/n3zwOOFfGtSsaaJbBAdT5AQG4loGvbt3alq+g1is0"+ - "JY5185VCIiASgYDdmrEFd3jl1z4Pm/VEW4QIwhfktshuDK+0yBN8KV08vJJRWi1Ty2Y8RB4vmFpGxiaw"+ - "yVzCilMmswlgJ8FjCK3oMzcASyIzAmDFQO5hEF5HPwkk/fVqUA+qcufqJjXZ8/I42YZUZEqASbY4M6GC"+ - "tOtD1huCPD/zAHvDR4pqd189pW/6ktwcbPVORBP89FF/a/qYfZoaS39IMTD6UoYOZk85k4CTad8rNoy7"+ - "n4k0aOQ6IRdl28PaC5lhkntKNor55L3kJazXTzICJO0+AwT9Kb9jgFB1y0pia/n9ZeI6xF+vMO0zxpEB"+ - "N+EaSVXyNvPBL3UBm4mkr78wwP07A14iGZCMrAtcgmIj6wJ61G/1UASfEMkswMxaBYU+TXQdUKakUFVh"+ - "+9avrWhsKCIzAsWj8d6xECiFBIkag/aDqSnQHzvgA+7DVErEMyF/5AB9pWYIaduUwgFB95WPbdJ87bAE"+ - "R6ACXr05cMHP1mnlqLVcd/Rle+WiIt3mYMrY12u7KT0UdVadimBty7bG827X/V866uVHib7w9Az11uxQ"+ - "76EqBPrVFRdL29guCPY45bw1rLRnFiUxMepJdXj2kK38NjNTJeMEToBtADTqWkx2ZvUMTeKr+2FCtrLM"+ - "RWSKT10v6rFHHtocMRHsxejn3gurn1oWHy28NfaUwC+o5GvNvT1ga/CkbqLSZ+0eGE6m5pqX/OOi6l+W"+ - "CPhS7XarmsRCW+ogWsQZ1zB46BJswEDIUnh6cfNhtKZQfuMT4HvQ0vWrnnMHm8BZN3RFU7VV6ku9duC9"+ - "SaLsd9dSqzwMHAD/NgacHob+HgNOB8Cvbe3/ZgDvjwxAxURO4oA+NELE9PojA9DPZMDiCQOmfsMAjH+Q"+ - "AdDvDFD4DQNEfzLgJwP+MwY8biPYj/s7CYHwM6oC2j0/JAQyyxAMGMNNSqFfrHPjEe/pWYlKw4/NAwm2"+ - "N+WGE83nduLUh3zczje7QBIawyLIKG9H+Z5G/Yug24G5hhk3g6AuLnJ9ABHYsPbtixBBpSxLLWIndvaX"+ - "TUm4t4nxveZfvmIaEduMckObOu+WFxVjfEcht96ONnl4+O7FhZiSC+TNCQ5sspWy6HI9pikzsLgdwCWO"+ - "LcFzYZLvRYdPHDDMYmQGfdVjeiDKD96/t/Fcymr12vXLdyOMBzE3rKEvp60+cU6nCsHPu1E6X2iEB46l"+ - "5eLEMsUytIMttCw1NvmKnYs94OqXjeVm5k3pVSLbXEOJLjCT5u2VeVUeD3vY2uxuJPV2W29ZH6d9WyBA"+ - "tLNvxIJx8Hz5iFJlZJgpD367Ap2FkNVWBofAQ4bpE/UQFy1eNv1caD9BojU/dg7SAlil4mxWS6GsV641"+ - "20N8J+6nZhhWaKguL96klsdNuM4VxzsUxzBSqzwq6gQqhCjiDVjLboCvMIH1VTs7nY/8AnxCzimcZAPM"+ - "iK2xHnDJqCGzAZZRKr/LBsRRnM4GpPidzgbEo/+QDXj2JMTKjLXuvv6j1+JfgRzmntj6AiRj4JyCpxDf"+ - "pN2FeoU7UIo+IbsHNTUC7b8y4DfZAPRv2QByiSjm79mA0tr7i4sYNr6ptl/zhmpIRvR0cQp2rsDQQ7vR"+ - "+1tjOt/O7rq0jiZDu5TOjOGMJL/0P10oeCodkMhrgeWU5+s/ihtUMdPYzdQTHrT2Eqqwv2OlrQwv7bg2"+ - "tR5mtqVXYcyJrAxAaJEMcOp/GiJa4Vkd7oNgQJM2ggF+xRCloiJTQTZHBAMa7MmaWF6yJIuujXOknawU"+ - "DPusyFoQOyq9rpwYQn7fZVinYnC3Nkh2kjVZeeux67MbR3V7kfxzuveM99mOPLJcblfq2bxnwTNst7Hd"+ - "b2MEXbjrwnXcn+/bRCpdLeiRkK0JX/E38LaHUGP4kfKtjwW8tLQO231jLhO6rnjzmTYGCvW2NnKlINZh"+ - "cCB/3NETFhXebfFUqfFlHsEwRXIMV4KlQNBDcedVzI8JWS1Cyjr1XIfo/zYInB6I/h4ETofA34IA9EcI"+ - "oGECuhEv3od4K2ctFMQ4EwI/VgYw/0EI8AF+VgZ+QuC/BgGe5ra+P68M/HahoMwL61FJBY0+Mh2QttMI"+ - "JiR4QJLf2TgJOkFCfIuJ1idw2vfLiJn0VFDJY2MfdIKxnb4XPDseUx48Rr3/FAQIhdRlZLnLs2/q8xMq"+ - "WlnVkcFfDpPgzshXk2ZpZ/kytyR8rwy8ElTKzmh6ugv2c5ItUWD5lg7wg7kufK3rpS2J3JguW6KPKiac"+ - "HHsd2cRPfYDLb947Lk7gZ+GC4eHSSZOSpyyjymYYGpldboruhWaJ+Zrv1pBYBZOeDTkx2e3QNJ3kGOWn"+ - "CwNHE0dGW3XVEw22wnyV3ZWHgQtSW1l7Ie3DK+EJ4M1elgNLCROj6Kc9JiPkjwRTa5nZ+DeZIzvhNztc"+ - "IdRh9Gahzn1WMyPAGD5jaeBIGikU2NJljiMZk0iTYQ9qthHvU+HSvpj7Gc5OkB0gnwqWS7wjF2mlx7qW"+ - "ejVIA3zh/jI0yyWUkjiUk83Y+NpxU/P1tlAW8okwvMc8wVD/tkeZbPNX7Z5d6XrKE+5xlgU8v6UEuHpF"+ - "f5MSMOX48rHxlS/uHh8qXt4b0/XNFyz2hQYvJN4p3ajgidFr4ZRfSPNEpSir9y9KDrYOVdO4CW7qdt/K"+ - "+WYBiMi6TViJ81ZbTD33t0UCQOQiARRdLO2m/BbqGy+fo0caYztLvt5inEq5VDSzV+2TRLc0Vn9ne12i"+ - "4lY8ar4nviaKEVyUl4u5tPzLIU0JNEfhE8lZUWw72xT81yoD4mVICkRB6fG/U6DsfynQeUIBLWX30o6a"+ - "qfVQileiZT0plgOsMk1JVdN2CfnpkWQBVrsO532MLkWjW8bOkRKMN3JX12sVVynXye/ds7yIGShNwoNT"+ - "Xq4rH9RlyfEo4WmYXEGsLK6pyocQ0sRtfp2yVpeJCKy30uPKz8NE3gkeTx5h6XziEObeJvWsj6opUHpX"+ - "8xQ7myirkq/lAxH1K0x3m6MMPnT0z1rPCPVfsKmaXnpHCiG43wKLSH2fpttVq3G3Nl4LWyr/SHo+Lwvi"+ - "p9IQmzVDjm0LdSLqeHM8ILiJRsdoNYS93WyEhi7IOdKXZLTCvCLifxTMEi+snNzAtfevk8DpkejvSeB0"+ - "BPza/oPKABD5z4SARKQEELP1WQsFMc+QwP8ATkmhK404AAA="; - - byte[] dgBytes = decompress(data); - List dgRecords = RecordFactory.createRecords(new ByteArrayInputStream(dgBytes)); - assertEquals(14, dgRecords.size()); - - int[] expectedSids = { - DrawingRecord.sid, ObjRecord.sid, - DrawingRecord.sid, ObjRecord.sid, - DrawingRecord.sid, ObjRecord.sid, - DrawingRecord.sid, ObjRecord.sid, - ContinueRecord.sid, ObjRecord.sid, - ContinueRecord.sid, ObjRecord.sid, - ContinueRecord.sid, ObjRecord.sid - }; - - int[] actualSids = dgRecords.stream().mapToInt(Record::getSid).toArray(); - assertArrayEquals(expectedSids, actualSids, "unexpected record.sid"); - - DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord()); - - // create a dummy sheet consisting of our test data - InternalSheet sheet = InternalSheet.createSheet(); - List records = sheet.getRecords(); - records.clear(); - records.addAll(dgRecords); - records.add(EOFRecord.instance); - - sheet.aggregateDrawingRecords(drawingManager, false); - assertEquals(2, records.size(), "drawing was not fully aggregated"); - assertTrue(records.get(0) instanceof EscherAggregate, "expected EscherAggregate"); - assertTrue(records.get(1) instanceof EOFRecord, "expected EOFRecord"); - - EscherAggregate agg = (EscherAggregate) records.get(0); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save"); - assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data brefpore and after save is different"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.java deleted file mode 100644 index 7dfcd66940..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.ddf.EscherDggRecord; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -final class TestDrawingManager2 { - private DrawingManager2 drawingManager2; - private EscherDggRecord dgg; - - @BeforeEach - void setUp() { - dgg = new EscherDggRecord(); - dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[0] ); - drawingManager2 = new DrawingManager2( dgg ); - } - - @Test - void testCreateDgRecord() { - EscherDgRecord dgRecord1 = drawingManager2.createDgRecord(); - assertEquals( 1, dgRecord1.getDrawingGroupId() ); - assertEquals( -1, dgRecord1.getLastMSOSPID() ); - - EscherDgRecord dgRecord2 = drawingManager2.createDgRecord(); - assertEquals( 2, dgRecord2.getDrawingGroupId() ); - assertEquals( -1, dgRecord2.getLastMSOSPID() ); - - assertEquals( 2, dgg.getDrawingsSaved( ) ); - assertEquals( 2, dgg.getFileIdClusters().length ); - assertEquals( 3, dgg.getNumIdClusters() ); - assertEquals( 0, dgg.getNumShapesSaved() ); - } - - @Test - void testCreateDgRecordOld() { - // converted from TestDrawingManager(1) - EscherDggRecord dgg = new EscherDggRecord(); - dgg.setDrawingsSaved( 0 ); - dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[]{} ); - DrawingManager2 dm = new DrawingManager2( dgg ); - - EscherDgRecord dgRecord = dm.createDgRecord(); - assertEquals( -1, dgRecord.getLastMSOSPID() ); - assertEquals( 0, dgRecord.getNumShapes() ); - assertEquals( 1, dm.getDgg().getDrawingsSaved() ); - assertEquals( 1, dm.getDgg().getFileIdClusters().length ); - assertEquals( 1, dm.getDgg().getFileIdClusters()[0].getDrawingGroupId() ); - assertEquals( 0, dm.getDgg().getFileIdClusters()[0].getNumShapeIdsUsed() ); - } - - @Test - void testAllocateShapeId() { - EscherDgRecord dgRecord1 = drawingManager2.createDgRecord(); - assertEquals( 1, dgg.getDrawingsSaved() ); - EscherDgRecord dgRecord2 = drawingManager2.createDgRecord(); - assertEquals( 2, dgg.getDrawingsSaved() ); - - assertEquals( 1024, drawingManager2.allocateShapeId( dgRecord1 ) ); - assertEquals( 1024, dgRecord1.getLastMSOSPID() ); - assertEquals( 1025, dgg.getShapeIdMax() ); - assertEquals( 1, dgg.getFileIdClusters()[0].getDrawingGroupId() ); - assertEquals( 1, dgg.getFileIdClusters()[0].getNumShapeIdsUsed() ); - assertEquals( 1, dgRecord1.getNumShapes() ); - assertEquals( 1025, drawingManager2.allocateShapeId( dgRecord1 ) ); - assertEquals( 1025, dgRecord1.getLastMSOSPID() ); - assertEquals( 1026, dgg.getShapeIdMax() ); - assertEquals( 1026, drawingManager2.allocateShapeId( dgRecord1 ) ); - assertEquals( 1026, dgRecord1.getLastMSOSPID() ); - assertEquals( 1027, dgg.getShapeIdMax() ); - assertEquals( 2048, drawingManager2.allocateShapeId( dgRecord2 ) ); - assertEquals( 2048, dgRecord2.getLastMSOSPID() ); - assertEquals( 2049, dgg.getShapeIdMax() ); - - for (int i = 0; i < 1021; i++) - { - drawingManager2.allocateShapeId( dgRecord1 ); - assertEquals( 2049, dgg.getShapeIdMax() ); - } - assertEquals( 3072, drawingManager2.allocateShapeId( dgRecord1 ) ); - assertEquals( 3073, dgg.getShapeIdMax() ); - - assertEquals( 2, dgg.getDrawingsSaved() ); - assertEquals( 4, dgg.getNumIdClusters() ); - assertEquals( 1026, dgg.getNumShapesSaved() ); - } - - @Test - void testFindNewDrawingGroupId() { - // converted from TestDrawingManager(1) - EscherDggRecord dgg = new EscherDggRecord(); - dgg.setDrawingsSaved( 1 ); - dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[]{ - new EscherDggRecord.FileIdCluster( 2, 10 )} ); - DrawingManager2 dm = new DrawingManager2( dgg ); - assertEquals( 1, dm.findNewDrawingGroupId() ); - dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[]{ - new EscherDggRecord.FileIdCluster( 1, 10 ), - new EscherDggRecord.FileIdCluster( 2, 10 )} ); - assertEquals( 3, dm.findNewDrawingGroupId() ); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java deleted file mode 100644 index 22cd1ee11c..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java +++ /dev/null @@ -1,853 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ddf.EscherBoolProperty; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.ddf.EscherOptRecord; -import org.apache.poi.ddf.EscherProperty; -import org.apache.poi.ddf.EscherPropertyTypes; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.ddf.EscherTextboxRecord; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.CommonObjectDataSubRecord; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.usermodel.HSSFAnchor; -import org.apache.poi.hssf.usermodel.HSSFChildAnchor; -import org.apache.poi.hssf.usermodel.HSSFClientAnchor; -import org.apache.poi.hssf.usermodel.HSSFComment; -import org.apache.poi.hssf.usermodel.HSSFPatriarch; -import org.apache.poi.hssf.usermodel.HSSFPicture; -import org.apache.poi.hssf.usermodel.HSSFPolygon; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFShape; -import org.apache.poi.hssf.usermodel.HSSFShapeGroup; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFSimpleShape; -import org.apache.poi.hssf.usermodel.HSSFTestHelper; -import org.apache.poi.hssf.usermodel.HSSFTextbox; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.HexDump; -import org.junit.jupiter.api.Test; - - -/** - * Test escher drawing - * - * optionally the system setting "poi.deserialize.escher" can be set to {@code true} - */ -class TestDrawingShapes { - /** - * HSSFShape tree bust be built correctly - * Check file with such records structure: - * -patriarch - * --shape - * --group - * ---group - * ----shape - * ----shape - * ---shape - * ---group - * ----shape - * ----shape - */ - @Test - void testDrawingGroups() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("groups"); - HSSFPatriarch patriarch = sheet.getDrawingPatriarch(); - assertEquals(patriarch.getChildren().size(), 2); - HSSFShapeGroup group = (HSSFShapeGroup) patriarch.getChildren().get(1); - assertEquals(3, group.getChildren().size()); - HSSFShapeGroup group1 = (HSSFShapeGroup) group.getChildren().get(0); - assertEquals(2, group1.getChildren().size()); - group1 = (HSSFShapeGroup) group.getChildren().get(2); - assertEquals(2, group1.getChildren().size()); - wb.close(); - } - - @Test - void testHSSFShapeCompatibility() { - HSSFSimpleShape shape = new HSSFSimpleShape(null, new HSSFClientAnchor()); - shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - assertEquals(0x08000040, shape.getLineStyleColor()); - assertEquals(0x08000009, shape.getFillColor()); - assertEquals(HSSFShape.LINEWIDTH_DEFAULT, shape.getLineWidth()); - assertEquals(HSSFShape.LINESTYLE_SOLID, shape.getLineStyle()); - assertFalse(shape.isNoFill()); - - EscherOptRecord opt = shape.getOptRecord(); - - assertEquals(7, opt.getEscherProperties().size()); - assertNotEquals(((EscherSimpleProperty) opt.lookup(EscherPropertyTypes.GROUPSHAPE__FLAGS)).getPropertyValue(), 0); - assertTrue(((EscherBoolProperty) opt.lookup(EscherPropertyTypes.LINESTYLE__NOLINEDRAWDASH)).isTrue()); - assertEquals(0x00000004, ((EscherSimpleProperty) opt.lookup(EscherPropertyTypes.GEOMETRY__SHAPEPATH)).getPropertyValue()); - assertNull(opt.lookup(EscherPropertyTypes.TEXT__SIZE_TEXT_TO_FIT_SHAPE)); - } - - @Test - void testDefaultPictureSettings() { - HSSFPicture picture = new HSSFPicture(null, new HSSFClientAnchor()); - assertEquals(picture.getLineWidth(), HSSFShape.LINEWIDTH_DEFAULT); - assertEquals(picture.getFillColor(), HSSFShape.FILL__FILLCOLOR_DEFAULT); - assertEquals(picture.getLineStyle(), HSSFShape.LINESTYLE_NONE); - assertEquals(picture.getLineStyleColor(), HSSFShape.LINESTYLE__COLOR_DEFAULT); - assertFalse(picture.isNoFill()); - assertEquals(picture.getPictureIndex(), -1);//not set yet - } - - /** - * No NullPointerException should appear - */ - @Test - void testDefaultSettingsWithEmptyContainer() { - EscherContainerRecord container = new EscherContainerRecord(); - EscherOptRecord opt = new EscherOptRecord(); - opt.setRecordId(EscherOptRecord.RECORD_ID); - container.addChildRecord(opt); - ObjRecord obj = new ObjRecord(); - CommonObjectDataSubRecord cod = new CommonObjectDataSubRecord(); - cod.setObjectType(HSSFSimpleShape.OBJECT_TYPE_PICTURE); - obj.addSubRecord(cod); - HSSFPicture picture = new HSSFPicture(container, obj); - - assertEquals(picture.getLineWidth(), HSSFShape.LINEWIDTH_DEFAULT); - assertEquals(picture.getFillColor(), HSSFShape.FILL__FILLCOLOR_DEFAULT); - assertEquals(picture.getLineStyle(), HSSFShape.LINESTYLE_DEFAULT); - assertEquals(picture.getLineStyleColor(), HSSFShape.LINESTYLE__COLOR_DEFAULT); - assertEquals(picture.isNoFill(), HSSFShape.NO_FILL_DEFAULT); - assertEquals(picture.getPictureIndex(), -1);//not set yet - } - - /** - * create a rectangle, save the workbook, read back and verify that all shape properties are there - */ - @Test - void testReadWriteRectangle() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - - HSSFPatriarch drawing = sheet.createDrawingPatriarch(); - HSSFClientAnchor anchor = new HSSFClientAnchor(10, 10, 50, 50, (short) 2, 2, (short) 4, 4); - anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE); - assertEquals(AnchorType.MOVE_DONT_RESIZE, anchor.getAnchorType()); - anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE); - assertEquals(AnchorType.MOVE_DONT_RESIZE, anchor.getAnchorType()); - - HSSFSimpleShape rectangle = drawing.createSimpleShape(anchor); - rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - rectangle.setLineWidth(10000); - rectangle.setFillColor(777); - assertEquals(rectangle.getFillColor(), 777); - assertEquals(10000, rectangle.getLineWidth()); - rectangle.setLineStyle(10); - assertEquals(10, rectangle.getLineStyle()); - assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_SQUARE); - rectangle.setLineStyleColor(1111); - rectangle.setNoFill(true); - rectangle.setWrapText(HSSFSimpleShape.WRAP_NONE); - rectangle.setString(new HSSFRichTextString("teeeest")); - assertEquals(rectangle.getLineStyleColor(), 1111); - EscherContainerRecord escherContainer = HSSFTestHelper.getEscherContainer(rectangle); - assertNotNull(escherContainer); - EscherRecord childById = escherContainer.getChildById(EscherOptRecord.RECORD_ID); - assertNotNull(childById); - EscherProperty lookup = ((EscherOptRecord) childById).lookup(EscherPropertyTypes.TEXT__TEXTID); - assertNotNull(lookup); - assertEquals(((EscherSimpleProperty) lookup).getPropertyValue(), "teeeest".hashCode()); - assertTrue(rectangle.isNoFill()); - assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_NONE); - assertEquals(rectangle.getString().getString(), "teeeest"); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - - HSSFSimpleShape rectangle2 = - (HSSFSimpleShape) drawing.getChildren().get(0); - assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, - rectangle2.getShapeType()); - assertEquals(10000, rectangle2.getLineWidth()); - assertEquals(10, rectangle2.getLineStyle()); - assertEquals(anchor, rectangle2.getAnchor()); - assertEquals(rectangle2.getLineStyleColor(), 1111); - assertEquals(rectangle2.getFillColor(), 777); - assertTrue(rectangle2.isNoFill()); - assertEquals(rectangle2.getString().getString(), "teeeest"); - assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_NONE); - - rectangle2.setFillColor(3333); - rectangle2.setLineStyle(9); - rectangle2.setLineStyleColor(4444); - rectangle2.setNoFill(false); - rectangle2.setLineWidth(77); - rectangle2.getAnchor().setDx1(2); - rectangle2.getAnchor().setDx2(3); - rectangle2.getAnchor().setDy1(4); - rectangle2.getAnchor().setDy2(5); - rectangle.setWrapText(HSSFSimpleShape.WRAP_BY_POINTS); - rectangle2.setString(new HSSFRichTextString("test22")); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sheet = wb3.getSheetAt(0); - drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - rectangle2 = (HSSFSimpleShape) drawing.getChildren().get(0); - assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, rectangle2.getShapeType()); - assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_BY_POINTS); - assertEquals(77, rectangle2.getLineWidth()); - assertEquals(9, rectangle2.getLineStyle()); - assertEquals(rectangle2.getLineStyleColor(), 4444); - assertEquals(rectangle2.getFillColor(), 3333); - assertEquals(rectangle2.getAnchor().getDx1(), 2); - assertEquals(rectangle2.getAnchor().getDx2(), 3); - assertEquals(rectangle2.getAnchor().getDy1(), 4); - assertEquals(rectangle2.getAnchor().getDy2(), 5); - assertFalse(rectangle2.isNoFill()); - assertEquals(rectangle2.getString().getString(), "test22"); - - HSSFSimpleShape rect3 = drawing.createSimpleShape(new HSSFClientAnchor()); - rect3.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3); - wb3.close(); - - drawing = wb4.getSheetAt(0).getDrawingPatriarch(); - assertEquals(drawing.getChildren().size(), 2); - wb4.close(); - } - - @Test - void testReadExistingImage() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("pictures"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - HSSFPicture picture = (HSSFPicture) drawing.getChildren().get(0); - - assertEquals(picture.getPictureIndex(), 2); - assertEquals(picture.getLineStyleColor(), HSSFShape.LINESTYLE__COLOR_DEFAULT); - assertEquals(picture.getFillColor(), 0x5DC943); - assertEquals(picture.getLineWidth(), HSSFShape.LINEWIDTH_DEFAULT); - assertEquals(picture.getLineStyle(), HSSFShape.LINESTYLE_DEFAULT); - assertFalse(picture.isNoFill()); - - picture.setPictureIndex(2); - assertEquals(picture.getPictureIndex(), 2); - wb.close(); - } - - - /* assert shape properties when reading shapes from a existing workbook */ - @Test - void testReadExistingRectangle() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("rectangles"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - - HSSFSimpleShape shape = (HSSFSimpleShape) drawing.getChildren().get(0); - assertFalse(shape.isNoFill()); - assertEquals(shape.getLineStyle(), HSSFShape.LINESTYLE_DASHDOTGEL); - assertEquals(shape.getLineStyleColor(), 0x616161); - assertEquals(shape.getFillColor(), 0x2CE03D, HexDump.toHex(shape.getFillColor())); - assertEquals(shape.getLineWidth(), HSSFShape.LINEWIDTH_ONE_PT * 2); - assertEquals(shape.getString().getString(), "POItest"); - assertEquals(shape.getRotationDegree(), 27); - wb.close(); - } - - @Test - void testShapeIds() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet1 = wb1.createSheet(); - HSSFPatriarch patriarch1 = sheet1.createDrawingPatriarch(); - for (int i = 0; i < 2; i++) { - patriarch1.createSimpleShape(new HSSFClientAnchor()); - } - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet1 = wb2.getSheetAt(0); - patriarch1 = sheet1.getDrawingPatriarch(); - - EscherAggregate agg1 = HSSFTestHelper.getEscherAggregate(patriarch1); - // last shape ID cached in EscherDgRecord - EscherDgRecord dg1 = agg1.getEscherContainer().getChildById(EscherDgRecord.RECORD_ID); - assertNotNull(dg1); - assertEquals(1026, dg1.getLastMSOSPID()); - - // iterate over shapes and check shapeId - EscherContainerRecord spgrContainer = - agg1.getEscherContainer().getChildContainers().get(0); - // root spContainer + 2 spContainers for shapes - assertEquals(3, spgrContainer.getChildCount()); - - EscherSpRecord sp0 = - ((EscherContainerRecord) spgrContainer.getChild(0)).getChildById(EscherSpRecord.RECORD_ID); - assertNotNull(sp0); - assertEquals(1024, sp0.getShapeId()); - - EscherSpRecord sp1 = - ((EscherContainerRecord) spgrContainer.getChild(1)).getChildById(EscherSpRecord.RECORD_ID); - assertNotNull(sp1); - assertEquals(1025, sp1.getShapeId()); - - EscherSpRecord sp2 = - ((EscherContainerRecord) spgrContainer.getChild(2)).getChildById(EscherSpRecord.RECORD_ID); - assertNotNull(sp2); - assertEquals(1026, sp2.getShapeId()); - wb2.close(); - } - - /** - * Test get new id for shapes from existing file - * File already have for 1 shape on each sheet, because document must contain EscherDgRecord for each sheet - */ - @Test - void testAllocateNewIds() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("empty.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFPatriarch patriarch = sheet.getDrawingPatriarch(); - - // 2048 - main SpContainer id - // 2049 - existing shape id - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 2050); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 2051); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 2052); - - sheet = wb.getSheetAt(1); - patriarch = sheet.getDrawingPatriarch(); - - // 3072 - main SpContainer id - // 3073 - existing shape id - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 3074); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 3075); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 3076); - - - sheet = wb.getSheetAt(2); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1026); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1027); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1028); - wb.close(); - } - - @Test - void testOpt() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - // create a sheet with a text box - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor()); - EscherOptRecord opt1 = HSSFTestHelper.getOptRecord(textbox); - EscherOptRecord opt2 = HSSFTestHelper.getEscherContainer(textbox).getChildById(EscherOptRecord.RECORD_ID); - assertSame(opt1, opt2); - wb.close(); - } - - @Test - void testCorrectOrderInOptRecord() throws IOException{ - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor()); - EscherOptRecord opt = HSSFTestHelper.getOptRecord(textbox); - - String opt1Str = opt.toXml(); - - textbox.setFillColor(textbox.getFillColor()); - EscherContainerRecord container = HSSFTestHelper.getEscherContainer(textbox); - EscherOptRecord optRecord = container.getChildById(EscherOptRecord.RECORD_ID); - assertNotNull(optRecord); - assertEquals(opt1Str, optRecord.toXml()); - textbox.setLineStyle(textbox.getLineStyle()); - assertEquals(opt1Str, optRecord.toXml()); - textbox.setLineWidth(textbox.getLineWidth()); - assertEquals(opt1Str, optRecord.toXml()); - textbox.setLineStyleColor(textbox.getLineStyleColor()); - assertEquals(opt1Str, optRecord.toXml()); - wb.close(); - } - - @Test - void testDgRecordNumShapes() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - EscherAggregate aggregate = HSSFTestHelper.getEscherAggregate(patriarch); - EscherDgRecord dgRecord = (EscherDgRecord) aggregate.getEscherRecord(0).getChild(0); - assertEquals(dgRecord.getNumShapes(), 1); - wb.close(); - } - - @Test - void testTextForSimpleShape() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFSimpleShape shape = patriarch.createSimpleShape(new HSSFClientAnchor()); - shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - - EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch); - assertEquals(agg.getShapeToObjMapping().size(), 2); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - shape = (HSSFSimpleShape) patriarch.getChildren().get(0); - - agg = HSSFTestHelper.getEscherAggregate(patriarch); - assertEquals(agg.getShapeToObjMapping().size(), 2); - - shape.setString(new HSSFRichTextString("string1")); - assertEquals(shape.getString().getString(), "string1"); - - assertNotNull(HSSFTestHelper.getEscherContainer(shape).getChildById(EscherTextboxRecord.RECORD_ID)); - assertEquals(agg.getShapeToObjMapping().size(), 2); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3); - wb3.close(); - sheet = wb4.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - shape = (HSSFSimpleShape) patriarch.getChildren().get(0); - - assertNotNull(HSSFTestHelper.getTextObjRecord(shape)); - assertEquals(shape.getString().getString(), "string1"); - assertNotNull(HSSFTestHelper.getEscherContainer(shape).getChildById(EscherTextboxRecord.RECORD_ID)); - assertEquals(agg.getShapeToObjMapping().size(), 2); - wb4.close(); - } - - @Test - void testRemoveShapes() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor()); - rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - - int idx = wb1.addPicture(new byte[]{1,2,3}, Workbook.PICTURE_TYPE_JPEG); - patriarch.createPicture(new HSSFClientAnchor(), idx); - - patriarch.createCellComment(new HSSFClientAnchor()); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPoints(new int[]{1,2}, new int[]{2,3}); - - patriarch.createTextbox(new HSSFClientAnchor()); - - HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); - group.createTextbox(new HSSFChildAnchor()); - group.createPicture(new HSSFChildAnchor(), idx); - - assertEquals(patriarch.getChildren().size(), 6); - assertEquals(group.getChildren().size(), 2); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - - assertEquals(patriarch.getChildren().size(), 6); - - group = (HSSFShapeGroup) patriarch.getChildren().get(5); - group.removeShape(group.getChildren().get(0)); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sheet = wb3.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - - group = (HSSFShapeGroup) patriarch.getChildren().get(5); - patriarch.removeShape(group); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3); - wb3.close(); - sheet = wb4.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 5); - - HSSFShape shape = patriarch.getChildren().get(0); - patriarch.removeShape(shape); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 4); - - HSSFWorkbook wb5 = HSSFTestDataSamples.writeOutAndReadBack(wb4); - wb4.close(); - sheet = wb5.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 4); - - HSSFPicture picture = (HSSFPicture) patriarch.getChildren().get(0); - patriarch.removeShape(picture); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 3); - - HSSFWorkbook wb6 = HSSFTestDataSamples.writeOutAndReadBack(wb5); - wb5.close(); - sheet = wb6.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 3); - - HSSFComment comment = (HSSFComment) patriarch.getChildren().get(0); - patriarch.removeShape(comment); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 2); - - HSSFWorkbook wb7 = HSSFTestDataSamples.writeOutAndReadBack(wb6); - wb6.close(); - sheet = wb7.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 2); - - polygon = (HSSFPolygon) patriarch.getChildren().get(0); - patriarch.removeShape(polygon); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 1); - - HSSFWorkbook wb8 = HSSFTestDataSamples.writeOutAndReadBack(wb7); - wb7.close(); - sheet = wb8.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 1); - - HSSFTextbox textbox = (HSSFTextbox) patriarch.getChildren().get(0); - patriarch.removeShape(textbox); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 0); - - HSSFWorkbook wb9 = HSSFTestDataSamples.writeOutAndReadBack(wb8); - wb8.close(); - sheet = wb9.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 0); - wb9.close(); - } - - @Test - void testShapeFlip() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor()); - rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - - assertFalse(rectangle.isFlipVertical()); - assertFalse(rectangle.isFlipHorizontal()); - - rectangle.setFlipVertical(true); - assertTrue(rectangle.isFlipVertical()); - rectangle.setFlipHorizontal(true); - assertTrue(rectangle.isFlipHorizontal()); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0); - - assertTrue(rectangle.isFlipHorizontal()); - rectangle.setFlipHorizontal(false); - assertFalse(rectangle.isFlipHorizontal()); - - assertTrue(rectangle.isFlipVertical()); - rectangle.setFlipVertical(false); - assertFalse(rectangle.isFlipVertical()); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sheet = wb3.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0); - - assertFalse(rectangle.isFlipVertical()); - assertFalse(rectangle.isFlipHorizontal()); - wb3.close(); - } - - @Test - void testRotation() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor(0,0,100,100, (short) 0,0,(short)5,5)); - rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - - assertEquals(rectangle.getRotationDegree(), 0); - rectangle.setRotationDegree((short) 45); - assertEquals(rectangle.getRotationDegree(), 45); - rectangle.setFlipHorizontal(true); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0); - assertEquals(rectangle.getRotationDegree(), 45); - rectangle.setRotationDegree((short) 30); - assertEquals(rectangle.getRotationDegree(), 30); - - patriarch.setCoordinates(0, 0, 10, 10); - rectangle.setString(new HSSFRichTextString("1234")); - wb2.close(); - } - - @SuppressWarnings("unused") - @Test - void testShapeContainerImplementsIterable() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - patriarch.createSimpleShape(new HSSFClientAnchor()); - patriarch.createSimpleShape(new HSSFClientAnchor()); - - int i=2; - - for (HSSFShape shape: patriarch){ - i--; - } - assertEquals(i, 0); - wb.close(); - } - - @Test - void testClearShapesForPatriarch() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - patriarch.createSimpleShape(new HSSFClientAnchor()); - patriarch.createSimpleShape(new HSSFClientAnchor()); - patriarch.createCellComment(new HSSFClientAnchor()); - - EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch); - - assertEquals(agg.getShapeToObjMapping().size(), 6); - assertEquals(agg.getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 3); - - patriarch.clear(); - - assertEquals(agg.getShapeToObjMapping().size(), 0); - assertEquals(agg.getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 0); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(agg.getShapeToObjMapping().size(), 0); - assertEquals(agg.getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 0); - wb2.close(); - } - - @Test - void testBug45312() throws Exception { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)1, 1, 0, 0, (short) 1, 1, 512, 100); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)1, 1, 512, 0, (short) 1, 1, 1024, 100); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setFlipVertical(true); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)2, 2, 0, 0, (short) 2, 2, 512, 100); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)2, 2, 0, 100, (short) 2, 2, 512, 200); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setFlipHorizontal(true); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - - checkWorkbookBack(wb); - } - } - - private void checkWorkbookBack(HSSFWorkbook wb) throws IOException { - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wbBack); - - HSSFSheet sheetBack = wbBack.getSheetAt(0); - assertNotNull(sheetBack); - - HSSFPatriarch patriarchBack = sheetBack.getDrawingPatriarch(); - assertNotNull(patriarchBack); - - List children = patriarchBack.getChildren(); - assertEquals(4, children.size()); - HSSFShape hssfShape = children.get(0); - assertTrue(hssfShape instanceof HSSFSimpleShape); - HSSFAnchor anchor = hssfShape.getAnchor(); - assertTrue(anchor instanceof HSSFClientAnchor); - assertEquals(0, anchor.getDx1()); - assertEquals(512, anchor.getDx2()); - assertEquals(0, anchor.getDy1()); - assertEquals(100, anchor.getDy2()); - HSSFClientAnchor cAnchor = (HSSFClientAnchor) anchor; - assertEquals(1, cAnchor.getCol1()); - assertEquals(1, cAnchor.getCol2()); - assertEquals(1, cAnchor.getRow1()); - assertEquals(1, cAnchor.getRow2()); - - hssfShape = children.get(1); - assertTrue(hssfShape instanceof HSSFSimpleShape); - anchor = hssfShape.getAnchor(); - assertTrue(anchor instanceof HSSFClientAnchor); - assertEquals(512, anchor.getDx1()); - assertEquals(1024, anchor.getDx2()); - assertEquals(0, anchor.getDy1()); - assertEquals(100, anchor.getDy2()); - cAnchor = (HSSFClientAnchor) anchor; - assertEquals(1, cAnchor.getCol1()); - assertEquals(1, cAnchor.getCol2()); - assertEquals(1, cAnchor.getRow1()); - assertEquals(1, cAnchor.getRow2()); - - hssfShape = children.get(2); - assertTrue(hssfShape instanceof HSSFSimpleShape); - anchor = hssfShape.getAnchor(); - assertTrue(anchor instanceof HSSFClientAnchor); - assertEquals(0, anchor.getDx1()); - assertEquals(512, anchor.getDx2()); - assertEquals(0, anchor.getDy1()); - assertEquals(100, anchor.getDy2()); - cAnchor = (HSSFClientAnchor) anchor; - assertEquals(2, cAnchor.getCol1()); - assertEquals(2, cAnchor.getCol2()); - assertEquals(2, cAnchor.getRow1()); - assertEquals(2, cAnchor.getRow2()); - - hssfShape = children.get(3); - assertTrue(hssfShape instanceof HSSFSimpleShape); - anchor = hssfShape.getAnchor(); - assertTrue(anchor instanceof HSSFClientAnchor); - assertEquals(0, anchor.getDx1()); - assertEquals(512, anchor.getDx2()); - assertEquals(100, anchor.getDy1()); - assertEquals(200, anchor.getDy2()); - cAnchor = (HSSFClientAnchor) anchor; - assertEquals(2, cAnchor.getCol1()); - assertEquals(2, cAnchor.getCol2()); - assertEquals(2, cAnchor.getRow1()); - assertEquals(2, cAnchor.getRow2()); - - wbBack.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.java b/src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.java deleted file mode 100644 index efd3f5feff..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.java +++ /dev/null @@ -1,104 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.apache.poi.ddf.DefaultEscherRecordFactory.isContainer; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.List; -import java.util.Random; - -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherTextboxRecord; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFTestHelper; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -class TestEscherRecordFactory { - - private static byte[] toByteArray(List records) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for (RecordBase rb : records) { - Record r = (org.apache.poi.hssf.record.Record) rb; - try { - out.write(r.serialize()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - return out.toByteArray(); - } - - @Test - void testDetectContainer() { - Random rnd = new Random(); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.DG_CONTAINER)); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.SOLVER_CONTAINER)); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.SP_CONTAINER)); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.DGG_CONTAINER)); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.BSTORE_CONTAINER)); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.SPGR_CONTAINER)); - - for (short i=EscherContainerRecord.DGG_CONTAINER; i<= EscherContainerRecord.SOLVER_CONTAINER; i++){ - assertTrue(isContainer(Integer.valueOf(rnd.nextInt(Short.MAX_VALUE)).shortValue(), i)); - } - - assertFalse(isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.SOLVER_CONTAINER + 1).shortValue())); - - assertTrue(isContainer((short) 0x000F, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertTrue(isContainer((short) 0xFFFF, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(isContainer((short) 0x000C, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(isContainer((short) 0xCCCC, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(isContainer((short) 0x000F, EscherTextboxRecord.RECORD_ID)); - assertFalse(isContainer((short) 0xCCCC, EscherTextboxRecord.RECORD_ID)); - } - - @Test - void testDgContainerMustBeRootOfHSSFSheetEscherRecords() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("47251.xls"); - HSSFSheet sh = wb.getSheetAt(0); - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - List records = ish.getRecords(); - // records to be aggregated - List dgRecords = records.subList(19, 23); - byte[] dgBytes = toByteArray(dgRecords); - sh.getDrawingPatriarch(); - EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - assertNotNull(agg); - assertTrue(agg.getEscherRecords().get(0) instanceof EscherContainerRecord); - assertEquals(EscherContainerRecord.DG_CONTAINER, agg.getEscherRecords().get(0).getRecordId()); - assertEquals((short) 0x0, agg.getEscherRecords().get(0).getOptions()); - agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - assertNotNull(agg); - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save"); - assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java deleted file mode 100644 index 0e8964daee..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java +++ /dev/null @@ -1,1581 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; -import java.util.Locale; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.common.UnicodeString; -import org.apache.poi.hssf.usermodel.FormulaExtractor; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.TestHSSFName; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.constant.ErrorConstant; -import org.apache.poi.ss.formula.ptg.*; -import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.junit.jupiter.api.Test; - -/** - * Test the low level formula parser functionality. High level tests are to - * be done via usermodel/HSSFCell.setFormulaValue(). - */ -final class TestFormulaParser { - - /** - * @return parsed token array already confirmed not null - */ - /* package */ static Ptg[] parseFormula(String formula) { - Ptg[] result = HSSFFormulaParser.parse(formula, null); - assertNotNull(result, "Ptg array should not be null"); - return result; - } - private static String toFormulaString(Ptg[] ptgs) { - return HSSFFormulaParser.toFormulaString(null, ptgs); - } - - @Test - void testSimpleFormula() { - confirmTokenClasses("2+2",IntPtg.class, IntPtg.class, AddPtg.class); - } - - @Test - void testFormulaWithSpace1() { - confirmTokenClasses(" 2 + 2 ",IntPtg.class, IntPtg.class, AddPtg.class); - } - - @Test - void testFormulaWithSpace2() { - Ptg[] ptgs = parseFormula("2+ sum( 3 , 4) "); - assertEquals(5, ptgs.length); - } - - @Test - void testFormulaWithSpaceNRef() { - Ptg[] ptgs = parseFormula("sum( A2:A3 )"); - assertEquals(2, ptgs.length); - } - - @Test - void testFormulaWithString() { - Ptg[] ptgs = parseFormula("\"hello\" & \"world\" "); - assertEquals(3, ptgs.length); - } - - @Test - void testTRUE() { - Ptg[] ptgs = parseFormula("TRUE"); - assertEquals(1, ptgs.length); - BoolPtg flag = (BoolPtg) ptgs[0]; - assertTrue(flag.getValue()); - } - - @Test - void testSumIf() { - Ptg[] ptgs = parseFormula("SUMIF(A1:A5,\">4000\",B1:B5)"); - assertEquals(4, ptgs.length); - } - - /** - * Bug Reported by xt-jens.riis@nokia.com (Jens Riis) - * Refers to Bug #17582 - * - */ - @Test - void testNonAlphaFormula() { - Ptg[] ptgs = parseFormula("\"TOTAL[\"&F3&\"]\""); - confirmTokenClasses(ptgs, StringPtg.class, RefPtg.class, ConcatPtg.class, StringPtg.class, ConcatPtg.class); - assertEquals("TOTAL[", ((StringPtg)ptgs[0]).getValue()); - } - - @Test - void testMacroFunction() throws IOException { - // testNames.xls contains a VB function called 'myFunc' - final String testFile = "testNames.xls"; - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(testFile)) { - HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(wb); - - //Expected ptg stack: [NamePtg(myFunc), StringPtg(arg), (additional operands go here...), FunctionPtg(myFunc)] - Ptg[] ptg = FormulaParser.parse("myFunc(\"arg\")", book, FormulaType.CELL, -1); - assertEquals(3, ptg.length); - - // the name gets encoded as the first operand on the stack - NamePtg tname = (NamePtg) ptg[0]; - assertEquals("myFunc", tname.toFormulaString(book)); - - // the function's arguments are pushed onto the stack from left-to-right as OperandPtgs - StringPtg arg = (StringPtg) ptg[1]; - assertEquals("arg", arg.getValue()); - - // The external FunctionPtg is the last Ptg added to the stack - // During formula evaluation, this Ptg pops off the the appropriate number of - // arguments (getNumberOfOperands()) and pushes the result on the stack - AbstractFunctionPtg tfunc = (AbstractFunctionPtg) ptg[2]; //FuncVarPtg - assertTrue(tfunc.isExternalFunction()); - - // confirm formula parsing is case-insensitive - FormulaParser.parse("mYfUnC(\"arg\")", book, FormulaType.CELL, -1); - - // confirm formula parsing doesn't care about argument count or type - // this should only throw an error when evaluating the formula. - FormulaParser.parse("myFunc()", book, FormulaType.CELL, -1); - FormulaParser.parse("myFunc(\"arg\", 0, TRUE)", book, FormulaType.CELL, -1); - - // A completely unknown formula name (not saved in workbook) should still be parseable and renderable - // but will throw an NotImplementedFunctionException or return a #NAME? error value if evaluated. - FormulaParser.parse("yourFunc(\"arg\")", book, FormulaType.CELL, -1); - - // Verify that myFunc and yourFunc were successfully added to Workbook names - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb)) { - // HSSFWorkbook/EXCEL97-specific side-effects user-defined function names must be added to Workbook's defined names in order to be saved. - HSSFName myFunc = wb2.getName("myFunc"); - assertNotNull(myFunc); - assertEqualsIgnoreCase("myFunc", myFunc.getNameName()); - HSSFName yourFunc = wb2.getName("yourFunc"); - assertNotNull(yourFunc); - assertEqualsIgnoreCase("yourFunc", yourFunc.getNameName()); - - // Manually check to make sure file isn't corrupted - // TODO: develop a process for occasionally manually reviewing workbooks - // to verify workbooks are not corrupted - /* - final File fileIn = HSSFTestDataSamples.getSampleFile(testFile); - final File reSavedFile = new File(fileIn.getParentFile(), fileIn.getName().replace(".xls", "-saved.xls")); - FileOutputStream fos = new FileOutputStream(reSavedFile); - wb2.write(fos); - fos.close(); - */ - } - } - } - - private static void assertEqualsIgnoreCase(String expected, String actual) { - assertEquals(expected.toLowerCase(Locale.ROOT), actual.toLowerCase(Locale.ROOT)); - } - - @Test - void testEmbeddedSlash() { - confirmTokenClasses("HYPERLINK(\"http://www.jakarta.org\",\"Jakarta\")", - StringPtg.class, StringPtg.class, FuncVarPtg.class); - } - - @Test - void testConcatenate() { - confirmTokenClasses("CONCATENATE(\"first\",\"second\")", - StringPtg.class, StringPtg.class, FuncVarPtg.class); - } - - @Test - void testWorksheetReferences() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - - HSSFSheet sheet1 = wb.createSheet("NoQuotesNeeded"); - sheet1.createRow(0).createCell(0).setCellValue("NoQuotesNeeded"); - HSSFSheet sheet2 = wb.createSheet("Quotes Needed Here &#$@"); - sheet2.createRow(0).createCell(0).setCellValue("Quotes Needed Here &#$@"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - HSSFCell cell; - String act; - - cell = row.createCell(0); - cell.setCellFormula("NoQuotesNeeded!A1"); - act = evaluator.evaluate(cell).getStringValue(); - assertEquals("NoQuotesNeeded", act); - - cell = row.createCell(1); - cell.setCellFormula("'Quotes Needed Here &#$@'!A1"); - act = evaluator.evaluate(cell).getStringValue(); - assertEquals("Quotes Needed Here &#$@", act); - } - } - - @Test - void testUnaryMinus() { - confirmTokenClasses("-A1", RefPtg.class, UnaryMinusPtg.class); - } - - @Test - void testUnaryPlus() { - confirmTokenClasses("+A1", RefPtg.class, UnaryPlusPtg.class); - } - - /** - * There may be multiple ways to encode an expression involving {@link UnaryPlusPtg} - * or {@link UnaryMinusPtg}. These may be perfectly equivalent from a formula - * evaluation perspective, or formula rendering. However, differences in the way - * POI encodes formulas may cause unnecessary confusion. These non-critical tests - * check that POI follows the same encoding rules as Excel. - */ - @Test - void testExactEncodingOfUnaryPlusAndMinus() { - // as tested in Excel: - confirmUnary("-3", -3, NumberPtg.class); - confirmUnary("--4", -4, NumberPtg.class, UnaryMinusPtg.class); - confirmUnary("+++5", 5, IntPtg.class, UnaryPlusPtg.class, UnaryPlusPtg.class); - confirmUnary("++-6", -6, NumberPtg.class, UnaryPlusPtg.class, UnaryPlusPtg.class); - - // Spaces muck things up a bit. It would be clearer why the following cases are - // reasonable if POI encoded tAttrSpace in the right places. - // Otherwise these differences look capricious. - confirmUnary("+ 12", 12, IntPtg.class, UnaryPlusPtg.class); - confirmUnary("- 13", 13, IntPtg.class, UnaryMinusPtg.class); - } - - private static void confirmUnary(String formulaText, double val, Class...expectedTokenTypes) { - Ptg[] ptgs = parseFormula(formulaText); - confirmTokenClasses(ptgs, expectedTokenTypes); - Ptg ptg0 = ptgs[0]; - if (ptg0 instanceof IntPtg) { - IntPtg intPtg = (IntPtg) ptg0; - assertEquals((int)val, intPtg.getValue()); - } else if (ptg0 instanceof NumberPtg) { - NumberPtg numberPtg = (NumberPtg) ptg0; - assertEquals(val, numberPtg.getValue(), 0.0); - } else { - fail("bad ptg0 " + ptg0); - } - } - - @Test - void testLeadingSpaceInString() { - String value = " hi "; - Ptg[] ptgs = parseFormula("\"" + value + "\""); - confirmTokenClasses(ptgs, StringPtg.class); - assertEquals(((StringPtg) ptgs[0]).getValue(), value, "ptg0 contains exact value"); - } - - @Test - void testLookupAndMatchFunctionArgs() { - Ptg[] ptgs = parseFormula("lookup(A1, A3:A52, B3:B52)"); - confirmTokenClasses(ptgs, RefPtg.class, AreaPtg.class, AreaPtg.class, FuncVarPtg.class); - assertEquals(ptgs[0].getPtgClass(), Ptg.CLASS_VALUE, "ptg0 has Value class"); - - ptgs = parseFormula("match(A1, A3:A52)"); - confirmTokenClasses(ptgs, RefPtg.class, AreaPtg.class, FuncVarPtg.class); - assertEquals(ptgs[0].getPtgClass(), Ptg.CLASS_VALUE, "ptg0 has Value class"); - } - - /** bug 33160*/ - @Test - void testLargeInt() { - confirmTokenClasses("40", IntPtg.class); - confirmTokenClasses("40000", IntPtg.class); - } - - /** bug 33160 */ - @Test - void testSimpleLongFormula() { - confirmTokenClasses("40000/2", IntPtg.class, IntPtg.class, DividePtg.class); - } - - /** bug 35027, underscore in sheet name */ - @Test - void testUnderscore() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet1 = wb.createSheet("Cash_Flow"); - sheet1.createRow(0).createCell(0).setCellValue("Cash_Flow"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell; - - cell = row.createCell(0); - cell.setCellFormula("Cash_Flow!A1"); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - String act = evaluator.evaluate(cell).getStringValue(); - assertEquals("Cash_Flow", act); - } - } - - /** bug 49725, defined names with underscore */ - @Test - void testNamesWithUnderscore() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); //or new XSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("NamesWithUnderscore"); - - HSSFName nm; - - nm = wb.createName(); - nm.setNameName("DA6_LEO_WBS_Number"); - nm.setRefersToFormula("33"); - - nm = wb.createName(); - nm.setNameName("DA6_LEO_WBS_Name"); - nm.setRefersToFormula("33"); - - nm = wb.createName(); - nm.setNameName("A1_"); - nm.setRefersToFormula("22"); - - nm = wb.createName(); - nm.setNameName("_A1"); - nm.setRefersToFormula("11"); - - nm = wb.createName(); - nm.setNameName("A_1"); - nm.setRefersToFormula("44"); - - nm = wb.createName(); - nm.setNameName("A_1_"); - nm.setRefersToFormula("44"); - - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - - cell.setCellFormula("DA6_LEO_WBS_Number*2"); - assertEquals("DA6_LEO_WBS_Number*2", cell.getCellFormula()); - - cell.setCellFormula("(A1_*_A1+A_1)/A_1_"); - assertEquals("(A1_*_A1+A_1)/A_1_", cell.getCellFormula()); - - cell.setCellFormula("INDEX(DA6_LEO_WBS_Name,MATCH($A3,DA6_LEO_WBS_Number,0))"); - assertEquals("INDEX(DA6_LEO_WBS_Name,MATCH($A3,DA6_LEO_WBS_Number,0))", cell.getCellFormula()); - - wb.close(); - } - - // bug 38396 : Formula with exponential numbers not parsed correctly. - @Test - void testExponentialParsing() { - confirmTokenClasses("1.3E21/2", NumberPtg.class, IntPtg.class, DividePtg.class); - confirmTokenClasses("1322E21/2", NumberPtg.class, IntPtg.class, DividePtg.class); - confirmTokenClasses("1.3E1/2", NumberPtg.class, IntPtg.class, DividePtg.class); - } - - @Test - void testExponentialInSheet() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - wb.createSheet("Cash_Flow"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - String formula; - - cell.setCellFormula("1.3E21/3"); - formula = cell.getCellFormula(); - assertEquals("1.3E+21/3", formula); - - cell.setCellFormula("-1.3E21/3"); - formula = cell.getCellFormula(); - assertEquals("-1.3E+21/3", formula); - - cell.setCellFormula("1322E21/3"); - formula = cell.getCellFormula(); - assertEquals("1.322E+24/3", formula); - - cell.setCellFormula("-1322E21/3"); - formula = cell.getCellFormula(); - assertEquals("-1.322E+24/3", formula); - - cell.setCellFormula("1.3E1/3"); - formula = cell.getCellFormula(); - assertEquals("13/3", formula); - - cell.setCellFormula("-1.3E1/3"); - formula = cell.getCellFormula(); - assertEquals("-13/3", formula); - - cell.setCellFormula("1.3E-4/3"); - formula = cell.getCellFormula(); - assertEquals("0.00013/3", formula); - - cell.setCellFormula("-1.3E-4/3"); - formula = cell.getCellFormula(); - assertEquals("-0.00013/3", formula); - - cell.setCellFormula("13E-15/3"); - formula = cell.getCellFormula(); - assertEquals("0.000000000000013/3", formula); - - cell.setCellFormula("-13E-15/3"); - formula = cell.getCellFormula(); - assertEquals("-0.000000000000013/3", formula); - - cell.setCellFormula("1.3E3/3"); - formula = cell.getCellFormula(); - assertEquals("1300/3", formula); - - cell.setCellFormula("-1.3E3/3"); - formula = cell.getCellFormula(); - assertEquals("-1300/3", formula); - - cell.setCellFormula("1300000000000000/3"); - formula = cell.getCellFormula(); - assertEquals("1300000000000000/3", formula); - - cell.setCellFormula("-1300000000000000/3"); - formula = cell.getCellFormula(); - assertEquals("-1300000000000000/3", formula); - - cell.setCellFormula("-10E-1/3.1E2*4E3/3E4"); - formula = cell.getCellFormula(); - assertEquals("-1/310*4000/30000", formula); - - wb.close(); - } - - @Test - void testNumbers() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - wb.createSheet("Cash_Flow"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - String formula; - - // starts from decimal point - - cell.setCellFormula(".1"); - formula = cell.getCellFormula(); - assertEquals("0.1", formula); - - cell.setCellFormula("+.1"); - formula = cell.getCellFormula(); - assertEquals("0.1", formula); - - cell.setCellFormula("-.1"); - formula = cell.getCellFormula(); - assertEquals("-0.1", formula); - - // has exponent - - cell.setCellFormula("10E1"); - formula = cell.getCellFormula(); - assertEquals("100", formula); - - cell.setCellFormula("10E+1"); - formula = cell.getCellFormula(); - assertEquals("100", formula); - - cell.setCellFormula("10E-1"); - formula = cell.getCellFormula(); - assertEquals("1", formula); - - wb.close(); - } - - @Test - void testRanges() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - wb.createSheet("Cash_Flow"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - String formula; - - cell.setCellFormula("A1.A2"); - formula = cell.getCellFormula(); - assertEquals("A1:A2", formula); - - cell.setCellFormula("A1..A2"); - formula = cell.getCellFormula(); - assertEquals("A1:A2", formula); - - cell.setCellFormula("A1...A2"); - formula = cell.getCellFormula(); - assertEquals("A1:A2", formula); - - wb.close(); - } - - @Test - void testMultiSheetReference() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - wb.createSheet("Cash_Flow"); - wb.createSheet("Test Sheet"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - String formula; - - - // References to a single cell: - - // One sheet - cell.setCellFormula("Cash_Flow!A1"); - formula = cell.getCellFormula(); - assertEquals("Cash_Flow!A1", formula); - - // Then the other - cell.setCellFormula("'Test Sheet'!A1"); - formula = cell.getCellFormula(); - assertEquals("'Test Sheet'!A1", formula); - - // Now both - cell.setCellFormula("Cash_Flow:'Test Sheet'!A1"); - formula = cell.getCellFormula(); - assertEquals("Cash_Flow:'Test Sheet'!A1", formula); - - - // References to a range (area) of cells: - - // One sheet - cell.setCellFormula("Cash_Flow!A1:B2"); - formula = cell.getCellFormula(); - assertEquals("Cash_Flow!A1:B2", formula); - - // Then the other - cell.setCellFormula("'Test Sheet'!A1:B2"); - formula = cell.getCellFormula(); - assertEquals("'Test Sheet'!A1:B2", formula); - - // Now both - cell.setCellFormula("Cash_Flow:'Test Sheet'!A1:B2"); - formula = cell.getCellFormula(); - assertEquals("Cash_Flow:'Test Sheet'!A1:B2", formula); - - wb.close(); - } - - /** - * Test for bug observable at svn revision 618865 (5-Feb-2008)
- * a formula consisting of a single no-arg function got rendered without the function braces - */ - @Test - void testToFormulaStringZeroArgFunction() throws IOException { - HSSFWorkbook book = new HSSFWorkbook(); - - Ptg[] ptgs = { - FuncPtg.create(10), - }; - assertEquals("NA()", HSSFFormulaParser.toFormulaString(book, ptgs)); - - book.close(); - } - - @Test - void testPercent() { - - confirmTokenClasses("5%", IntPtg.class, PercentPtg.class); - // spaces OK - confirmTokenClasses(" 250 % ", IntPtg.class, PercentPtg.class); - // double percent OK - confirmTokenClasses("12345.678%%", NumberPtg.class, PercentPtg.class, PercentPtg.class); - - // percent of a bracketed expression - confirmTokenClasses("(A1+35)%*B1%", RefPtg.class, IntPtg.class, AddPtg.class, ParenthesisPtg.class, - PercentPtg.class, RefPtg.class, PercentPtg.class, MultiplyPtg.class); - - // percent of a text quantity - confirmTokenClasses("\"8.75\"%", StringPtg.class, PercentPtg.class); - - // percent to the power of - confirmTokenClasses("50%^3", IntPtg.class, PercentPtg.class, IntPtg.class, PowerPtg.class); - - // things that parse OK but would *evaluate* to an error - confirmTokenClasses("\"abc\"%", StringPtg.class, PercentPtg.class); - confirmTokenClasses("#N/A%", ErrPtg.class, PercentPtg.class); - } - - /** - * Tests combinations of various operators in the absence of brackets - */ - @Test - void testPrecedenceAndAssociativity() { - - // TRUE=TRUE=2=2 evaluates to FALSE - confirmTokenClasses("TRUE=TRUE=2=2", BoolPtg.class, BoolPtg.class, EqualPtg.class, - IntPtg.class, EqualPtg.class, IntPtg.class, EqualPtg.class); - - // 2^3^2 evaluates to 64 not 512 - confirmTokenClasses("2^3^2", IntPtg.class, IntPtg.class, PowerPtg.class, - IntPtg.class, PowerPtg.class); - - // "abc" & 2 + 3 & "def" evaluates to "abc5def" - confirmTokenClasses("\"abc\"&2+3&\"def\"", StringPtg.class, IntPtg.class, IntPtg.class, - AddPtg.class, ConcatPtg.class, StringPtg.class, ConcatPtg.class); - - // (1 / 2) - (3 * 4) - confirmTokenClasses("1/2-3*4", IntPtg.class, IntPtg.class, DividePtg.class, - IntPtg.class, IntPtg.class, MultiplyPtg.class, SubtractPtg.class); - - // 2 * (2^2) - // NOT: (2 *2) ^ 2 -> int int multiply int power - confirmTokenClasses("2*2^2", IntPtg.class, IntPtg.class, IntPtg.class, PowerPtg.class, MultiplyPtg.class); - - // 2^200% -> 2 not 1.6E58 - confirmTokenClasses("2^200%", IntPtg.class, IntPtg.class, PercentPtg.class, PowerPtg.class); - } - - /* package */ static Ptg[] confirmTokenClasses(String formula, Class...expectedClasses) { - Ptg[] ptgs = parseFormula(formula); - confirmTokenClasses(ptgs, expectedClasses); - return ptgs; - } - - private static void confirmTokenClasses(Ptg[] ptgs, Class...expectedClasses) { - assertEquals(expectedClasses.length, ptgs.length); - for (int i = 0; i < expectedClasses.length; i++) { - assertEquals(expectedClasses[i], ptgs[i].getClass(), - "difference at token[" + i + "]: expected (" - + expectedClasses[i].getName() + ") but got (" - + ptgs[i].getClass().getName() + ")"); - } - } - - @Test - void testPower() { - confirmTokenClasses("2^5", IntPtg.class, IntPtg.class, PowerPtg.class); - } - - private static Ptg parseSingleToken(String formula, Class ptgClass) { - Ptg[] ptgs = parseFormula(formula); - assertEquals(1, ptgs.length); - Ptg result = ptgs[0]; - assertEquals(ptgClass, result.getClass()); - return result; - } - - @Test - void testParseNumber() { - IntPtg ip; - - // bug 33160 - ip = (IntPtg) parseSingleToken("40", IntPtg.class); - assertEquals(40, ip.getValue()); - ip = (IntPtg) parseSingleToken("40000", IntPtg.class); - assertEquals(40000, ip.getValue()); - - // check the upper edge of the IntPtg range: - ip = (IntPtg) parseSingleToken("65535", IntPtg.class); - assertEquals(65535, ip.getValue()); - NumberPtg np = (NumberPtg) parseSingleToken("65536", NumberPtg.class); - assertEquals(65536, np.getValue(), 0); - - np = (NumberPtg) parseSingleToken("65534.6", NumberPtg.class); - assertEquals(65534.6, np.getValue(), 0); - } - - @Test - void testMissingArgs() { - confirmTokenClasses("if(A1, ,C1)", - RefPtg.class, - AttrPtg.class, // tAttrIf - MissingArgPtg.class, - AttrPtg.class, // tAttrSkip - RefPtg.class, - AttrPtg.class, // tAttrSkip - FuncVarPtg.class - ); - - confirmTokenClasses("counta( , A1:B2, )", MissingArgPtg.class, AreaPtg.class, MissingArgPtg.class, - FuncVarPtg.class); - } - - @Test - void testParseErrorLiterals() { - - confirmParseErrorLiteral(ErrPtg.NULL_INTERSECTION, "#NULL!"); - confirmParseErrorLiteral(ErrPtg.DIV_ZERO, "#DIV/0!"); - confirmParseErrorLiteral(ErrPtg.VALUE_INVALID, "#VALUE!"); - confirmParseErrorLiteral(ErrPtg.REF_INVALID, "#REF!"); - confirmParseErrorLiteral(ErrPtg.NAME_INVALID, "#NAME?"); - confirmParseErrorLiteral(ErrPtg.NUM_ERROR, "#NUM!"); - confirmParseErrorLiteral(ErrPtg.N_A, "#N/A"); - parseFormula("HLOOKUP(F7,#REF!,G7,#REF!)"); - } - - private static void confirmParseErrorLiteral(ErrPtg expectedToken, String formula) { - assertEquals(expectedToken, parseSingleToken(formula, ErrPtg.class)); - } - - /** - * To aid readability the parameters have been encoded with single quotes instead of double - * quotes. This method converts single quotes to double quotes before performing the parse - * and result check. - */ - private static void confirmStringParse(String singleQuotedValue) { - // formula: internal quotes become double double, surround with double quotes - String formula = '"' + singleQuotedValue.replaceAll("'", "\"\"") + '"'; - String expectedValue = singleQuotedValue.replace('\'', '"'); - - StringPtg sp = (StringPtg) parseSingleToken(formula, StringPtg.class); - assertEquals(expectedValue, sp.getValue()); - } - - @Test - void testParseStringLiterals_bug28754() throws IOException { - - StringPtg sp; - try { - sp = (StringPtg) parseSingleToken("\"test\"\"ing\"", StringPtg.class); - } catch (RuntimeException e) { - if(e.getMessage().startsWith("Cannot Parse")) { - fail("Identified bug 28754a"); - } - throw e; - } - assertEquals("test\"ing", sp.getValue()); - - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - wb.setSheetName(0, "Sheet1"); - - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("right(\"test\"\"ing\", 3)"); - String actualCellFormula = cell.getCellFormula(); - assertNotEquals("RIGHT(\"test\"ing\",3)", actualCellFormula, "Identified bug 28754b"); - assertEquals("RIGHT(\"test\"\"ing\",3)", actualCellFormula); - } - } - - @Test - void testParseStringLiterals() { - confirmStringParse("goto considered harmful"); - - confirmStringParse("goto 'considered' harmful"); - - confirmStringParse(""); - confirmStringParse("'"); - confirmStringParse("''"); - confirmStringParse("' '"); - confirmStringParse(" ' "); - } - - @Test - void testParseSumIfSum() { - String formulaString; - Ptg[] ptgs; - ptgs = parseFormula("sum(5, 2, if(3>2, sum(A1:A2), 6))"); - formulaString = toFormulaString(ptgs); - assertEquals("SUM(5,2,IF(3>2,SUM(A1:A2),6))", formulaString); - - ptgs = parseFormula("if(1<2,sum(5, 2, if(3>2, sum(A1:A2), 6)),4)"); - formulaString = toFormulaString(ptgs); - assertEquals("IF(1<2,SUM(5,2,IF(3>2,SUM(A1:A2),6)),4)", formulaString); - } - - @Test - void testParserErrors() { - parseExpectedException(" 12 . 345 "); - parseExpectedException("1 .23 "); - - parseExpectedException("sum(#NAME)"); - parseExpectedException("1 + #N / A * 2"); - parseExpectedException("#value?"); - parseExpectedException("#DIV/ 0+2"); - - - parseExpectedException("IF(TRUE)"); - parseExpectedException("countif(A1:B5, C1, D1)"); - - parseExpectedException("("); - parseExpectedException(")"); - parseExpectedException("+"); - parseExpectedException("42+"); - - parseExpectedException("IF("); - } - - private static void parseExpectedException(String formula) { - FormulaParseException e = assertThrows(FormulaParseException.class, () -> parseFormula(formula)); - assertNotNull(e.getMessage()); - } - - @Test - void testSetFormulaWithRowBeyond32768_Bug44539() throws IOException { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - wb.setSheetName(0, "Sheet1"); - - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("SUM(A32769:A32770)"); - assertNotEquals("SUM(A-32767:A-32766)", cell.getCellFormula(), "Identified bug 44539"); - assertEquals("SUM(A32769:A32770)", cell.getCellFormula()); - - wb.close(); - } - - @Test - void testSpaceAtStartOfFormula() { - // Simulating cell formula of "= 4" (note space) - // The same Ptg array can be observed if an excel file is saved with that exact formula - - AttrPtg spacePtg = AttrPtg.createSpace(AttrPtg.SpaceType.SPACE_BEFORE, 1); - Ptg[] ptgs = { spacePtg, new IntPtg(4), }; - String formulaString; - try { - formulaString = toFormulaString(ptgs); - } catch (IllegalStateException e) { - if(e.getMessage().equalsIgnoreCase("too much stuff left on the stack")) { - fail("Identified bug 44609"); - } - // else some unexpected error - throw e; - } - // FormulaParser strips spaces anyway - assertEquals("4", formulaString); - - ptgs = new Ptg[] { new IntPtg(3), spacePtg, new IntPtg(4), spacePtg, AddPtg.instance, }; - formulaString = toFormulaString(ptgs); - assertEquals("3+4", formulaString); - } - - /** - * Checks some internal error detecting logic ('stack underflow error' in toFormulaString) - */ - @Test - void testTooFewOperandArgs() { - // Simulating badly encoded cell formula of "=/1" - // Not sure if Excel could ever produce this - Ptg[] ptgs = { - // Excel would probably have put tMissArg here - new IntPtg(1), - DividePtg.instance, - }; - IllegalStateException e = assertThrows(IllegalStateException.class, () -> toFormulaString(ptgs)); - assertTrue(e.getMessage().startsWith("Too few arguments supplied to operation")); - } - - /** - * Make sure that POI uses the right Func Ptg when encoding formulas. Functions with variable - * number of args should get FuncVarPtg, functions with fixed args should get FuncPtg.

- * - * Prior to the fix for bug 44675 POI would encode FuncVarPtg for all functions. In many cases - * Excel tolerates the wrong Ptg and evaluates the formula OK (e.g. SIN), but in some cases - * (e.g. COUNTIF) Excel fails to evaluate the formula, giving '#VALUE!' instead. - */ - @Test - void testFuncPtgSelection() { - - Ptg[] ptgs = parseFormula("countif(A1:A2, 1)"); - assertEquals(3, ptgs.length); - assertFalse(ptgs[2] instanceof FuncVarPtg, "Identified bug 44675"); - confirmTokenClasses(ptgs, AreaPtg.class, IntPtg.class, FuncPtg.class); - - confirmTokenClasses("sin(1)", IntPtg.class, FuncPtg.class); - } - - @Test - void testWrongNumberOfFunctionArgs() throws IOException { - confirmArgCountMsg("sin()", "Too few arguments to function 'SIN'. Expected 1 but got 0."); - confirmArgCountMsg("countif(1, 2, 3, 4)", "Too many arguments to function 'COUNTIF'. Expected 2 but got 4."); - confirmArgCountMsg("index(1, 2, 3, 4, 5, 6)", "Too many arguments to function 'INDEX'. At most 4 were expected but got 6."); - confirmArgCountMsg("vlookup(1, 2)", "Too few arguments to function 'VLOOKUP'. At least 3 were expected but got 2."); - } - - private static void confirmArgCountMsg(String formula, String expectedMessage) throws IOException { - try (HSSFWorkbook book = new HSSFWorkbook()) { - FormulaParseException e = assertThrows(FormulaParseException.class, () -> HSSFFormulaParser.parse(formula, book)); - confirmParseException(e, expectedMessage); - } - } - - @Test - void testParseErrorExpectedMsg() { - FormulaParseException e; - e = assertThrows(FormulaParseException.class, () -> parseFormula("round(3.14;2)")); - confirmParseException(e, "Parse error near char 10 ';' in specified formula 'round(3.14;2)'. Expected ',' or ')'"); - - e = assertThrows(FormulaParseException.class, () -> parseFormula(" =2+2")); - confirmParseException(e, "The specified formula ' =2+2' starts with an equals sign which is not allowed."); - } - - /** - * this function name has a dot in it. - */ - @Test - void testParseErrorTypeFunction() { - - Ptg[] ptgs; - try { - ptgs = parseFormula("error.type(A1)"); - } catch (IllegalArgumentException e) { - if (e.getMessage().equals("Invalid Formula cell reference: 'error'")) { - fail("Identified bug 45334"); - } - throw e; - } - confirmTokenClasses(ptgs, RefPtg.class, FuncPtg.class); - assertEquals("ERROR.TYPE", ((FuncPtg) ptgs[1]).getName()); - } - - @Test - void testNamedRangeThatLooksLikeCell() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFName name = wb.createName(); - name.setRefersToFormula("Sheet1!B1"); - name.setNameName("pfy1"); - - Ptg[] ptgs; - try { - ptgs = HSSFFormulaParser.parse("count(pfy1)", wb); - } catch (IllegalArgumentException e) { - if (e.getMessage().equals("Specified colIx (1012) is out of range")) { - fail("Identified bug 45354"); - } - throw e; - } - confirmTokenClasses(ptgs, NamePtg.class, FuncVarPtg.class); - - HSSFCell cell = sheet.createRow(0).createCell(0); - cell.setCellFormula("count(pfy1)"); - assertEquals("COUNT(pfy1)", cell.getCellFormula()); - FormulaParseException e = assertThrows(FormulaParseException.class, () -> cell.setCellFormula("count(pf1)")); - confirmParseException(e, "Specified named range 'pf1' does not exist in the current workbook."); - cell.setCellFormula("count(fp1)"); // plain cell ref, col is in range - } - } - - @Test - void testParseAreaRefHighRow_bug45358() throws IOException { - Ptg[] ptgs; - AreaI aptg; - - HSSFWorkbook book = new HSSFWorkbook(); - book.createSheet("Sheet1"); - - ptgs = HSSFFormulaParser.parse("Sheet1!A10:A40000", book); - aptg = (AreaI) ptgs[0]; - assertNotEquals(-25537, aptg.getLastRow(), "Identified bug 45358"); - assertEquals(39999, aptg.getLastRow()); - - ptgs = HSSFFormulaParser.parse("Sheet1!A10:A65536", book); - aptg = (AreaI) ptgs[0]; - assertEquals(65535, aptg.getLastRow()); - - // plain area refs should be ok too - ptgs = parseFormula("A10:A65536"); - aptg = (AreaI) ptgs[0]; - assertEquals(65535, aptg.getLastRow()); - - book.close(); - } - - @Test - void testParseArray() { - Ptg[] ptgs; - ptgs = parseFormula("mode({1,2,2,#REF!;FALSE,3,3,2})"); - confirmTokenClasses(ptgs, ArrayPtg.class, FuncVarPtg.class); - assertEquals("{1,2,2,#REF!;FALSE,3,3,2}", ptgs[0].toFormulaString()); - - ArrayPtg aptg = (ArrayPtg) ptgs[0]; - Object[][] values = aptg.getTokenArrayValues(); - assertEquals(ErrorConstant.valueOf(FormulaError.REF.getCode()), values[0][3]); - assertEquals(Boolean.FALSE, values[1][0]); - } - - @Test - void testParseStringElementInArray() { - Ptg[] ptgs; - ptgs = parseFormula("MAX({\"5\"},3)"); - confirmTokenClasses(ptgs, ArrayPtg.class, IntPtg.class, FuncVarPtg.class); - Object element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0]; - // this would cause ClassCastException below - assertFalse(element instanceof UnicodeString, "Wrong encoding of array element value"); - assertEquals(String.class, element.getClass()); - - // make sure the formula encodes OK - int encSize = Ptg.getEncodedSize(ptgs); - byte[] data = new byte[encSize]; - Ptg.serializePtgs(ptgs, data, 0); - byte[] expData = HexRead.readFromString( - "20 00 00 00 00 00 00 00 " // tArray - + "1E 03 00 " // tInt(3) - + "42 02 07 00 " // tFuncVar(MAX) 2-arg - + "00 00 00 " // Array data: 1 col, 1 row - + "02 01 00 00 35" // elem (type=string, len=1, "5") - ); - assertArrayEquals(expData, data); - int initSize = Ptg.getEncodedSizeWithoutArrayData(ptgs); - Ptg[] ptgs2 = Ptg.readTokens(initSize, new LittleEndianByteArrayInputStream(data)); - confirmTokenClasses(ptgs2, ArrayPtg.class, IntPtg.class, FuncVarPtg.class); - } - - @Test - void testParseArrayNegativeElement() { - Ptg[] ptgs; - try { - ptgs = parseFormula("{-42}"); - } catch (FormulaParseException e) { - if (e.getMessage().equals("Parse error near char 1 '-' in specified formula '{-42}'. Expected Integer")) { - fail("Identified bug - failed to parse negative array element."); - } - throw e; - } - confirmTokenClasses(ptgs, ArrayPtg.class); - Object element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0]; - - assertEquals(-42.0, (Double) element, 0.0); - - // Should be able to handle whitespace between unary minus and digits (Excel - // accepts this formula after presenting the user with a confirmation dialog). - ptgs = parseFormula("{- 5}"); - element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0]; - assertEquals(-5.0, (Double) element, 0.0); - } - - @Test - void testRangeOperator() throws IOException { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - HSSFCell cell = sheet.createRow(0).createCell(0); - - wb.setSheetName(0, "Sheet1"); - cell.setCellFormula("Sheet1!B$4:Sheet1!$C1"); // explicit range ':' operator - assertEquals("Sheet1!B$4:Sheet1!$C1", cell.getCellFormula()); - - cell.setCellFormula("Sheet1!B$4:$C1"); // plain area ref - assertEquals("Sheet1!B1:$C$4", cell.getCellFormula()); // note - area ref is normalised - - cell.setCellFormula("Sheet1!$C1...B$4"); // different syntax for plain area ref - assertEquals("Sheet1!B1:$C$4", cell.getCellFormula()); - - // with funny sheet name - wb.setSheetName(0, "A1...A2"); - cell.setCellFormula("A1...A2!B1"); - assertEquals("A1...A2!B1", cell.getCellFormula()); - - wb.close(); - } - - @Test - void testBooleanNamedSheet() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("true"); - HSSFCell cell = sheet.createRow(0).createCell(0); - cell.setCellFormula("'true'!B2"); - - assertEquals("'true'!B2", cell.getCellFormula()); - - wb.close(); - } - - @Test - void testParseExternalWorkbookReference() throws IOException { - HSSFWorkbook wbA = HSSFTestDataSamples.openSampleWorkbook("multibookFormulaA.xls"); - HSSFCell cell = wbA.getSheetAt(0).getRow(0).getCell(0); - - // make sure formula in sample is as expected - assertEquals("[multibookFormulaB.xls]BSheet1!B1", cell.getCellFormula()); - Ptg[] expectedPtgs = FormulaExtractor.getPtgs(cell); - confirmSingle3DRef(expectedPtgs, 1); - - // now try (re-)parsing the formula - Ptg[] actualPtgs = HSSFFormulaParser.parse("[multibookFormulaB.xls]BSheet1!B1", wbA); - confirmSingle3DRef(actualPtgs, 1); // externalSheetIndex 1 -> BSheet1 - - // try parsing a formula pointing to a different external sheet - Ptg[] otherPtgs = HSSFFormulaParser.parse("[multibookFormulaB.xls]AnotherSheet!B1", wbA); - confirmSingle3DRef(otherPtgs, 0); // externalSheetIndex 0 -> AnotherSheet - - // try setting the same formula in a cell - cell.setCellFormula("[multibookFormulaB.xls]AnotherSheet!B1"); - assertEquals("[multibookFormulaB.xls]AnotherSheet!B1", cell.getCellFormula()); - - wbA.close(); - } - - private static void confirmSingle3DRef(Ptg[] ptgs, int expectedExternSheetIndex) { - assertEquals(1, ptgs.length); - Ptg ptg0 = ptgs[0]; - assertTrue(ptg0 instanceof Ref3DPtg); - assertEquals(expectedExternSheetIndex, ((Ref3DPtg)ptg0).getExternSheetIndex()); - } - - @Test - void testUnion() throws IOException { - String formula = "Sheet1!$B$2:$C$3,OFFSET(Sheet1!$E$2:$E$4,1,Sheet1!$A$1),Sheet1!$D$6"; - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1); - - confirmTokenClasses(ptgs, - // TODO - AttrPtg.class, // Excel prepends this - MemFuncPtg.class, - Area3DPtg.class, - Area3DPtg.class, - IntPtg.class, - Ref3DPtg.class, - FuncVarPtg.class, - UnionPtg.class, - Ref3DPtg.class, - UnionPtg.class - ); - MemFuncPtg mf = (MemFuncPtg)ptgs[0]; - assertEquals(45, mf.getLenRefSubexpression()); - - // We don't check the type of the operands. - confirmTokenClasses("1,2", MemAreaPtg.class, IntPtg.class, IntPtg.class, UnionPtg.class); - - wb.close(); - } - - @Test - void testIntersection() throws IOException { - String formula = "Sheet1!$B$2:$C$3 OFFSET(Sheet1!$E$2:$E$4, 1,Sheet1!$A$1) Sheet1!$D$6"; - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1); - - confirmTokenClasses(ptgs, - // TODO - AttrPtg.class, // Excel prepends this - MemFuncPtg.class, - Area3DPtg.class, - Area3DPtg.class, - IntPtg.class, - Ref3DPtg.class, - FuncVarPtg.class, - IntersectionPtg.class, - Ref3DPtg.class, - IntersectionPtg.class - ); - MemFuncPtg mf = (MemFuncPtg)ptgs[0]; - assertEquals(45, mf.getLenRefSubexpression()); - - // This used to be an error but now parses. Union has the same behaviour. - confirmTokenClasses("1 2", MemAreaPtg.class, IntPtg.class, IntPtg.class, IntersectionPtg.class); - - wb.close(); - } - - @Test - void testComparisonInParen() { - confirmTokenClasses("(A1 > B2)", - RefPtg.class, - RefPtg.class, - GreaterThanPtg.class, - ParenthesisPtg.class - ); - } - - @Test - void testUnionInParen() { - confirmTokenClasses("(A1:B2,B2:C3)", - MemAreaPtg.class, - AreaPtg.class, - AreaPtg.class, - UnionPtg.class, - ParenthesisPtg.class - ); - } - - @Test - void testIntersectionInParen() { - confirmTokenClasses("(A1:B2 B2:C3)", - MemAreaPtg.class, - AreaPtg.class, - AreaPtg.class, - IntersectionPtg.class, - ParenthesisPtg.class - ); - } - - // https://bz.apache.org/bugzilla/show_bug.cgi?id=60980 - @Test - void testIntersectionInFunctionArgs() { - confirmTokenClasses("SUM(A1:B2 B2:C3)", - MemAreaPtg.class, - AreaPtg.class, - AreaPtg.class, - IntersectionPtg.class, - AttrPtg.class - ); - } - - @Test - void testIntersectionNamesInFunctionArgs() { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFName name1 = wb.createName(); - name1.setNameName("foo1"); - name1.setRefersToFormula("A1:A3"); - - HSSFName name2 = wb.createName(); - name2.setNameName("foo2"); - name2.setRefersToFormula("A1:B3"); - - Ptg[] ptgs = FormulaParser.parse("SUM(foo1 foo2)", HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1); - - confirmTokenClasses(ptgs, - MemFuncPtg.class, - NamePtg.class, - NamePtg.class, - IntersectionPtg.class, - AttrPtg.class - ); - } - - @Test - void testRange_bug46643() throws IOException { - String formula = "Sheet1!A1:Sheet1!B3"; - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1, -1); - - if (ptgs.length == 3) { - confirmTokenClasses(ptgs, Ref3DPtg.class, Ref3DPtg.class, RangePtg.class); - fail("Identified bug 46643"); - } - - confirmTokenClasses(ptgs, - MemFuncPtg.class, - Ref3DPtg.class, - Ref3DPtg.class, - RangePtg.class - ); - MemFuncPtg mf = (MemFuncPtg)ptgs[0]; - assertEquals(15, mf.getLenRefSubexpression()); - wb.close(); - } - - /** Named ranges with backslashes, e.g. 'POI\\2009' */ - @Test - void testBackSlashInNames() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFName name = wb.createName(); - name.setNameName("POI\\2009"); - name.setRefersToFormula("Sheet1!$A$1"); - - HSSFSheet sheet = wb.createSheet(); - HSSFRow row = sheet.createRow(0); - - HSSFCell cell_C1 = row.createCell(2); - cell_C1.setCellFormula("POI\\2009"); - assertEquals("POI\\2009", cell_C1.getCellFormula()); - - HSSFCell cell_D1 = row.createCell(2); - cell_D1.setCellFormula("NOT(POI\\2009=\"3.5-final\")"); - assertEquals("NOT(POI\\2009=\"3.5-final\")", cell_D1.getCellFormula()); - - wb.close(); - } - - /** - * See the related/similar test: {@link BaseTestBugzillaIssues#bug42448()} - */ - @Test - void testParseAbnormalSheetNamesAndRanges_bug42448() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("A"); - try { - HSSFFormulaParser.parse("SUM(A!C7:A!C67)", wb); - } catch (StringIndexOutOfBoundsException e) { - fail("Identified bug 42448"); - } - // the exact example from the bugzilla description: - HSSFFormulaParser.parse("SUMPRODUCT(A!C7:A!C67, B8:B68) / B69", wb); - - wb.close(); - } - - @Test - void testRangeFuncOperand_bug46951() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - Ptg[] ptgs; - try { - ptgs = HSSFFormulaParser.parse("SUM(C1:OFFSET(C1,0,B1))", wb); - } catch (RuntimeException e) { - if (e.getMessage().equals("Specified named range 'OFFSET' does not exist in the current workbook.")) { - fail("Identified bug 46951"); - } - throw e; - } - confirmTokenClasses(ptgs, - MemFuncPtg.class, // [len=23] - RefPtg.class, // [C1] - RefPtg.class, // [C1] - IntPtg.class, // [0] - RefPtg.class, // [B1] - FuncVarPtg.class, // [OFFSET nArgs=3] - RangePtg.class, // - AttrPtg.class // [sum ] - ); - } - } - - @Test - void testUnionOfFullCollFullRowRef() throws IOException { - parseFormula("3:4"); - Ptg[] ptgs = parseFormula("$Z:$AC"); - confirmTokenClasses(ptgs, AreaPtg.class); - parseFormula("B:B"); - - ptgs = parseFormula("$11:$13"); - confirmTokenClasses(ptgs, AreaPtg.class); - - ptgs = parseFormula("$A:$A,$1:$4"); - confirmTokenClasses(ptgs, MemAreaPtg.class, - AreaPtg.class, - AreaPtg.class, - UnionPtg.class - ); - - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - ptgs = HSSFFormulaParser.parse("Sheet1!$A:$A,Sheet1!$1:$4", wb); - confirmTokenClasses(ptgs, MemFuncPtg.class, - Area3DPtg.class, - Area3DPtg.class, - UnionPtg.class - ); - - ptgs = HSSFFormulaParser.parse("'Sheet1'!$A:$A,'Sheet1'!$1:$4", wb); - confirmTokenClasses(ptgs, - MemFuncPtg.class, - Area3DPtg.class, - Area3DPtg.class, - UnionPtg.class - ); - - wb.close(); - } - - @Test - void testExplicitRangeWithTwoSheetNames() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - Ptg[] ptgs = HSSFFormulaParser.parse("Sheet1!F1:Sheet1!G2", wb); - confirmTokenClasses(ptgs, - MemFuncPtg.class, - Ref3DPtg.class, - Ref3DPtg.class, - RangePtg.class - ); - MemFuncPtg mf; - mf = (MemFuncPtg)ptgs[0]; - assertEquals(15, mf.getLenRefSubexpression()); - wb.close(); - } - - /** - * Checks that the area-ref and explicit range operators get the right associativity - * and that the {@link MemFuncPtg} / {@link MemAreaPtg} is added correctly - */ - @Test - void testComplexExplicitRangeEncodings() { - - Ptg[] ptgs; - ptgs = parseFormula("SUM(OFFSET(A1,0,0):B2:C3:D4:E5:OFFSET(F6,1,1):G7)"); - confirmTokenClasses(ptgs, - // AttrPtg.class, // [volatile ] // POI doesn't do this yet (Apr 2009) - MemFuncPtg.class, // len 57 - RefPtg.class, // [A1] - IntPtg.class, // [0] - IntPtg.class, // [0] - FuncVarPtg.class, // [OFFSET nArgs=3] - AreaPtg.class, // [B2:C3] - RangePtg.class, - AreaPtg.class, // [D4:E5] - RangePtg.class, - RefPtg.class, // [F6] - IntPtg.class, // [1] - IntPtg.class, // [1] - FuncVarPtg.class, // [OFFSET nArgs=3] - RangePtg.class, - RefPtg.class, // [G7] - RangePtg.class, - AttrPtg.class // [sum ] - ); - - MemFuncPtg mf = (MemFuncPtg)ptgs[0]; - assertEquals(57, mf.getLenRefSubexpression()); - assertEquals("D4:E5", ptgs[7].toFormulaString()); - assertTrue(((AttrPtg)ptgs[16]).isSum()); - - ptgs = parseFormula("SUM(A1:B2:C3:D4)"); - confirmTokenClasses(ptgs, - // AttrPtg.class, // [volatile ] // POI doesn't do this yet (Apr 2009) - MemAreaPtg.class, // len 19 - AreaPtg.class, // [A1:B2] - AreaPtg.class, // [C3:D4] - RangePtg.class, - AttrPtg.class // [sum ] - ); - MemAreaPtg ma = (MemAreaPtg)ptgs[0]; - assertEquals(19, ma.getLenRefSubexpression()); - } - - - /** - * Mostly confirming that erroneous conditions are detected. Actual error message wording is not critical. - * - */ - @Test - void testEdgeCaseParserErrors() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - - confirmParseError(wb, "A1:ROUND(B1,1)", "The RHS of the range operator ':' at position 3 is not a proper reference."); - - confirmParseError(wb, "Sheet1!!!", "Parse error near char 7 '!' in specified formula 'Sheet1!!!'. Expected number, string, defined name, or data table"); - confirmParseError(wb, "Sheet1!.Name", "Parse error near char 7 '.' in specified formula 'Sheet1!.Name'. Expected number, string, defined name, or data table"); - confirmParseError(wb, "Sheet1!Sheet1", "Specified name 'Sheet1' for sheet Sheet1 not found"); - confirmParseError(wb, "Sheet1!F:Sheet1!G", "'Sheet1!F' is not a proper reference."); - confirmParseError(wb, "Sheet1!F..foobar", "Complete area reference expected after sheet name at index 11."); - confirmParseError(wb, "Sheet1!A .. B", "Dotted range (full row or column) expression 'A .. B' must not contain whitespace."); - confirmParseError(wb, "Sheet1!A...B", "Dotted range (full row or column) expression 'A...B' must have exactly 2 dots."); - confirmParseError(wb, "Sheet1!A foobar", "Second part of cell reference expected after sheet name at index 10."); - - confirmParseError(wb, "foobar", "Specified named range 'foobar' does not exist in the current workbook."); - confirmParseError(wb, "A1:1", "The RHS of the range operator ':' at position 3 is not a proper reference."); - wb.close(); - } - - private static void confirmParseError(HSSFWorkbook wb, String formula, String expectedMessage) { - FormulaParseException e = assertThrows(FormulaParseException.class, () -> HSSFFormulaParser.parse(formula, wb)); - confirmParseException(e, expectedMessage); - } - - /** - * In bug 47078, POI had trouble evaluating a defined name flagged as 'complex'. - * POI should also be able to parse such defined names. - */ - @Test - void testParseComplexName() throws IOException { - - // Mock up a spreadsheet to match the critical details of the sample - try (HSSFWorkbook wb = new HSSFWorkbook()) { - wb.createSheet("Sheet1"); - HSSFName definedName = wb.createName(); - definedName.setNameName("foo"); - definedName.setRefersToFormula("Sheet1!B2"); - - // Set the complex flag - POI doesn't usually manipulate this flag - NameRecord nameRec = TestHSSFName.getNameRecord(definedName); - nameRec.setOptionFlag((short) 0x10); // 0x10 -> complex - - Ptg[] result; - try { - result = HSSFFormulaParser.parse("1+foo", wb); - } catch (FormulaParseException e) { - if (e.getMessage().equals("Specified name 'foo' is not a range as expected.")) { - fail("Identified bug 47078c"); - } - throw e; - } - confirmTokenClasses(result, IntPtg.class, NamePtg.class, AddPtg.class); - } - } - - /** - * Zero is not a valid row number so cell references like 'A0' are not valid. - * Actually, they should be treated like defined names. - *
- * In addition, leading zeros (on the row component) should be removed from cell - * references during parsing. - */ - @Test - void testZeroRowRefs() throws IOException { - String badCellRef = "B0"; // bad because zero is not a valid row number - String leadingZeroCellRef = "B000001"; // this should get parsed as "B1" - HSSFWorkbook wb = new HSSFWorkbook(); - - FormulaParseException e = assertThrows(FormulaParseException.class, () -> HSSFFormulaParser.parse(badCellRef, wb), - "Identified bug 47312b - Shouldn't be able to parse cell ref '" + badCellRef + "'."); - confirmParseException(e, "Specified named range '" + badCellRef + "' does not exist in the current workbook."); - - Ptg[] ptgs; - try { - ptgs = HSSFFormulaParser.parse(leadingZeroCellRef, wb); - assertEquals("B1", ptgs[0].toFormulaString()); - } catch (FormulaParseException e2) { - confirmParseException(e2, "Specified named range '" + leadingZeroCellRef + "' does not exist in the current workbook."); - // close but no cigar - fail("Identified bug 47312c - '" + leadingZeroCellRef + "' should parse as 'B1'."); - } - - // create a defined name called 'B0' and try again - Name n = wb.createName(); - n.setNameName("B0"); - n.setRefersToFormula("1+1"); - ptgs = HSSFFormulaParser.parse("B0", wb); - confirmTokenClasses(ptgs, NamePtg.class); - - wb.close(); - } - - private static void confirmParseException(FormulaParseException e, String expMsg) { - assertEquals(expMsg, e.getMessage()); - } - - @Test - void test57196_Formula() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - Ptg[] ptgs = HSSFFormulaParser.parse("DEC2HEX(HEX2DEC(O8)-O2+D2)", wb, FormulaType.CELL, -1); - assertNotNull(ptgs, "Ptg array should not be null"); - - confirmTokenClasses(ptgs, - NameXPtg.class, // ?? - NameXPtg.class, // ?? - RefPtg.class, // O8 - FuncVarPtg.class, // HEX2DEC - RefPtg.class, // O2 - SubtractPtg.class, - RefPtg.class, // D2 - AddPtg.class, - FuncVarPtg.class // DEC2HEX - ); - - RefPtg o8 = (RefPtg) ptgs[2]; - FuncVarPtg hex2Dec = (FuncVarPtg) ptgs[3]; - RefPtg o2 = (RefPtg) ptgs[4]; - RefPtg d2 = (RefPtg) ptgs[6]; - FuncVarPtg dec2Hex = (FuncVarPtg) ptgs[8]; - - assertEquals("O8", o8.toFormulaString()); - assertEquals(255, hex2Dec.getFunctionIndex()); - //assertEquals("", hex2Dec.toString()); - assertEquals("O2", o2.toFormulaString()); - assertEquals("D2", d2.toFormulaString()); - assertEquals(255, dec2Hex.getFunctionIndex()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java deleted file mode 100644 index 8b41f96879..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java +++ /dev/null @@ -1,99 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.NamePtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -/** - * Test the low level formula parser functionality, - * but using parts which need to use - * HSSFFormulaEvaluator. - */ -final class TestFormulaParserEval { - - @Test - void testWithNamedRange() { - HSSFWorkbook workbook = new HSSFWorkbook(); - - HSSFSheet s = workbook.createSheet("Foo"); - s.createRow(0).createCell(0).setCellValue(1.1); - s.createRow(1).createCell(0).setCellValue(2.3); - s.createRow(2).createCell(2).setCellValue(3.1); - - HSSFName name = workbook.createName(); - name.setNameName("testName"); - name.setRefersToFormula("A1:A2"); - - confirmParseFormula(workbook); - - // Now make it a single cell - name.setRefersToFormula("C3"); - confirmParseFormula(workbook); - - // And make it non-contiguous - // using area unions - name.setRefersToFormula("A1:A2,C3"); - - confirmParseFormula(workbook); - } - - /** - * Makes sure that a formula referring to the named range parses properly - */ - private static void confirmParseFormula(HSSFWorkbook workbook) { - Ptg[] ptgs = HSSFFormulaParser.parse("SUM(testName)", workbook); - assertEquals(2, ptgs.length, "two tokens expected, got " + ptgs.length); - assertEquals(NamePtg.class, ptgs[0].getClass()); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - } - - @Test - void testEvaluateFormulaWithRowBeyond32768_Bug44539() { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - wb.setSheetName(0, "Sheet1"); - - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("SUM(A32769:A32770)"); - - // put some values in the cells to make the evaluation more interesting - sheet.createRow(32768).createCell(0).setCellValue(31); - sheet.createRow(32769).createCell(0).setCellValue(11); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - // Check for: Found reference to named range "A", but that named range wasn't defined! - CellValue result= fe.evaluate(cell); - assertEquals(CellType.NUMERIC, result.getCellType()); - assertEquals(42.0, result.getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java deleted file mode 100644 index f9c06bbedb..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java +++ /dev/null @@ -1,238 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.formula.ptg.AddPtg; -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.BoolPtg; -import org.apache.poi.ss.formula.ptg.FuncPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.IntPtg; -import org.apache.poi.ss.formula.ptg.LessEqualPtg; -import org.apache.poi.ss.formula.ptg.LessThanPtg; -import org.apache.poi.ss.formula.ptg.MultiplyPtg; -import org.apache.poi.ss.formula.ptg.NotEqualPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.formula.ptg.StringPtg; -import org.junit.jupiter.api.Test; - -/** - * Tests FormulaParser specifically with respect to IF() functions - */ -final class TestFormulaParserIf { - private static Ptg[] parseFormula(String formula) { - return TestFormulaParser.parseFormula(formula); - } - - private static Ptg[] confirmTokenClasses(String formula, Class[] expectedClasses) { - return TestFormulaParser.confirmTokenClasses(formula, expectedClasses); - } - - private static void confirmAttrData(Ptg[] ptgs, int i, int expectedData) { - Ptg ptg = ptgs[i]; - assertTrue(ptg instanceof AttrPtg, "Token[" + i + "] was not AttrPtg as expected"); - AttrPtg attrPtg = (AttrPtg) ptg; - assertEquals(expectedData, attrPtg.getData()); - } - - @Test - void testSimpleIf() { - - Class[] expClss = { - RefPtg.class, - AttrPtg.class, // tAttrIf - IntPtg.class, - AttrPtg.class, // tAttrSkip - IntPtg.class, - AttrPtg.class, // tAttrSkip - FuncVarPtg.class, - }; - - Ptg[] ptgs = confirmTokenClasses("if(A1,1,2)", expClss); - - confirmAttrData(ptgs, 1, 7); - confirmAttrData(ptgs, 3, 10); - confirmAttrData(ptgs, 5, 3); - } - - @Test - void testSimpleIfNoFalseParam() { - - Class[] expClss = { - RefPtg.class, - AttrPtg.class, // tAttrIf - RefPtg.class, - AttrPtg.class, // tAttrSkip - FuncVarPtg.class, - }; - - Ptg[] ptgs = confirmTokenClasses("if(A1,B1)", expClss); - - confirmAttrData(ptgs, 1, 9); - confirmAttrData(ptgs, 3, 3); - } - - @Test - void testIfWithLargeParams() { - - Class[] expClss = { - RefPtg.class, - AttrPtg.class, // tAttrIf - - RefPtg.class, - IntPtg.class, - MultiplyPtg.class, - RefPtg.class, - IntPtg.class, - AddPtg.class, - FuncPtg.class, - AttrPtg.class, // tAttrSkip - - RefPtg.class, - RefPtg.class, - FuncPtg.class, - - AttrPtg.class, // tAttrSkip - FuncVarPtg.class, - }; - - Ptg[] ptgs = confirmTokenClasses("if(A1,round(B1*100,C1+2),round(B1,C1))", expClss); - - confirmAttrData(ptgs, 1, 25); - confirmAttrData(ptgs, 9, 20); - confirmAttrData(ptgs, 13, 3); - } - - @Test - void testNestedIf() { - - Class[] expClss = { - RefPtg.class, - AttrPtg.class, // A tAttrIf - RefPtg.class, - AttrPtg.class, // B tAttrIf - IntPtg.class, - AttrPtg.class, // B tAttrSkip - IntPtg.class, - AttrPtg.class, // B tAttrSkip - FuncVarPtg.class, - AttrPtg.class, // A tAttrSkip - RefPtg.class, - AttrPtg.class, // C tAttrIf - IntPtg.class, - AttrPtg.class, // C tAttrSkip - IntPtg.class, - AttrPtg.class, // C tAttrSkip - FuncVarPtg.class, - AttrPtg.class, // A tAttrSkip - FuncVarPtg.class, - }; - - Ptg[] ptgs = confirmTokenClasses("if(A1,if(B1,1,2),if(C1,3,4))", expClss); - confirmAttrData(ptgs, 1, 31); - confirmAttrData(ptgs, 3, 7); - confirmAttrData(ptgs, 5, 10); - confirmAttrData(ptgs, 7, 3); - confirmAttrData(ptgs, 9, 34); - confirmAttrData(ptgs, 11, 7); - confirmAttrData(ptgs, 13, 10); - confirmAttrData(ptgs, 15, 3); - confirmAttrData(ptgs, 17, 3); - } - - @Test - void testEmbeddedIf() { - Ptg[] ptgs = parseFormula("IF(3>=1,\"*\",IF(4<>1,\"first\",\"second\"))"); - assertEquals(17, ptgs.length); - - assertEquals(AttrPtg.class, ptgs[5].getClass(), "6th Ptg is not a goto (Attr) ptg"); - assertEquals(NotEqualPtg.class, ptgs[8].getClass(), "9th Ptg is not a not equal ptg"); - assertEquals(FuncVarPtg.class, ptgs[14].getClass(), "15th Ptg is not the inner IF variable function ptg"); - } - - @Test - void testSimpleLogical() { - Ptg[] ptgs = parseFormula("IF(A1 - * TODO get OOO documentation updated to reflect this (that EXTERNALBOOK is optional). - * - * It's not clear what exact steps need to be taken in Excel to create such a workbook - */ - @Test - void testLinkTableWithoutExternalBookRecord_bug45046() { - // Bug 45046 b: DEFINEDNAME is part of LinkTable - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex45046-21984.xls"); - // some other sanity checks - assertEquals(3, wb.getNumberOfSheets()); - String formula = wb.getSheetAt(0).getRow(4).getCell(13).getCellFormula(); - - // The reported symptom of this bugzilla is an earlier bug (already fixed) - // This is observable in version 3.0 - assertNotEquals("ipcSummenproduktIntern($P5,N$6,$A$9,N$5)", formula); - - assertEquals("ipcSummenproduktIntern($C5,N$2,$A$9,N$1)", formula); - } - - @Test - void testMultipleExternSheetRecords_bug45698() { - // Bug: Extern sheet is part of LinkTable - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex45698-22488.xls"); - // some other sanity checks - assertEquals(7, wb.getNumberOfSheets()); - } - - @Test - void testExtraSheetRefs_bug45978() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex45978-extraLinkTableSheets.xls"); - /* - ex45978-extraLinkTableSheets.xls is a cut-down version of attachment 22561. - The original file produces the same error. - - This bug was caused by a combination of invalid sheet indexes in the EXTERNSHEET - record, and eager initialisation of the extern sheet references. Note - the workbook - has 2 sheets, but the EXTERNSHEET record refers to sheet indexes 0, 1 and 2. - - Offset 0x3954 (14676) - recordid = 0x17, size = 32 - [EXTERNSHEET] - numOfRefs = 5 - refrec #0: extBook=0 firstSheet=0 lastSheet=0 - refrec #1: extBook=1 firstSheet=2 lastSheet=2 - refrec #2: extBook=2 firstSheet=1 lastSheet=1 - refrec #3: extBook=0 firstSheet=-1 lastSheet=-1 - refrec #4: extBook=0 firstSheet=1 lastSheet=1 - [/EXTERNSHEET] - - As it turns out, the formula in question doesn't even use externSheetIndex #1 - it - uses #4, which resolves to sheetIndex 1 -> 'Data'. - - It is not clear exactly what externSheetIndex #4 would refer to. Excel seems to - display such a formula as "''!$A2", but then complains of broken link errors. - */ - - HSSFCell cell = wb.getSheetAt(0).getRow(1).getCell(1); - // Bug: IndexOutOfBoundsException - Index: 2, Size: 2 - String cellFormula = cell.getCellFormula(); - assertEquals("Data!$A2", cellFormula); - } - - /** - * This problem was visible in POI svn r763332 - * when reading the workbook of attachment 23468 from bugzilla 47001 - */ - @Test - void testMissingExternSheetRecord_bug47001b() { - - Record[] recs = { - SupBookRecord.createAddInFunctions(), - new SSTRecord(), - }; - List recList = Arrays.asList(recs); - WorkbookRecordList wrl = new WorkbookRecordList(); - - // Bug 47001b: Expected an EXTERNSHEET record but got (org.apache.poi.hssf.record.SSTRecord) - LinkTable lt = new LinkTable(recList, 0, wrl, Collections.emptyMap()); - assertNotNull(lt); - } - - @Test - void testNameCommentRecordBetweenNameRecords() { - - final Record[] recs = { - new NameRecord(), - new NameCommentRecord("name1", "comment1"), - new NameRecord(), - new NameCommentRecord("name2", "comment2"), - - }; - final List recList = Arrays.asList(recs); - final WorkbookRecordList wrl = new WorkbookRecordList(); - final Map commentRecords = new LinkedHashMap<>(); - - final LinkTable lt = new LinkTable(recList, 0, wrl, commentRecords); - assertNotNull(lt); - - assertEquals(2, commentRecords.size()); - assertSame(recs[1], commentRecords.get("name1")); //== is intentionally not .equals()! - assertSame(recs[3], commentRecords.get("name2")); //== is intentionally not .equals()! - - assertEquals(2, lt.getNumNames()); - } - - @Test - void testAddNameX(){ - WorkbookRecordList wrl = new WorkbookRecordList(); - wrl.add(0, new BOFRecord()); - wrl.add(1, new CountryRecord()); - wrl.add(2, EOFRecord.instance); - - int numberOfSheets = 3; - LinkTable tbl = new LinkTable(numberOfSheets, wrl); - // creation of a new LinkTable insert two new records: SupBookRecord followed by ExternSheetRecord - // assure they are in place: - // [BOFRecord] - // [CountryRecord] - // [SUPBOOK Internal References nSheets= 3] - // [EXTERNSHEET] - // [EOFRecord] - - assertEquals(5, wrl.getRecords().size()); - assertTrue(wrl.get(2) instanceof SupBookRecord); - SupBookRecord sup1 = (SupBookRecord)wrl.get(2); - assertEquals(numberOfSheets, sup1.getNumberOfSheets()); - assertTrue(wrl.get(3) instanceof ExternSheetRecord); - ExternSheetRecord extSheet = (ExternSheetRecord)wrl.get(3); - assertEquals(0, extSheet.getNumOfRefs()); - - assertNull(tbl.getNameXPtg("ISODD", -1)); - assertEquals(5, wrl.getRecords().size()); //still have five records - - NameXPtg namex1 = tbl.addNameXPtg("ISODD"); // adds two new rercords - assertEquals(0, namex1.getSheetRefIndex()); - assertEquals(0, namex1.getNameIndex()); - NameXPtg act = tbl.getNameXPtg("ISODD", -1); - assertNotNull(act); - assertEquals(namex1.toString(), act.toString()); - - // Can only find on the right sheet ref, if restricting - act = tbl.getNameXPtg("ISODD", 0); - assertNotNull(act); - assertEquals(namex1.toString(), act.toString()); - assertNull(tbl.getNameXPtg("ISODD", 1)); - assertNull(tbl.getNameXPtg("ISODD", 2)); - - // assure they are in place: - // [BOFRecord] - // [CountryRecord] - // [SUPBOOK Internal References nSheets= 3] - // [SUPBOOK Add-In Functions nSheets= 1] - // [EXTERNALNAME .name = ISODD] - // [EXTERNSHEET] - // [EOFRecord] - - assertEquals(7, wrl.getRecords().size()); - assertTrue(wrl.get(3) instanceof SupBookRecord); - SupBookRecord sup2 = (SupBookRecord)wrl.get(3); - assertTrue(sup2.isAddInFunctions()); - assertTrue(wrl.get(4) instanceof ExternalNameRecord); - ExternalNameRecord ext1 = (ExternalNameRecord)wrl.get(4); - assertEquals("ISODD", ext1.getText()); - assertTrue(wrl.get(5) instanceof ExternSheetRecord); - assertEquals(1, extSheet.getNumOfRefs()); - - //check that - assertEquals(0, tbl.resolveNameXIx(namex1.getSheetRefIndex(), namex1.getNameIndex())); - assertEquals("ISODD", tbl.resolveNameXText(namex1.getSheetRefIndex(), namex1.getNameIndex(), null)); - - assertNull(tbl.getNameXPtg("ISEVEN", -1)); - NameXPtg namex2 = tbl.addNameXPtg("ISEVEN"); // adds two new rercords - assertEquals(0, namex2.getSheetRefIndex()); - assertEquals(1, namex2.getNameIndex()); // name index increased by one - act = tbl.getNameXPtg("ISEVEN", -1); - assertNotNull(act); - assertEquals(namex2.toString(), act.toString()); - assertEquals(8, wrl.getRecords().size()); - // assure they are in place: - // [BOFRecord] - // [CountryRecord] - // [SUPBOOK Internal References nSheets= 3] - // [SUPBOOK Add-In Functions nSheets= 1] - // [EXTERNALNAME .name = ISODD] - // [EXTERNALNAME .name = ISEVEN] - // [EXTERNSHEET] - // [EOFRecord] - assertTrue(wrl.get(3) instanceof SupBookRecord); - assertTrue(wrl.get(4) instanceof ExternalNameRecord); - assertTrue(wrl.get(5) instanceof ExternalNameRecord); - assertEquals("ISODD", ((ExternalNameRecord)wrl.get(4)).getText()); - assertEquals("ISEVEN", ((ExternalNameRecord)wrl.get(5)).getText()); - assertTrue(wrl.get(6) instanceof ExternSheetRecord); - assertTrue(wrl.get(7) instanceof EOFRecord); - - assertEquals(0, tbl.resolveNameXIx(namex2.getSheetRefIndex(), namex2.getNameIndex())); - assertEquals("ISEVEN", tbl.resolveNameXText(namex2.getSheetRefIndex(), namex2.getNameIndex(), null)); - - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestOperandClassTransformer.java b/src/testcases/org/apache/poi/hssf/model/TestOperandClassTransformer.java deleted file mode 100644 index f36ee053a8..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestOperandClassTransformer.java +++ /dev/null @@ -1,150 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.apache.poi.ss.formula.functions.MatrixFunction; -import org.apache.poi.ss.formula.ptg.AbstractFunctionPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * Tests specific formula examples in OperandClassTransformer. - */ -final class TestOperandClassTransformer { - - private static Ptg[] parseFormula(String formula) { - Ptg[] result = HSSFFormulaParser.parse(formula, null); - assertNotNull(result, "Ptg array should not be null"); - return result; - } - - @Test - void testMdeterm() { - String formula = "MDETERM(ABS(A1))"; - Ptg[] ptgs = parseFormula(formula); - - confirmTokenClass(ptgs, 0, Ptg.CLASS_ARRAY); - confirmFuncClass(ptgs, 1, "ABS", Ptg.CLASS_ARRAY); - confirmFuncClass(ptgs, 2, "MDETERM", Ptg.CLASS_VALUE); - } - - @Test - void testMdetermReturnsValueInvalidOnABlankCell() { - ValueEval matrixRef = EvalFactory.createAreaEval("A1:B2", - new ValueEval[]{ - BlankEval.instance, - new NumberEval(1), - new NumberEval(2), - new NumberEval(3) - } - ); - ValueEval result = MatrixFunction.MDETERM.evaluate(new ValueEval[]{matrixRef} , 0, 0); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - /** - * In the example: INDEX(PI(),1), Excel encodes PI() as 'array'. It is not clear - * what rule justifies this. POI currently encodes it as 'value' which Excel(2007) seems to - * tolerate. Changing the metadata for INDEX to have first parameter as 'array' class breaks - * other formulas involving INDEX. It seems like a special case needs to be made. Perhaps an - * important observation is that INDEX is one of very few functions that returns 'reference' type. - *

- * This test has been added but disabled in order to document this issue. - */ - @Test - @Disabled - void testIndexPi1() { - String formula = "INDEX(PI(),1)"; - Ptg[] ptgs = parseFormula(formula); - - confirmFuncClass(ptgs, 1, "PI", Ptg.CLASS_ARRAY); // fails as of POI 3.1 - confirmFuncClass(ptgs, 2, "INDEX", Ptg.CLASS_VALUE); - } - - /** - * Even though count expects args of type R, because A1 is a direct operand of a - * value operator it must get type V - */ - @Test - void testDirectOperandOfValueOperator() { - String formula = "COUNT(A1*1)"; - Ptg[] ptgs = parseFormula(formula); - assertNotEquals(Ptg.CLASS_REF, ptgs[0].getPtgClass()); - confirmTokenClass(ptgs, 0, Ptg.CLASS_VALUE); - confirmTokenClass(ptgs, 3, Ptg.CLASS_VALUE); - } - - /** - * A cell ref passed to a function expecting type V should be converted to type V - */ - @Test - void testRtoV() { - - String formula = "lookup(A1, A3:A52, B3:B52)"; - Ptg[] ptgs = parseFormula(formula); - confirmTokenClass(ptgs, 0, Ptg.CLASS_VALUE); - } - - @Test - void testComplexIRR_bug45041() { - String formula = "(1+IRR(SUMIF(A:A,ROW(INDIRECT(MIN(A:A)&\":\"&MAX(A:A))),B:B),0))^365-1"; - Ptg[] ptgs = parseFormula(formula); - - FuncVarPtg rowFunc = (FuncVarPtg) ptgs[10]; - FuncVarPtg sumifFunc = (FuncVarPtg) ptgs[12]; - assertEquals("ROW", rowFunc.getName()); - assertEquals("SUMIF", sumifFunc.getName()); - - assertNotEquals(Ptg.CLASS_VALUE, rowFunc.getPtgClass()); - assertNotEquals(Ptg.CLASS_VALUE, sumifFunc.getPtgClass()); - confirmTokenClass(ptgs, 1, Ptg.CLASS_REF); - confirmTokenClass(ptgs, 2, Ptg.CLASS_REF); - confirmFuncClass(ptgs, 3, "MIN", Ptg.CLASS_VALUE); - confirmTokenClass(ptgs, 6, Ptg.CLASS_REF); - confirmFuncClass(ptgs, 7, "MAX", Ptg.CLASS_VALUE); - confirmFuncClass(ptgs, 9, "INDIRECT", Ptg.CLASS_REF); - confirmFuncClass(ptgs, 10, "ROW", Ptg.CLASS_ARRAY); - confirmTokenClass(ptgs, 11, Ptg.CLASS_REF); - confirmFuncClass(ptgs, 12, "SUMIF", Ptg.CLASS_ARRAY); - confirmFuncClass(ptgs, 14, "IRR", Ptg.CLASS_VALUE); - } - - private void confirmFuncClass(Ptg[] ptgs, int i, String expectedFunctionName, byte operandClass) { - confirmTokenClass(ptgs, i, operandClass); - AbstractFunctionPtg afp = (AbstractFunctionPtg) ptgs[i]; - assertEquals(expectedFunctionName, afp.getName()); - } - - private void confirmTokenClass(Ptg[] ptgs, int i, byte operandClass) { - Ptg ptg = ptgs[i]; - assertFalse(ptg.isBaseToken(), "ptg[" + i + "] is a base token"); - assertEquals(operandClass, ptg.getPtgClass()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestRVA.java b/src/testcases/org/apache/poi/hssf/model/TestRVA.java deleted file mode 100644 index 488a9e6fc5..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestRVA.java +++ /dev/null @@ -1,132 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Stream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.FormulaExtractor; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.CellType; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Tests 'operand class' transformation performed by - * OperandClassTransformer by comparing its results with those - * directly produced by Excel (in a sample spreadsheet). - */ -final class TestRVA { - - private static final String NEW_LINE = System.getProperty("line.separator"); - private static POIFSFileSystem poifs; - private static HSSFWorkbook workbook; - - - @AfterAll - public static void closeResource() throws Exception { - workbook.close(); - poifs.close(); - } - - public static Stream data() throws Exception { - poifs = new POIFSFileSystem(HSSFTestDataSamples.getSampleFile("testRVA.xls"), true); - workbook = new HSSFWorkbook(poifs); - HSSFSheet sheet = workbook.getSheetAt(0); - - List data = new ArrayList<>(); - - for (int rowIdx = 0; true; rowIdx++) { - HSSFRow row = sheet.getRow(rowIdx); - if (row == null) { - break; - } - HSSFCell cell = row.getCell(0); - if (cell == null || cell.getCellType() == CellType.BLANK) { - break; - } - - String formula = cell.getCellFormula(); - data.add(Arguments.of(cell,formula)); - } - - return data.stream(); - } - - @ParameterizedTest - @MethodSource("data") - void confirmCell(HSSFCell formulaCell, String formula) { - Ptg[] excelPtgs = FormulaExtractor.getPtgs(formulaCell); - Ptg[] poiPtgs = HSSFFormulaParser.parse(formula, workbook); - int nExcelTokens = excelPtgs.length; - int nPoiTokens = poiPtgs.length; - if (nExcelTokens != nPoiTokens) { - assertTrue(nExcelTokens == nPoiTokens + 1 && excelPtgs[0].getClass() == AttrPtg.class, - "Expected " + nExcelTokens + " tokens but got " + nPoiTokens); - - // compensate for missing tAttrVolatile, which belongs in any formula - // involving OFFSET() et al. POI currently does not insert where required - Ptg[] temp = new Ptg[nExcelTokens]; - temp[0] = excelPtgs[0]; - System.arraycopy(poiPtgs, 0, temp, 1, nPoiTokens); - poiPtgs = temp; - } - boolean hasMismatch = false; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < nExcelTokens; i++) { - Ptg poiPtg = poiPtgs[i]; - Ptg excelPtg = excelPtgs[i]; - if (excelPtg.getClass() != poiPtg.getClass()) { - hasMismatch = true; - sb.append(" mismatch token type[").append(i).append("] ").append(getShortClassName(excelPtg)).append(" ").append(excelPtg.getRVAType()).append(" - ").append(getShortClassName(poiPtg)).append(" ").append(poiPtg.getRVAType()); - sb.append(NEW_LINE); - continue; - } - if (poiPtg.isBaseToken()) { - continue; - } - sb.append(" token[").append(i).append("] ").append(excelPtg).append(" ").append(excelPtg.getRVAType()); - - if (excelPtg.getPtgClass() != poiPtg.getPtgClass()) { - hasMismatch = true; - sb.append(" - was ").append(poiPtg.getRVAType()); - } - sb.append(NEW_LINE); - } - assertFalse(hasMismatch); - } - - private String getShortClassName(Object o) { - String cn = o.getClass().getName(); - int pos = cn.lastIndexOf('.'); - return cn.substring(pos + 1); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java b/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java deleted file mode 100644 index fde901216b..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Arrays; - -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RowRecord; -import org.apache.poi.hssf.record.UnknownRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.pivottable.ViewDefinitionRecord; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link RowBlocksReader} - * - * @author Josh Micich - */ -final class TestRowBlocksReader { - @Test - void testAbnormalPivotTableRecords_bug46280() { - int SXVIEW_SID = ViewDefinitionRecord.sid; - Record[] inRecs = { - new RowRecord(0), - new NumberRecord(), - // normally MSODRAWING(0x00EC) would come here before SXVIEW - new UnknownRecord(SXVIEW_SID, "dummydata (SXVIEW: View Definition)".getBytes(LocaleUtil.CHARSET_1252)), - new WindowTwoRecord(), - }; - RecordStream rs = new RecordStream(Arrays.asList(inRecs), 0); - RowBlocksReader rbr = new RowBlocksReader(rs); - assertNotEquals(WindowTwoRecord.class, rs.peekNextClass(), - "Should have stopped at the SXVIEW record - Identified bug 46280b"); - - RecordStream rbStream = rbr.getPlainRecordStream(); - assertEquals(inRecs[0], rbStream.getNext()); - assertEquals(inRecs[1], rbStream.getNext()); - assertFalse(rbStream.hasNext()); - assertTrue(rs.hasNext()); - assertEquals(inRecs[2], rs.getNext()); - assertEquals(inRecs[3], rs.getNext()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestSheet.java b/src/testcases/org/apache/poi/hssf/model/TestSheet.java deleted file mode 100644 index aef0c5e40b..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestSheet.java +++ /dev/null @@ -1,784 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.ddf.EscherDggRecord; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.*; -import org.apache.poi.hssf.record.aggregates.ConditionalFormattingTable; -import org.apache.poi.hssf.record.aggregates.PageSettingsBlock; -import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.FormulaShifter; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Unit test for the {@link InternalSheet} class. - */ -final class TestSheet { - private static InternalSheet createSheet(List inRecs) { - return InternalSheet.createSheet(new RecordStream(inRecs, 0)); - } - - @Test - void testCreateSheet() { - // Check we're adding row and cell aggregates - List records = new ArrayList<>(); - records.add(BOFRecord.createSheetBOF()); - records.add( new DimensionsRecord() ); - records.add(createWindow2Record()); - records.add(EOFRecord.instance); - InternalSheet sheet = createSheet(records); - - List outRecs = new ArrayList<>(); - sheet.visitContainedRecords(outRecs::add, 0); - - Iterator iter = outRecs.iterator(); - assertTrue(iter.next() instanceof BOFRecord ); - assertTrue(iter.next() instanceof IndexRecord); - assertTrue(iter.next() instanceof DimensionsRecord); - assertTrue(iter.next() instanceof WindowTwoRecord ); - assertTrue(iter.next() instanceof EOFRecord); - } - - private static org.apache.poi.hssf.record.Record createWindow2Record() { - WindowTwoRecord result = new WindowTwoRecord(); - result.setOptions(( short ) 0x6b6); - result.setTopRow(( short ) 0); - result.setLeftCol(( short ) 0); - result.setHeaderColor(0x40); - result.setPageBreakZoom(( short ) 0); - result.setNormalZoom(( short ) 0); - return result; - } - - private static final class MergedCellListener implements RecordVisitor { - - private int _count; - public MergedCellListener() { - _count = 0; - } - @Override - public void visitRecord(org.apache.poi.hssf.record.Record r) { - if (r instanceof MergeCellsRecord) { - _count++; - } - } - public int getCount() { - return _count; - } - } - - @Test - void testAddMergedRegion() { - InternalSheet sheet = InternalSheet.createSheet(); - final int regionsToAdd = 4096; - - //simple test that adds a load of regions - for (int n = 0; n < regionsToAdd; n++) - { - int index = sheet.addMergedRegion(0, (short) 0, 1, (short) 1); - assertEquals(index, n, "Merged region index expected to be " + n + " got " + index); - } - - //test all the regions were indeed added - assertEquals(sheet.getNumMergedRegions(), regionsToAdd); - - //test that the regions were spread out over the appropriate number of records - MergedCellListener mcListener = new MergedCellListener(); - sheet.visitContainedRecords(mcListener, 0); - int recordsAdded = mcListener.getCount(); - int recordsExpected = regionsToAdd/1027; - //noinspection ConstantConditions - if ((regionsToAdd % 1027) != 0) { - recordsExpected++; - } - assertEquals(recordsAdded, recordsExpected, - "The " + regionsToAdd + " merged regions should have been spread out over " - + recordsExpected + " records, not " + recordsAdded); - // Check we can't add one with invalid date - IllegalArgumentException e; - e = assertThrows(IllegalArgumentException.class, () -> sheet.addMergedRegion(10, (short)10, 9, (short)12)); - assertEquals("The 'to' row (9) must not be less than the 'from' row (10)", e.getMessage()); - - e = assertThrows(IllegalArgumentException.class, () -> sheet.addMergedRegion(10, (short)10, 12, (short)9)); - assertEquals("The 'to' col (9) must not be less than the 'from' col (10)", e.getMessage()); - } - - @Test - void testRemoveMergedRegion() { - InternalSheet sheet = InternalSheet.createSheet(); - int regionsToAdd = 4096; - - for (int n = 0; n < regionsToAdd; n++) { - sheet.addMergedRegion(n, 0, n, 1); - } - - int nSheetRecords = sheet.getRecords().size(); - - //remove a third from the beginning - for (int n = 0; n < regionsToAdd/3; n++) - { - sheet.removeMergedRegion(0); - //assert they have been deleted - assertEquals(regionsToAdd - n - 1, sheet.getNumMergedRegions(), "Num of regions"); - } - - // merge records are removed from within the MergedCellsTable, - // so the sheet record count should not change - assertEquals(nSheetRecords, sheet.getRecords().size(), "Sheet Records"); - } - - /** - * Bug: 22922 (Reported by Xuemin Guan) - *

- * Remove mergedregion fails when a sheet loses records after an initial CreateSheet - * fills up the records. - * - */ - @Test - void testMovingMergedRegion() { - List records = new ArrayList<>(); - - CellRangeAddress[] cras = { - new CellRangeAddress(0, 1, 0, 2), - }; - MergeCellsRecord merged = new MergeCellsRecord(cras, 0, cras.length); - records.add(BOFRecord.createSheetBOF()); - records.add(new DimensionsRecord()); - records.add(new RowRecord(0)); - records.add(new RowRecord(1)); - records.add(new RowRecord(2)); - records.add(createWindow2Record()); - records.add(EOFRecord.instance); - records.add(merged); - - InternalSheet sheet = createSheet(records); - sheet.getRecords().remove(0); // TODO - what does this line do? - - //stub object to throw off list INDEX operations - sheet.removeMergedRegion(0); - assertEquals(0, sheet.getNumMergedRegions(), "Should be no more merged regions"); - } - - // @Test - // void testGetMergedRegionAt() { - // TODO - // } - - // @Test - // void testGetNumMergedRegions() { - // TODO - // } - - /** - * Makes sure all rows registered for this sheet are aggregated, they were being skipped - * - */ - @Test - void testRowAggregation() { - List records = new ArrayList<>(); - - records.add(InternalSheet.createBOF()); - records.add(new DimensionsRecord()); - records.add(new RowRecord(0)); - records.add(new RowRecord(1)); - FormulaRecord formulaRecord = new FormulaRecord(); - formulaRecord.setCachedResultTypeString(); - records.add(formulaRecord); - records.add(new StringRecord()); - records.add(new RowRecord(2)); - records.add(createWindow2Record()); - records.add(EOFRecord.instance); - - InternalSheet sheet = createSheet(records); - assertNotNull(sheet.getRow(2), "Row [2] was skipped"); - } - - /** - * Make sure page break functionality works (in memory) - * - */ - @Test - void testRowPageBreaks() { - short colFrom = 0; - short colTo = 255; - - InternalSheet worksheet = InternalSheet.createSheet(); - PageSettingsBlock sheet = worksheet.getPageSettings(); - sheet.setRowBreak(0, colFrom, colTo); - - assertTrue(sheet.isRowBroken(0), "no row break at 0"); - assertEquals(1, sheet.getNumRowBreaks(), "1 row break available"); - - sheet.setRowBreak(0, colFrom, colTo); - sheet.setRowBreak(0, colFrom, colTo); - - assertTrue(sheet.isRowBroken(0), "no row break at 0"); - assertEquals(1, sheet.getNumRowBreaks(), "1 row break available"); - - sheet.setRowBreak(10, colFrom, colTo); - sheet.setRowBreak(11, colFrom, colTo); - - assertTrue(sheet.isRowBroken(10), "no row break at 10"); - assertTrue(sheet.isRowBroken(11), "no row break at 11"); - assertEquals(3, sheet.getNumRowBreaks(), "3 row break available"); - - - boolean is10 = false; - boolean is0 = false; - boolean is11 = false; - - int[] rowBreaks = sheet.getRowBreaks(); - for (int main : rowBreaks) { - assertTrue(main == 0 || main == 10 || main == 11, "Invalid page break"); - if (main == 0) is0 = true; - if (main == 10) is10 = true; - if (main == 11) is11 = true; - } - - assertTrue(is0 && is10 && is11, "one of the breaks didnt make it"); - - sheet.removeRowBreak(11); - assertFalse(sheet.isRowBroken(11), "row should be removed"); - - sheet.removeRowBreak(0); - assertFalse(sheet.isRowBroken(0), "row should be removed"); - - sheet.removeRowBreak(10); - assertFalse(sheet.isRowBroken(10), "row should be removed"); - - assertEquals(0, sheet.getNumRowBreaks(), "no more breaks"); - } - - /** - * Make sure column pag breaks works properly (in-memory) - * - */ - @Test - void testColPageBreaks() { - short rowFrom = 0; - short rowTo = (short)65535; - - InternalSheet worksheet = InternalSheet.createSheet(); - PageSettingsBlock sheet = worksheet.getPageSettings(); - sheet.setColumnBreak((short)0, rowFrom, rowTo); - - assertTrue(sheet.isColumnBroken(0), "no col break at 0"); - assertEquals(1, sheet.getNumColumnBreaks(), "1 col break available"); - - sheet.setColumnBreak((short)0, rowFrom, rowTo); - - assertTrue(sheet.isColumnBroken(0), "no col break at 0"); - assertEquals(1, sheet.getNumColumnBreaks(), "1 col break available"); - - sheet.setColumnBreak((short)1, rowFrom, rowTo); - sheet.setColumnBreak((short)10, rowFrom, rowTo); - sheet.setColumnBreak((short)15, rowFrom, rowTo); - - assertTrue(sheet.isColumnBroken(1), "no col break at 1"); - assertTrue(sheet.isColumnBroken(10), "no col break at 10"); - assertTrue(sheet.isColumnBroken(15), "no col break at 15"); - assertEquals(4, sheet.getNumColumnBreaks(), "4 col break available"); - - boolean is10 = false; - boolean is0 = false; - boolean is1 = false; - boolean is15 = false; - - int[] colBreaks = sheet.getColumnBreaks(); - for (int main : colBreaks) { - assertTrue(main == 0 || main == 1 || main == 10 || main == 15, "Invalid page break"); - if (main == 0) is0 = true; - if (main == 1) is1 = true; - if (main == 10) is10= true; - if (main == 15) is15 = true; - } - - assertTrue(is0 && is1 && is10 && is15, "one of the breaks didnt make it"); - - sheet.removeColumnBreak(15); - assertFalse(sheet.isColumnBroken(15), "column break should not be there"); - - sheet.removeColumnBreak(0); - assertFalse(sheet.isColumnBroken(0), "column break should not be there"); - - sheet.removeColumnBreak(1); - assertFalse(sheet.isColumnBroken(1), "column break should not be there"); - - sheet.removeColumnBreak(10); - assertFalse(sheet.isColumnBroken(10), "column break should not be there"); - - assertEquals(0, sheet.getNumColumnBreaks(), "no more breaks"); - } - - /** - * test newly added method Sheet.getXFIndexForColAt(..) - * works as designed. - */ - @Test - void testXFIndexForColumn() { - final short TEST_IDX = 10; - final short DEFAULT_IDX = 0xF; // 15 - InternalSheet sheet = InternalSheet.createSheet(); - - // without ColumnInfoRecord - int xfindex = sheet.getXFIndexForColAt((short) 0); - assertEquals(DEFAULT_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 1); - assertEquals(DEFAULT_IDX, xfindex); - - ColumnInfoRecord nci = new ColumnInfoRecord(); - sheet._columnInfos.insertColumn(nci); - - // single column ColumnInfoRecord - nci.setFirstColumn((short) 2); - nci.setLastColumn((short) 2); - nci.setXFIndex(TEST_IDX); - xfindex = sheet.getXFIndexForColAt((short) 0); - assertEquals(DEFAULT_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 1); - assertEquals(DEFAULT_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 2); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 3); - assertEquals(DEFAULT_IDX, xfindex); - - // ten column ColumnInfoRecord - nci.setFirstColumn((short) 2); - nci.setLastColumn((short) 11); - nci.setXFIndex(TEST_IDX); - xfindex = sheet.getXFIndexForColAt((short) 1); - assertEquals(DEFAULT_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 2); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 6); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 11); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 12); - assertEquals(DEFAULT_IDX, xfindex); - - // single column ColumnInfoRecord starting at index 0 - nci.setFirstColumn((short) 0); - nci.setLastColumn((short) 0); - nci.setXFIndex(TEST_IDX); - xfindex = sheet.getXFIndexForColAt((short) 0); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 1); - assertEquals(DEFAULT_IDX, xfindex); - - // ten column ColumnInfoRecord starting at index 0 - nci.setFirstColumn((short) 0); - nci.setLastColumn((short) 9); - nci.setXFIndex(TEST_IDX); - xfindex = sheet.getXFIndexForColAt((short) 0); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 7); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 9); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 10); - assertEquals(DEFAULT_IDX, xfindex); - } - - /** - * Prior to bug 45066, POI would get the estimated sheet size wrong - * when an UncalcedRecord was present.

- */ - @Test - void testUncalcSize_bug45066() { - - List records = new ArrayList<>(); - records.add(BOFRecord.createSheetBOF()); - records.add(new UncalcedRecord()); - records.add(new DimensionsRecord()); - records.add(createWindow2Record()); - records.add(EOFRecord.instance); - InternalSheet sheet = createSheet(records); - - // The original bug was due to different logic for collecting records for sizing and - // serialization. The code has since been refactored into a single method for visiting - // all contained records. Now this test is much less interesting - int[] totalSize = { 0 }; - byte[] buf = new byte[100]; - - sheet.visitContainedRecords(r -> { - int estimatedSize = r.getRecordSize(); - int serializedSize = r.serialize(0, buf); - assertEquals(estimatedSize, serializedSize, "serialized size mismatch for record (" + r.getClass().getName() + ")"); - totalSize[0] += estimatedSize; - }, 0); - assertEquals(90, totalSize[0]); - } - - /** - * Prior to bug 45145 RowRecordsAggregate and ValueRecordsAggregate could - * sometimes occur in reverse order. This test reproduces one of those situations and makes - * sure that RRA comes before VRA.
- * - * The code here represents a normal POI use case where a spreadsheet is created from scratch. - */ - @Test - void testRowValueAggregatesOrder_bug45145() { - - InternalSheet sheet = InternalSheet.createSheet(); - - RowRecord rr = new RowRecord(5); - sheet.addRow(rr); - - CellValueRecordInterface cvr = new BlankRecord(); - cvr.setColumn((short)0); - cvr.setRow(5); - sheet.addValueRecord(5, cvr); - - - int dbCellRecordPos = getDbCellRecordPos(sheet); - // The overt symptom of the bug - // DBCELL record pos is calculated wrong if VRA comes before RRA - assertNotEquals (252, dbCellRecordPos); - -// if (false) { -// // make sure that RRA and VRA are in the right place -// // (Aug 2008) since the VRA is now part of the RRA, there is much less chance that -// // they could get out of order. Still, one could write serialize the sheet here, -// // and read back with EventRecordFactory to make sure... -// } - assertEquals(242, dbCellRecordPos); - } - - /** - * @return the value calculated for the position of the first DBCELL record for this sheet. - * That value is found on the IndexRecord. - */ - private static int getDbCellRecordPos(InternalSheet sheet) { - - MyIndexRecordListener myIndexListener = new MyIndexRecordListener(); - sheet.visitContainedRecords(myIndexListener, 0); - IndexRecord indexRecord = myIndexListener.getIndexRecord(); - return indexRecord.getDbcellAt(0); - } - - private static final class MyIndexRecordListener implements RecordVisitor { - - private IndexRecord _indexRecord; - public MyIndexRecordListener() { - // no-arg constructor - } - public IndexRecord getIndexRecord() { - return _indexRecord; - } - @Override - public void visitRecord(org.apache.poi.hssf.record.Record r) { - if (r instanceof IndexRecord) { - if (_indexRecord != null) { - throw new RuntimeException("too many index records"); - } - _indexRecord = (IndexRecord)r; - } - } - } - - /** - * Checks for bug introduced around r682282-r683880 that caused a second GUTS records - * which in turn got the dimensions record out of alignment - */ - @Test - void testGutsRecord_bug45640() { - - InternalSheet sheet = InternalSheet.createSheet(); - sheet.addRow(new RowRecord(0)); - sheet.addRow(new RowRecord(1)); - sheet.groupRowRange( 0, 1, true ); - assertNotNull(sheet.toString()); - List recs = sheet.getRecords(); - long count = recs.stream().filter(r -> r instanceof GutsRecord).count(); - assertNotEquals(2, count); - assertEquals(1, count); - } - - @Test - void testMisplacedMergedCellsRecords_bug45699() throws Exception { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex45698-22488.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - HSSFRow row = sheet.getRow(3); - HSSFCell cell = row.getCell(4); - assertNotNull(cell, "Identified bug 45699"); - assertEquals("Informations", cell.getRichStringCellValue().getString()); - } - } - /** - * In 3.1, setting margins between creating first row and first cell caused an exception. - */ - @Test - void testSetMargins_bug45717() throws Exception { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Vorschauliste"); - HSSFRow row = sheet.createRow(0); - - sheet.setMargin(HSSFSheet.LeftMargin, 0.3); - try { - row.createCell(0); - } catch (IllegalStateException e) { - if (e.getMessage().equals("Cannot create value records before row records exist")) { - fail("Identified bug 45717"); - } - throw e; - } finally { - workbook.close(); - } - } - - /** - * Some apps seem to write files with missing DIMENSION records. - * Excel(2007) tolerates this, so POI should too. - */ - @Test - void testMissingDims() { - - int rowIx = 5; - int colIx = 6; - NumberRecord nr = new NumberRecord(); - nr.setRow(rowIx); - nr.setColumn((short) colIx); - nr.setValue(3.0); - - List inRecs = new ArrayList<>(); - inRecs.add(BOFRecord.createSheetBOF()); - inRecs.add(new RowRecord(rowIx)); - inRecs.add(nr); - inRecs.add(createWindow2Record()); - inRecs.add(EOFRecord.instance); - InternalSheet sheet = createSheet(inRecs); - - List outRecs = new ArrayList<>(); - sheet.visitContainedRecords(outRecs::add, rowIx); - assertEquals(8, outRecs.size()); - DimensionsRecord dims = (DimensionsRecord) outRecs.get(5); - assertEquals(rowIx, dims.getFirstRow()); - assertEquals(rowIx, dims.getLastRow()); - assertEquals(colIx, dims.getFirstCol()); - assertEquals(colIx, dims.getLastCol()); - } - - /** - * Prior to the fix for bug 46547, shifting formulas would have the side-effect - * of creating a {@link ConditionalFormattingTable}. There was no impairment to - * functionality since empty record aggregates are equivalent to missing record - * aggregates. However, since this unnecessary creation helped expose bug 46547b, - * and since there is a slight performance hit the fix was made to avoid it. - */ - @Test - void testShiftFormulasAddCondFormat_bug46547() { - // Create a sheet with data validity (similar to bugzilla attachment id=23131). - InternalSheet sheet = InternalSheet.createSheet(); - - List sheetRecs = sheet.getRecords(); - assertEquals(23, sheetRecs.size()); - - FormulaShifter shifter = FormulaShifter.createForRowShift(0, "", 0, 0, 1, SpreadsheetVersion.EXCEL97); - sheet.updateFormulasAfterCellShift(shifter, 0); - assertFalse(sheetRecs.size() == 24 && sheetRecs.get(22) instanceof ConditionalFormattingTable); - assertEquals(23, sheetRecs.size()); - } - /** - * Bug 46547 happened when attempting to add conditional formatting to a sheet - * which already had data validity constraints. - */ - @Test - void testAddCondFormatAfterDataValidation_bug46547() { - // Create a sheet with data validity (similar to bugzilla attachment id=23131). - InternalSheet sheet = InternalSheet.createSheet(); - sheet.getOrCreateDataValidityTable(); - - // attempt to add conditional formatting - ConditionalFormattingTable cft = sheet.getConditionalFormattingTable(); - assertNotNull(cft); - } - - @Test - void testCloneMulBlank_bug46776() { - org.apache.poi.hssf.record.Record[] recs = { - InternalSheet.createBOF(), - new DimensionsRecord(), - new RowRecord(1), - new MulBlankRecord(1, 3, new short[] { 0x0F, 0x0F, 0x0F, } ), - new RowRecord(2), - createWindow2Record(), - EOFRecord.instance, - }; - - InternalSheet sheet = createSheet(Arrays.asList(recs)); - - InternalSheet sheet2 = sheet.cloneSheet(); - - List clonedRecs = new ArrayList<>(); - sheet2.visitContainedRecords(clonedRecs::add, 0); - // +2 for INDEX and DBCELL - assertEquals(recs.length+2, clonedRecs.size()); - } - - @Test - void testCreateAggregate() { - String msoDrawingRecord1 = - "0F 00 02 F0 20 01 00 00 10 00 08 F0 08 00 00 00 \n" + - "03 00 00 00 02 04 00 00 0F 00 03 F0 08 01 00 00 \n" + - "0F 00 04 F0 28 00 00 00 01 00 09 F0 10 00 00 00 \n" + - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \n" + - "02 00 0A F0 08 00 00 00 00 04 00 00 05 00 00 00 \n" + - "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 \n" + - "01 04 00 00 00 0A 00 00 73 00 0B F0 2A 00 00 00 \n" + - "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 \n" + - "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 \n" + - "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 \n" + - "00 00 00 00 01 00 54 00 05 00 45 00 01 00 88 03 \n" + - "05 00 94 00 00 00 11 F0 00 00 00 00"; - - String msoDrawingRecord2 = - "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 " + - "02 04 00 00 80 0A 00 00 73 00 0B F0 2A 00 00 00 " + - "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 " + - "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 " + - "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 " + - "00 00 00 00 01 00 8D 03 05 00 E4 00 03 00 4D 03 " + - "0B 00 0C 00 00 00 11 F0 00 00 00 00"; - - DrawingRecord d1 = new DrawingRecord(); - d1.setData( HexRead.readFromString( msoDrawingRecord1 ) ); - - ObjRecord r1 = new ObjRecord(); - - DrawingRecord d2 = new DrawingRecord(); - d2.setData( HexRead.readFromString( msoDrawingRecord2 ) ); - - TextObjectRecord r2 = new TextObjectRecord(); - r2.setStr(new HSSFRichTextString("Aggregated")); - NoteRecord n2 = new NoteRecord(); - - List recordStream = new ArrayList<>(); - recordStream.add(InternalSheet.createBOF()); - recordStream.add( d1 ); - recordStream.add( r1 ); - recordStream.add(createWindow2Record()); - recordStream.add(EOFRecord.instance); - - confirmAggregatedRecords(recordStream); - - - recordStream = new ArrayList<>(); - recordStream.add(InternalSheet.createBOF()); - recordStream.add( d1 ); - recordStream.add( r1 ); - recordStream.add( d2 ); - recordStream.add( r2 ); - recordStream.add(createWindow2Record()); - recordStream.add(EOFRecord.instance); - - confirmAggregatedRecords(recordStream); - - recordStream = new ArrayList<>(); - recordStream.add(InternalSheet.createBOF()); - recordStream.add( d1 ); - recordStream.add( r1 ); - recordStream.add( d2 ); - recordStream.add( r2 ); - recordStream.add( n2 ); - recordStream.add(createWindow2Record()); - recordStream.add(EOFRecord.instance); - - confirmAggregatedRecords(recordStream); - } - - private void confirmAggregatedRecords(List recordStream){ - InternalSheet sheet = InternalSheet.createSheet(); - sheet.getRecords().clear(); - sheet.getRecords().addAll(recordStream); - - List sheetRecords = sheet.getRecords(); - - DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord() ); - sheet.aggregateDrawingRecords(drawingManager, false); - - assertEquals(4, sheetRecords.size()); - assertEquals(BOFRecord.sid, ((org.apache.poi.hssf.record.Record)sheetRecords.get(0)).getSid()); - assertEquals(EscherAggregate.sid, ((org.apache.poi.hssf.record.Record)sheetRecords.get(1)).getSid()); - assertEquals(WindowTwoRecord.sid, ((org.apache.poi.hssf.record.Record)sheetRecords.get(2)).getSid()); - assertEquals(EOFRecord.sid, ((org.apache.poi.hssf.record.Record)sheetRecords.get(3)).getSid()); - } - - @Test - void testSheetDimensions() { - InternalSheet sheet = InternalSheet.createSheet(); - DimensionsRecord dimensions = (DimensionsRecord)sheet.findFirstRecordBySid(DimensionsRecord.sid); - assertNotNull(dimensions); - assertEquals(0, dimensions.getFirstCol()); - assertEquals(0, dimensions.getFirstRow()); - assertEquals(1, dimensions.getLastCol()); // plus pne - assertEquals(1, dimensions.getLastRow()); // plus pne - - RowRecord rr = new RowRecord(0); - sheet.addRow(rr); - - assertEquals(0, dimensions.getFirstCol()); - assertEquals(0, dimensions.getFirstRow()); - assertEquals(1, dimensions.getLastCol()); - assertEquals(1, dimensions.getLastRow()); - - CellValueRecordInterface cvr; - - cvr = new BlankRecord(); - cvr.setColumn((short)0); - cvr.setRow(0); - sheet.addValueRecord(0, cvr); - - assertEquals(0, dimensions.getFirstCol()); - assertEquals(0, dimensions.getFirstRow()); - assertEquals(1, dimensions.getLastCol()); - assertEquals(1, dimensions.getLastRow()); - - cvr = new BlankRecord(); - cvr.setColumn((short)1); - cvr.setRow(0); - sheet.addValueRecord(0, cvr); - - assertEquals(0, dimensions.getFirstCol()); - assertEquals(0, dimensions.getFirstRow()); - assertEquals(2, dimensions.getLastCol()); //YK: failed until Bugzilla 53414 was fixed - assertEquals(1, dimensions.getLastRow()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java b/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java deleted file mode 100644 index c58dd39849..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.apache.poi.hssf.record.ColumnInfoRecord; -import org.junit.jupiter.api.Test; - -final class TestSheetAdditional { - @Test - void testGetCellWidth() { - InternalSheet sheet = InternalSheet.createSheet(); - ColumnInfoRecord nci = new ColumnInfoRecord(); - - // Prepare test model - nci.setFirstColumn(5); - nci.setLastColumn(10); - nci.setColumnWidth(100); - - - sheet._columnInfos.insertColumn(nci); - - assertEquals(100,sheet.getColumnWidth(5)); - assertEquals(100,sheet.getColumnWidth(6)); - assertEquals(100,sheet.getColumnWidth(7)); - assertEquals(100,sheet.getColumnWidth(8)); - assertEquals(100,sheet.getColumnWidth(9)); - assertEquals(100,sheet.getColumnWidth(10)); - - sheet.setColumnWidth(6,200); - - assertEquals(100,sheet.getColumnWidth(5)); - assertEquals(200,sheet.getColumnWidth(6)); - assertEquals(100,sheet.getColumnWidth(7)); - assertEquals(100,sheet.getColumnWidth(8)); - assertEquals(100,sheet.getColumnWidth(9)); - assertEquals(100,sheet.getColumnWidth(10)); - } - - @Test - void testMaxColumnWidth() { - InternalSheet sheet = InternalSheet.createSheet(); - // the limit - sheet.setColumnWidth(0, 255*256); - - // over the limit - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> sheet.setColumnWidth(0, 256*256) - ); - assertEquals("The maximum column width for an individual cell is 255 characters.", ex.getMessage()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java b/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java deleted file mode 100644 index ba63dc70b7..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java +++ /dev/null @@ -1,173 +0,0 @@ -/* ==================================================================== - 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.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.record.CountryRecord; -import org.apache.poi.hssf.record.FontRecord; -import org.apache.poi.hssf.record.RecalcIdRecord; -import org.apache.poi.hssf.record.WriteAccessRecord; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.TestHSSFWorkbook; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; -import org.apache.poi.ss.formula.udf.DefaultUDFFinder; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.junit.jupiter.api.Test; - -/** - * Unit test for the Workbook class. - */ -final class TestWorkbook { - @Test - void testFontStuff() throws IOException { - HSSFWorkbook hwb = new HSSFWorkbook(); - InternalWorkbook wb = TestHSSFWorkbook.getInternalWorkbook(hwb); - - assertEquals(4, wb.getNumberOfFontRecords()); - assertEquals(68, wb.getRecords().size()); - - FontRecord f1 = wb.getFontRecordAt(0); - FontRecord f4 = wb.getFontRecordAt(3); - - assertEquals(0, wb.getFontIndex(f1)); - assertEquals(3, wb.getFontIndex(f4)); - - assertEquals(f1, wb.getFontRecordAt(0)); - assertEquals(f4, wb.getFontRecordAt(3)); - - // There is no 4! new ones go in at 5 - - FontRecord n = wb.createNewFont(); - assertEquals(69, wb.getRecords().size()); - assertEquals(5, wb.getNumberOfFontRecords()); - assertEquals(5, wb.getFontIndex(n)); - assertEquals(n, wb.getFontRecordAt(5)); - - // And another - FontRecord n6 = wb.createNewFont(); - assertEquals(70, wb.getRecords().size()); - assertEquals(6, wb.getNumberOfFontRecords()); - assertEquals(6, wb.getFontIndex(n6)); - assertEquals(n6, wb.getFontRecordAt(6)); - - - // Now remove the one formerly at 5 - assertEquals(70, wb.getRecords().size()); - wb.removeFontRecord(n); - - // Check that 6 has gone to 5 - assertEquals(69, wb.getRecords().size()); - assertEquals(5, wb.getNumberOfFontRecords()); - assertEquals(5, wb.getFontIndex(n6)); - assertEquals(n6, wb.getFontRecordAt(5)); - - // Check that the earlier ones are unchanged - assertEquals(0, wb.getFontIndex(f1)); - assertEquals(3, wb.getFontIndex(f4)); - assertEquals(f1, wb.getFontRecordAt(0)); - assertEquals(f4, wb.getFontRecordAt(3)); - - // Finally, add another one - FontRecord n7 = wb.createNewFont(); - assertEquals(70, wb.getRecords().size()); - assertEquals(6, wb.getNumberOfFontRecords()); - assertEquals(6, wb.getFontIndex(n7)); - assertEquals(n7, wb.getFontRecordAt(6)); - - hwb.close(); - } - - @Test - void testAddNameX() throws IOException { - HSSFWorkbook hwb = new HSSFWorkbook(); - InternalWorkbook wb = TestHSSFWorkbook.getInternalWorkbook(hwb); - assertNotNull(wb.getNameXPtg("ISODD", AggregatingUDFFinder.DEFAULT)); - - FreeRefFunction NotImplemented = (args, ec) -> { - throw new RuntimeException("not implemented"); - }; - - /* - * register the two test UDFs in a UDF finder, to be passed to the evaluator - */ - UDFFinder udff1 = new DefaultUDFFinder(new String[] { "myFunc", }, - new FreeRefFunction[] { NotImplemented }); - UDFFinder udff2 = new DefaultUDFFinder(new String[] { "myFunc2", }, - new FreeRefFunction[] { NotImplemented }); - UDFFinder udff = new AggregatingUDFFinder(udff1, udff2); - assertNotNull(wb.getNameXPtg("myFunc", udff)); - assertNotNull(wb.getNameXPtg("myFunc2", udff)); - - assertNull(wb.getNameXPtg("myFunc3", udff)); // myFunc3 is unknown - - hwb.close(); - } - - @Test - void testRecalcId() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - assertFalse(wb.getForceFormulaRecalculation()); - - InternalWorkbook iwb = TestHSSFWorkbook.getInternalWorkbook(wb); - int countryPos = iwb.findFirstRecordLocBySid(CountryRecord.sid); - assertTrue(countryPos != -1); - // RecalcIdRecord is not present in new workbooks - assertNull(iwb.findFirstRecordBySid(RecalcIdRecord.sid)); - RecalcIdRecord record = iwb.getRecalcId(); - assertNotNull(record); - assertSame(record, iwb.getRecalcId()); - - assertSame(record, iwb.findFirstRecordBySid(RecalcIdRecord.sid)); - assertEquals(countryPos + 1, iwb.findFirstRecordLocBySid(RecalcIdRecord.sid)); - - record.setEngineId(100); - assertEquals(100, record.getEngineId()); - assertTrue(wb.getForceFormulaRecalculation()); - - wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero - assertEquals(0, record.getEngineId()); - assertFalse(wb.getForceFormulaRecalculation()); - - wb.close(); - } - - @Test - void testWriteAccess() { - HSSFWorkbook wb = new HSSFWorkbook(); - InternalWorkbook iwb = TestHSSFWorkbook.getInternalWorkbook(wb); - - int oldRecordsCount = iwb.getNumRecords(); - assertEquals(68, oldRecordsCount, "records count"); - - WriteAccessRecord writeAccess = iwb.getWriteAccess(); - assertNotNull(writeAccess); - assertEquals(WriteAccessRecord.sid, writeAccess.getSid()); - - int newRecordsCount = iwb.getNumRecords(); - assertEquals(oldRecordsCount, newRecordsCount, "records count after getWriteAccess"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestWorkbookRecordList.java b/src/testcases/org/apache/poi/hssf/model/TestWorkbookRecordList.java deleted file mode 100644 index bc610c42e8..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestWorkbookRecordList.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - 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.model; - -import org.apache.poi.hssf.record.chart.ChartRecord; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -import java.io.IOException; - -import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class TestWorkbookRecordList { - - @Test - public void tabposIsOnlyUpdatedIfWorkbookHasTabIdRecord() throws IOException { - try (HSSFWorkbook wb = openSampleWorkbook("55982.xls")) { - WorkbookRecordList records = wb.getInternalWorkbook().getWorkbookRecordList(); - assertEquals(-1, records.getTabpos()); - - // Add an arbitrary record to the front of the list - records.add(0, new ChartRecord()); - - assertEquals(-1, records.getTabpos()); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java b/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java deleted file mode 100644 index 8433fb4cb1..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.CellRangeAddress8Bit; -import org.apache.poi.ss.formula.Formula; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaRenderer; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -final class TestArrayRecord { - - @Test - void testRead() { - String hex = - "21 02 25 00 01 00 01 00 01 01 00 00 00 00 00 00 " + - "17 00 65 00 00 01 00 02 C0 02 C0 65 00 00 01 00 " + - "03 C0 03 C0 04 62 01 07 00"; - byte[] data = HexRead.readFromString(hex); - RecordInputStream in = TestcaseRecordInputStream.create(data); - ArrayRecord r1 = new ArrayRecord(in); - CellRangeAddress8Bit range = r1.getRange(); - assertEquals(1, range.getFirstColumn()); - assertEquals(1, range.getLastColumn()); - assertEquals(1, range.getFirstRow()); - assertEquals(1, range.getLastRow()); - - Ptg[] ptg = r1.getFormulaTokens(); - assertEquals("MAX(C1:C2-D1:D2)", FormulaRenderer.toFormulaString(null, ptg)); - - //construct a new ArrayRecord with the same contents as r1 - Ptg[] fmlaPtg = FormulaParser.parse("MAX(C1:C2-D1:D2)", null, FormulaType.ARRAY, 0); - ArrayRecord r2 = new ArrayRecord(Formula.create(fmlaPtg), new CellRangeAddress8Bit(1, 1, 1, 1)); - byte[] ser = r2.serialize(); - //serialize and check that the data is the same as in r1 - assertEquals(HexDump.toHex(data), HexDump.toHex(ser)); - } - - @Test - void testBug57231() { - HSSFWorkbook wb = HSSFTestDataSamples - .openSampleWorkbook("57231_MixedGasReport.xls"); - HSSFSheet sheet = wb.getSheet("master"); - - HSSFSheet newSheet = wb.cloneSheet(wb.getSheetIndex(sheet)); - int idx = wb.getSheetIndex(newSheet); - wb.setSheetName(idx, "newName"); - - // Write the output to a file - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wbBack); - - assertNotNull(wbBack.getSheet("master")); - assertNotNull(wbBack.getSheet("newName")); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java b/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java deleted file mode 100644 index 9c855f8b3e..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** - * Tests the AutoFilterInfoRecord class. - */ -final class TestAutoFilterInfoRecord { - private final byte[] data = new byte[] { - 0x05, 0x00 - }; - - @Test - void testRead() { - - AutoFilterInfoRecord record = new AutoFilterInfoRecord(TestcaseRecordInputStream.create(AutoFilterInfoRecord.sid, data)); - - assertEquals(AutoFilterInfoRecord.sid, record.getSid()); - assertEquals(data.length, record.getDataSize()); - assertEquals(5, record.getNumEntries()); - record.setNumEntries((short)3); - assertEquals(3, record.getNumEntries()); - } - - @Test - void testWrite() { - AutoFilterInfoRecord record = new AutoFilterInfoRecord(); - record.setNumEntries((short)3); - - byte [] ser = record.serialize(); - assertEquals(ser.length - 4, data.length); - record = new AutoFilterInfoRecord(TestcaseRecordInputStream.create(ser)); - assertEquals(3, record.getNumEntries()); - } - - @Test - void testClone() - { - AutoFilterInfoRecord record = new AutoFilterInfoRecord(); - record.setNumEntries((short)3); - byte[] src = record.serialize(); - - AutoFilterInfoRecord cloned = record.copy(); - assertEquals(3, record.getNumEntries()); - byte[] cln = cloned.serialize(); - - assertEquals(record.getDataSize(), cloned.getDataSize()); - assertArrayEquals(src, cln); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java deleted file mode 100644 index bbf5bf3549..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Sheet; -import org.junit.jupiter.api.Test; - -final class TestBOFRecord { - @Test - void testBOFRecord() throws IOException { - // This used to throw an error before - #42794 - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("bug_42794.xls")) { - Sheet sh = wb.getSheetAt(0); - for (int i=1; i<=10; i++) { - double act = sh.getRow(i).getCell(0).getNumericCellValue(); - assertEquals(i, act, 0); - } - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java deleted file mode 100644 index 700f415f07..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link BoolErrRecord} - */ -final class TestBoolErrRecord { - - @Test - void testError() { - byte[] data = HexRead.readFromString( - "00 00 00 00 0F 00 " + // row, col, xfIndex - "07 01 " // #DIV/0!, isError - ); - - RecordInputStream in = TestcaseRecordInputStream.create(BoolErrRecord.sid, data); - BoolErrRecord ber = new BoolErrRecord(in); - assertTrue(ber.isError()); - assertEquals(7, ber.getErrorValue()); - - TestcaseRecordInputStream.confirmRecordEncoding(BoolErrRecord.sid, data, ber.serialize()); - } - - /** - * Bugzilla 47479 was due to an apparent error in OOO which (as of version 3.0.1) - * writes the value field of BOOLERR records as 2 bytes instead of 1.
- * Coincidentally, the extra byte written is zero, which is exactly the value - * required by the isError field. This probably why Excel seems to have - * no problem. OOO does not have the same bug for error values (which wouldn't - * work by the same coincidence). - */ - @Test - void testOooBadFormat_bug47479() { - byte[] data = HexRead.readFromString( - "05 02 09 00 " + // sid, size - "00 00 00 00 0F 00 " + // row, col, xfIndex - "01 00 00 " // extra 00 byte here - ); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - BoolErrRecord ber = new BoolErrRecord(in); - boolean hasMore = in.hasNextRecord(); - assertFalse(hasMore); - assertTrue(ber.isBoolean()); - assertTrue(ber.getBooleanValue()); - - // Check that the record re-serializes correctly - byte[] outData = ber.serialize(); - byte[] expData = HexRead.readFromString( - "05 02 08 00 " + - "00 00 00 00 0F 00 " + - "01 00 " // normal number of data bytes - ); - assertArrayEquals(expData, outData); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java deleted file mode 100644 index 3ee14a90ba..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java +++ /dev/null @@ -1,123 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests BoundSheetRecord. - */ -final class TestBoundSheetRecord { - - @Test - void testRecordLength() { - BoundSheetRecord record = new BoundSheetRecord("Sheet1"); - assertEquals(18, record.getRecordSize()); - } - - @Test - void testWideRecordLength() { - BoundSheetRecord record = new BoundSheetRecord("Sheet\u20ac"); - assertEquals(24, record.getRecordSize()); - } - - @Test - void testName() { - BoundSheetRecord record = new BoundSheetRecord("1234567890223456789032345678904"); - assertThrows(IllegalArgumentException.class, () -> record.setSheetname("s//*s")); - } - - @Test - void testDeserializeUnicode() { - - byte[] data = HexRead.readFromString("" - + "85 00 1A 00" // sid, length - + "3C 09 00 00" // bof - + "00 00"// flags - + "09 01" // str-len. unicode flag - // string data - + "21 04 42 04 40 04" - + "30 04 3D 04 38 04" - + "47 04 3A 04 30 04" - ); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - BoundSheetRecord bsr = new BoundSheetRecord(in); - // sheet name is unicode Russian for 'minor page' - assertEquals("\u0421\u0442\u0440\u0430\u043D\u0438\u0447\u043A\u0430", bsr.getSheetname()); - - byte[] data2 = bsr.serialize(); - assertArrayEquals(data, data2); - } - - @Test - void testOrdering() { - BoundSheetRecord bs1 = new BoundSheetRecord("SheetB"); - BoundSheetRecord bs2 = new BoundSheetRecord("SheetC"); - BoundSheetRecord bs3 = new BoundSheetRecord("SheetA"); - bs1.setPositionOfBof(11); - bs2.setPositionOfBof(33); - bs3.setPositionOfBof(22); - - List l = new ArrayList<>(); - l.add(bs1); - l.add(bs2); - l.add(bs3); - - BoundSheetRecord[] r = BoundSheetRecord.orderByBofPosition(l); - assertEquals(3, r.length); - assertEquals(bs1, r[0]); - assertEquals(bs3, r[1]); - assertEquals(bs2, r[2]); - } - - @Test - void testValidNames() { - assertTrue(isValid("Sheet1")); - assertTrue(isValid("O'Brien's sales")); - assertTrue(isValid(" data # ")); - assertTrue(isValid("data $1.00")); - - assertFalse(isValid("data?")); - assertFalse(isValid("abc/def")); - assertFalse(isValid("data[0]")); - assertFalse(isValid("data*")); - assertFalse(isValid("abc\\def")); - assertFalse(isValid("'data")); - assertFalse(isValid("data'")); - } - - private static boolean isValid(String sheetName) { - try { - new BoundSheetRecord(sheetName); - return true; - } catch (IllegalArgumentException e) { - return false; - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java deleted file mode 100644 index 0a43dbfdb6..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java +++ /dev/null @@ -1,202 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the {@link CFHeaderRecord} - * and {@link CFHeader12Record} classes works correctly. - */ -final class TestCFHeaderRecord { - @Test - void testCreateCFHeaderRecord () { - CFHeaderRecord record = new CFHeaderRecord(); - CellRangeAddress[] ranges = { - new CellRangeAddress(0,0xFFFF,5,5), - new CellRangeAddress(0,0xFFFF,6,6), - new CellRangeAddress(0,1,0,1), - new CellRangeAddress(0,1,2,3), - new CellRangeAddress(2,3,0,1), - new CellRangeAddress(2,3,2,3), - }; - record.setCellRanges(ranges); - ranges = record.getCellRanges(); - assertEquals(6,ranges.length); - CellRangeAddress enclosingCellRange = record.getEnclosingCellRange(); - assertEquals(0, enclosingCellRange.getFirstRow()); - assertEquals(65535, enclosingCellRange.getLastRow()); - assertEquals(0, enclosingCellRange.getFirstColumn()); - assertEquals(6, enclosingCellRange.getLastColumn()); - - assertFalse(record.getNeedRecalculation()); - assertEquals(0, record.getID()); - - record.setNeedRecalculation(true); - assertTrue(record.getNeedRecalculation()); - assertEquals(0, record.getID()); - - record.setID(7); - record.setNeedRecalculation(false); - assertFalse(record.getNeedRecalculation()); - assertEquals(7, record.getID()); - } - - @Test - void testCreateCFHeader12Record () { - CFHeader12Record record = new CFHeader12Record(); - CellRangeAddress[] ranges = { - new CellRangeAddress(0,0xFFFF,5,5), - new CellRangeAddress(0,0xFFFF,6,6), - new CellRangeAddress(0,1,0,1), - new CellRangeAddress(0,1,2,3), - new CellRangeAddress(2,3,0,1), - new CellRangeAddress(2,3,2,3), - }; - record.setCellRanges(ranges); - ranges = record.getCellRanges(); - assertEquals(6,ranges.length); - CellRangeAddress enclosingCellRange = record.getEnclosingCellRange(); - assertEquals(0, enclosingCellRange.getFirstRow()); - assertEquals(65535, enclosingCellRange.getLastRow()); - assertEquals(0, enclosingCellRange.getFirstColumn()); - assertEquals(6, enclosingCellRange.getLastColumn()); - - assertFalse(record.getNeedRecalculation()); - assertEquals(0, record.getID()); - - record.setNeedRecalculation(true); - assertTrue(record.getNeedRecalculation()); - assertEquals(0, record.getID()); - - record.setID(7); - record.setNeedRecalculation(false); - assertFalse(record.getNeedRecalculation()); - assertEquals(7, record.getID()); - } - - @Test - void testSerialization() { - byte[] recordData = - { - (byte)0x03, (byte)0x00, - (byte)0x01, (byte)0x00, - - (byte)0x00, (byte)0x00, - (byte)0x03, (byte)0x00, - (byte)0x00, (byte)0x00, - (byte)0x03, (byte)0x00, - - (byte)0x04, (byte)0x00, // nRegions - - (byte)0x00, (byte)0x00, - (byte)0x01, (byte)0x00, - (byte)0x00, (byte)0x00, - (byte)0x01, (byte)0x00, - - (byte)0x00, (byte)0x00, - (byte)0x01, (byte)0x00, - (byte)0x02, (byte)0x00, - (byte)0x03, (byte)0x00, - - (byte)0x02, (byte)0x00, - (byte)0x03, (byte)0x00, - (byte)0x00, (byte)0x00, - (byte)0x01, (byte)0x00, - - (byte)0x02, (byte)0x00, - (byte)0x03, (byte)0x00, - (byte)0x02, (byte)0x00, - (byte)0x03, (byte)0x00, - }; - - CFHeaderRecord record = new CFHeaderRecord(TestcaseRecordInputStream.create(CFHeaderRecord.sid, recordData)); - - assertEquals(3, record.getNumberOfConditionalFormats(), "#CFRULES"); - assertTrue(record.getNeedRecalculation()); - confirm(record.getEnclosingCellRange(), 0, 3, 0, 3); - CellRangeAddress[] ranges = record.getCellRanges(); - assertEquals(4, ranges.length); - confirm(ranges[0], 0, 1, 0, 1); - confirm(ranges[1], 0, 1, 2, 3); - confirm(ranges[2], 2, 3, 0, 1); - confirm(ranges[3], 2, 3, 2, 3); - assertEquals(recordData.length+4, record.getRecordSize()); - - byte[] output = record.serialize(); - confirmRecordEncoding(CFHeaderRecord.sid, recordData, output); - } - - @Test - void testExtremeRows() { - byte[] recordData = { - (byte)0x13, (byte)0x00, // nFormats - (byte)0x00, (byte)0x00, - - (byte)0x00, (byte)0x00, - (byte)0xFF, (byte)0xFF, - (byte)0x00, (byte)0x00, - (byte)0xFF, (byte)0x00, - - (byte)0x03, (byte)0x00, // nRegions - - (byte)0x40, (byte)0x9C, - (byte)0x50, (byte)0xC3, - (byte)0x02, (byte)0x00, - (byte)0x02, (byte)0x00, - - (byte)0x00, (byte)0x00, - (byte)0xFF, (byte)0xFF, - (byte)0x05, (byte)0x00, - (byte)0x05, (byte)0x00, - - (byte)0x07, (byte)0x00, - (byte)0x07, (byte)0x00, - (byte)0x00, (byte)0x00, - (byte)0xFF, (byte)0x00, - }; - - // bug 44739b - invalid cell range (-25536, 2, -15536, 2) - CFHeaderRecord record = new CFHeaderRecord(TestcaseRecordInputStream.create(CFHeaderRecord.sid, recordData)); - - assertEquals(19, record.getNumberOfConditionalFormats(), "#CFRULES"); - assertFalse(record.getNeedRecalculation()); - confirm(record.getEnclosingCellRange(), 0, 65535, 0, 255); - CellRangeAddress[] ranges = record.getCellRanges(); - assertEquals(3, ranges.length); - confirm(ranges[0], 40000, 50000, 2, 2); - confirm(ranges[1], 0, 65535, 5, 5); - confirm(ranges[2], 7, 7, 0, 255); - - byte[] output = record.serialize(); - confirmRecordEncoding(CFHeaderRecord.sid, recordData, output); - } - - private static void confirm(CellRangeAddress cr, int expFirstRow, int expLastRow, int expFirstCol, int expLastColumn) { - assertEquals(expFirstRow, cr.getFirstRow(), "first row"); - assertEquals(expLastRow, cr.getLastRow(), "last row"); - assertEquals(expFirstCol, cr.getFirstColumn(), "first column"); - assertEquals(expLastColumn, cr.getLastColumn(), "last column"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java deleted file mode 100644 index 81689f140c..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java +++ /dev/null @@ -1,453 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator; -import org.apache.poi.hssf.record.cf.BorderFormatting; -import org.apache.poi.hssf.record.cf.FontFormatting; -import org.apache.poi.hssf.record.cf.PatternFormatting; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefNPtg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold.RangeType; -import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet; -import org.apache.poi.util.LittleEndian; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the TestCFRuleRecord - * class works correctly. - */ -final class TestCFRuleRecord { - @Test - void testConstructors () throws IOException { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFSheet sheet = workbook.createSheet(); - - CFRuleRecord rule1 = CFRuleRecord.create(sheet, "7"); - assertEquals(CFRuleBase.CONDITION_TYPE_FORMULA, rule1.getConditionType()); - assertEquals(ComparisonOperator.NO_COMPARISON, rule1.getComparisonOperation()); - assertNotNull(rule1.getParsedExpression1()); - assertSame(Ptg.EMPTY_PTG_ARRAY, rule1.getParsedExpression2()); - - CFRuleRecord rule2 = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5"); - assertEquals(CFRuleBase.CONDITION_TYPE_CELL_VALUE_IS, rule2.getConditionType()); - assertEquals(ComparisonOperator.BETWEEN, rule2.getComparisonOperation()); - assertNotNull(rule2.getParsedExpression1()); - assertNotNull(rule2.getParsedExpression2()); - - CFRuleRecord rule3 = CFRuleRecord.create(sheet, ComparisonOperator.EQUAL, null, null); - assertEquals(CFRuleBase.CONDITION_TYPE_CELL_VALUE_IS, rule3.getConditionType()); - assertEquals(ComparisonOperator.EQUAL, rule3.getComparisonOperation()); - assertSame(Ptg.EMPTY_PTG_ARRAY, rule3.getParsedExpression2()); - assertSame(Ptg.EMPTY_PTG_ARRAY, rule3.getParsedExpression2()); - } - } - - @SuppressWarnings("squid:S2699") - @Test - void testCreateCFRuleRecord() throws IOException { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFSheet sheet = workbook.createSheet(); - CFRuleRecord record = CFRuleRecord.create(sheet, "7"); - testCFRuleRecord(record); - - // Serialize - byte[] serializedRecord = record.serialize(); - - // Strip header - byte[] recordData = Arrays.copyOfRange(serializedRecord, 4, serializedRecord.length); - - // Deserialize - record = new CFRuleRecord(TestcaseRecordInputStream.create(CFRuleRecord.sid, recordData)); - - // Serialize again - byte[] output = record.serialize(); - confirmRecordEncoding(CFRuleRecord.sid, recordData, output); - } - } - - @SuppressWarnings("squid:S2699") - @Test - void testCreateCFRule12Record() throws IOException { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFSheet sheet = workbook.createSheet(); - CFRule12Record record = CFRule12Record.create(sheet, "7"); - testCFRule12Record(record); - - // Serialize - byte[] serializedRecord = record.serialize(); - - // Strip header - byte[] recordData = Arrays.copyOfRange(serializedRecord, 4, serializedRecord.length); - - // Deserialize - record = new CFRule12Record(TestcaseRecordInputStream.create(CFRule12Record.sid, recordData)); - - // Serialize again - byte[] output = record.serialize(); - confirmRecordEncoding(CFRule12Record.sid, recordData, output); - } - } - - @Test - void testCreateIconCFRule12Record() throws IOException { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFSheet sheet = workbook.createSheet(); - CFRule12Record record = CFRule12Record.create(sheet, IconSet.GREY_5_ARROWS); - record.getMultiStateFormatting().getThresholds()[1].setType(RangeType.PERCENT.id); - record.getMultiStateFormatting().getThresholds()[1].setValue(10d); - record.getMultiStateFormatting().getThresholds()[2].setType(RangeType.NUMBER.id); - record.getMultiStateFormatting().getThresholds()[2].setValue(-4d); - - // Check it - testCFRule12Record(record); - assertEquals(IconSet.GREY_5_ARROWS, record.getMultiStateFormatting().getIconSet()); - assertEquals(5, record.getMultiStateFormatting().getThresholds().length); - - // Serialize - byte[] serializedRecord = record.serialize(); - - // Strip header - byte[] recordData = Arrays.copyOfRange(serializedRecord, 4, serializedRecord.length); - - // Deserialize - record = new CFRule12Record(TestcaseRecordInputStream.create(CFRule12Record.sid, recordData)); - - // Check it has the icon, and the right number of thresholds - assertEquals(IconSet.GREY_5_ARROWS, record.getMultiStateFormatting().getIconSet()); - assertEquals(5, record.getMultiStateFormatting().getThresholds().length); - - // Serialize again - byte[] output = record.serialize(); - confirmRecordEncoding(CFRule12Record.sid, recordData, output); - } - } - - private void testCFRuleRecord(CFRuleRecord record) { - testCFRuleBase(record); - - assertFalse(record.isLeftBorderModified()); - record.setLeftBorderModified(true); - assertTrue(record.isLeftBorderModified()); - - assertFalse(record.isRightBorderModified()); - record.setRightBorderModified(true); - assertTrue(record.isRightBorderModified()); - - assertFalse(record.isTopBorderModified()); - record.setTopBorderModified(true); - assertTrue(record.isTopBorderModified()); - - assertFalse(record.isBottomBorderModified()); - record.setBottomBorderModified(true); - assertTrue(record.isBottomBorderModified()); - - assertFalse(record.isTopLeftBottomRightBorderModified()); - record.setTopLeftBottomRightBorderModified(true); - assertTrue(record.isTopLeftBottomRightBorderModified()); - - assertFalse(record.isBottomLeftTopRightBorderModified()); - record.setBottomLeftTopRightBorderModified(true); - assertTrue(record.isBottomLeftTopRightBorderModified()); - - - assertFalse(record.isPatternBackgroundColorModified()); - record.setPatternBackgroundColorModified(true); - assertTrue(record.isPatternBackgroundColorModified()); - - assertFalse(record.isPatternColorModified()); - record.setPatternColorModified(true); - assertTrue(record.isPatternColorModified()); - - assertFalse(record.isPatternStyleModified()); - record.setPatternStyleModified(true); - assertTrue(record.isPatternStyleModified()); - } - private void testCFRule12Record(CFRule12Record record) { - assertEquals(CFRule12Record.sid, record.getFutureRecordType()); - assertEquals("A1", record.getAssociatedRange().formatAsString()); - testCFRuleBase(record); - } - private void testCFRuleBase(CFRuleBase record) { - FontFormatting fontFormatting = new FontFormatting(); - testFontFormattingAccessors(fontFormatting); - assertFalse(record.containsFontFormattingBlock()); - record.setFontFormatting(fontFormatting); - assertTrue(record.containsFontFormattingBlock()); - - BorderFormatting borderFormatting = new BorderFormatting(); - testBorderFormattingAccessors(borderFormatting); - assertFalse(record.containsBorderFormattingBlock()); - record.setBorderFormatting(borderFormatting); - assertTrue(record.containsBorderFormattingBlock()); - - PatternFormatting patternFormatting = new PatternFormatting(); - testPatternFormattingAccessors(patternFormatting); - assertFalse(record.containsPatternFormattingBlock()); - record.setPatternFormatting(patternFormatting); - assertTrue(record.containsPatternFormattingBlock()); - } - - private void testPatternFormattingAccessors(PatternFormatting patternFormatting) { - patternFormatting.setFillBackgroundColor(HSSFColorPredefined.GREEN.getIndex()); - assertEquals(HSSFColorPredefined.GREEN.getIndex(),patternFormatting.getFillBackgroundColor()); - - patternFormatting.setFillForegroundColor(HSSFColorPredefined.INDIGO.getIndex()); - assertEquals(HSSFColorPredefined.INDIGO.getIndex(),patternFormatting.getFillForegroundColor()); - - patternFormatting.setFillPattern(PatternFormatting.DIAMONDS); - assertEquals(PatternFormatting.DIAMONDS,patternFormatting.getFillPattern()); - } - - private void testBorderFormattingAccessors(BorderFormatting borderFormatting) { - borderFormatting.setBackwardDiagonalOn(false); - assertFalse(borderFormatting.isBackwardDiagonalOn()); - borderFormatting.setBackwardDiagonalOn(true); - assertTrue(borderFormatting.isBackwardDiagonalOn()); - - borderFormatting.setBorderBottom(BorderFormatting.BORDER_DOTTED); - assertEquals(BorderFormatting.BORDER_DOTTED, borderFormatting.getBorderBottom()); - - borderFormatting.setBorderDiagonal(BorderFormatting.BORDER_MEDIUM); - assertEquals(BorderFormatting.BORDER_MEDIUM, borderFormatting.getBorderDiagonal()); - - borderFormatting.setBorderLeft(BorderFormatting.BORDER_MEDIUM_DASH_DOT_DOT); - assertEquals(BorderFormatting.BORDER_MEDIUM_DASH_DOT_DOT, borderFormatting.getBorderLeft()); - - borderFormatting.setBorderRight(BorderFormatting.BORDER_MEDIUM_DASHED); - assertEquals(BorderFormatting.BORDER_MEDIUM_DASHED, borderFormatting.getBorderRight()); - - borderFormatting.setBorderTop(BorderFormatting.BORDER_HAIR); - assertEquals(BorderFormatting.BORDER_HAIR, borderFormatting.getBorderTop()); - - borderFormatting.setBottomBorderColor(HSSFColorPredefined.AQUA.getIndex()); - assertEquals(HSSFColorPredefined.AQUA.getIndex(), borderFormatting.getBottomBorderColor()); - - borderFormatting.setDiagonalBorderColor(HSSFColorPredefined.RED.getIndex()); - assertEquals(HSSFColorPredefined.RED.getIndex(), borderFormatting.getDiagonalBorderColor()); - - assertFalse(borderFormatting.isForwardDiagonalOn()); - borderFormatting.setForwardDiagonalOn(true); - assertTrue(borderFormatting.isForwardDiagonalOn()); - - borderFormatting.setLeftBorderColor(HSSFColorPredefined.BLACK.getIndex()); - assertEquals(HSSFColorPredefined.BLACK.getIndex(), borderFormatting.getLeftBorderColor()); - - borderFormatting.setRightBorderColor(HSSFColorPredefined.BLUE.getIndex()); - assertEquals(HSSFColorPredefined.BLUE.getIndex(), borderFormatting.getRightBorderColor()); - - borderFormatting.setTopBorderColor(HSSFColorPredefined.GOLD.getIndex()); - assertEquals(HSSFColorPredefined.GOLD.getIndex(), borderFormatting.getTopBorderColor()); - } - - - private void testFontFormattingAccessors(FontFormatting fontFormatting) { - // Check for defaults - assertFalse(fontFormatting.isEscapementTypeModified()); - assertFalse(fontFormatting.isFontCancellationModified()); - assertFalse(fontFormatting.isFontOutlineModified()); - assertFalse(fontFormatting.isFontShadowModified()); - assertFalse(fontFormatting.isFontStyleModified()); - assertFalse(fontFormatting.isUnderlineTypeModified()); - assertFalse(fontFormatting.isFontWeightModified()); - - assertFalse(fontFormatting.isBold()); - assertFalse(fontFormatting.isItalic()); - assertFalse(fontFormatting.isOutlineOn()); - assertFalse(fontFormatting.isShadowOn()); - assertFalse(fontFormatting.isStruckout()); - - assertEquals(0, fontFormatting.getEscapementType()); - assertEquals(-1, fontFormatting.getFontColorIndex()); - assertEquals(-1, fontFormatting.getFontHeight()); - assertEquals(0, fontFormatting.getFontWeight()); - assertEquals(0, fontFormatting.getUnderlineType()); - - fontFormatting.setBold(true); - assertTrue(fontFormatting.isBold()); - fontFormatting.setBold(false); - assertFalse(fontFormatting.isBold()); - - fontFormatting.setEscapementType(org.apache.poi.ss.usermodel.Font.SS_SUB); - assertEquals(org.apache.poi.ss.usermodel.Font.SS_SUB, fontFormatting.getEscapementType()); - fontFormatting.setEscapementType(org.apache.poi.ss.usermodel.Font.SS_SUPER); - assertEquals(org.apache.poi.ss.usermodel.Font.SS_SUPER, fontFormatting.getEscapementType()); - fontFormatting.setEscapementType(org.apache.poi.ss.usermodel.Font.SS_NONE); - assertEquals(org.apache.poi.ss.usermodel.Font.SS_NONE, fontFormatting.getEscapementType()); - - fontFormatting.setEscapementTypeModified(false); - assertFalse(fontFormatting.isEscapementTypeModified()); - 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); - assertTrue(fontFormatting.isFontCancellationModified()); - - fontFormatting.setFontColorIndex((short)10); - assertEquals(10,fontFormatting.getFontColorIndex()); - - fontFormatting.setFontHeight(100); - assertEquals(100,fontFormatting.getFontHeight()); - - fontFormatting.setFontOutlineModified(false); - assertFalse(fontFormatting.isFontOutlineModified()); - fontFormatting.setFontOutlineModified(true); - assertTrue(fontFormatting.isFontOutlineModified()); - - fontFormatting.setFontShadowModified(false); - assertFalse(fontFormatting.isFontShadowModified()); - fontFormatting.setFontShadowModified(true); - assertTrue(fontFormatting.isFontShadowModified()); - - fontFormatting.setFontStyleModified(false); - assertFalse(fontFormatting.isFontStyleModified()); - fontFormatting.setFontStyleModified(true); - assertTrue(fontFormatting.isFontStyleModified()); - - fontFormatting.setItalic(false); - assertFalse(fontFormatting.isItalic()); - fontFormatting.setItalic(true); - assertTrue(fontFormatting.isItalic()); - - fontFormatting.setOutline(false); - assertFalse(fontFormatting.isOutlineOn()); - fontFormatting.setOutline(true); - assertTrue(fontFormatting.isOutlineOn()); - - fontFormatting.setShadow(false); - assertFalse(fontFormatting.isShadowOn()); - fontFormatting.setShadow(true); - assertTrue(fontFormatting.isShadowOn()); - - fontFormatting.setStrikeout(false); - assertFalse(fontFormatting.isStruckout()); - fontFormatting.setStrikeout(true); - assertTrue(fontFormatting.isStruckout()); - - fontFormatting.setUnderlineType(org.apache.poi.ss.usermodel.Font.U_DOUBLE_ACCOUNTING); - assertEquals(org.apache.poi.ss.usermodel.Font.U_DOUBLE_ACCOUNTING, fontFormatting.getUnderlineType()); - - fontFormatting.setUnderlineTypeModified(false); - assertFalse(fontFormatting.isUnderlineTypeModified()); - fontFormatting.setUnderlineTypeModified(true); - assertTrue(fontFormatting.isUnderlineTypeModified()); - } - - @Test - void testWrite() throws IOException { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFSheet sheet = workbook.createSheet(); - CFRuleRecord rr = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "5", "10"); - - PatternFormatting patternFormatting = new PatternFormatting(); - patternFormatting.setFillPattern(PatternFormatting.BRICKS); - rr.setPatternFormatting(patternFormatting); - - byte[] data = rr.serialize(); - assertEquals(26, data.length); - assertEquals(3, LittleEndian.getShort(data, 6)); - assertEquals(3, LittleEndian.getShort(data, 8)); - - int flags = LittleEndian.getInt(data, 10); - assertEquals(0x00380000, flags & 0x00380000, "unused flags should be 111"); - // Otherwise Excel gets unhappy - assertEquals(0, flags & 0x03C00000, "undocumented flags should be 0000"); - // check all remaining flag bits (some are not well understood yet) - assertEquals(0x203FFFFF, flags); - } - } - - private static final byte[] DATA_REFN = { - // formula extracted from bugzilla 45234 att 22141 - 1, 3, - 9, // formula 1 length - 0, 0, 0, -1, -1, 63, 32, 2, -128, 0, 0, 0, 5, - // formula 1: "=B3=1" (formula is relative to B4) - 76, -1, -1, 0, -64, // tRefN(B1) - 30, 1, 0, - 11, - }; - - /** - * tRefN and tAreaN tokens must be preserved when re-serializing conditional format formulas - */ - @Test - void testReserializeRefNTokens() { - - RecordInputStream is = TestcaseRecordInputStream.create(CFRuleRecord.sid, DATA_REFN); - CFRuleRecord rr = new CFRuleRecord(is); - Ptg[] ptgs = rr.getParsedExpression1(); - assertEquals(3, ptgs.length); - assertFalse(ptgs[0] instanceof RefPtg, "Identified bug 45234"); - assertEquals(RefNPtg.class, ptgs[0].getClass()); - RefNPtg refNPtg = (RefNPtg) ptgs[0]; - assertTrue(refNPtg.isColRelative()); - assertTrue(refNPtg.isRowRelative()); - - byte[] data = rr.serialize(); - confirmRecordEncoding(CFRuleRecord.sid, DATA_REFN, data); - } - - @Test - void testBug53691() throws IOException { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFSheet sheet = workbook.createSheet(); - - CFRuleRecord record = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5"); - - CFRuleRecord clone = record.copy(); - - byte[] serializedRecord = record.serialize(); - byte[] serializedClone = clone.serialize(); - assertArrayEquals(serializedRecord, serializedClone); - } - } - - @Test - void testBug57231_rewrite() throws IOException { - try (HSSFWorkbook wb1 = HSSFITestDataProvider.instance.openSampleWorkbook("57231_MixedGasReport.xls")) { - assertEquals(7, wb1.getNumberOfSheets()); - try (HSSFWorkbook wb2 = HSSFITestDataProvider.instance.writeOutAndReadBack(wb1)) { - assertEquals(7, wb2.getNumberOfSheets()); - } - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java b/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java deleted file mode 100644 index 6d472b9c2b..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link ColumnInfoRecord} - */ -final class TestColumnInfoRecord { - - @Test - void testBasic() { - byte[] data = HexRead.readFromString("7D 00 0C 00 14 00 9B 00 C7 19 0F 00 01 13 00 00"); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - ColumnInfoRecord cir = new ColumnInfoRecord(in); - assertEquals(0, in.remaining()); - - assertEquals(20, cir.getFirstColumn()); - assertEquals(155, cir.getLastColumn()); - assertEquals(6599, cir.getColumnWidth()); - assertEquals(15, cir.getXFIndex()); - assertTrue(cir.getHidden()); - assertEquals(3, cir.getOutlineLevel()); - assertTrue(cir.getCollapsed()); - assertArrayEquals(data, cir.serialize()); - } - - /** - * Some applications skip the last reserved field when writing {@link ColumnInfoRecord}s - * The attached file was apparently created by "SoftArtisans OfficeWriter for Excel". - * Excel reads that file OK and assumes zero for the value of the reserved field. - */ - @Test - void testZeroResevedBytes_bug48332() { - // Taken from bugzilla attachment 24661 (offset 0x1E73) - byte[] inpData = HexRead.readFromString("7D 00 0A 00 00 00 00 00 D5 19 0F 00 02 00"); - byte[] outData = HexRead.readFromString("7D 00 0C 00 00 00 00 00 D5 19 0F 00 02 00 00 00"); - - RecordInputStream in = TestcaseRecordInputStream.create(inpData); - // bug 48332 - Unusual record size remaining=(0) - ColumnInfoRecord cir = new ColumnInfoRecord(in); - assertEquals(0, in.remaining()); - assertArrayEquals(outData, cir.serialize()); - } - - /** - * Some sample files have just one reserved byte (field 6): - * OddStyleRecord.xls, NoGutsRecords.xls, WORKBOOK_in_capitals.xls - * but this seems to cause no problem to Excel - */ - @Test - void testOneReservedByte() { - byte[] inpData = HexRead.readFromString("7D 00 0B 00 00 00 00 00 24 02 0F 00 00 00 01"); - byte[] outData = HexRead.readFromString("7D 00 0C 00 00 00 00 00 24 02 0F 00 00 00 01 00"); - RecordInputStream in = TestcaseRecordInputStream.create(inpData); - ColumnInfoRecord cir = new ColumnInfoRecord(in); - assertEquals(0, in.remaining()); - assertArrayEquals(outData, cir.serialize()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java deleted file mode 100644 index 5fccfd0975..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the {@link CommonObjectDataSubRecord} - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestCommonObjectDataSubRecord { - byte[] data = new byte[] { - (byte)0x12,(byte)0x00,(byte)0x01,(byte)0x00, - (byte)0x01,(byte)0x00,(byte)0x11,(byte)0x60, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0x0D,(byte)0x26,(byte)0x01, - (byte)0x00,(byte)0x00, - }; - - @Test - void testLoad() { - CommonObjectDataSubRecord record = new CommonObjectDataSubRecord(TestcaseRecordInputStream.createLittleEndian(data), data.length); - - assertEquals( CommonObjectDataSubRecord.OBJECT_TYPE_LIST_BOX, record.getObjectType()); - assertEquals((short) 1, record.getObjectId()); - assertEquals((short) 1, record.getOption()); - assertTrue(record.isLocked()); - assertFalse(record.isPrintable()); - assertFalse(record.isAutofill()); - assertFalse(record.isAutoline()); - assertEquals(24593, record.getReserved1()); - assertEquals(218103808, record.getReserved2()); - assertEquals(294, record.getReserved3()); - assertEquals(18, record.getDataSize()); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - CommonObjectDataSubRecord record = new CommonObjectDataSubRecord(); - - record.setObjectType(CommonObjectDataSubRecord.OBJECT_TYPE_LIST_BOX); - record.setObjectId( 1); - record.setOption((short) 1); - record.setLocked(true); - record.setPrintable(false); - record.setAutofill(false); - record.setAutoline(false); - record.setReserved1(24593); - record.setReserved2(218103808); - record.setReserved3(294); - - byte[] recordBytes = record.serialize(); - confirmRecordEncoding(CommonObjectDataSubRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java deleted file mode 100644 index c6ea64d6b6..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * ==================================================================== - * 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.util.LittleEndianOutputStream; -import org.junit.jupiter.api.Test; - -/** - * Unit tests for DConRefRecord class. - */ -class TestDConRefRecord { - /** - * record of a proper single-byte external 'volume'-style path with multiple parts and a sheet - * name. - */ - final byte[] volumeString = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 17, 0,//cchFile (2 bytes) - 0, //char type - 1, 1, 'c', '[', 'f', 'o', 'o', 0x3, - 'b', 'a', 'r', ']', 's', 'h', 'e', 'e', - 't' - }; - /** - * record of a proper single-byte external 'unc-volume'-style path with multiple parts and a - * sheet name. - */ - final byte[] uncVolumeString = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 34, 0,//cchFile (2 bytes) - 0, //char type - 1, 1, '@', '[', 'c', 'o', 'm', 'p', - 0x3, 's', 'h', 'a', 'r', 'e', 'd', 0x3, - 'r', 'e', 'l', 'a', 't', 'i', 'v', 'e', - 0x3, 'f', 'o', 'o', ']', 's', 'h', 'e', - 'e', 't' - }; - /** - * record of a proper single-byte external 'simple-file-path-dcon' style path with a sheet name. - */ - final byte[] simpleFilePathDconString = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - 0, //char type - 1, 'c', '[', 'f', 'o', 'o', 0x3, 'b', - 'a', 'r', ']', 's', 'h', 'e', 'e', 't' - }; - /** - * record of a proper 'transfer-protocol'-style path. This one has a sheet name at the end, and - * another one inside the file path. The spec doesn't seem to care about what they are. - */ - final byte[] transferProtocolString = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 33, 0,//cchFile (2 bytes) - 0, //char type - 0x1, 0x5, 30, //count = 30 - '[', 'h', 't', 't', 'p', ':', '/', '/', - '[', 'f', 'o', 'o', 0x3, 'b', 'a', 'r', - ']', 's', 'h', 'e', 'e', 't', '1', ']', - 's', 'h', 'e', 'e', 't', 'x' - }; - /** - * startup-type path. - */ - final byte[] relVolumeString = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - 0, //char type - 0x1, 0x2, '[', 'f', 'o', 'o', 0x3, 'b', - 'a', 'r', ']', 's', 'h', 'e', 'e', 't' - }; - /** - * startup-type path. - */ - final byte[] startupString = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - 0, //char type - 0x1, 0x6, '[', 'f', 'o', 'o', 0x3, 'b', - 'a', 'r', ']', 's', 'h', 'e', 'e', 't' - }; - /** - * alt-startup-type path. - */ - final byte[] altStartupString = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - 0, //char type - 0x1, 0x7, '[', 'f', 'o', 'o', 0x3, 'b', - 'a', 'r', ']', 's', 'h', 'e', 'e', 't' - }; - /** - * library-style path. - */ - final byte[] libraryString = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - 0, //char type - 0x1, 0x8, '[', 'f', 'o', 'o', 0x3, 'b', - 'a', 'r', ']', 's', 'h', 'e', 'e', 't' - }; - /** - * record of single-byte string, external, volume path. - */ - final byte[] data1 = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 10, 0,//cchFile (2 bytes) - 0, //char type - 1, 1, (byte) 'b', (byte) 'l', (byte) 'a', (byte) ' ', (byte) 't', - (byte) 'e', (byte) 's', (byte) 't' - //unused doesn't exist as stFile[1] != 2 - }; - /** - * record of double-byte string, self-reference. - */ - final byte[] data2 = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 9, 0,//cchFile (2 bytes) - 1, //char type = unicode - 2, 0, (byte) 'b', 0, (byte) 'l', 0, (byte) 'a', 0, (byte) ' ', 0, (byte) 't', 0, - (byte) 'e', 0, (byte) 's', (byte) 't', 0,//stFile - 0, 0 //unused (2 bytes as we're using double-byte chars) - }; - /** - * record of single-byte string, self-reference. - */ - final byte[] data3 = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 9, 0,//cchFile (2 bytes) - 0, //char type = ansi - 2, (byte) 'b', (byte) 'l', (byte) 'a', (byte) ' ', (byte) 't', (byte) 'e', (byte) 's', - (byte) 't',//stFile - 0 //unused (1 byte as we're using single byes) - }; - /** - * double-byte string, external reference, unc-volume. - */ - final byte[] data4 = { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - //stFile starts here: - 1, //char type = unicode - 1, 0, 1, 0, 0x40, 0, (byte) 'c', 0, (byte) 'o', 0, (byte) 'm', 0, (byte) 'p', 0, 0x03, 0, - (byte) 'b', 0, (byte) 'l', 0, (byte) 'a', 0, 0x03, 0, (byte) 't', 0, (byte) 'e', 0, - (byte) 's', 0, (byte) 't', 0, - //unused doesn't exist as stFile[1] != 2 - }; - - /** - * test read-constructor-then-serialize for a single-byte external reference strings of - * various flavours. This uses the RecordInputStream constructor. - */ - @Test - void testReadWriteSBExtRef() throws IOException { - testReadWrite(data1, "read-write single-byte external reference, volume type path"); - testReadWrite(volumeString, - "read-write properly formed single-byte external reference, volume type path"); - testReadWrite(uncVolumeString, - "read-write properly formed single-byte external reference, UNC volume type path"); - testReadWrite(relVolumeString, - "read-write properly formed single-byte external reference, rel-volume type path"); - testReadWrite(simpleFilePathDconString, - "read-write properly formed single-byte external reference, simple-file-path-dcon type path"); - testReadWrite(transferProtocolString, - "read-write properly formed single-byte external reference, transfer-protocol type path"); - testReadWrite(startupString, - "read-write properly formed single-byte external reference, startup type path"); - testReadWrite(altStartupString, - "read-write properly formed single-byte external reference, alt-startup type path"); - testReadWrite(libraryString, - "read-write properly formed single-byte external reference, library type path"); - } - - /** - * test read-constructor-then-serialize for a double-byte external reference 'UNC-Volume' style - * string - */ - @Test - void testReadWriteDBExtRefUncVol() throws IOException { - testReadWrite(data4, "read-write double-byte external reference, UNC volume type path"); - } - - private void testReadWrite(byte[] data, String message) throws IOException { - RecordInputStream is = TestcaseRecordInputStream.create(81, data); - DConRefRecord d = new DConRefRecord(is); - ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length); - LittleEndianOutputStream o = new LittleEndianOutputStream(bos); - d.serialize(o); - o.flush(); - - assertArrayEquals(data, bos.toByteArray(), message); - } - - /** - * test read-constructor-then-serialize for a double-byte self-reference style string - */ - @Test - void testReadWriteDBSelfRef() throws IOException { - testReadWrite(data2, "read-write double-byte self reference"); - } - - /** - * test read-constructor-then-serialize for a single-byte self-reference style string - */ - @Test - void testReadWriteSBSelfRef() throws IOException { - testReadWrite(data3, "read-write single byte self reference"); - } - - /** - * Test of getDataSize method, of class DConRefRecord. - */ - @Test - void testGetDataSize() { - DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); - int expResult = data1.length; - int result = instance.getDataSize(); - assertEquals(expResult, result, "single byte external reference, volume type path data size"); - instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data2)); - assertEquals(data2.length, instance.getDataSize(), "double byte self reference data size"); - instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data3)); - assertEquals(data3.length, instance.getDataSize(), "single byte self reference data size"); - instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data4)); - assertEquals(data4.length, instance.getDataSize(), - "double byte external reference, UNC volume type path data size"); - } - - /** - * Test of getSid method, of class DConRefRecord. - */ - @Test - void testGetSid() { - DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); - short expResult = 81; - short result = instance.getSid(); - assertEquals(expResult, result, "SID"); - } - - /** - * Test of getPath method, of class DConRefRecord. - */ - @Test - void testGetPath() { - // TODO: different types of paths. - DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); - byte[] expResult = Arrays.copyOfRange(data1, 9, data1.length); - byte[] result = instance.getPath(); - assertArrayEquals(expResult, result, "get path"); - } - - /** - * Test of isExternalRef method, of class DConRefRecord. - */ - @Test - void testIsExternalRef() { - DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); - assertTrue(instance.isExternalRef(), "external reference"); - instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data2)); - assertFalse(instance.isExternalRef(), "internal reference"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java deleted file mode 100644 index 00b25ac225..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.io.ByteArrayInputStream; - -import org.apache.poi.util.LittleEndian; -import org.junit.jupiter.api.Test; - -final class TestDVALRecord { - @Test - void testRead() { - byte[] data = new byte[22]; - LittleEndian.putShort(data, 0, DVALRecord.sid); - LittleEndian.putShort(data, 2, (short)18); - LittleEndian.putShort(data, 4, (short)55); - LittleEndian.putInt(data, 6, 56); - LittleEndian.putInt(data, 10, 57); - LittleEndian.putInt(data, 14, 58); - LittleEndian.putInt(data, 18, 59); - - RecordInputStream in = new RecordInputStream(new ByteArrayInputStream(data)); - in.nextRecord(); - DVALRecord dv = new DVALRecord(in); - - assertEquals(55, dv.getOptions()); - assertEquals(56, dv.getHorizontalPos()); - assertEquals(57, dv.getVerticalPos()); - assertEquals(58, dv.getObjectID()); - assertNotEquals(0, dv.getDVRecNo(), "Identified bug 44510"); - assertEquals(59, dv.getDVRecNo()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.java deleted file mode 100644 index e7c97e86ec..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.cut; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.util.HexDump; -import org.junit.jupiter.api.Test; - -final class TestDrawingGroupRecord { - private static final int MAX_RECORD_SIZE = 8228; - private static final int MAX_DATA_SIZE = MAX_RECORD_SIZE - 4; - - @Test - void testGetRecordSize() { - DrawingGroupRecord r = new DrawingGroupRecord(); - assertEquals(4, r.getRecordSize()); - - EscherSpRecord sp = new EscherSpRecord(); - sp.setRecordId(EscherSpRecord.RECORD_ID); - sp.setOptions((short) 0x1111); - sp.setFlags(-1); - sp.setShapeId(-1); - EscherContainerRecord dggContainer = new EscherContainerRecord(); - dggContainer.setOptions((short) 0x000F); - dggContainer.setRecordId((short) 0xF000); - dggContainer.addChildRecord(sp); - - r.addEscherRecord(dggContainer); - assertEquals(28, r.getRecordSize()); - - byte[] data = new byte[28]; - int size = r.serialize(0, data); - assertEquals("[EB, 00, 18, 00, 0F, 00, 00, F0, 10, 00, 00, 00, 11, 11, 0A, F0, 08, 00, 00, 00, FF, FF, FF, FF, FF, FF, FF, FF]", HexDump.toHex(data)); - assertEquals(28, size); - - assertEquals(24, dggContainer.getRecordSize()); - - - r = new DrawingGroupRecord( ); - r.setRawData( new byte[MAX_DATA_SIZE] ); - assertEquals( MAX_RECORD_SIZE, r.getRecordSize() ); - r.setRawData( new byte[MAX_DATA_SIZE+1] ); - assertEquals( MAX_RECORD_SIZE + 5, r.getRecordSize() ); - r.setRawData( new byte[MAX_DATA_SIZE*2] ); - assertEquals( MAX_RECORD_SIZE * 2, r.getRecordSize() ); - r.setRawData( new byte[MAX_DATA_SIZE*2 + 1] ); - assertEquals( MAX_RECORD_SIZE * 2 + 5, r.getRecordSize() ); - } - - @Test - void testSerialize() { - // Check under max record size - DrawingGroupRecord r = new DrawingGroupRecord(); - byte[] rawData = new byte[100]; - rawData[0] = 100; - rawData[99] = (byte) 200; - r.setRawData( rawData ); - byte[] buffer = new byte[r.getRecordSize()]; - int size = r.serialize( 0, buffer ); - assertEquals( 104, size ); - assertEquals("[EB, 00, 64, 00, 64, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, C8]", HexDump.toHex(buffer)); - - // check at max record size - rawData = new byte[MAX_DATA_SIZE]; - r.setRawData( rawData ); - buffer = new byte[r.getRecordSize()]; - size = r.serialize( 0, buffer ); - assertEquals( MAX_RECORD_SIZE, size ); - - // check over max record size - rawData = new byte[MAX_DATA_SIZE+1]; - rawData[rawData.length-1] = (byte) 255; - r.setRawData( rawData ); - buffer = new byte[r.getRecordSize()]; - size = r.serialize( 0, buffer ); - assertEquals( MAX_RECORD_SIZE + 5, size ); - assertEquals( "[EB, 00, 20, 20]", HexDump.toHex(cut(buffer, 0, 4) )); - assertEquals( "[00, EB, 00, 01, 00, FF]", HexDump.toHex(cut(buffer, MAX_RECORD_SIZE - 1, MAX_RECORD_SIZE + 5) )); - - // check continue record - rawData = new byte[MAX_DATA_SIZE * 2 + 1]; - rawData[rawData.length-1] = (byte) 255; - r.setRawData( rawData ); - buffer = new byte[r.getRecordSize()]; - size = r.serialize( 0, buffer ); - assertEquals( MAX_RECORD_SIZE * 2 + 5, size ); - assertEquals( MAX_RECORD_SIZE * 2 + 5, r.getRecordSize() ); - assertEquals( "[EB, 00, 20, 20]", HexDump.toHex(cut(buffer, 0, 4) )); - assertEquals( "[EB, 00, 20, 20]", HexDump.toHex(cut(buffer, MAX_RECORD_SIZE, MAX_RECORD_SIZE + 4) )); - assertEquals( "[3C, 00, 01, 00, FF]", HexDump.toHex(cut(buffer, MAX_RECORD_SIZE * 2, MAX_RECORD_SIZE * 2 + 5) )); - - // check continue record - rawData = new byte[664532]; - r.setRawData( rawData ); - buffer = new byte[r.getRecordSize()]; - size = r.serialize( 0, buffer ); - assertEquals( 664856, size ); - assertEquals( 664856, r.getRecordSize() ); - } - - @Test - void testGrossSizeFromDataSize() { - assertEquals( 4, DrawingGroupRecord.grossSizeFromDataSize( 0 ) ); - assertEquals( 5, DrawingGroupRecord.grossSizeFromDataSize( 1 ) ); - assertEquals( MAX_RECORD_SIZE, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE ) ); - assertEquals( MAX_RECORD_SIZE + 5, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE + 1 ) ); - assertEquals( MAX_RECORD_SIZE * 2, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE * 2 ) ); - assertEquals( MAX_RECORD_SIZE * 2 + 5, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE * 2 + 1 ) ); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java deleted file mode 100644 index bac766e08a..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -final class TestDrawingRecord { - - /** - * Check that RecordFactoryInputStream properly handles continued DrawingRecords - * See Bugzilla #47548 - */ - @Test - void testReadContinued() throws IOException { - - //simulate a continues drawing record - ByteArrayOutputStream out = new ByteArrayOutputStream(); - //main part - DrawingRecord dg = new DrawingRecord(); - byte[] data1 = new byte[8224]; - Arrays.fill(data1, (byte)1); - dg.setData(data1); - out.write(dg.serialize()); - - //continued part - byte[] data2 = new byte[4048]; - Arrays.fill(data2, (byte)2); - ContinueRecord cn = new ContinueRecord(data2); - out.write(cn.serialize()); - - List rec = RecordFactory.createRecords(new ByteArrayInputStream(out.toByteArray())); - assertEquals(2, rec.size()); - assertTrue(rec.get(0) instanceof DrawingRecord); - assertTrue(rec.get(1) instanceof ContinueRecord); - - assertArrayEquals(data1, ((DrawingRecord)rec.get(0)).getRecordData()); - assertArrayEquals(data2, ((ContinueRecord)rec.get(1)).getData()); - - } - -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java deleted file mode 100644 index 0f936fd405..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java +++ /dev/null @@ -1,154 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the TestEmbeddedObjectRefSubRecord - * class works correctly. Test data taken directly from a real Excel file. - */ -final class TestEmbeddedObjectRefSubRecord { - - private static final short EORSR_SID = EmbeddedObjectRefSubRecord.sid; - - @Test - void testStore() { - String data1 - = "20 00 05 00 FC 10 76 01 02 24 14 DF 00 03 10 00 " - + "00 46 6F 72 6D 73 2E 43 68 65 63 6B 42 6F 78 2E " - + "31 00 00 00 00 00 70 00 00 00 00 00 00 00 00 00 " - + "00 00"; - - byte[] src = hr(data1); - - RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, src); - - EmbeddedObjectRefSubRecord record1 = new EmbeddedObjectRefSubRecord(in, src.length); - - byte[] ser = record1.serialize(); - - RecordInputStream in2 = TestcaseRecordInputStream.create(ser); - EmbeddedObjectRefSubRecord record2 = new EmbeddedObjectRefSubRecord(in2, ser.length-4); - confirmRecordEncoding(EmbeddedObjectRefSubRecord.sid, src, ser); - assertEquals(record1.getOLEClassName(), record2.getOLEClassName()); - - byte[] ser2 = record1.serialize(); - assertArrayEquals(ser, ser2); - } - - @Test - void testCreate() { - EmbeddedObjectRefSubRecord record1 = new EmbeddedObjectRefSubRecord(); - - byte[] ser = record1.serialize(); - RecordInputStream in2 = TestcaseRecordInputStream.create(ser); - EmbeddedObjectRefSubRecord record2 = new EmbeddedObjectRefSubRecord(in2, ser.length-4); - - assertEquals(record1.getOLEClassName(), record2.getOLEClassName()); - assertEquals(record1.getStreamId(), record2.getStreamId()); - - byte[] ser2 = record1.serialize(); - assertArrayEquals(ser, ser2); - } - - @SuppressWarnings("squid:S2699") - @Test - void testCameraTool_bug45912() { - /* - * taken from ftPictFmla sub-record in attachment 22645 (offset 0x40AB). - */ - byte[] data45912 = hr( - "12 00 0B 00 F8 02 88 04 3B 00 " + - "00 00 00 01 00 00 00 01 " + - "00 00"); - RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data45912); - - EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data45912.length); - byte[] ser2 = rec.serialize(); - confirmRecordEncoding(EmbeddedObjectRefSubRecord.sid, data45912, ser2); - } - - private static byte[] hr(String string) { - return HexRead.readFromString(string); - } - - /** - * tests various examples of OLE controls - */ - @SuppressWarnings("squid:S2699") - @Test - void testVarious() { - String[] rawData = { - "12 00 0B 00 70 95 0B 05 3B 01 00 36 00 40 00 18 00 19 00 18", - "12 00 0B 00 B0 4D 3E 03 3B 00 00 00 00 01 00 00 80 01 C0 00", - "0C 00 05 00 60 AF 3B 03 24 FD FF FE C0 FE", - "24 00 05 00 40 42 3E 03 02 80 CD B4 04 03 15 00 00 46 6F 72 6D 73 2E 43 6F 6D 6D 61 6E 64 42 75 74 74 6F 6E 2E 31 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00", - "22 00 05 00 10 4E 3E 03 02 00 4C CC 04 03 12 00 00 46 6F 72 6D 73 2E 53 70 69 6E 42 75 74 74 6F 6E 2E 31 00 54 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00", - "20 00 05 00 E0 41 3E 03 02 00 FC 0B 05 03 10 00 00 46 6F 72 6D 73 2E 43 6F 6D 62 6F 42 6F 78 2E 31 00 74 00 00 00 4C 00 00 00 00 00 00 00 00 00 00 00", - "24 00 05 00 00 4C AF 03 02 80 E1 93 05 03 14 00 00 46 6F 72 6D 73 2E 4F 70 74 69 6F 6E 42 75 74 74 6F 6E 2E 31 00 C0 00 00 00 70 00 00 00 00 00 00 00 00 00 00 00", - "20 00 05 00 E0 A4 28 04 02 80 EA 93 05 03 10 00 00 46 6F 72 6D 73 2E 43 68 65 63 6B 42 6F 78 2E 31 00 30 01 00 00 6C 00 00 00 00 00 00 00 00 00 00 00", - "1C 00 05 00 30 40 3E 03 02 00 CC B4 04 03 0D 00 00 46 6F 72 6D 73 2E 4C 61 62 65 6C 2E 31 9C 01 00 00 54 00 00 00 00 00 00 00 00 00 00 00", - "1E 00 05 00 B0 A4 28 04 02 00 D0 0A 05 03 0F 00 00 46 6F 72 6D 73 2E 4C 69 73 74 42 6F 78 2E 31 F0 01 00 00 48 00 00 00 00 00 00 00 00 00 00 00", - "24 00 05 00 C0 AF 3B 03 02 80 D1 0A 05 03 14 00 00 46 6F 72 6D 73 2E 54 6F 67 67 6C 65 42 75 74 74 6F 6E 2E 31 00 38 02 00 00 6C 00 00 00 00 00 00 00 00 00 00 00", - "1E 00 05 00 90 AF 3B 03 02 80 D4 0A 05 03 0F 00 00 46 6F 72 6D 73 2E 54 65 78 74 42 6F 78 2E 31 A4 02 00 00 48 00 00 00 00 00 00 00 00 00 00 00", - "24 00 05 00 60 40 3E 03 02 00 D6 0A 05 03 14 00 00 46 6F 72 6D 73 2E 54 6F 67 67 6C 65 42 75 74 74 6F 6E 2E 31 00 EC 02 00 00 6C 00 00 00 00 00 00 00 00 00 00 00", - "20 00 05 00 20 4D 3E 03 02 00 D9 0A 05 03 11 00 00 46 6F 72 6D 73 2E 53 63 72 6F 6C 6C 42 61 72 2E 31 58 03 00 00 20 00 00 00 00 00 00 00 00 00 00 00", - "20 00 05 00 00 AF 28 04 02 80 31 AC 04 03 10 00 00 53 68 65 6C 6C 2E 45 78 70 6C 6F 72 65 72 2E 32 00 78 03 00 00 AC 00 00 00 00 00 00 00 00 00 00 00", - }; - - for (int i = 0; i < rawData.length; i++) { - confirmRead(hr(rawData[i]), i); - } - } - - private static void confirmRead(byte[] data, int i) { - RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data); - - EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data.length); - byte[] ser2 = rec.serialize(); - confirmRecordEncoding("Test record " + i, EORSR_SID, data, ser2); - } - - @SuppressWarnings("squid:S2699") - @Test - void testVisioDrawing_bug46199() { - /* - * taken from ftPictFmla sub-record in attachment 22860 (stream offset 0x768F).
- * Note that the since the string length is zero, there is no unicode flag byte - */ - byte[] data46199 = hr( - "0E 00 " - + "05 00 " - + "28 25 A3 01 " - + "02 6C D1 34 02 " - + "03 00 00 " - + "0F CB E8 00"); - RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data46199); - - // bug 22860 - Not enough data (3) to read requested (4) bytes - EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data46199.length); - byte[] ser2 = rec.serialize(); - confirmRecordEncoding(EORSR_SID, data46199, ser2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java deleted file mode 100644 index 0a69b6554f..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java +++ /dev/null @@ -1,44 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the EndSubRecord - * class works correctly. Test data taken directly from a real Excel file. - */ -final class TestEndSubRecord { - private static final byte[] data = { }; - - @Test - void testLoad() { - EndSubRecord record = new EndSubRecord(TestcaseRecordInputStream.create(0x00, data), 0); - assertEquals(0, record.getDataSize()); - } - - @Test - void testStore() { - EndSubRecord record = new EndSubRecord(); - byte [] recordBytes = record.serialize(); - assertEquals(0, recordBytes.length - 4); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java b/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java deleted file mode 100644 index 3578a8d99b..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ddf.EscherClientDataRecord; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests the EscherAggregate class. - */ -final class TestEscherAggregate { - /** - * Tests that the create aggregate method correctly rejoins escher records together. - */ - @Test - void testCreateAggregate() { - String msoDrawingRecord1 = - "0F 00 02 F0 20 01 00 00 10 00 08 F0 08 00 00 00 \n" + - "03 00 00 00 02 04 00 00 0F 00 03 F0 08 01 00 00 \n" + - "0F 00 04 F0 28 00 00 00 01 00 09 F0 10 00 00 00 \n" + - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \n" + - "02 00 0A F0 08 00 00 00 00 04 00 00 05 00 00 00 \n" + - "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 \n" + - "01 04 00 00 00 0A 00 00 73 00 0B F0 2A 00 00 00 \n" + - "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 \n" + - "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 \n" + - "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 \n" + - "00 00 00 00 01 00 54 00 05 00 45 00 01 00 88 03 \n" + - "05 00 94 00 00 00 11 F0 00 00 00 00"; - - String msoDrawingRecord2 = - "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 " + - "02 04 00 00 80 0A 00 00 73 00 0B F0 2A 00 00 00 " + - "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 " + - "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 " + - "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 " + - "00 00 00 00 01 00 8D 03 05 00 E4 00 03 00 4D 03 " + - "0B 00 0C 00 00 00 11 F0 00 00 00 00"; - - DrawingRecord d1 = new DrawingRecord(); - d1.setData( HexRead.readFromString( msoDrawingRecord1 ) ); - - ObjRecord r1 = new ObjRecord(); - - DrawingRecord d2 = new DrawingRecord(); - d2.setData( HexRead.readFromString( msoDrawingRecord2 ) ); - - ObjRecord r2 = new ObjRecord(); - - List records = new ArrayList<>(); - records.add( d1 ); - records.add( r1 ); - records.add( d2 ); - records.add( r2 ); - - EscherAggregate aggregate = EscherAggregate.createAggregate(records, 0); - - assertEquals( 1, aggregate.getEscherRecords().size() ); - assertEquals( (short) 0xF002, aggregate.getEscherRecord( 0 ).getRecordId() ); - assertEquals( 2, aggregate.getEscherRecord( 0 ).getChildRecords().size() ); - } - - @Test - void testSerialize() { - - EscherContainerRecord container1 = new EscherContainerRecord(); - EscherContainerRecord spContainer1 = new EscherContainerRecord(); - EscherContainerRecord spContainer2 = new EscherContainerRecord(); - EscherContainerRecord spContainer3 = new EscherContainerRecord(); - EscherSpRecord sp1 = new EscherSpRecord(); - EscherSpRecord sp2 = new EscherSpRecord(); - EscherSpRecord sp3 = new EscherSpRecord(); - EscherClientDataRecord d2 = new EscherClientDataRecord(); - EscherClientDataRecord d3 = new EscherClientDataRecord(); - - container1.setOptions( (short) 0x000F ); - spContainer1.setOptions( (short) 0x000F ); - spContainer1.setRecordId( EscherContainerRecord.SP_CONTAINER ); - spContainer2.setOptions( (short) 0x000F ); - spContainer2.setRecordId( EscherContainerRecord.SP_CONTAINER ); - spContainer3.setOptions( (short) 0x000F ); - spContainer3.setRecordId( EscherContainerRecord.SP_CONTAINER ); - d2.setRecordId( EscherClientDataRecord.RECORD_ID ); - d2.setRemainingData( new byte[0] ); - d3.setRecordId( EscherClientDataRecord.RECORD_ID ); - d3.setRemainingData( new byte[0] ); - container1.addChildRecord( spContainer1 ); - container1.addChildRecord( spContainer2 ); - container1.addChildRecord( spContainer3 ); - spContainer1.addChildRecord( sp1 ); - spContainer2.addChildRecord( sp2 ); - spContainer3.addChildRecord( sp3 ); - spContainer2.addChildRecord( d2 ); - spContainer3.addChildRecord( d3 ); - - EscherAggregate aggregate = new EscherAggregate(false); - aggregate.addEscherRecord( container1 ); - aggregate.associateShapeToObjRecord( d2, new ObjRecord() ); - aggregate.associateShapeToObjRecord( d3, new ObjRecord() ); - - byte[] data = new byte[112]; - int bytesWritten = aggregate.serialize( 0, data ); - assertEquals( 112, bytesWritten ); - assertEquals( "[EC, 00, 40, 00, 0F, 00, 00, 00, 58, 00, 00, 00, 0F, 00, 04, F0, 10, 00, 00, 00, 00, 00, 0A, F0, 08, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 0F, 00, 04, F0, 18, 00, 00, 00, 00, 00, 0A, F0, 08, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 11, F0, 00, 00, 00, 00, 5D, 00, 00, 00, EC, 00, 20, 00, 0F, 00, 04, F0, 18, 00, 00, 00, 00, 00, 0A, F0, 08, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 11, F0, 00, 00, 00, 00, 5D, 00, 00, 00]", - HexDump.toHex( data ) ); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java deleted file mode 100644 index 6b0933cc31..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * ==================================================================== - * 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.poifs.storage.RawDataUtil; -import org.junit.jupiter.api.Test; - -final class TestExtSSTRecord { - - /** - * ExtSSTRecord can be continued. Ensure we properly read the continue remainder. - */ - @Test - void test50967() throws IOException { - // hex dump from ISBN_UPD_PL_20100104_1525.xls attached to Bugzilla 50867 - byte[] bytes = RawDataUtil.decompress("H4sIAAAAAAAAACWaBbAVxxZF9/jgrkFDcAvu7hrc3d3dLbhrgBDcXR8OwV2CEz" + - "RIIFhw+4G/Zqiiqrn3zkyvvc/p7tM976sSp/CVOJIUVVJH2sa022lX0e6OLK0zpE9RpKemdCQav9lSlhhSCldqEEuq7EsbYkuLuGdJHG" + - "km90yNJ43ggZETSP/jnuwJpR+4Z0QiqVdMaU5iaTz3NkoiVeGeH5JK8eNKtZJJZbk3SXIpenzpOu0p2l4ppTY8I0sq+uXeBT/Qx3dwpY" + - "aLZ+xMK63h3tjpJfBUOYNUFO4FGbkO7mOZuMaSmmWRajhSnaxSefjn/AiHJ5nZpTfoyJ1DSgf/jzml79H8P9rntF9ySf+iJ00eKWF0fM" + - "iLD+j5lI/+0TOxgDQEDzIVkpKho2BhWNExpIjUDf4eRaVWeDG2mDQAHS2KoxUvZpaQRqNnWEmuQU+vUuhEz5DS3Icno8tI/dA1pCyf8a" + - "JVOQkk9SovlUTfuQrSb+h7VVHaj77rlaQVGLDlJ56JvthVpTvoy1BN+oC+gtWJCfo61eD/6NpdEyZ0xa0t/UWcCtbhd3TlrouP6CpfD7" + - "3EqXx9WvStaQAP8TrQUJqMzkwkyyd09mgiFUdfrWbEEl2xW9Avuh61lLah50Qr6Rf0xG1DP+ip1fZbnJ62IwbouNEeDnQ87yD9io5Wnb" + - "iWOC3rTLzQMbUL8UTHw67SdHSU7S69I9/W9JDqoWNRT/IIHYd64RM6KvchdsQpbj9Y0RG1P/EPcnUA36Oj3kDJh//QIK6Hf+cQfIc/yT" + - "BYiU+j4dwD/84RfE9cHv5Mv+goPYo8Qcf00eglHj+MlWLCP2Sc1AH+iePxB/5hE/AYgTUmwo2OJpOkiuhoM5nv0DF1ijQIHcemEit0ZJ" + - "qOv+iYOIP70bFqJrmBjk+z6BsdhWcTQ3TUmMPz0HFxLvFGx4FfGZ/EI9lvxA0db2jv0N6Z/23c+Av5Dl3RF/EsdI1dTO6gq89SchA9lZ" + - "dJ+dFTfDn5Slz8lVyPrr0M/gnoyrlGsoJxs1bKhp4266Q86Km2XkqJnlsbpLXoWbFR6o2ebZukn9FzfbO0kjx7ukXaha5/tko7gvkgQr" + - "qGrsjbadGVZof0lnzrtlMqhq6ru6Tl6Mq/R4pEfDrslQqgZ/Q+qTZ6ru7nd/Q0OSBlJc9GHJSqo2fFIfonTmcOS/PQZR6VzqOrzjEpLX" + - "pqHf+Wb+dO4Du6Lp4kRsQr72n8Rd/9s8QEPb3OE1N0xLyAB+iocpGxj47pl/AoGCdX8Bz+qVeJA9xPr5G/xCXFDfqGe9BNYgl3g9tohH" + - "f7nW/j/te7jCH8L3mPsQr3svvEEt4PD/g/vBf/hgf/szxmLMB77B+pJ5wFn0qP4Wz3TEqAgN3Ppbb4n/Bf6TC8515KA+Ft9VqKA+f4N1" + - "K+YK5+K82GN8N76Qq8Iz4QP3gXfJQqwet+ljbj90PaaXD7/0lbyaNWX3gOfl//Ko2Cv5ph6Cv8PUxDKYP5yjJUAr9324bawt/NNZQcny" + - "96hoYG4zqSEfr8v8iGVsHfKKqhqPi7LZqhFvzwJrqhRfD3YNB8T94otqF18JePY+gDfheNa+g5OlrFMxQX/u3xDbWCv3BCQ0/JlzqJDL" + - "nwd0tsKEUwLyXhPvgnJjVUEN8fJTM0E/4VKQzVgnt0KkO54VVq+oF3XRpDDYJ5NR3f4/PM9IZYQvQwgxH6vSiToWzwFs1i6Cy827MaKo" + - "PPLbIZeg3v/uyGfoIzSU5Dq+FckstQjsDnPIZ2wDknr6H0+Dw9v6FU8I0sYCgefCULGbqAv50KG/oPzvEsTt/BV7I435MX0ZnM58Hplj" + - "I0A86dpQ2Vg/OHcoY2w7movBFYpUwVDf1KPlysZKgkfI2qGDoD37Cqhl7B92s1/IbvtxqGopMHHWoZugFf8dqGNsHXpY6hO/jYqZ6hW/" + - "g4soGhd/C9amioGVwLGhuKSdw7NOU++Dq0oIXr31aGmsBTua2hvfC0aWeIFFWnDob+hWd7R0P54anW2dBF4nuki6Gy8AzpZsiE50Z3Q4" + - "3w6xUm94CnQ2/iDE/pvoaO4depfoYq49eQAVyPTz6DdCw8QwbzGZ7SQ7kOnjTDDa0gD5eMMJQGn8yRhkYwft6MMtSL/Gsz5lv+VR4HH3" + - "7ZTGILiOeXiYbmwLVosqHCcC2bYqg4eddrGr7C1W0GfsGVe5ahP+CqMpt8g+uvuYYG4U+7eeQdPOnmGzpEfv270NB44rZ9saEa+BN3ma" + - "ENcAxYbighHH+t4D58Gs8gILU0fg0tHMsopkrC0WsD+Q3Hgk3w4E/sLdwPR5+thuLDsWQbfHA0iDD0idbfbmgZcTu3w1An4vbHLkNd4O" + - "qwx1BkuPrs4z58WrffUEV82vm7oTrwmQfRj187aevA+e6Qoen41uUoeuF8dMzQSDjXnDA0Gs7RpxincE4+Y6gDnA3OGcoLZ6s/4IHz3Q" + - "X8gbPyJfTAuegKOuHaexV/8WvddeJGHAfdMFSPOL65aegcfL/cJu7wrbpLf0EteI/O4Blxn7yCp85DQznJr+uPDG2DZxnBIxVV8injJc" + - "ivZ4a6EtiELwydhyv/y2/jsfBrQ+/h+vWNoZrke4/3hjLDk/ujoRfwrPpsqDk+NfnPUCI4mnylhWOTYao9HCMsU4XgKO6a+kz8bvmmZt" + - "F/8SimYtHvgmimOtNvupim3jPOvvDlafKmRRxTOfChYlxT39Hv1XimluPHkfimZhCvDwlMHYXjUCJT04iX+Z2p8/iyJImp7vjSL6mpcv" + - "BsSmZqKPnUKoWpXMRtU0o+w1UtlamUcG35wdRw/Hma2tQu+HKnNeUQt0bpTGWGc0V6U5RcKp/RlA3viUwmmliPspi6DveRrKaGwJ0mmx" + - "nWgfmzm2Gd2ymHGda5b3KaWgf/9VympsN/P7ep34J8y2vqAPzV8pmKCv/M/KaqwF+woBnOF38UMjUe/h+LmPoH/n5FTeUM1oliprLA/6" + - "Y4zyXvWpQ0lQz+LaVMdYL/U2lTW4hz+bLwwl+xnBmO1zrlzbCO+qUC/aDjTkVTv6CjbGU+EO8sP5l6SLuXH3uhI2E1U+eCda86z0fHzh" + - "qmuqHjVU1Tq9BRsDY60dGujqnvyYOLdeEN1un6pq6io2ID+iUO/6PdEsSjkans6NjS2FQH8uNTE1Ob0DOomanc6CjYnOfRnmlhaiR63r" + - "VEH3oStoYDPcPamMqPngVtTbEV0Jl2ppgqdaq9KS7RZYrDruiJ3snUSgT/0NnUPvSU72LqAfHp19VUPPTU62bqLe2C7jwHXdt6mKoaxK" + - "enqZ5BfHqZGoyuFH3IB+Kjvqbmou9D3295Fr+/qY3ocweYWkicPtHOQF+GQaYOB3XJYPIYnaWHmLqLzhpDTb1AZxeKoSjoazPclEXeFR" + - "1h6k/a+D/zPPSmG2nqYDA+aPui1x9tajF5eIa2LbpfjTFFqa0jFPGV0X11nCks1Jbxpgqie9EEUxnQ/Xwi8UO3O9nUxGB/MsXUHOL5gX" + - "YIulNMM7WC8Rx5hqmpwb6LdmQwrmby3KDummUqcTC+fzG1l9acbWos+tPNMbUB/fXmmvoL/T1YJIM6v8M84ob+4mySTqB/8nxTCdGdc6" + - "Gp3ehOtsjUMvK1+GJ+R3+zJeQzunss5X50b1hmKi96660ww33LyJXf8vXH1Wa4L76+xlQd9B1aa6o4P4xfZyoy+g6t5zP6Rm7kenTV2G" + - "TqD9qxm035xLXGFjOcR6ttJX/QWWebqcvobBNBngf1znb40JdpB/mMvj47GXfoW7WLcYuuy7tN1UDXqT2myqPrw158Ja7F95vaj74Gvz" + - "P+0Vf8AJ/Rl/sgeY6+Pod4DvomHzYVPdg3H/mmL/Exxhv6mh1nngj23idM9UbnDyfNcB+Q9xT5RDyXnTYVA50jzph6RlvlrKkd6M10jj" + - "xDb/7z5AXx/P6CqXHEMe5FUwPRWfgS8yM621xmHkRnsyumTqKz4lVTW9HZ7pqpC+icep15GJ2n/mQ+ROf/bphqic5lt+gXfZtuM9+i77" + - "c7pjz0LbvL9+hb9ZepOOgbeY98pj1231Q24vfvA1N10Xnkoams6Nz5t6lU6Hz6yFRNdJr/MN7R2eKJKZY8vXlqqlFQLzwz1SYI9AtT7d" + - "D3jrYJ+j5R7LRA35mX+EY8s7zGN3TmfmNqATpLvyUP0Vnlnamd6GzynrxC54APZriPO/WR+QR9tz6ZKhsrWJ9MxUVnFha5X9BZ4wt5TT" + - "w7fWWeCvY9svQKvZcNS0XRWZ7NWBDHIbYV5ulkx9IndM50gUbfEs8K1/XYkSwNQF+KyJbYmmpiFEssidpGMZ6SSy9Hs1QMfZej0zrB+m" + - "ZpGvpyx7K0EH0jYlt6gb5XcSw1RFfJeJbWo+tdfEtN0ZMmoaUp6NmeyFIq9ET+zlLP8DzH0nH0LElqKQY6TiSzlAsd+VNYWoqOA3SeGR" + - "0rvrfCeF1PZakUOvKn5nd0ZEpjaRbxmpnWkoGOReksRUPHhvRWOO76ZLR0KqgLMlliClCPzJaOoUdZrfBcJ+GPljqgowNF/H50PMpuqS" + - "DxeZjDUn50NMplaRM6zDyWaqGjVl5Lq9AxLJ+ly+TfsfyWkqDDZ9JqgI5uhSwdCc47CluKj450RfE1qLOKWTLRkbeEpfHo6FfS0hl0HC" + - "plKSH8ycpY4fnNorKW3qEjWXlLVcHsV8HSWvg/VLSEFA2ojK8I61DF0ny4t1e19ATuH6tbag53hhrf/G9Q09IkuC/WsuTBfau2pVhwP2" + - "Ly+Q7uDXUt3aN9U89SWvjbNLA0F/53DS2lJw5vSOq08Ldogr/B+Glq6Tzj50QzS/+hoyBFX2f4Z7YkfsThf62scLwUbWOpO/zr2lq6Sx" + - "wKt+cz/K068Hz8r9bR0igrWM8s1cX/VV0s3XaDcxq4yJ9h3S1FoEM9yQP4f+tl6ULUYP2yVBP+6H0tlYA7Zj/yIKiT+lvKE9QZAyx1Df" + - "Z1Ay0dDOrIQeiAf+YQSyfhLznMUl+4e1HsrIZ76khLR/E982hLzeBNNNZi7EixxlkaAu+u8VZYf5+cYIX7lJMTaeE9O8lSYXgPT7aUE9" + - "+XTyHOcB+faikv3Ien8T3+n55uhedlh2fyGf93UZxkgHvlbOIN98E5lrLDXf1XSwfgrjqP/IN7/W+WksH9bD75BHf1hfyO7wkWWxpJ3t" + - "RcYukQ/O2XWrqO742XkUfoaLycFv/nr2A843vVVZZ+Q0/yNVZ4zpRgnRXupyM2MC7gdjZbqgbvrC2W7sNrbbPC87DBEYwXeKPssFQH3m" + - "K7LE2EM9UeS13gS7rPUjv4yuy3NB2+z79bKouvpQ5amgrf4EPcD1+iI5ZawVXzqKVFcM1j0P2Dz5+P81y4xpy0RAmvjKfxHZ8nnOF3+D" + - "6eZZzhb8fzlk7A+eKCpYrwJb1kqR9+Hr9sKQ18B69aSgFf0ut8j5/eDfThY9OblvbCee8W8x+c6e/gG5z1/7K0Hc6I+5bi4tvyh/gA14" + - "NHVngut/4fS2y5tfappQLw/P7c0k/E++i/5B0cUV5bmo1fj99Y6g3Hs3eW+sNR/SN5Dkf9z5Ye41Pj/yw9o/8XXy0NpN/1hq1C9LvDtF" + - "UGf9batgrQf1XX1m386ezZ+g+Otr6t9/hzN5KtavgzNIqtV/BUjWqLJVn5otkipGoY3dYZfNrFopoJn6bEtGXClzS2rYnkYeY4tn6Ds3" + - "9cW08D3+LzPXEdl8AOz9W3JrSVBt6Oie1wPz/uO76He3USW0ng/juprTqM/zzJba3Av7YpbF1Hx/CUdnguOOF7W1/Q83cqO9wfRqS2lQ" + - "4d6dPZmgP/rPR2OO/+SfFWFv4XGW1RMqt+Zjucd7tmoV8u2Jf1G/+8bLYiw30zu63ycH/OYasN3LFy2xoEd6U8tnbCbeSz1Qnu1gzGi3" + - "BHK2irH/FeWMhWdHhfF7bVBN5RReEMeCmu/oXzfQlbLeB8X8oOzy8/l+H5cBYqh5/EPV8FW1PhHFfRFiWAZlXmPvgaVrG1Db5E1Wx1g6" + - "9EdVu/wvdfDVu1iP9/NWnhq1Db1hL4htexdYP56XFdW8XhK1Pf1gJ83dHAVmx8bdiI58H5Z2NbOeF72dQOz/dyMSgnwjeqla078O2giI" + - "gN19p2tj7h45MOtlhyFIVNZR3ysRyb2pnEO1Z3W43gWdqTPIFnTG+bNZrx0ddWfPo/3I/n0H+8Abaa4dPggbZOwTF8sK1z+LR6qM2ek3" + - "wZjo/kZf8RxAeO0z/bSgzH7VHEB59ajrG1CZ5942yxxVXqiXa4r347yVYx/Ok7xdZheBJNs9USnobT7fAct8JMW7PwJ2KWLQtf8sy2NZ" + - "z4PZljh/P1vbm2ssK1Z54dntv+Pt9WNHxZvZBxANeTRVwH1+3FtjLCdXKJrQSMm2lLGTe0nZfZ4f627nJbSxk/9VfYWg5vGTZL0+CtsM" + - "rWOvwrt9rWGuJbfQ3+w99/LfmHn63X2TqBju4sppfxdfMGfAvm843f8rH/Jq6jPbrZVgb0bN7C7/j8ZKutyuiKFGGrA37H2m6rR6Bvhx" + - "2eZxTbST7g//JdPAd9o3bb+od23h46Q+ftveQH/h/ex7hB78r9tqKid+HvjBvyYe6Bb+Pr5kFbRdG9/hBxRO/5w+QNet8eIQ+Ceeso4w" + - "u9WY+Tv+iNhZjm6H1Amwe9B0/aiofeladsUTJq42niAMJCJo/XtOPO2rqJ7obnbK0njjnO2/oZ/fn+sDUO3Wkv2OpLPFNetNUd/S9oi6" + - "H/4CWei/6Bl22dpS1yxdYUfGh81dZGfCh0zdYkfIh23VZjfHhPW454Z7tB/PEh4ua3eD9jEiiCDy9u81x8uHTHVlp8WH/XloH+o3/ZSk" + - "T8I+5xPT6svI+OYL55wGd8+P2hrTj4sPJvvqdd/Yh5FD+mPbb1AD96spicxY8iT2zNxo/mT22x9VFrNiEsWRr+HP34MOmFrcf40JdBfw" + - "EffnpJ/uJDkVfchw/FMGsuPsR6Y6s9PqR9azM348s7W/3Rn+q9rYGB/g+2dqA/80dbo9Cf9ZOtMejP+Blf0V/pf3b4niLjf3xmHGb9wu" + - "/4UOkr3+NDXTnajA8DDUdX8GGt6cgL9FuOYqG7jONoIXkw0OV39MfwHbVFb8NIjiLQO5dN5C30Lozi6D56p0R1xFZKkaI7YmrT8hiO/k" + - "HnfzGd8L3YtNiOLqMvV1xHfdDVPJ6jZeialcDRdfRsTOToDToyJnHUCe62SR2tgXtCMic8nzuf3FFceL+mcML3eNO+53nE7WUqRznhrZ" + - "na0S/wDk/j6Ai8+9I6MuGNk95RLXgHZnC0Fd7XGR1lhLNvZkcbicuVLI5AVawfHZUL5t/sjqrCmTGHE9a3OXI6YRzW53L0N7yTcjs6Sh" + - "yMvI7y4X+5fI6Gwr2WYu0B/qcv6Kgp/DEKOyoD9+wijs7jd182MRvh/ruEo+Twni/tKBJ5lL4c18N3toKj5/j4sZIjlkw9qOKEdVPV6o" + - "66wPF7TUd36L8xk3JwnjmPYnY3/U6q52gd/c5rwGf6PdkQ3/FtUmO+p9+NTfAvqJuaOkqMX+mbOypLnPe0cMJz89atHI3Er5RtiBN+DW" + - "/raBE8H9lURjGC9cAJzze3dkI3XIm64B8+xermKBU+Ve/uhPPw7B5O+L4hVS9HufAnTh9HqeGc0tfRYjjv9XP0Fs6I/o6Ok58RA5xwHx" + - "YxkBbeoYMdTYP37yGOPsLbepgT1s/thzsaCO+4EU74/qHrSEfDg3lpFPkKb0GVjVlmrKPKxLbUOHIP5rrjnfBsZ8oEJzyj6z0Jz4jxjs" + - "mO9sN+YQo5h7c9pzkaAHvWGY5y4+3LmY4+wP7nL47+CuaWOY5KwlzsVzwL1v55jlbA+v43R1+IbdcF5DKssRYRM1hjLHYUH9a2S4gZrG" + - "OWOZoMa8sVjjrAem+VE84R69c44d5kyjq0hTUyHsH18yZHXfH02mZHh+H6aaujAnDt2eZoJVzrt3MfXM13OvoJrly7HaWEq/4ecg2u6n" + - "sdFYFr/j5H4/AywQFHFlwnDzJm4fp8iBwOuI446glX66OOqpODV445OghflBOO3hP7aCcdPYHzPe0l/LROO7oLb5wzjl7iZ46zzBH4Wf" + - "Wco6xwlzvvKC1+lvgDHvibX3RUjFyYdgk9YQ3thGfPX684uslY736NMUZOpP3TkUMujLvB3IKOgywQC9FR5LajpPA/uANXMObvch9jJ/" + - "29b3NUkfv8jo54Dxy9pv1Ie4Wxf/ghPqLr+N/0h660TLQOehYyEXVHT/unjgqhY/EzJ9juaetzR5QdevzC0S709H7JHICOHa+ccE06/M" + - "bRLHREe+fodrAWvXfCs/MHH/ET/q2fuR/+9l94Lr7flKv18EaxXN3E9/mOq65w9fddVcLf5ZHd8Cy8bjRXcem/UAxXTOOaG9MN9yAJYr" + - "v6g/47x3GVgfjXjct19J88vqvr9F8ugSub/s8ndDWePPg9sasBwZyfxNVDOOYndcN3Gr2Tu+FZ8ekUrkbDE5HSVTf8m/e9G75zaZrKVR" + - "J8zPGDq+e0rVO7+h7On9K4iox/RdK6+kSbIB08+Jg6vas7wZ41g6uL+HmbdiY6zjIRjCQ/5lFY18DX05nd8Gx/fhb0oGswyZE7qCF/RB" + - "z/UmZzdTXQmd3VmWBPmMPVbnz+SrsNvTdzupqO3o25XLVB7+zcbrhH7J4HP9A9I6+riuiekM9VyWBvm99VE/S/LuBqFfoTFXJ1jjzKzI" + - "b5Pj6UK0Jn+PC1KM/Hh3nF4UR/pZL4SN7MLe2qWrBWlHXDd3OJKri6FuwlKrmai47qP7mKA/+TKq5W86jU1Vw9gHtudVf14bVqujoI78" + - "8ErxScj+u4Wgnfi7rkAXxN67tKCVfGhq6ewFW7sasE8Jxv4moKPPGau7oEz6yWrmrj/4XWrqbhd7a2rl4GtWU7V14Kxm17V7PwuURHV7" + - "eDmrKTG75rz9eF++Hb09VVXbjad+d6uGb0cJUNrrq9XL3Fx6O9XTXHv3194Q7Wqv5uWCPNHegqDz59HsTzyd/MQ10dD/auw9ywJr40nP" + - "wlPzb+TP7C132UqxjBmjXG1WH41o91w7/1OT7ODc/U801wtTeo/SYSd/iMyeQHfB2nuHqFf0enEj/inXK6q2VwVp3h6jKcTWeSv8H8O4" + - "s4wPn2F1f9ghp3jhuucX3nuvpCnCPNczURH2/SNoM7+XxXS+BOv8AN17oCC93wbHn9Irjw9R6Tahv4Cy11dYB4T1nmKn6Q3ytcHULHd6" + - "tcLSCfvyO4Y9HRfA35jo6ea91wbzZlnRv+UcbfFKy10FFso6sN4Tzt6g1+D9+MLvSc3uKqIDoitrpKE+zV2cg1IB+uRbgqi57NO9zwHU" + - "/zXTwfHfd2k3exg/karmCPtI/noGM9i1My+CcdQC/+xzjkalCwJzmMv/jf+yg+wX/tmBvW4odPuMoF97WTxBPu9KddzYb79RniDXeU86" + - "4ItUr94WorvHUvEl98H3WZ+MJ58wpxhS/zdVfz4Mt8gzZYm2+6SgtXpNuu+sL1+Y6r9nA9/os8w9cy991wPUn5kDyGy3rkqjt+nn/sqh" + - "h+lnrqakZQAz93tZlxdPylq0T0v+eNq2j4VPu9G64Hcz8xLug3z3+uRuFHza+ultJfbcPTcvq7YHlKRT/7HE8x6Cep56kj+uP5nlrSX/" + - "JInjonC/6exNNEfLgU1VMG9KeM7qkX/daN6YklViVie/qF/hfG8fSOeM1l4/VvML8k9MJ3/CUS8zscF5J44buLCsk8LUD/4+SeCpNXcV" + - "J6agNPy+897SQu+1J5igtX79ReePYUi8UvOHv6Lp2nLnCNyeDpFj54mTw1xYdKWdADT7FsnkhlvczhqQJxGJfb0wM44uVDB/meoICnrs" + - "F8XtgLa/amFM676D9pcU+9g/WvhKfh+B+tlKfW9Ju5tKdR+HK7jKd89Hu0vBeehayu5OkRPtSs4mkq+o9X8+Sie0pNT2fwf35tL/ybi3" + - "FMGsfod3g9T/vRbzXwwr/dKtLQ0wB86N/I0/bgbKmxp0xw/NzU0wF8yNrcUwc4drX09AGOa628cFylbOOpERyV2noaG9Q77b7xnG2P38" + - "H629HTeLhedvIUmx86diFu8HXu6ompQvO7eeGZeM0exA9/yvXy1A5/LvTxwneljft5GhLM+/09ncCnSQO98O86tw72dJm8+TjUU2J8qj" + - "3cUx/4lo7wdIQ4HWSjeR/OzyM9JYHTGOPpe/gyjvVUkTj1Hoff8K0dj9/E66eJnhoSr9mTiRt8H6d68vBv9XRPO4I9wUwv3JueneXpJj" + - "4mmuMpLVzZ5noqAte+Xz2dxseFv3laj3/7FvAZ/xYv8sI9wIwlnhbDNWMZLfGLWOHpcHCWusrTWnjervHCs7hJ6/ALjj83eLoKx4RN+B" + - "qcxWzxFD2Y5xnUU4nnhQhP5+BouMNTvaA+3OWF62LKvZ6S0f+TfeQD/iw+QF7Tf+pD6Kf/97TBO+P0R7zwb1X2HCW/8afpceKIPwVOMt" + - "7w5egpL3w3U4lFezA8087BC091ipVgD7/vgqeXfrBn95QSnveXPaWHZ9JVT78Ttz+veYqGPyn/9FQdrro3PI3Dn9S3PNWGb/VtfISv/l" + - "1PE8ivKfc8HSR+FottLuKW/qGn+vAV+9tTd/hGPSIO+PXyMfMDfuV4Ai+ceZ55ahbUqS8Yt+RXvH+98G8b47z0wjP0fK+88N1YsdfkL7" + - "ypmcSr4GPPt174bmz4e+aLoM7+6Ok6Pt797CkqnAW+ML7hHPfVC8/UUhq+KsI5xvK1Bc6Bth/+zU8MBll+OOeTLCfgfO37ShbUFZF9lY" + - "SzUFRfdfGxaTRfA+GMFcNXZjhLxfTF9kzzY/liiVDLOL6Gwjc8nq/5cOVL4KsmXNES++HfbnVN4msCXDOS+tpI/l9L5ustfLlS+KpKns" + - "2mCN8KX6QffKUO6uXUvurjY+00vrrDVy6tr5bwtU3n62d8PJje120452X0w/onUmZfpeBLn4XriHfWbL7aB2en2fkd/zbm8PUMvmi5fZ" + - "VjHOzK4+t9MA7ywxms1wXpH767hXwlhatzEV+r8a1xUV9z4ZtQzA/rjK/FfRXAP6+krxJwpi3tqzl81cv4mgRfmbK+hsNXvRyf4Wta3t" + - "c8fLxSAV/xsXYlP/zb4pOV/XA+GVjFF1scrWQD/y+8xar7Gg3nsxp++I4kQW1fjeCcUsfXVfIyoq6vL8Q5Rn1ftcjLHA189YN7eUNfz/" + - "E1dWNfHeC+1NRXkuCMsLmv7HAubenrKX7ebe0rXTBu2/p6CN/Ndn4433UmuWbCF9HR1y34Onb2NZ0fnnXxRUmv+t18DcPHSD18/Uj+le" + - "jpqx18vXuhBz8H9va1BM57fXxFhm9Ufz/c498e4MuF6/ZA2mCfNNhXq2AfOsTXL/g6iaQJ6twXw3zFx9fVI3z9Ae+EkeQpvu4Y5Ydnvm" + - "XG+OoE7/ux33g/s9nx4Z07gTyG9/ZE9AXzziRfj4Kz/8m+2CLq9RTMDPZ503xhtbpO9zUI/voz/bBeXzmL/uGOMRu/4D48h/7Jh1i/Ei" + - "98PU97K1ZQv/nhGWX3+b6GwO8sJH5wJ13kK0Pg82JfH+DPsdQPzyTfLvNlwt1+ha8++N17pa8R8C9d7esM/LPX+uE7i2fr0Q3nyY2+KD" + - "W0Y7Ovv/xgH+2HZ06tt/maHNQ9EfhH/Fvv4DOcR3eSL3D+HwCCjIRqMAAA"); - - RecordInputStream in = TestcaseRecordInputStream.create(bytes); - assertEquals(ExtSSTRecord.sid, in.getSid()); - ExtSSTRecord src = new ExtSSTRecord(in); - assertEquals(12386, src.getDataSize()); - ExtSSTRecord.InfoSubRecord[] sub1 = src.getInfoSubRecords(); - - byte[] serialized = src.serialize(); - - in = TestcaseRecordInputStream.create(serialized); - assertEquals(ExtSSTRecord.sid, in.getSid()); - ExtSSTRecord dst = new ExtSSTRecord(in); - assertEquals(12386, dst.getDataSize()); - ExtSSTRecord.InfoSubRecord[] sub2 = src.getInfoSubRecords(); - assertEquals(sub1.length, sub2.length); - - for(int i = 0; i < sub1.length; i++){ - ExtSSTRecord.InfoSubRecord s1 = sub1[i]; - ExtSSTRecord.InfoSubRecord s2 = sub2[i]; - - assertEquals(s1.getBucketSSTOffset(), s2.getBucketSSTOffset()); - assertEquals(s1.getStreamPos(), s2.getStreamPos()); - - } - } - - -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java deleted file mode 100644 index f4d191d69f..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java +++ /dev/null @@ -1,162 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -final class TestExtendedFormatRecord { - - private static final byte[] data = { - 0, 0, // Font 0 - 0, 0, // Format 0 - 0xF5 - 256, 0xFF - 256, // Cell opts ... - 0x20, 0, // Alignment 20 - 0, 0, // Ident 0 - 0, 0, // Border 0 - 0, 0, // Palette 0 - 0, 0, 0, 0, // ADTL Palette 0 - 0xC0 - 256, 0x20 // Fill Palette 20c0 - }; - - private static ExtendedFormatRecord createEFR() { - return new ExtendedFormatRecord(TestcaseRecordInputStream.create(0x00E0, data)); - } - - @Test - void testLoad() { - ExtendedFormatRecord record = createEFR(); - assertEquals(0, record.getFontIndex()); - assertEquals(0, record.getFormatIndex()); - assertEquals(0xF5 - 256, record.getCellOptions()); - assertEquals(0x20, record.getAlignmentOptions()); - assertEquals(0, record.getIndentionOptions()); - assertEquals(0, record.getBorderOptions()); - assertEquals(0, record.getPaletteOptions()); - assertEquals(0, record.getAdtlPaletteOptions()); - assertEquals(0x20c0, record.getFillPaletteOptions()); - - assertEquals(20 + 4, record.getRecordSize()); - } - - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { -// .fontindex = 0 -// .formatindex = 0 -// .celloptions = fffffff5 -// .islocked = true -// .ishidden = false -// .recordtype= 1 -// .parentidx = fff -// .alignmentoptions= 20 -// .alignment = 0 -// .wraptext = false -// .valignment= 2 -// .justlast = 0 -// .rotation = 0 -// .indentionoptions= 0 -// .indent = 0 -// .shrinktoft= false -// .mergecells= false -// .readngordr= 0 -// .formatflag= false -// .fontflag = false -// .prntalgnmt= false -// .borderflag= false -// .paternflag= false -// .celloption= false -// .borderoptns = 0 -// .lftln = 0 -// .rgtln = 0 -// .topln = 0 -// .btmln = 0 -// .paleteoptns = 0 -// .leftborder= 0 -// .rghtborder= 0 -// .diag = 0 -// .paleteoptn2 = 0 -// .topborder = 0 -// .botmborder= 0 -// .adtldiag = 0 -// .diaglnstyl= 0 -// .fillpattrn= 0 -// .fillpaloptn = 20c0 -// .foreground= 40 -// .background= 41 - - ExtendedFormatRecord record = new ExtendedFormatRecord(); - record.setFontIndex((short) 0); - record.setFormatIndex((short) 0); - - record.setLocked(true); - record.setHidden(false); - record.setXFType((short) 1); - record.setParentIndex((short) 0xfff); - - record.setVerticalAlignment((short) 2); - - record.setFillForeground((short) 0x40); - record.setFillBackground((short) 0x41); - - byte[] recordBytes = record.serialize(); - confirmRecordEncoding(ExtendedFormatRecord.sid, data, recordBytes); - } - - - - @SuppressWarnings("squid:S2699") - @Test - void testCloneOnto() { - ExtendedFormatRecord base = createEFR(); - - ExtendedFormatRecord other = new ExtendedFormatRecord(); - other.cloneStyleFrom(base); - - byte[] recordBytes = other.serialize(); - confirmRecordEncoding(ExtendedFormatRecord.sid, data, recordBytes); - } - - @Test - void testRotation() { - ExtendedFormatRecord record = createEFR(); - assertEquals(0, record.getRotation()); - - record.setRotation((short)1); - assertEquals(1, record.getRotation()); - - record.setRotation((short)89); - assertEquals(89, record.getRotation()); - - record.setRotation((short)90); - assertEquals(90, record.getRotation()); - - // internally values below zero are stored differently - record.setRotation((short)-1); - assertEquals(255, record.getRotation()); - - record.setRotation((short)-89); - assertEquals(-77, 90-record.getRotation()); - - record.setRotation((short)-90); - assertEquals(-76, 90-record.getRotation()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java deleted file mode 100644 index 41372882c6..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java +++ /dev/null @@ -1,172 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -final class TestExternalNameRecord { - - private static final byte[] dataFDS = { - 0, 0, 0, 0, 0, 0, 3, 0, 70, 68, 83, 0, 0, - }; - - // data taken from bugzilla 44774 att 21790 - private static final byte[] dataAutoDocName = { - -22, 127, 0, 0, 0, 0, 29, 0, 39, 49, 57, 49, 50, 49, 57, 65, 87, 52, 32, 67, 111, 114, - 112, 44, 91, 87, 79, 82, 75, 79, 85, 84, 95, 80, 88, 93, 39, - }; - - // data taken from bugzilla 44774 att 21790 - private static final byte[] dataPlainName = { - 0, 0, 0, 0, 0, 0, 9, 0, 82, 97, 116, 101, 95, 68, 97, 116, 101, 9, 0, 58, 0, 0, 0, 0, 4, 0, 8, 0 - // TODO - the last 2 bytes of formula data (8,0) seem weird. They encode to ConcatPtg, UnknownPtg - // UnknownPtg is otherwise not created by any other test cases - }; - - private static ExternalNameRecord createSimpleENR(byte[] data) { - return new ExternalNameRecord(TestcaseRecordInputStream.create(0x0023, data)); - } - - @Test - void testBasicDeserializeReserialize() { - - ExternalNameRecord enr = createSimpleENR(dataFDS); - assertEquals("FDS", enr.getText()); - - // bug 44695 - confirmRecordEncoding(0x0023, dataFDS, enr.serialize()); - } - - @Test - void testBasicSize() { - ExternalNameRecord enr = createSimpleENR(dataFDS); - assertNotEquals(13, enr.getRecordSize(), "Identified bug 44695"); - assertEquals(17, enr.getRecordSize()); - - assertNotNull(enr.serialize()); - } - - @Test - void testAutoStdDocName() { - - ExternalNameRecord enr = createSimpleENR(dataAutoDocName); - assertEquals("'191219AW4 Corp,[WORKOUT_PX]'", enr.getText()); - assertTrue(enr.isAutomaticLink()); - assertFalse(enr.isBuiltInName()); - assertFalse(enr.isIconifiedPictureLink()); - assertFalse(enr.isOLELink()); - assertFalse(enr.isPicureLink()); - assertTrue(enr.isStdDocumentNameIdentifier()); - - confirmRecordEncoding(0x0023, dataAutoDocName, enr.serialize()); - } - - @Test - void testPlainName() { - - ExternalNameRecord enr = createSimpleENR(dataPlainName); - assertEquals("Rate_Date", enr.getText()); - assertFalse(enr.isAutomaticLink()); - assertFalse(enr.isBuiltInName()); - assertFalse(enr.isIconifiedPictureLink()); - assertFalse(enr.isOLELink()); - assertFalse(enr.isPicureLink()); - assertFalse(enr.isStdDocumentNameIdentifier()); - - confirmRecordEncoding(0x0023, dataPlainName, enr.serialize()); - } - - @Test - void testDDELink_bug47229() { - /* - * Hex dump read directly from text of bugzilla 47229 - */ - final byte[] dataDDE = HexRead.readFromString( - "E2 7F 00 00 00 00 " + - "37 00 " + // text len - // 010672AT0 MUNI,[RTG_MOODY_UNDERLYING,RTG_SP_UNDERLYING] - "30 31 30 36 37 32 41 54 30 20 4D 55 4E 49 2C " + - "5B 52 54 47 5F 4D 4F 4F 44 59 5F 55 4E 44 45 52 4C 59 49 4E 47 2C " + - "52 54 47 5F 53 50 5F 55 4E 44 45 52 4C 59 49 4E 47 5D " + - // constant array { { "#N/A N.A.", "#N/A N.A.", }, } - " 01 00 00 " + - "02 09 00 00 23 4E 2F 41 20 4E 2E 41 2E " + - "02 09 00 00 23 4E 2F 41 20 4E 2E 41 2E"); - - // actual msg reported in bugzilla 47229 is different - // because that seems to be using a version from before svn r646666 - ExternalNameRecord enr = createSimpleENR(dataDDE); - assertEquals("010672AT0 MUNI,[RTG_MOODY_UNDERLYING,RTG_SP_UNDERLYING]", enr.getText()); - - confirmRecordEncoding(0x0023, dataDDE, enr.serialize()); - } - - @Test - void testUnicodeName_bug47384() { - // data taken from bugzilla 47384 att 23830 at offset 0x13A0 - byte[] dataUN = HexRead.readFromString( - "23 00 22 00" + - "00 00 00 00 00 00 " + - "0C 01 " + - "59 01 61 00 7A 00 65 00 6E 00 ED 00 5F 00 42 00 69 00 6C 00 6C 00 61 00" + - "00 00"); - - RecordInputStream in = TestcaseRecordInputStream.create(dataUN); - ExternalNameRecord enr = new ExternalNameRecord(in); - assertEquals("\u0159azen\u00ED_Billa", enr.getText()); - byte[] ser = enr.serialize(); - assertEquals(HexDump.toHex(dataUN), HexDump.toHex(ser)); - } - - @Test - void test48339() { - // data taken from bugzilla 48339 - byte[] data = HexRead.readFromString( - "23 00 09 00" + - "F4, FF, 14, 2D, 61, 01, 01, 00, 27"); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - ExternalNameRecord enr = new ExternalNameRecord(in); - byte[] ser = enr.serialize(); - assertEquals(HexDump.toHex(data), HexDump.toHex(ser)); - } - - @Test - void testNPEWithFileFrom49219() { - // the file at test-data/spreadsheet/49219.xls has ExternalNameRecords without actual data, - // we did handle this during reading, but failed during serializing this out, ensure it works now - byte[] data = new byte[] { - 2, 127, 0, 0, 0, 0, - 9, 0, 82, 97, 116, 101, 95, 68, 97, 116, 101}; - - ExternalNameRecord enr = createSimpleENR(data); - - byte[] ser = enr.serialize(); - assertEquals("[23, 00, 11, 00, 02, 7F, 00, 00, 00, 00, 09, 00, 52, 61, 74, 65, 5F, 44, 61, 74, 65]", - HexDump.toHex(ser)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java deleted file mode 100644 index c6a9cd9581..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java +++ /dev/null @@ -1,198 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.common.FeatFormulaErr2; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFTestHelper; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for FeatRecord - */ -final class TestFeatRecord { - @Test - void testWithoutFeatRecord() throws Exception { - HSSFWorkbook hssf = - HSSFTestDataSamples.openSampleWorkbook("46136-WithWarnings.xls"); - InternalWorkbook wb = HSSFTestHelper.getWorkbookForTest(hssf); - - assertEquals(1, hssf.getNumberOfSheets()); - - int countFR = 0; - int countFRH = 0; - - // Check on the workbook, but shouldn't be there! - for(org.apache.poi.hssf.record.Record r : wb.getRecords()) { - if(r instanceof FeatRecord) { - countFR++; - } else if (r.getSid() == FeatRecord.sid) { - countFR++; - } - if(r instanceof FeatHdrRecord) { - countFRH++; - } else if (r.getSid() == FeatHdrRecord.sid) { - countFRH++; - } - } - - assertEquals(0, countFR); - assertEquals(0, countFRH); - - // Now check on the sheet - HSSFSheet s = hssf.getSheetAt(0); - InternalSheet sheet = HSSFTestHelper.getSheetForTest(s); - - for(RecordBase rb : sheet.getRecords()) { - if(rb instanceof Record) { - Record r = (org.apache.poi.hssf.record.Record)rb; - if(r instanceof FeatRecord) { - countFR++; - } else if (r.getSid() == FeatRecord.sid) { - countFR++; - } - if(r instanceof FeatHdrRecord) { - countFRH++; - } else if (r.getSid() == FeatHdrRecord.sid) { - countFRH++; - } - } - } - - assertEquals(0, countFR); - assertEquals(0, countFRH); - } - - @Test - void testReadFeatRecord() { - HSSFWorkbook hssf = - HSSFTestDataSamples.openSampleWorkbook("46136-NoWarnings.xls"); - InternalWorkbook wb = HSSFTestHelper.getWorkbookForTest(hssf); - - FeatRecord fr = null; - FeatHdrRecord fhr = null; - - assertEquals(1, hssf.getNumberOfSheets()); - - // First check it isn't on the Workbook - int countFR = 0; - int countFRH = 0; - for(org.apache.poi.hssf.record.Record r : wb.getRecords()) { - if(r instanceof FeatRecord) { - fr = (FeatRecord)r; - countFR++; - } else if (r.getSid() == FeatRecord.sid) { - fail("FeatRecord SID found but not created correctly!"); - } - if(r instanceof FeatHdrRecord) { - countFRH++; - } else if (r.getSid() == FeatHdrRecord.sid) { - fail("FeatHdrRecord SID found but not created correctly!"); - } - } - - assertEquals(0, countFR); - assertEquals(0, countFRH); - - // Now find it on our sheet - HSSFSheet s = hssf.getSheetAt(0); - InternalSheet sheet = HSSFTestHelper.getSheetForTest(s); - - for(RecordBase rb : sheet.getRecords()) { - if(rb instanceof Record) { - Record r = (org.apache.poi.hssf.record.Record)rb; - if(r instanceof FeatRecord) { - fr = (FeatRecord)r; - countFR++; - } else if (r.getSid() == FeatRecord.sid) { - countFR++; - } - if(r instanceof FeatHdrRecord) { - fhr = (FeatHdrRecord)r; - countFRH++; - } else if (r.getSid() == FeatHdrRecord.sid) { - countFRH++; - } - } - } - - assertEquals(1, countFR); - assertEquals(1, countFRH); - assertNotNull(fr); - assertNotNull(fhr); - - // Now check the contents are as expected - assertEquals( - FeatHdrRecord.SHAREDFEATURES_ISFFEC2, - fr.getIsf_sharedFeatureType() - ); - - // Applies to one cell only - assertEquals(1, fr.getCellRefs().length); - assertEquals(0, fr.getCellRefs()[0].getFirstRow()); - assertEquals(0, fr.getCellRefs()[0].getLastRow()); - assertEquals(0, fr.getCellRefs()[0].getFirstColumn()); - assertEquals(0, fr.getCellRefs()[0].getLastColumn()); - - // More checking of shared features stuff - assertEquals(4, fr.getCbFeatData()); - assertEquals(4, fr.getSharedFeature().getDataSize()); - assertEquals(FeatFormulaErr2.class, fr.getSharedFeature().getClass()); - - FeatFormulaErr2 fferr2 = (FeatFormulaErr2)fr.getSharedFeature(); - assertEquals(0x04, fferr2._getRawErrorCheckValue()); - - assertFalse(fferr2.getCheckCalculationErrors()); - assertFalse(fferr2.getCheckDateTimeFormats()); - assertFalse(fferr2.getCheckEmptyCellRef()); - assertFalse(fferr2.getCheckInconsistentFormulas()); - assertFalse(fferr2.getCheckInconsistentRanges()); - assertTrue(fferr2.getCheckNumbersAsText()); - assertFalse(fferr2.getCheckUnprotectedFormulas()); - assertFalse(fferr2.getPerformDataValidation()); - } - - /** - * cloning sheets with feat records - */ - @Test - void testCloneSheetWithFeatRecord() throws IOException { - try (HSSFWorkbook wb = - HSSFTestDataSamples.openSampleWorkbook("46136-WithWarnings.xls")) { - HSSFSheet src = wb.getSheetAt(0); - HSSFSheet dst = wb.cloneSheet(0); - - InternalSheet isrc = HSSFTestHelper.getSheetForTest(src); - InternalSheet idst = HSSFTestHelper.getSheetForTest(dst); - - assertEquals(isrc.getRecords().size(), idst.getRecords().size()); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java deleted file mode 100644 index 2dbaeb4818..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java +++ /dev/null @@ -1,157 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the {@link FontRecord} - * class works correctly. Test data taken directly from a real Excel file. - */ -final class TestFontRecord { - - private static final int SID = 0x31; - private static final byte[] data = { - 0xC8-256, 0, // font height = xc8 - 0, 0, // attrs = 0 - 0xFF-256, 0x7F, // colour palette = x7fff - 0x90-256, 0x01, // bold weight = x190 - 0, 0, // supersubscript - 0, 0, // underline, family - 0, 0, // charset, padding - 5, 0, // name length, unicode flag - 0x41, 0x72, 0x69, 0x61, 0x6C, // Arial, as unicode - - }; - - @Test - void testLoad() { - - FontRecord record = new FontRecord(TestcaseRecordInputStream.create(0x31, data)); - assertEquals(0xc8, record.getFontHeight()); - assertEquals(0x00, record.getAttributes()); - assertFalse(record.isItalic()); - assertFalse(record.isStruckout()); - assertFalse(record.isMacoutlined()); - assertFalse(record.isMacshadowed()); - assertEquals(0x7fff, record.getColorPaletteIndex()); - assertEquals(0x190, record.getBoldWeight()); - assertEquals(0x00, record.getSuperSubScript()); - assertEquals(0x00, record.getUnderline()); - assertEquals(0x00, record.getFamily()); - assertEquals(0x00, record.getCharset()); - assertEquals("Arial", record.getFontName()); - - assertEquals(21 + 4, record.getRecordSize()); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { -// .fontheight = c8 -// .attributes = 0 -// .italic = false -// .strikout = false -// .macoutlined= false -// .macshadowed= false -// .colorpalette = 7fff -// .boldweight = 190 -// .supersubscript = 0 -// .underline = 0 -// .family = 0 -// .charset = 0 -// .namelength = 5 -// .fontname = Arial - - FontRecord record = new FontRecord(); - record.setFontHeight((short)0xc8); - record.setAttributes((short)0); - record.setColorPaletteIndex((short)0x7fff); - record.setBoldWeight((short)0x190); - record.setSuperSubScript((short)0); - record.setUnderline((byte)0); - record.setFamily((byte)0); - record.setCharset((byte)0); - record.setFontName("Arial"); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(0x31, data, recordBytes); - } - - @Test - void testCloneOnto() { - FontRecord base = new FontRecord(TestcaseRecordInputStream.create(0x31, data)); - - FontRecord other = new FontRecord(); - other.cloneStyleFrom(base); - - byte [] recordBytes = other.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals(data[i], recordBytes[i+4], "At offset " + i); - } - - @Test - void testSameProperties() { - FontRecord f1 = new FontRecord(TestcaseRecordInputStream.create(0x31, data)); - FontRecord f2 = new FontRecord(TestcaseRecordInputStream.create(0x31, data)); - - assertTrue(f1.sameProperties(f2)); - - f2.setFontName("Arial2"); - assertFalse(f1.sameProperties(f2)); - f2.setFontName("Arial"); - assertTrue(f1.sameProperties(f2)); - - f2.setFontHeight((short)11); - assertFalse(f1.sameProperties(f2)); - f2.setFontHeight((short)0xc8); - assertTrue(f1.sameProperties(f2)); - } - - /** - * Bugzilla 47250 suggests that the unicode options byte should be present even when the name - * length is zero. The OOO documentation seems to agree with this and POI had no test data - * samples to say otherwise. - */ - @Test - void testEmptyName_bug47250() { - byte[] emptyNameData = HexRead.readFromString( - "C8 00 00 00 FF 7F 90 01 00 00 00 00 00 00 " - + "00" // zero length - + "00" // unicode options byte - ); - - RecordInputStream in = TestcaseRecordInputStream.create(SID, emptyNameData); - FontRecord fr = new FontRecord(in); - assertNotEquals(1, in.available()); - assertEquals(0, in.available()); - - assertEquals(0, fr.getFontName().length()); - byte[] recordBytes = fr.serialize(); - confirmRecordEncoding(SID, emptyNameData, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java deleted file mode 100644 index 623588ffee..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java +++ /dev/null @@ -1,200 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.IntPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaError; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link FormulaRecord} - */ -final class TestFormulaRecord { - - @Test - void testCreateFormulaRecord () { - FormulaRecord record = new FormulaRecord(); - record.setColumn((short)0); - record.setRow(1); - record.setXFIndex((short)4); - - assertEquals(record.getColumn(),0); - assertEquals(record.getRow(), 1); - assertEquals(record.getXFIndex(),4); - } - - /** - * Make sure a NAN value is preserved - * This formula record is a representation of =1/0 at row 0, column 0 - */ - @Test - void testCheckNanPreserve() { - byte[] formulaByte = { - 0, 0, 0, 0, - 0x0F, 0x00, - - // 8 bytes cached number is a 'special value' in this case - 0x02, // special cached value type 'error' - 0x00, - FormulaError.DIV0.getCode(), - 0x00, - 0x00, - 0x00, - (byte)0xFF, - (byte)0xFF, - - 0x00, - 0x00, - 0x00, - 0x00, - - (byte)0xE0, //18 - (byte)0xFC, - // Ptgs - 0x07, 0x00, // encoded length - 0x1E, 0x01, 0x00, // IntPtg(1) - 0x1E, 0x00, 0x00, // IntPtg(0) - 0x06, // DividePtg - - }; - - FormulaRecord record = new FormulaRecord(TestcaseRecordInputStream.create(FormulaRecord.sid, formulaByte)); - assertEquals(0, record.getRow(), "Row"); - assertEquals(0, record.getColumn(), "Column"); - //noinspection deprecation - assertEquals(CellType.ERROR.getCode(), record.getCachedResultType()); - assertEquals(CellType.ERROR, record.getCachedResultTypeEnum()); - - byte[] output = record.serialize(); - // includes sid+recordlength - assertEquals(33, output.length, "Output size"); - - for (int i = 5; i < 13;i++) { - assertEquals(formulaByte[i], output[i+4], "FormulaByte NaN doesn't match"); - } - } - - /** - * Tests to see if the shared formula cells properly reserialize the expPtg - */ - @Test - void testExpFormula() { - byte[] formulaByte = new byte[27]; - - formulaByte[4] =(byte)0x0F; - formulaByte[14]=(byte)0x08; - formulaByte[18]=(byte)0xE0; - formulaByte[19]=(byte)0xFD; - formulaByte[20]=(byte)0x05; - formulaByte[22]=(byte)0x01; - FormulaRecord record = new FormulaRecord(TestcaseRecordInputStream.create(FormulaRecord.sid, formulaByte)); - assertEquals(0, record.getRow(), "Row"); - assertEquals(0, record.getColumn(), "Column"); - byte[] output = record.serialize(); - // includes sid+recordlength - assertEquals(31, output.length, "Output size"); - assertEquals(1, output[26], "Offset 22"); - } - - @Test - void testWithConcat() { - // =CHOOSE(2,A2,A3,A4) - byte[] data = { - 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 - 25, 4, 3, 0, // Attr - 8, 0, 17, 0, 26, 0, // jumpTable - 35, 0, // chooseOffset - 36, 1, 0, 0, -64, // Ref - A2 - 25, 8, 21, 0, // Attr - 36, 2, 0, 0, -64, // Ref - A3 - 25, 8, 12, 0, // Attr - 36, 3, 0, 0, -64, // Ref - A4 - 25, 8, 3, 0, // Attr - 66, 4, 100, 0 // CHOOSE - }; - RecordInputStream inp = TestcaseRecordInputStream.create(FormatRecord.sid, data); - - FormulaRecord fr = new FormulaRecord(inp); - - Ptg[] ptgs = fr.getParsedExpression(); - assertEquals(9, ptgs.length); - assertEquals(IntPtg.class, ptgs[0].getClass()); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals(RefPtg.class, ptgs[2].getClass()); - assertEquals(AttrPtg.class, ptgs[3].getClass()); - assertEquals(RefPtg.class, ptgs[4].getClass()); - assertEquals(AttrPtg.class, ptgs[5].getClass()); - assertEquals(RefPtg.class, ptgs[6].getClass()); - assertEquals(AttrPtg.class, ptgs[7].getClass()); - assertEquals(FuncVarPtg.class, ptgs[8].getClass()); - - FuncVarPtg choose = (FuncVarPtg)ptgs[8]; - assertEquals("CHOOSE", choose.getName()); - } - - @Test - void testReserialize() { - FormulaRecord formulaRecord = new FormulaRecord(); - formulaRecord.setRow(1); - formulaRecord.setColumn((short) 1); - formulaRecord.setParsedExpression(new Ptg[] { new RefPtg("B$5"), }); - formulaRecord.setValue(3.3); - byte[] ser = formulaRecord.serialize(); - assertEquals(31, ser.length); - - RecordInputStream in = TestcaseRecordInputStream.create(ser); - FormulaRecord fr2 = new FormulaRecord(in); - assertEquals(3.3, fr2.getValue(), 0.0); - Ptg[] ptgs = fr2.getParsedExpression(); - assertEquals(1, ptgs.length); - RefPtg rp = (RefPtg) ptgs[0]; - assertEquals("B$5", rp.toFormulaString()); - } - - /** - * Bug noticed while fixing 46479. Operands of conditional operator ( ? : ) were swapped - * inside {@link FormulaRecord} - */ - @Test - void testCachedValue_bug46479() { - FormulaRecord fr0 = new FormulaRecord(); - FormulaRecord fr1 = new FormulaRecord(); - // test some other cached value types - fr0.setValue(3.5); - assertEquals(3.5, fr0.getValue(), 0.0); - fr0.setCachedResultErrorCode(FormulaError.REF.getCode()); - assertEquals(FormulaError.REF.getCode(), fr0.getCachedErrorValue()); - - fr0.setCachedResultBoolean(false); - fr1.setCachedResultBoolean(true); - assertFalse(fr0.getCachedBooleanValue() && !fr1.getCachedBooleanValue(), "Identified bug 46479c"); - assertFalse(fr0.getCachedBooleanValue()); - assertTrue(fr1.getCachedBooleanValue()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java deleted file mode 100644 index 2804fe3d71..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the FtCblsSubRecord - * class works correctly. - */ -final class TestFtCblsSubRecord { - private final byte[] data = new byte[] { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, - 0x01, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00 - }; - - @Test - void testRead() { - FtCblsSubRecord record = new FtCblsSubRecord(TestcaseRecordInputStream.create(FtCblsSubRecord.sid, data), data.length); - - assertEquals(FtCblsSubRecord.sid, record.getSid()); - assertEquals(data.length, record.getDataSize()); - } - - @Test - void testWrite() { - FtCblsSubRecord record = new FtCblsSubRecord(); - assertEquals(FtCblsSubRecord.sid, record.getSid()); - assertEquals(data.length, record.getDataSize()); - - byte [] ser = record.serialize(); - assertEquals(ser.length - 4, data.length); - } - - @Test - void testClone() { - FtCblsSubRecord record = new FtCblsSubRecord(); - byte[] src = record.serialize(); - - FtCblsSubRecord cloned = record.copy(); - byte[] cln = cloned.serialize(); - - assertEquals(record.getDataSize(), cloned.getDataSize()); - assertArrayEquals(src, cln); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java b/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java deleted file mode 100644 index a372d11685..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java +++ /dev/null @@ -1,545 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.hpsf.ClassID; -import org.apache.poi.hpsf.ClassIDPredefined; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; -import org.junit.jupiter.api.Test; - -/** - * Test HyperlinkRecord - */ -final class TestHyperlinkRecord { - - //link to http://www.lakings.com/ - private static final byte[] data1 = { - 0x02, 0x00, //First row of the hyperlink - 0x02, 0x00, //Last row of the hyperlink - 0x00, 0x00, //First column of the hyperlink - 0x00, 0x00, //Last column of the hyperlink - - //16-byte GUID. Seems to be always the same. Does not depend on the hyperlink type - (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - 0x02, 0x00, 0x00, 0x00, //integer, always 2 - - // flags. Define the type of the hyperlink: - // HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL - 0x17, 0x00, 0x00, 0x00, - - 0x08, 0x00, 0x00, 0x00, //length of the label including the trailing '\0' - - //label: - 0x4D, 0x00, 0x79, 0x00, 0x20, 0x00, 0x4C, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x6B, 0x00, 0x00, 0x00, - - //16-byte link moniker: HyperlinkRecord.URL_MONIKER - (byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - //count of bytes in the address including the tail - 0x48, 0x00, 0x00, 0x00, //integer - - //the actual link, terminated by '\u0000' - 0x68, 0x00, 0x74, 0x00, 0x74, 0x00, 0x70, 0x00, 0x3A, 0x00, 0x2F, 0x00, - 0x2F, 0x00, 0x77, 0x00, 0x77, 0x00, 0x77, 0x00, 0x2E, 0x00, 0x6C, 0x00, - 0x61, 0x00, 0x6B, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x73, 0x00, - 0x2E, 0x00, 0x63, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x2F, 0x00, 0x00, 0x00, - - //standard 24-byte tail of a URL link. Seems to always be the same for all URL HLINKs - 0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, 0x2C, - (byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00, - 0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00 - }; - - //link to a file in the current directory: link1.xls - private static final byte[] data2 = { - 0x00, 0x00, - 0x00, 0x00, - 0x00, 0x00, - 0x00, 0x00, - //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type - (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - 0x02, 0x00, 0x00, 0x00, //integer, always 2 - - 0x15, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL - - 0x05, 0x00, 0x00, 0x00, //length of the label - //label - 0x66, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x65, 0x00, 0x00, 0x00, - - //16-byte link moniker: HyperlinkRecord.FILE_MONIKER - 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, - - 0x00, 0x00, //level - 0x0A, 0x00, 0x00, 0x00, //length of the path ) - - //path to the file (plain ISO-8859 bytes, NOT UTF-16LE!) - 0x6C, 0x69, 0x6E, 0x6B, 0x31, 0x2E, 0x78, 0x6C, 0x73, 0x00, - - //standard 24-byte tail of a file link - (byte)0xFF, (byte)0xFF, (byte)0xAD, (byte)0xDE, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, - - 0x00, 0x00, 0x00, 0x00, // length of address link field - }; - - // mailto:ebgans@mail.ru?subject=Hello,%20Ebgans! - private static final byte[] data3 = { - 0x01, 0x00, - 0x01, 0x00, - 0x00, 0x00, - 0x00, 0x00, - - //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type - (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - 0x02, 0x00, 0x00, 0x00, //integer, always 2 - - 0x17, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL - - 0x06, 0x00, 0x00, 0x00, //length of the label - 0x65, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x00, 0x00, //label - - //16-byte link moniker: HyperlinkRecord.URL_MONIKER - (byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - //length of the address including the tail. - 0x76, 0x00, 0x00, 0x00, - - //the address is terminated by '\u0000' - 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x74, 0x00, 0x6F, 0x00, - 0x3A, 0x00, 0x65, 0x00, 0x62, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6E, 0x00, - 0x73, 0x00, 0x40, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, - 0x2E, 0x00, 0x72, 0x00, 0x75, 0x00, 0x3F, 0x00, 0x73, 0x00, 0x75, 0x00, - 0x62, 0x00, 0x6A, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x3D, 0x00, - 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x2C, 0x00, - 0x25, 0x00, 0x32, 0x00, 0x30, 0x00, 0x45, 0x00, 0x62, 0x00, 0x67, 0x00, - 0x61, 0x00, 0x6E, 0x00, 0x73, 0x00, 0x21, 0x00, 0x00, 0x00, - - //standard 24-byte tail of a URL link - 0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, (byte)0x2C, - (byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00, - 0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00 - }; - - //link to a place in worksheet: Sheet1!A1 - private static final byte[] data4 = { - 0x03, 0x00, - 0x03, 0x00, - 0x00, 0x00, - 0x00, 0x00, - - //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type - (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - 0x02, 0x00, 0x00, 0x00, //integer, always 2 - - 0x1C, 0x00, 0x00, 0x00, //flags: HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE - - 0x06, 0x00, 0x00, 0x00, //length of the label - - 0x70, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x63, 0x00, 0x65, 0x00, 0x00, 0x00, //label - - 0x0A, 0x00, 0x00, 0x00, //length of the document link including trailing zero - - //link: Sheet1!A1 - 0x53, 0x00, 0x68, 0x00, 0x65, 0x00, 0x65, 0x00, 0x74, 0x00, 0x31, 0x00, 0x21, - 0x00, 0x41, 0x00, 0x31, 0x00, 0x00, 0x00 - }; - - private static final byte[] dataLinkToWorkbook = HexRead.readFromString( - "01 00 01 00 01 00 01 00 " + - "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + - "02 00 00 00 " + - "1D 00 00 00 " + // options: LABEL | PLACE | FILE_OR_URL - // label: "My Label" - "09 00 00 00 " + - "4D 00 79 00 20 00 4C 00 61 00 62 00 65 00 6C 00 00 00 " + - "03 03 00 00 00 00 00 00 C0 00 00 00 00 00 00 46 " + // file GUID - "00 00 " + // file options - // shortFileName: "YEARFR~1.XLS" - "0D 00 00 00 " + - "59 45 41 52 46 52 7E 31 2E 58 4C 53 00 " + - // FILE_TAIL - unknown byte sequence - "FF FF AD DE 00 00 00 00 " + - "00 00 00 00 00 00 00 00 " + - "00 00 00 00 00 00 00 00 " + - // field len, char data len - "2E 00 00 00 " + - "28 00 00 00 " + - "03 00 " + // unknown ushort - // _address: "yearfracExamples.xls" - "79 00 65 00 61 00 72 00 66 00 72 00 61 00 63 00 " + - "45 00 78 00 61 00 6D 00 70 00 6C 00 65 00 73 00 " + - "2E 00 78 00 6C 00 73 00 " + - // textMark: "Sheet1!B6" - "0A 00 00 00 " + - "53 00 68 00 65 00 65 00 74 00 31 00 21 00 42 00 " + - "36 00 00 00" - ); - - private static final byte[] dataTargetFrame = HexRead.readFromString( - "0E 00 0E 00 00 00 00 00 " + - "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + - "02 00 00 00 " + - "83 00 00 00 " + // options: TARGET_FRAME | ABS | FILE_OR_URL - // targetFrame: "_blank" - "07 00 00 00 " + - "5F 00 62 00 6C 00 61 00 6E 00 6B 00 00 00 " + - // url GUID - "E0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + - // address: "http://www.regnow.com/softsell/nph-softsell.cgi?currency=USD&item=7924-37" - "94 00 00 00 " + - "68 00 74 00 74 00 70 00 3A 00 2F 00 2F 00 77 00 " + - "77 00 77 00 2E 00 72 00 65 00 67 00 6E 00 6F 00 " + - "77 00 2E 00 63 00 6F 00 6D 00 2F 00 73 00 6F 00 " + - "66 00 74 00 73 00 65 00 6C 00 6C 00 2F 00 6E 00 " + - "70 00 68 00 2D 00 73 00 6F 00 66 00 74 00 73 00 " + - "65 00 6C 00 6C 00 2E 00 63 00 67 00 69 00 3F 00 " + - "63 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 " + - "3D 00 55 00 53 00 44 00 26 00 69 00 74 00 65 00 " + - "6D 00 3D 00 37 00 39 00 32 00 34 00 2D 00 33 00 " + - "37 00 00 00" - ); - - - private static final byte[] dataUNC = HexRead.readFromString( - "01 00 01 00 01 00 01 00 " + - "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + - "02 00 00 00 " + - "1F 01 00 00 " + // options: UNC_PATH | LABEL | TEXT_MARK | ABS | FILE_OR_URL - "09 00 00 00 " + // label: "My Label" - "4D 00 79 00 20 00 6C 00 61 00 62 00 65 00 6C 00 00 00 " + - // note - no moniker GUID - "27 00 00 00 " + // "\\\\MyServer\\my-share\\myDir\\PRODNAME.xls" - "5C 00 5C 00 4D 00 79 00 53 00 65 00 72 00 76 00 " + - "65 00 72 00 5C 00 6D 00 79 00 2D 00 73 00 68 00 " + - "61 00 72 00 65 00 5C 00 6D 00 79 00 44 00 69 00 " + - "72 00 5C 00 50 00 52 00 4F 00 44 00 4E 00 41 00 " + - "4D 00 45 00 2E 00 78 00 6C 00 73 00 00 00 " + - - "0C 00 00 00 " + // textMark: PRODNAME!C2 - "50 00 52 00 4F 00 44 00 4E 00 41 00 4D 00 45 00 21 00 " + - "43 00 32 00 00 00" - ); - - - /** - * From Bugzilla 47498 - */ - private static final byte[] data_47498 = { - 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xD0, (byte)0xC9, - (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C, - (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x02, 0x00, - 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x50, 0x00, - 0x44, 0x00, 0x46, 0x00, 0x00, 0x00, (byte)0xE0, (byte)0xC9, (byte)0xEA, - 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, (byte)0x11, (byte)0x8C, (byte)0x82, - 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x28, 0x00, 0x00, 0x00, - 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x66, 0x00, 0x6F, 0x00, - 0x6C, 0x00, 0x64, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2F, 0x00, 0x74, 0x00, - 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x2E, 0x00, 0x50, 0x00, 0x44, 0x00, - 0x46, 0x00, 0x00, 0x00 - }; - - - private void confirmGUID(ClassID expectedGuid, ClassID actualGuid) { - assertEquals(expectedGuid, actualGuid); - } - - @Test - void testReadURLLink(){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data1); - HyperlinkRecord link = new HyperlinkRecord(is); - assertEquals(2, link.getFirstRow()); - assertEquals(2, link.getLastRow()); - assertEquals(0, link.getFirstColumn()); - assertEquals(0, link.getLastColumn()); - confirmGUID(ClassIDPredefined.STD_MONIKER.getClassID(), link.getGuid()); - confirmGUID(ClassIDPredefined.URL_MONIKER.getClassID(), link.getMoniker()); - assertEquals(2, link.getLabelOptions()); - int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL; - assertEquals(0x17, opts); - assertEquals(opts, link.getLinkOptions()); - assertEquals(0, link.getFileOptions()); - - assertEquals("My Link", link.getLabel()); - assertEquals("http://www.lakings.com/", link.getAddress()); - } - - @Test - void testReadFileLink(){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data2); - HyperlinkRecord link = new HyperlinkRecord(is); - assertEquals(0, link.getFirstRow()); - assertEquals(0, link.getLastRow()); - assertEquals(0, link.getFirstColumn()); - assertEquals(0, link.getLastColumn()); - confirmGUID(ClassIDPredefined.STD_MONIKER.getClassID(), link.getGuid()); - confirmGUID(ClassIDPredefined.FILE_MONIKER.getClassID(), link.getMoniker()); - assertEquals(2, link.getLabelOptions()); - int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL; - assertEquals(0x15, opts); - assertEquals(opts, link.getLinkOptions()); - - assertEquals("file", link.getLabel()); - assertEquals("link1.xls", link.getShortFilename()); - assertEquals("link1.xls", link.getAddress()); - } - - @Test - void testReadEmailLink(){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data3); - HyperlinkRecord link = new HyperlinkRecord(is); - assertEquals(1, link.getFirstRow()); - assertEquals(1, link.getLastRow()); - assertEquals(0, link.getFirstColumn()); - assertEquals(0, link.getLastColumn()); - confirmGUID(ClassIDPredefined.STD_MONIKER.getClassID(), link.getGuid()); - confirmGUID(ClassIDPredefined.URL_MONIKER.getClassID(), link.getMoniker()); - assertEquals(2, link.getLabelOptions()); - int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL; - assertEquals(0x17, opts); - assertEquals(opts, link.getLinkOptions()); - - assertEquals("email", link.getLabel()); - assertEquals("mailto:ebgans@mail.ru?subject=Hello,%20Ebgans!", link.getAddress()); - } - - @Test - void testReadDocumentLink(){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data4); - HyperlinkRecord link = new HyperlinkRecord(is); - assertEquals(3, link.getFirstRow()); - assertEquals(3, link.getLastRow()); - assertEquals(0, link.getFirstColumn()); - assertEquals(0, link.getLastColumn()); - confirmGUID(ClassIDPredefined.STD_MONIKER.getClassID(), link.getGuid()); - assertEquals(2, link.getLabelOptions()); - int opts = HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE; - assertEquals(0x1C, opts); - assertEquals(opts, link.getLinkOptions()); - - assertEquals("place", link.getLabel()); - assertEquals("Sheet1!A1", link.getTextMark()); - assertEquals("Sheet1!A1", link.getAddress()); - } - - private void serialize(byte[] data){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data); - HyperlinkRecord link = new HyperlinkRecord(is); - byte[] bytes1 = link.serialize(); - is = TestcaseRecordInputStream.create(bytes1); - link = new HyperlinkRecord(is); - byte[] bytes2 = link.serialize(); - assertEquals(bytes1.length, bytes2.length); - assertArrayEquals(bytes1, bytes2); - } - - @Test - void testSerialize(){ - serialize(data1); - serialize(data2); - serialize(data3); - serialize(data4); - } - - @Test - void testCreateURLRecord() { - HyperlinkRecord link = new HyperlinkRecord(); - link.newUrlLink(); - link.setFirstRow((short)2); - link.setLastRow((short)2); - link.setLabel("My Link"); - link.setAddress("http://www.lakings.com/"); - - byte[] tmp = link.serialize(); - byte[] ser = Arrays.copyOfRange(tmp, 4, tmp.length); - assertEquals(data1.length, ser.length); - assertArrayEquals(data1, ser); - } - - @Test - void testCreateFileRecord() { - HyperlinkRecord link = new HyperlinkRecord(); - link.newFileLink(); - link.setFirstRow((short)0); - link.setLastRow((short)0); - link.setLabel("file"); - link.setShortFilename("link1.xls"); - - byte[] tmp = link.serialize(); - byte[] ser = Arrays.copyOfRange(tmp, 4, tmp.length); - assertEquals(data2.length, ser.length); - assertArrayEquals(data2, ser); - } - - @Test - void testCreateDocumentRecord() { - HyperlinkRecord link = new HyperlinkRecord(); - link.newDocumentLink(); - link.setFirstRow((short)3); - link.setLastRow((short)3); - link.setLabel("place"); - link.setTextMark("Sheet1!A1"); - - byte[] tmp = link.serialize(); - byte[] ser = Arrays.copyOfRange(tmp, 4, tmp.length); - assertEquals(data4.length, ser.length); - assertArrayEquals(data4, ser); - } - - @Test - void testCreateEmailtRecord() { - HyperlinkRecord link = new HyperlinkRecord(); - link.newUrlLink(); - link.setFirstRow((short)1); - link.setLastRow((short)1); - link.setLabel("email"); - link.setAddress("mailto:ebgans@mail.ru?subject=Hello,%20Ebgans!"); - - byte[] tmp = link.serialize(); - byte[] ser = Arrays.copyOfRange(tmp, 4, tmp.length); - assertEquals(data3.length, ser.length); - assertArrayEquals(data3, ser); - } - - @Test - void testClone() { - byte[][] data = {data1, data2, data3, data4}; - for (final byte[] d : data) { - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, d); - HyperlinkRecord link = new HyperlinkRecord(is); - HyperlinkRecord clone = link.copy(); - assertArrayEquals(link.serialize(), clone.serialize()); - } - - } - - @SuppressWarnings("squid:S2699") - @Test - void testReserializeTargetFrame() { - RecordInputStream in = TestcaseRecordInputStream.create(HyperlinkRecord.sid, dataTargetFrame); - HyperlinkRecord hr = new HyperlinkRecord(in); - byte[] ser = hr.serialize(); - confirmRecordEncoding(HyperlinkRecord.sid, dataTargetFrame, ser); - } - - @Test - void testReserializeLinkToWorkbook() { - - RecordInputStream in = TestcaseRecordInputStream.create(HyperlinkRecord.sid, dataLinkToWorkbook); - HyperlinkRecord hr = new HyperlinkRecord(in); - byte[] ser = hr.serialize(); - confirmRecordEncoding(HyperlinkRecord.sid, dataLinkToWorkbook, ser); - assertNotEquals("Identified bug in reading workbook link", "YEARFR~1.XLS", hr.getAddress()); - assertEquals("yearfracExamples.xls", hr.getAddress()); - } - - @Test - void testReserializeUNC() { - - RecordInputStream in = TestcaseRecordInputStream.create(HyperlinkRecord.sid, dataUNC); - HyperlinkRecord hr = new HyperlinkRecord(in); - byte[] ser = hr.serialize(); - confirmRecordEncoding(HyperlinkRecord.sid, dataUNC, ser); - assertNotNull(hr.toString()); - } - - @Test - void testGUID() throws IOException { - ClassID g; - g = new ClassID("3F2504E0-4F89-11D3-9A0C-0305E82C3301"); - confirmGUID(g, 0x3F2504E0, 0x4F89, 0x11D3, 0x9A0C0305E82C3301L); - assertEquals("{3F2504E0-4F89-11D3-9A0C-0305E82C3301}", g.toString()); - - g = new ClassID("13579BDF-0246-8ACE-0123-456789ABCDEF"); - confirmGUID(g, 0x13579BDF, 0x0246, 0x8ACE, 0x0123456789ABCDEFL); - assertEquals("{13579BDF-0246-8ACE-0123-456789ABCDEF}", g.toString()); - - byte[] buf = new byte[16]; - g.write(new LittleEndianByteArrayOutputStream(buf, 0)); - String expectedDump = "[DF, 9B, 57, 13, 46, 02, CE, 8A, 01, 23, 45, 67, 89, AB, CD, EF]"; - assertEquals(expectedDump, HexDump.toHex(buf)); - - // STD Moniker - g = createFromStreamDump("[D0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]"); - assertEquals("{79EAC9D0-BAF9-11CE-8C82-00AA004BA90B}", g.toString()); - // URL Moniker - g = createFromStreamDump("[E0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]"); - assertEquals("{79EAC9E0-BAF9-11CE-8C82-00AA004BA90B}", g.toString()); - // File Moniker - g = createFromStreamDump("[03, 03, 00, 00, 00, 00, 00, 00, C0, 00, 00, 00, 00, 00, 00, 46]"); - assertEquals("{00000303-0000-0000-C000-000000000046}", g.toString()); - } - - private static ClassID createFromStreamDump(String s) { - return new ClassID(new LittleEndianByteArrayInputStream(HexRead.readFromString(s))); - } - - private void confirmGUID(ClassID g, int d1, int d2, int d3, long d4) throws IOException { - try (DataInputStream dis = new DataInputStream(new ByteArrayInputStream(g.getBytes()))) { - assertEquals(d1, dis.readInt()); - assertEquals(d2, dis.readShort() & 0xFFFF); - assertEquals(d3, dis.readShort() & 0xFFFF); - assertEquals(d4, dis.readLong()); - } - } - - @Test - void test47498(){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data_47498); - HyperlinkRecord link = new HyperlinkRecord(is); - assertEquals(2, link.getFirstRow()); - assertEquals(2, link.getLastRow()); - assertEquals(0, link.getFirstColumn()); - assertEquals(0, link.getLastColumn()); - confirmGUID(ClassIDPredefined.STD_MONIKER.getClassID(), link.getGuid()); - confirmGUID(ClassIDPredefined.URL_MONIKER.getClassID(), link.getMoniker()); - assertEquals(2, link.getLabelOptions()); - int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL; - assertEquals(opts, link.getLinkOptions()); - assertEquals(0, link.getFileOptions()); - - assertEquals("PDF", link.getLabel()); - assertEquals("testfolder/test.PDF", link.getAddress()); - - byte[] ser = link.serialize(); - confirmRecordEncoding(HyperlinkRecord.sid, data_47498, ser); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java b/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java deleted file mode 100644 index 169efaf2ad..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.ByteArrayInputStream; -import java.util.List; - -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the EndSubRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestInterfaceEndRecord { - - @Test - void testCreate() { - InterfaceEndRecord record = InterfaceEndRecord.instance; - assertEquals(0, record.getDataSize()); - } - - /** - * Silently swallow unexpected contents in InterfaceEndRecord. - * Although it violates the spec, Excel silently converts this - * data to an {@link InterfaceHdrRecord}. - */ - @Test - void testUnexpectedBytes_bug47251(){ - String hex = "" + - "09 08 10 00 00 06 05 00 EC 15 CD 07 C1 C0 00 00 06 03 00 00 " + //BOF - "E2 00 02 00 B0 04 " + //INTERFACEEND with extra two bytes - "0A 00 00 00"; // EOF - byte[] data = HexRead.readFromString(hex); - List records = RecordFactory.createRecords(new ByteArrayInputStream(data)); - assertEquals(3, records.size()); - Record rec1 = records.get(1); - assertEquals(InterfaceHdrRecord.class, rec1.getClass()); - InterfaceHdrRecord r = (InterfaceHdrRecord)rec1; - assertEquals("[E1, 00, 02, 00, B0, 04]", HexDump.toHex(r.serialize())); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java b/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java deleted file mode 100644 index 84946bd6b2..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for LabelRecord - */ -final class TestLabelRecord { - - @Test - void testEmptyString() throws IOException { - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("ex42570-20305.xls"); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - HSSFSheet s1 = wb1.getSheetAt(0); - HSSFSheet s2 = wb2.getSheetAt(0); - for (int c=0; c<2; c++) { - for (int r=0; r<146; r++) { - assertEquals(s1.getRow(r).getCell(c).getNumericCellValue(), s2.getRow(r).getCell(c).getNumericCellValue(), 0); - } - } - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java deleted file mode 100644 index afd988fb37..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java +++ /dev/null @@ -1,177 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndianInputStream; -import org.apache.poi.util.LittleEndianOutputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the LbsDataSubRecord class works correctly. - */ -final class TestLbsDataSubRecord { - - /** - * test read-write round trip - * test data was taken from 47701.xls - */ - @Test - void test_47701(){ - byte[] data = HexRead.readFromString( - "15, 00, 12, 00, 12, 00, 02, 00, 11, 20, " + - "00, 00, 00, 00, 80, 3D, 03, 05, 00, 00, " + - "00, 00, 0C, 00, 14, 00, 00, 00, 00, 00, " + - "00, 00, 00, 00, 00, 00, 01, 00, 0A, 00, " + - "00, 00, 10, 00, 01, 00, 13, 00, EE, 1F, " + - "10, 00, 09, 00, 40, 9F, 74, 01, 25, 09, " + - "00, 0C, 00, 07, 00, 07, 00, 07, 04, 00, " + - "00, 00, 08, 00, 00, 00"); - RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, data); - // check read OK - ObjRecord record = new ObjRecord(in); - assertEquals(3, record.getSubRecords().size()); - SubRecord sr = record.getSubRecords().get(2); - assertTrue(sr instanceof LbsDataSubRecord); - LbsDataSubRecord lbs = (LbsDataSubRecord)sr; - assertEquals(4, lbs.getNumberOfItems()); - - assertTrue(lbs.getFormula() instanceof AreaPtg); - AreaPtg ptg = (AreaPtg)lbs.getFormula(); - CellRangeAddress range = new CellRangeAddress( - ptg.getFirstRow(), ptg.getLastRow(), ptg.getFirstColumn(), ptg.getLastColumn()); - assertEquals("H10:H13", range.formatAsString()); - - // check that it re-serializes to the same data - byte[] ser = record.serialize(); - confirmRecordEncoding(ObjRecord.sid, data, ser); - } - - /** - * test data was taken from the file attached to Bugzilla 45778 - */ - @Test - void test_45778(){ - byte[] data = HexRead.readFromString( - "15, 00, 12, 00, 14, 00, 01, 00, 01, 00, " + - "01, 21, 00, 00, 3C, 13, F4, 03, 00, 00, " + - "00, 00, 0C, 00, 14, 00, 00, 00, 00, 00, " + - "00, 00, 00, 00, 00, 00, 01, 00, 08, 00, 00, " + - "00, 10, 00, 00, 00, " + - "13, 00, EE, 1F, " + - "00, 00, " + - "08, 00, " + //number of items - "08, 00, " + //selected item - "01, 03, " + //flags - "00, 00, " + //objId - //LbsDropData - "0A, 00, " + //flags - "14, 00, " + //the number of lines to be displayed in the dropdown - "6C, 00, " + //the smallest width in pixels allowed for the dropdown window - "00, 00, " + //num chars - "00, 00"); - RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, data); - // check read OK - ObjRecord record = new ObjRecord(in); - - SubRecord sr = record.getSubRecords().get(2); - assertTrue(sr instanceof LbsDataSubRecord); - LbsDataSubRecord lbs = (LbsDataSubRecord)sr; - assertEquals(8, lbs.getNumberOfItems()); - assertNull(lbs.getFormula()); - - // check that it re-serializes to the same data - byte[] ser = record.serialize(); - confirmRecordEncoding(ObjRecord.sid, data, ser); - - } - - /** - * Test data produced by OpenOffice 3.1 by opening and saving 47701.xls - * There are 5 padding bytes that are removed by POI - */ - @Test - void test_remove_padding(){ - byte[] data = HexRead.readFromString( - "5D, 00, 4C, 00, " + - "15, 00, 12, 00, 12, 00, 01, 00, 11, 00, " + - "00, 00, 00, 00, 00, 00, 00, 00, 00, 00, " + - "00, 00, 0C, 00, 14, 00, 00, 00, 00, 00, " + - "00, 00, 00, 00, 00, 00, 01, 00, 09, 00, " + - "00, 00, 0F, 00, 01, 00, " + - "13, 00, 1B, 00, " + - "10, 00, " + //next 16 bytes is a ptg aray - "09, 00, 00, 00, 00, 00, 25, 09, 00, 0C, 00, 07, 00, 07, 00, 00, " + - "01, 00, " + //num lines - "00, 00, " + //selected - "08, 00, " + - "00, 00, " + - "00, 00, 00, 00, 00"); //padding bytes - - RecordInputStream in = TestcaseRecordInputStream.create(data); - // check read OK - ObjRecord record = new ObjRecord(in); - // check that it re-serializes to the same data - byte[] ser = record.serialize(); - - assertEquals(data.length-5, ser.length); - for(int i=0; i < ser.length; i++) assertEquals(data[i],ser[i]); - - //check we can read the trimmed record - RecordInputStream in2 = TestcaseRecordInputStream.create(ser); - ObjRecord record2 = new ObjRecord(in2); - byte[] ser2 = record2.serialize(); - assertArrayEquals(ser, ser2); - } - - @Test - void test_LbsDropData() throws IOException{ - byte[] data = HexRead.readFromString( - //LbsDropData - "0A, 00, " + //flags - "14, 00, " + //the number of lines to be displayed in the dropdown - "6C, 00, " + //the smallest width in pixels allowed for the dropdown window - "00, 00, " + //num chars - "00, " + //compression flag - "00"); //padding byte - - try (LittleEndianInputStream in = new LittleEndianInputStream(new ByteArrayInputStream(data))) { - LbsDataSubRecord.LbsDropData lbs = new LbsDataSubRecord.LbsDropData(in); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try (LittleEndianOutputStream out = new LittleEndianOutputStream(baos)) { - lbs.serialize(out); - - assertArrayEquals(data, baos.toByteArray()); - } - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java b/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java deleted file mode 100644 index 7e9e1da0d0..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Collections; - -import org.apache.poi.hssf.model.RecordStream; -import org.apache.poi.hssf.record.aggregates.MergedCellsTable; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Test; - - -/** - * Make sure the merge cells record behaves - */ -final class TestMergeCellsRecord { - - /** - * Make sure when a clone is called, we actually clone it. - */ - @Test - void testCloneReferences() { - CellRangeAddress[] cras = { new CellRangeAddress(0, 1, 0, 2), }; - MergeCellsRecord merge = new MergeCellsRecord(cras, 0, cras.length); - MergeCellsRecord clone = merge.copy(); - - assertNotSame(merge, clone, "Merged and cloned objects are the same"); - - CellRangeAddress mergeRegion = merge.getAreaAt(0); - CellRangeAddress cloneRegion = clone.getAreaAt(0); - assertNotSame(mergeRegion, cloneRegion, "Should not point to same objects when cloning"); - assertEquals(mergeRegion.getFirstRow(), cloneRegion.getFirstRow(), "New Clone Row From doesnt match"); - assertEquals(mergeRegion.getLastRow(), cloneRegion.getLastRow(), "New Clone Row To doesnt match"); - assertEquals(mergeRegion.getFirstColumn(), cloneRegion.getFirstColumn(), "New Clone Col From doesnt match"); - assertEquals(mergeRegion.getLastColumn(), cloneRegion.getLastColumn(), "New Clone Col To doesnt match"); - - assertNotSame(merge.getAreaAt(0), clone.getAreaAt(0)); - } - - @Test - void testMCTable_bug46009() { - MergedCellsTable mct = new MergedCellsTable(); - CellRangeAddress[] cras = { new CellRangeAddress(0, 0, 0, 3) }; - MergeCellsRecord mcr1 = new MergeCellsRecord(cras, 0, 1); - RecordStream rs = new RecordStream(Collections.singletonList(mcr1), 0); - mct.read(rs); - mct.visitContainedRecords(r -> { - assertTrue(r instanceof MergeCellsRecord); - MergeCellsRecord mcr2 = (MergeCellsRecord)r; - assertEquals(mcr1.getNumAreas(), mcr2.getNumAreas()); - assertEquals(mcr1.getAreaAt(0), mcr2.getAreaAt(0)); - }); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java deleted file mode 100644 index 9884379747..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests the NameCommentRecord serializes/deserializes correctly - */ -final class TestNameCommentRecord { - @Test - void testReserialize() { - final byte[] data = HexRead - .readFromString("" - + "94 08 00 00 00 00 00 00 00 00 00 00 04 00 07 00 00 6E 61 6D 65 00 63 6F 6D 6D 65 6E 74]"); - final RecordInputStream in = TestcaseRecordInputStream.create(NameCommentRecord.sid, data); - final NameCommentRecord ncr = new NameCommentRecord(in); - assertEquals(0x0894, ncr.getRecordType()); - assertEquals("name", ncr.getNameText()); - assertEquals("comment", ncr.getCommentText()); - final byte[] data2 = ncr.serialize(); - confirmRecordEncoding(NameCommentRecord.sid, data, data2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java deleted file mode 100644 index 12da160752..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java +++ /dev/null @@ -1,159 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.ArrayPtg; -import org.apache.poi.ss.formula.ptg.NamePtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.Ref3DPtg; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests the NameRecord serializes/deserializes correctly - */ -final class TestNameRecord { - - /** - * Makes sure that additional name information is parsed properly such as menu/description - */ - @Test - void testFillExtras() { - - byte[] examples = HexRead.readFromString("" - + "88 03 67 06 07 00 00 00 00 00 00 23 00 00 00 4D " - + "61 63 72 6F 31 3A 01 00 00 00 11 00 00 4D 61 63 " - + "72 6F 20 72 65 63 6F 72 64 65 64 20 32 37 2D 53 " - + "65 70 2D 39 33 20 62 79 20 41 4C 4C 57 4F 52"); - - NameRecord name = new NameRecord(TestcaseRecordInputStream.create(NameRecord.sid, examples)); - String description = name.getDescriptionText(); - assertNotNull(description); - assertTrue(description.endsWith("Macro recorded 27-Sep-93 by ALLWOR")); - } - - @Test - void testReserialize() { - byte[] data = HexRead - .readFromString("" - + "20 00 00 01 0B 00 00 00 01 00 00 00 00 00 00 06 3B 00 00 00 00 02 00 00 00 09 00]"); - RecordInputStream in = TestcaseRecordInputStream.create(NameRecord.sid, data); - NameRecord nr = new NameRecord(in); - assertEquals(0x0020, nr.getOptionFlag()); - byte[] data2 = nr.serialize(); - confirmRecordEncoding(NameRecord.sid, data, data2); - } - - @Test - void testFormulaRelAbs_bug46174() throws IOException { - // perhaps this testcase belongs on TestHSSFName - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFName name = wb.createName(); - wb.createSheet("Sheet1"); - name.setNameName("test"); - name.setRefersToFormula("Sheet1!$B$3"); - assertNotEquals("Sheet1!B3", name.getRefersToFormula()); - assertEquals("Sheet1!$B$3", name.getRefersToFormula()); - } - } - - @Test - void testFormulaGeneral() throws IOException { - // perhaps this testcase belongs on TestHSSFName - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFName name = wb.createName(); - wb.createSheet("Sheet1"); - name.setNameName("test"); - name.setRefersToFormula("Sheet1!A1+Sheet1!A2"); - assertEquals("Sheet1!A1+Sheet1!A2", name.getRefersToFormula()); - name.setRefersToFormula("5*6"); - assertEquals("5*6", name.getRefersToFormula()); - - wb.close(); - } - - /** - * A NameRecord followed by a ContinueRecord. See Bugzilla 50244 - */ - @Test - void test50244() throws IOException { - byte[] data1 = RawDataUtil.decompress( - "H4sIAAAAAAAAAI3Zu2qWQRAA0I8EQcHGzkrwBcLO7B0sBR9AwdYIKdKFoPhovp7xLyQWyX+m2OWw7TIX5u3x/t1xHG9ePhyXxyl+" + - "fbz+cf3p/ufd3c3nm/vbm6tvx++L18fXy4fr4tVxxNWXLFelhCENlRCIZuiERAzDJFTEMmxCM/RiCMJApKESJqIZOmEhhmESNmIZ" + - "tiCKIYohCIlIQyVURDN0QkMMwyR0xDJswjDMYoizGH9Lzib8+6NnEIREpKESKqIZOqEhhmESOmIZNmEUQje0bViEipiGQUhENzRC" + - "IKohCQURZ3FKT0kYiDAUQjc87iCfwyJUxDQMQiK6oRECUQ1JKIgwFEHZhrUNizAR0zAIA9ENjdAR1ZCEhghDIVRDbsMiBGIaBqEg" + - "uqEZpmEZNiEMWQxBqIg0VEJDNEMndMQwTMJALMMmTMMqhiBsRBqqIAqiGTohEMMwCYlYhk2ohlYMQeiINFTCQDRDP4vT/FMNzdAJ" + - "gRiGSUjEMmxCNbRiCEJHpKEahqEbGqEhqiEJFRGGQkhDbMMiFMQ0jLM4padlmIZB6IhuaIT2Pz4c3188+VoNSaiIMBRCGh7PGc9h" + - "EQpiGoagbEQ3NMJCVEMSJiIMhTAMjxdcz2ERGmIaBqEiuqERElENSQhEGMrT+APX2vm3iyMAAA==" - ); - - RecordInputStream in1 = TestcaseRecordInputStream.create(data1); - NameRecord nr1 = new NameRecord(in1); - assert_bug50244(nr1); - - byte[] data2 = nr1.serialize(); - - assertEquals(data1.length, data2.length); - RecordInputStream in2 = TestcaseRecordInputStream.create(data2); - NameRecord nr2 = new NameRecord(in2); - assert_bug50244(nr2); - } - - private void assert_bug50244(NameRecord nr){ - assertEquals("wDataGruppeSerie.", nr.getNameText()); - Ptg[] ptg = nr.getNameDefinition(); - assertEquals(1, ptg.length); - ArrayPtg arr = (ArrayPtg)ptg[0]; - assertEquals(696, arr.getRowCount()); - assertEquals(1, arr.getColumnCount()); - Object[][] vals = arr.getTokenArrayValues(); - assertEquals("1.T20.001", vals[0][0]); - assertEquals("1.T20.010", vals[vals.length - 1][0]); - } - - @Test - void testBug57923() { - NameRecord record = new NameRecord(); - assertEquals(0, record.getExternSheetNumber()); - - record.setNameDefinition(Ptg.EMPTY_PTG_ARRAY); - assertEquals(0, record.getExternSheetNumber()); - - record.setNameDefinition(new Ptg[] {new NamePtg(1)}); - assertEquals(0, record.getExternSheetNumber()); - - record.setNameDefinition(new Ptg[] {new Area3DPtg("area", 1)}); - assertEquals(1, record.getExternSheetNumber()); - - record.setNameDefinition(new Ptg[] {new Ref3DPtg("A1", 1)}); - assertEquals(1, record.getExternSheetNumber()); - } - -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java deleted file mode 100644 index b59541da10..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java +++ /dev/null @@ -1,138 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the NoteRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestNoteRecord { - private final byte[] testData = HexRead.readFromString( - "06 00 01 00 02 00 02 04 " + - "1A 00 00 " + - "41 70 61 63 68 65 20 53 6F 66 74 77 61 72 65 20 46 6F 75 6E 64 61 74 69 6F 6E " + - "00" // padding byte - ); - - @Test - void testRead() { - - NoteRecord record = new NoteRecord(TestcaseRecordInputStream.create(NoteRecord.sid, testData)); - - assertEquals(NoteRecord.sid, record.getSid()); - assertEquals(6, record.getRow()); - assertEquals(1, record.getColumn()); - assertEquals(NoteRecord.NOTE_VISIBLE, record.getFlags()); - assertEquals(1026, record.getShapeId()); - assertEquals("Apache Software Foundation", record.getAuthor()); - } - - @Test - void testWrite() { - NoteRecord record = new NoteRecord(); - assertEquals(NoteRecord.sid, record.getSid()); - - record.setRow((short)6); - record.setColumn((short)1); - record.setFlags(NoteRecord.NOTE_VISIBLE); - record.setShapeId((short)1026); - record.setAuthor("Apache Software Foundation"); - - byte[] ser = record.serialize(); - confirmRecordEncoding(NoteRecord.sid, testData, ser); - } - - @Test - void testClone() { - NoteRecord record = new NoteRecord(); - - record.setRow((short)1); - record.setColumn((short)2); - record.setFlags(NoteRecord.NOTE_VISIBLE); - record.setShapeId((short)1026); - record.setAuthor("Apache Software Foundation"); - - NoteRecord cloned = record.copy(); - assertEquals(record.getRow(), cloned.getRow()); - assertEquals(record.getColumn(), cloned.getColumn()); - assertEquals(record.getFlags(), cloned.getFlags()); - assertEquals(record.getShapeId(), cloned.getShapeId()); - assertEquals(record.getAuthor(), cloned.getAuthor()); - - //finally check that the serialized data is the same - byte[] src = record.serialize(); - byte[] cln = cloned.serialize(); - assertArrayEquals(src, cln); - } - - @Test - void testUnicodeAuthor() { - // This sample data was created by setting the 'user name' field in the 'Personalize' - // section of Excel's options to \u30A2\u30D1\u30C3\u30C1\u65CF, and then - // creating a cell comment. - byte[] data = HexRead.readFromString("01 00 01 00 00 00 03 00 " + - "05 00 01 " + // len=5, 16bit - "A2 30 D1 30 C3 30 C1 30 CF 65 " + // character data - "00 " // padding byte - ); - RecordInputStream in = TestcaseRecordInputStream.create(NoteRecord.sid, data); - NoteRecord nr = new NoteRecord(in); - assertNotEquals("Identified bug in reading note with unicode author","\u00A2\u0030\u00D1\u0030\u00C3", nr.getAuthor()); - assertEquals("\u30A2\u30D1\u30C3\u30C1\u65CF", nr.getAuthor()); - assertTrue(nr.authorIsMultibyte()); - - byte[] ser = nr.serialize(); - confirmRecordEncoding(NoteRecord.sid, data, ser); - - // Re-check - in = TestcaseRecordInputStream.create(ser); - nr = new NoteRecord(in); - assertEquals("\u30A2\u30D1\u30C3\u30C1\u65CF", nr.getAuthor()); - assertTrue(nr.authorIsMultibyte()); - - - // Change to a non unicode author, will stop being unicode - nr.setAuthor("Simple"); - ser = nr.serialize(); - in = TestcaseRecordInputStream.create(ser); - nr = new NoteRecord(in); - - assertEquals("Simple", nr.getAuthor()); - assertFalse(nr.authorIsMultibyte()); - - // Now set it back again - nr.setAuthor("Unicode\u1234"); - ser = nr.serialize(); - in = TestcaseRecordInputStream.create(ser); - nr = new NoteRecord(in); - - assertEquals("Unicode\u1234", nr.getAuthor()); - assertTrue(nr.authorIsMultibyte()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java deleted file mode 100644 index 9aa690b79f..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the NoteRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestNoteStructureSubRecord { - private final byte[] data = new byte[] { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0x80, 0x00, 0x00, 0x00, - 0x00, 0x00, (byte)0xBF, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0x81, 0x01, - (byte)0xCC, (byte)0xEC - }; - - @Test - void testRead() { - NoteStructureSubRecord record = new NoteStructureSubRecord(TestcaseRecordInputStream.create(NoteStructureSubRecord.sid, data), data.length); - - assertEquals(NoteStructureSubRecord.sid, record.getSid()); - assertEquals(data.length, record.getDataSize()); - } - - @Test - void testWrite() { - NoteStructureSubRecord record = new NoteStructureSubRecord(); - assertEquals(NoteStructureSubRecord.sid, record.getSid()); - assertEquals(data.length, record.getDataSize()); - - byte [] ser = record.serialize(); - assertEquals(ser.length - 4, data.length); - } - - @Test - void testClone() { - NoteStructureSubRecord record = new NoteStructureSubRecord(); - byte[] src = record.serialize(); - - NoteStructureSubRecord cloned = record.copy(); - byte[] cln = cloned.serialize(); - - assertEquals(record.getDataSize(), cloned.getDataSize()); - assertArrayEquals(src, cln); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java b/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java deleted file mode 100644 index f797358de9..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java +++ /dev/null @@ -1,144 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the ObjRecord class works correctly. - * Test data taken directly from a real Excel file. - */ -final class TestObjRecord { - /** - * OBJ record data containing two sub-records. - * The data taken directly from a real Excel file. - * - * [OBJ] - * [ftCmo] - * [ftEnd] - */ - private static final byte[] recdata = HexRead.readFromString("" - + "15 00 12 00 06 00 01 00 11 60 " - + "F4 02 41 01 14 10 1F 02 00 00 " - +"00 00 00 00 00 00" - // TODO - this data seems to require two extra bytes padding. not sure where original file is. - // it's not bug 38607 attachment 17639 - ); - - /** - * Hex dump from - * offset 0x2072 in att 22076 of bug 45133 - */ - private static final byte[] recdataNeedingPadding = HexRead.readFromString("" - + "5D 00 20 00" - + "15 00 12 00 00 00 01 00 11 60 00 00 00 00 38 6F CC 03 00 00 00 00 06 00 02 00 00 00 00 00 00 00" - ); - - @Test - void testLoad() { - ObjRecord record = new ObjRecord(TestcaseRecordInputStream.create(ObjRecord.sid, recdata)); - - assertEquals(26, record.getRecordSize() - 4); - - List subrecords = record.getSubRecords(); - assertEquals(2, subrecords.size() ); - assertTrue(subrecords.get(0) instanceof CommonObjectDataSubRecord); - assertTrue(subrecords.get(1) instanceof EndSubRecord ); - - } - - @Test - void testStore() { - ObjRecord record = new ObjRecord(TestcaseRecordInputStream.create(ObjRecord.sid, recdata)); - - byte [] recordBytes = record.serialize(); - assertEquals(26, recordBytes.length - 4); - byte[] subData = Arrays.copyOfRange(recordBytes, 4, 4+recdata.length); - assertArrayEquals(recdata, subData); - } - - @Test - void testConstruct() { - ObjRecord record = new ObjRecord(); - CommonObjectDataSubRecord ftCmo = new CommonObjectDataSubRecord(); - ftCmo.setObjectType( CommonObjectDataSubRecord.OBJECT_TYPE_COMMENT); - ftCmo.setObjectId( 1024 ); - ftCmo.setLocked( true ); - ftCmo.setPrintable( true ); - ftCmo.setAutofill( true ); - ftCmo.setAutoline( true ); - record.addSubRecord(ftCmo); - EndSubRecord ftEnd = new EndSubRecord(); - record.addSubRecord(ftEnd); - - //serialize and read again - byte [] recordBytes = record.serialize(); - //cut off the record header - byte [] bytes = Arrays.copyOfRange(recordBytes, 4, recordBytes.length); - - record = new ObjRecord(TestcaseRecordInputStream.create(ObjRecord.sid, bytes)); - List subrecords = record.getSubRecords(); - assertEquals( 2, subrecords.size() ); - assertTrue( subrecords.get(0) instanceof CommonObjectDataSubRecord); - assertTrue( subrecords.get(1) instanceof EndSubRecord ); - } - - @Test - void testReadWriteWithPadding_bug45133() { - ObjRecord record = new ObjRecord(TestcaseRecordInputStream.create(recdataNeedingPadding)); - assertNotEquals(34, record.getRecordSize(), "Identified bug 45133"); - assertEquals(36, record.getRecordSize()); - - List subrecords = record.getSubRecords(); - assertEquals(3, subrecords.size() ); - assertEquals(CommonObjectDataSubRecord.class, subrecords.get(0).getClass()); - assertEquals(GroupMarkerSubRecord.class, subrecords.get(1).getClass()); - assertEquals(EndSubRecord.class, subrecords.get(2).getClass()); - } - - /** - * Check that ObjRecord tolerates and preserves padding to a 4-byte boundary - * (normally padding is to a 2-byte boundary). - */ - @SuppressWarnings("squid:S2699") - @Test - void test4BytePadding() { - // actual data from file saved by Excel 2007 - byte[] data = HexRead.readFromString("" - + "15 00 12 00 1E 00 01 00 11 60 B4 6D 3C 01 C4 06 " - + "49 06 00 00 00 00 00 00 00 00 00 00"); - // this data seems to have 2 extra bytes of padding more than usual - // the total may have been padded to the nearest quad-byte length - RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, data); - // check read OK - ObjRecord record = new ObjRecord(in); - // check that it re-serializes to the same data - byte[] ser = record.serialize(); - confirmRecordEncoding(ObjRecord.sid, data, ser); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java b/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java deleted file mode 100644 index 55fc393bde..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -import java.io.InputStream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.DVConstraint; -import org.apache.poi.hssf.usermodel.HSSFDataValidation; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.junit.jupiter.api.Test; - -/** - * Verify that presence of PLV record doesn't break data - * validation, bug #53972: - * https://issues.apache.org/bugzilla/show_bug.cgi?id=53972 - */ - -final class TestPLVRecord { - private static final String DV_DEFINITION = "$A$1:$A$5"; - private static final String XLS_FILENAME = "53972.xls"; - private static final String SHEET_NAME = "S2"; - - @Test - void testPLVRecord() throws Exception { - try (InputStream is = HSSFTestDataSamples.openSampleFileStream(XLS_FILENAME); - HSSFWorkbook workbook = new HSSFWorkbook(is)) { - - CellRangeAddressList cellRange = new CellRangeAddressList(0, 0, 1, 1); - DataValidationConstraint constraint = DVConstraint.createFormulaListConstraint(DV_DEFINITION); - HSSFDataValidation dataValidation = new HSSFDataValidation(cellRange, constraint); - - // This used to throw an IllegalStateException before - // Identified bug 53972, PLV record breaks addDataValidation() - HSSFSheet sheet = workbook.getSheet(SHEET_NAME); - assertDoesNotThrow(() -> sheet.addValidationData(dataValidation)); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java b/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java deleted file mode 100644 index ac97d99d4e..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.poi.hssf.util.HSSFColor; -import org.junit.jupiter.api.Test; - -/** - * Verifies that custom palette editing works correctly - */ -final class TestPaletteRecord { - - /** - * Tests that the default palette matches the constants of HSSFColor - */ - @Test - void testDefaultPalette() { - PaletteRecord palette = new PaletteRecord(); - - //make sure all the HSSFColor constants match - Map colors = HSSFColor.getIndexHash(); - for (Entry entry : colors.entrySet()) { - int index = entry.getKey(); - HSSFColor c = entry.getValue(); - short[] rgbTriplet = c.getTriplet(); - byte[] paletteTriplet = palette.getColor((short) index); - String msg = "Expected HSSFColor constant to match PaletteRecord at index" + (index == c.getIndex2() ? "2" : "") + " 0x" - + Integer.toHexString(index); - assertNotNull(paletteTriplet); - assertEquals(rgbTriplet[0], paletteTriplet[0] & 0xff, msg); - assertEquals(rgbTriplet[1], paletteTriplet[1] & 0xff, msg); - assertEquals(rgbTriplet[2], paletteTriplet[2] & 0xff, msg); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestPaneRecord.java b/src/testcases/org/apache/poi/hssf/record/TestPaneRecord.java deleted file mode 100644 index c20209cf5b..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestPaneRecord.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the PaneRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestPaneRecord { - byte[] data = new byte[] { - (byte)0x01, (byte)0x00, - (byte)0x02, (byte)0x00, - (byte)0x03, (byte)0x00, - (byte)0x04, (byte)0x00, - (byte)0x02, (byte)0x00, - }; - - @Test - void testLoad() { - PaneRecord record = new PaneRecord(TestcaseRecordInputStream.create(0x41, data)); - - assertEquals( (short)1, record.getX()); - assertEquals( (short)2, record.getY()); - assertEquals( (short)3, record.getTopRow()); - assertEquals( (short)4, record.getLeftColumn()); - assertEquals( PaneRecord.ACTIVE_PANE_LOWER_LEFT, record.getActivePane()); - - assertEquals( 14, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - PaneRecord record = new PaneRecord(); - - record.setX( (short) 1); - record.setY( (short) 2); - record.setTopRow( (short) 3); - record.setLeftColumn( (short) 4); - record.setActivePane( PaneRecord.ACTIVE_PANE_LOWER_LEFT); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(PaneRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java b/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java deleted file mode 100644 index 670e2fe70c..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -final class TestRecalcIdRecord { - - private static RecalcIdRecord create(byte[] data) { - RecordInputStream in = TestcaseRecordInputStream.create(RecalcIdRecord.sid, data); - RecalcIdRecord result = new RecalcIdRecord(in); - assertEquals(0, in.remaining()); - return result; - } - - @SuppressWarnings("squid:S2699") - @Test - void testBasicDeserializeReserialize() { - - byte[] data = HexRead.readFromString( - "C1 01" + // rt - "00 00" + // reserved - "1D EB 01 00"); // engine id - - RecalcIdRecord r = create(data); - confirmRecordEncoding(RecalcIdRecord.sid, data, r.serialize()); - } - - @Test - void testBadFirstField_bug48096() { - /* - * Data taken from the sample file referenced in Bugzilla 48096, file offset 0x0D45. - * The apparent problem is that the first data short field has been written with the - * wrong endianness. Excel seems to ignore whatever value is present in this - * field, and always rewrites it as (C1, 01). POI now does the same. - */ - byte[] badData = HexRead.readFromString("C1 01 08 00 01 C1 00 00 00 01 69 61"); - byte[] goodData = HexRead.readFromString("C1 01 08 00 C1 01 00 00 00 01 69 61"); - - RecordInputStream in = TestcaseRecordInputStream.create(badData); - - // bug 48096 - expected 449 but got 49409 - RecalcIdRecord r = new RecalcIdRecord(in); - - assertEquals(0, in.remaining()); - assertArrayEquals(r.serialize(), goodData); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java b/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java deleted file mode 100644 index 11f66367e1..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java +++ /dev/null @@ -1,234 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests the record factory - */ -final class TestRecordFactory { - - - /** - * TEST NAME: Test Basic Record Construction

- * OBJECTIVE: Test that the RecordFactory given the required parameters for know - * record types can construct the proper record w/values.

- * SUCCESS: Record factory creates the records with the expected values.

- * FAILURE: The wrong records are creates or contain the wrong values

- * - */ - @Test - void testBasicRecordConstruction() { - short recType = BOFRecord.sid; - byte[] data = { - 0, 6, 5, 0, -2, 28, -51, 7, -55, 64, 0, 0, 6, 1, 0, 0 - }; - Record[] record = RecordFactory.createRecord(TestcaseRecordInputStream.create(recType, data)); - - assertEquals(BOFRecord.class.getName(), - record[ 0 ].getClass().getName()); - BOFRecord bofRecord = ( BOFRecord ) record[ 0 ]; - - assertEquals(7422, bofRecord.getBuild()); - assertEquals(1997, bofRecord.getBuildYear()); - assertEquals(16585, bofRecord.getHistoryBitMask()); - assertEquals(20, bofRecord.getRecordSize()); - assertEquals(262, bofRecord.getRequiredVersion()); - assertEquals(2057, bofRecord.getSid()); - assertEquals(5, bofRecord.getType()); - assertEquals(1536, bofRecord.getVersion()); - recType = MMSRecord.sid; - data = new byte[] { - 0, 0 - }; - record = RecordFactory.createRecord(TestcaseRecordInputStream.create(recType, data)); - assertEquals(MMSRecord.class.getName(), - record[ 0 ].getClass().getName()); - MMSRecord mmsRecord = ( MMSRecord ) record[ 0 ]; - - assertEquals(0, mmsRecord.getAddMenuCount()); - assertEquals(0, mmsRecord.getDelMenuCount()); - assertEquals(6, mmsRecord.getRecordSize()); - assertEquals(193, mmsRecord.getSid()); - } - - /** - * TEST NAME: Test Special Record Construction

- * OBJECTIVE: Test that the RecordFactory given the required parameters for - * constructing a RKRecord will return a NumberRecord.

- * SUCCESS: Record factory creates the Number record with the expected values.

- * FAILURE: The wrong records are created or contain the wrong values

- * - */ - @Test - void testSpecial() { - short recType = RKRecord.sid; - byte[] data = { - 0, 0, 0, 0, 21, 0, 0, 0, 0, 0 - }; - Record[] record = RecordFactory.createRecord(TestcaseRecordInputStream.create(recType, data)); - - assertEquals(NumberRecord.class.getName(), - record[ 0 ].getClass().getName()); - NumberRecord numberRecord = ( NumberRecord ) record[ 0 ]; - - assertEquals(0, numberRecord.getColumn()); - assertEquals(18, numberRecord.getRecordSize()); - assertEquals(0, numberRecord.getRow()); - assertEquals(515, numberRecord.getSid()); - assertEquals(0.0, numberRecord.getValue(), 0.001); - assertEquals(21, numberRecord.getXFIndex()); - } - - /** - * TEST NAME: Test Creating ContinueRecords After Unknown Records From An InputStream

- * OBJECTIVE: Test that the RecordFactory given an InputStream - * constructs the expected array of records.

- * SUCCESS: Record factory creates the expected records.

- * FAILURE: The wrong records are created or contain the wrong values

- */ - @Test - 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 - }; - - ByteArrayInputStream bois = new ByteArrayInputStream(data); - Record[] records = RecordFactory.createRecords(bois).toArray(new Record[0]); - assertEquals(3, records.length, "Created record count"); - assertEquals(UnknownRecord.class.getName(), records[ 0 ].getClass().getName(), "1st record's type"); - assertEquals((short)-256, records[0].getSid(), "1st record's sid"); - assertEquals(ContinueRecord.class.getName(), records[ 1 ].getClass().getName(), "2nd record's type"); - ContinueRecord record = (ContinueRecord) records[1]; - assertEquals(0x3C, record.getSid(), "2nd record's sid"); - assertEquals(1, record.getData()[ 0 ], "1st data byte"); - assertEquals(2, record.getData()[ 1 ], "2nd data byte"); - assertEquals(3, record.getData()[ 2 ], "3rd data byte"); - assertEquals(ContinueRecord.class.getName(), records[ 2 ].getClass().getName(), "3rd record's type"); - record = (ContinueRecord) records[2]; - assertEquals(0x3C, record.getSid(), "3nd record's sid"); - assertEquals(4, record.getData()[ 0 ], "4th data byte"); - } - - /** - * Drawing records have a very strange continue behaviour. - * There can actually be OBJ records mixed between the continues. - * Record factory must preserve this structure when reading records. - */ - @Test - void testMixedContinue() throws IOException { - // Adapted from a real test sample file 39512.xls (Offset 0x4854). - // See Bug 39512 for details. - String dump = - //OBJ - "5D 00 48 00 15 00 12 00 0C 00 3C 00 11 00 A0 2E 03 01 CC 42 " + - "CF 00 00 00 00 00 0A 00 0C 00 00 00 00 00 00 00 00 00 00 00 " + - "03 00 0B 00 06 00 28 01 03 01 00 00 12 00 08 00 00 00 00 00 " + - "00 00 03 00 11 00 04 00 3D 00 00 00 00 00 00 00 " + - //MSODRAWING - "EC 00 08 00 00 00 0D F0 00 00 00 00 " + - //TXO (and 2 trailing CONTINUE records) - "B6 01 12 00 22 02 00 00 00 00 00 00 00 00 10 00 10 00 00 00 00 00 " + - "3C 00 11 00 00 4F 70 74 69 6F 6E 20 42 75 74 74 6F 6E 20 33 39 " + - "3C 00 10 00 00 00 05 00 00 00 00 00 10 00 00 00 00 00 00 00 " + - // another CONTINUE - "3C 00 7E 00 0F 00 04 F0 7E 00 00 00 92 0C 0A F0 08 00 00 00 " + - "3D 04 00 00 00 0A 00 00 A3 00 0B F0 3C 00 00 00 7F 00 00 01 " + - "00 01 80 00 8C 01 03 01 85 00 01 00 00 00 8B 00 02 00 00 00 " + - "BF 00 08 00 1A 00 7F 01 29 00 29 00 81 01 41 00 00 08 BF 01 " + - "00 00 10 00 C0 01 40 00 00 08 FF 01 00 00 08 00 00 00 10 F0 " + - "12 00 00 00 02 00 02 00 A0 03 18 00 B5 00 04 00 30 02 1A 00 " + - "00 00 00 00 11 F0 00 00 00 00 " + - //OBJ - "5D 00 48 00 15 00 12 00 0C 00 3D 00 11 00 8C 01 03 01 C8 59 CF 00 00 " + - "00 00 00 0A 00 0C 00 00 00 00 00 00 00 00 00 00 00 03 00 0B 00 06 00 " + - "7C 16 03 01 00 00 12 00 08 00 00 00 00 00 00 00 03 00 11 00 04 00 01 " + - "00 00 00 00 00 00 00"; - byte[] data = HexRead.readFromString(dump); - - List records = RecordFactory.createRecords(new ByteArrayInputStream(data)); - assertEquals(5, records.size()); - assertTrue(records.get(0) instanceof ObjRecord); - assertTrue(records.get(1) instanceof DrawingRecord); - assertTrue(records.get(2) instanceof TextObjectRecord); - assertTrue(records.get(3) instanceof ContinueRecord); - assertTrue(records.get(4) instanceof ObjRecord); - - //serialize and verify that the serialized data is the same as the original - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for(org.apache.poi.hssf.record.Record rec : records){ - out.write(rec.serialize()); - } - - byte[] ser = out.toByteArray(); - assertEquals(data.length, ser.length); - assertArrayEquals(data, ser); - } - - @Test - void testNonZeroPadding_bug46987() throws IOException { - Record[] recs = { - new BOFRecord(), - new WriteAccessRecord(), // need *something* between BOF and EOF - EOFRecord.instance, - BOFRecord.createSheetBOF(), - EOFRecord.instance, - }; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - for (org.apache.poi.hssf.record.Record rec : recs) { - try { - baos.write(rec.serialize()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - //simulate the bad padding at the end of the workbook stream in attachment 23483 of bug 46987 - baos.write(0x00); - baos.write(0x11); - baos.write(0x00); - baos.write(0x02); - for (int i = 0; i < 192; i++) { - baos.write(0x00); - } - - - POIFSFileSystem fs = new POIFSFileSystem(); - fs.createDocument(new ByteArrayInputStream(baos.toByteArray()), "dummy"); - InputStream is = fs.getRoot().createDocumentInputStream("dummy"); - - List outRecs = RecordFactory.createRecords(is); - // Buffer underrun - requested 512 bytes but 192 was available - assertEquals(5, outRecs.size()); - fs.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java deleted file mode 100644 index 9c7d6be428..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java +++ /dev/null @@ -1,162 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link RecordFactoryInputStream} - * - * @author Josh Micich - */ -final class TestRecordFactoryInputStream { - /** - * Hex dump of a BOF record and most of a FILEPASS record. - * A 16 byte saltHash should be added to complete the second record - */ - private static final String COMMON_HEX_DATA = "" - // BOF - + "09 08 10 00" - + "00 06 05 00 D3 10 CC 07 01 00 00 00 00 06 00 00" - // FILEPASS - + "2F 00 36 00" - + "01 00 01 00 01 00" - + "BAADF00D BAADF00D BAADF00D BAADF00D" // docId - + "DEADBEEF DEADBEEF DEADBEEF DEADBEEF" // saltData - ; - - /** - * Hex dump of a sample WINDOW1 record - */ - private static final String SAMPLE_WINDOW1 = "3D 00 12 00" - + "00 00 00 00 40 38 55 23 38 00 00 00 00 00 01 00 58 02"; - - - /** - * Makes sure that a default password mismatch condition is represented with {@link EncryptedDocumentException} - */ - @Test - void defaultPasswordWrong() { - // This encodng depends on docId, password and stream position - final String SAMPLE_WINDOW1_ENCR1 = "3D 00 12 00" - + "C4, 9B, 02, 50, 86, E0, DF, 34, FB, 57, 0E, 8C, CE, 25, 45, E3, 80, 01"; - - byte[] dataWrongDefault = HexRead.readFromString("" - + COMMON_HEX_DATA - + "00000000 00000000 00000000 00000001" - + SAMPLE_WINDOW1_ENCR1 - ); - - EncryptedDocumentException ex = assertThrows( - EncryptedDocumentException.class, - () -> createRFIS(dataWrongDefault) - ); - assertTrue(ex.getMessage().contains("Default password is invalid for salt/verifier/verifierHash")); - } - - @Test - void defaultPasswordOK() { - // This encodng depends on docId, password and stream position - final String SAMPLE_WINDOW1_ENCR1 = "3D 00 12 00" - + "C4, 9B, 02, 50, 86, E0, DF, 34, FB, 57, 0E, 8C, CE, 25, 45, E3, 80, 01"; - - byte[] dataCorrectDefault = HexRead.readFromString("" - + COMMON_HEX_DATA - + "137BEF04 969A200B 306329DE 52254005" // correct saltHash for default password (and docId/saltHash) - + SAMPLE_WINDOW1_ENCR1 - ); - - RecordFactoryInputStream rfis = createRFIS(dataCorrectDefault); - confirmReadInitialRecords(rfis); - } - - - /** - * Makes sure that an incorrect user supplied password condition is represented with {@link EncryptedDocumentException} - */ - @Test - void suppliedPasswordWrong() { - // This encoding depends on docId, password and stream position - final String SAMPLE_WINDOW1_ENCR2 = "3D 00 12 00" - + "45, B9, 90, FE, B6, C6, EC, 73, EE, 3F, 52, 45, 97, DB, E3, C1, D6, FE"; - - byte[] dataWrongDefault = HexRead.readFromString("" - + COMMON_HEX_DATA - + "00000000 00000000 00000000 00000000" - + SAMPLE_WINDOW1_ENCR2 - ); - - Biff8EncryptionKey.setCurrentUserPassword("passw0rd"); - try { - EncryptedDocumentException ex = assertThrows( - EncryptedDocumentException.class, - () -> createRFIS(dataWrongDefault) - ); - assertEquals("Supplied password is invalid for salt/verifier/verifierHash", ex.getMessage()); - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } - - @Test - void suppliedPasswordOK() { - // This encoding depends on docId, password and stream position - final String SAMPLE_WINDOW1_ENCR2 = "3D 00 12 00" - + "45, B9, 90, FE, B6, C6, EC, 73, EE, 3F, 52, 45, 97, DB, E3, C1, D6, FE"; - - byte[] dataCorrectDefault = HexRead.readFromString("" - + COMMON_HEX_DATA - + "C728659A C38E35E0 568A338F C3FC9D70" // correct saltHash for supplied password (and docId/saltHash) - + SAMPLE_WINDOW1_ENCR2 - ); - - Biff8EncryptionKey.setCurrentUserPassword("passw0rd"); - try { - RecordFactoryInputStream rfis = createRFIS(dataCorrectDefault); - confirmReadInitialRecords(rfis); - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } - - - /** - * makes sure the record stream starts with {@link BOFRecord}, {@link FilePassRecord} and then {@link WindowOneRecord} - * The third record is decrypted so this method also checks its content. - */ - private void confirmReadInitialRecords(RecordFactoryInputStream rfis) { - assertEquals(BOFRecord.class, rfis.nextRecord().getClass()); - FilePassRecord recFP = (FilePassRecord) rfis.nextRecord(); - WindowOneRecord rec1 = (WindowOneRecord) rfis.nextRecord(); - assertArrayEquals(HexRead.readFromString(SAMPLE_WINDOW1),rec1.serialize()); - } - - private static RecordFactoryInputStream createRFIS(byte[] data) { - return new RecordFactoryInputStream(new ByteArrayInputStream(data), true); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java deleted file mode 100644 index 0956350283..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; - -/** - * Tests for {@link RecordInputStream} - */ -final class TestRecordInputStream { - - /** - * Data inspired by attachment 22626 of bug 45866
- * A unicode string of 18 chars, with a continue record where the compression flag changes - */ - private static final String HED_DUMP1 = "" - + "1A 59 00 8A 9E 8A " // 3 uncompressed unicode chars - + "3C 00 " // Continue sid - + "10 00 " // rec size 16 (1+15) - + "00" // next chunk is compressed - + "20 2D 20 4D 75 6C 74 69 6C 69 6E 67 75 61 6C " // 15 chars - ; - /** - * same string re-arranged - */ - private static final String HED_DUMP2 = "" - // 15 chars at end of current record - + "4D 75 6C 74 69 6C 69 6E 67 75 61 6C 20 2D 20" - + "3C 00 " // Continue sid - + "07 00 " // rec size 7 (1+6) - + "01" // this bit uncompressed - + "1A 59 00 8A 9E 8A " // 3 uncompressed unicode chars - ; - - - @Test - void testChangeOfCompressionFlag_bug25866() { - byte[] changingFlagSimpleData = HexRead.readFromString("" - + "AA AA " // fake SID - + "06 00 " // first rec len 6 - + HED_DUMP1 - ); - RecordInputStream in = TestcaseRecordInputStream.create(changingFlagSimpleData); - - // bug 45866 - compressByte in continue records must be 1 while reading unicode LE string - String actual = in.readUnicodeLEString(18); - assertEquals("\u591A\u8A00\u8A9E - Multilingual", actual); - } - - @Test - void testChangeFromUnCompressedToCompressed() { - byte[] changingFlagSimpleData = HexRead.readFromString("" - + "AA AA " // fake SID - + "0F 00 " // first rec len 15 - + HED_DUMP2 - ); - RecordInputStream in = TestcaseRecordInputStream.create(changingFlagSimpleData); - String actual = in.readCompressedUnicode(18); - assertEquals("Multilingual - \u591A\u8A00\u8A9E", actual); - } - - @Test - void testReadString() { - byte[] changingFlagFullData = HexRead.readFromString("" - + "AA AA " // fake SID - + "12 00 " // first rec len 18 (15 + next 3 bytes) - + "12 00 " // total chars 18 - + "00 " // this bit compressed - + HED_DUMP2 - ); - RecordInputStream in = TestcaseRecordInputStream.create(changingFlagFullData); - String actual = in.readString(); - assertEquals("Multilingual - \u591A\u8A00\u8A9E", actual); - } - - @ParameterizedTest - @CsvSource({"1, 200", "0, 200", "999999999, 200", HeaderRecord.sid+", 200"}) - void testLeftoverDataException(int sid, int remainingByteCount) { - // just ensure that the exception is created correctly, even with unknown sids - assertDoesNotThrow(() -> new RecordInputStream.LeftoverDataException(sid, remainingByteCount)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java deleted file mode 100644 index 92e5abff02..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the SCLRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestSCLRecord { - byte[] data = new byte[] { - (byte)0x3,(byte)0x0,(byte)0x4,(byte)0x0 - }; - - @Test - void testLoad() { - SCLRecord record = new SCLRecord(TestcaseRecordInputStream.create(0xa0, data)); - assertEquals( 3, record.getNumerator()); - assertEquals( 4, record.getDenominator()); - - assertEquals( 8, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - SCLRecord record = new SCLRecord(); - record.setNumerator( (short)3 ); - record.setDenominator( (short)4 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(SCLRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java b/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java deleted file mode 100644 index 7bde03cb06..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java +++ /dev/null @@ -1,125 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.common.UnicodeString; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.IntMapper; -import org.junit.jupiter.api.Test; - -/** - * Exercise the SSTDeserializer class. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -final class TestSSTDeserializer { - private static final int FAKE_SID = -5555; - - private static byte[] concat(byte[] a, byte[] b) { - byte[] result = new byte[a.length + b.length]; - System.arraycopy(a, 0, result, 0, a.length); - System.arraycopy(b, 0, result, a.length, b.length); - return result; - } - - private static byte[] readSampleHexData(String sampleFileName, String sectionName, int recSid) - throws IOException { - InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName); - byte[] data = HexRead.readData(is, sectionName); - byte[] result = TestcaseRecordInputStream.mergeDataAndSid(recSid, data.length, data); - is.close(); - return result; - } - - @Test - void testSpanRichTextToPlainText() throws IOException { - byte[] header = readSampleHexData("richtextdata.txt", "header", FAKE_SID); - byte[] continueBytes = readSampleHexData("richtextdata.txt", "continue1", ContinueRecord.sid); - RecordInputStream in = TestcaseRecordInputStream.create(concat(header, continueBytes)); - - - IntMapper strings = new IntMapper<>(); - SSTDeserializer deserializer = new SSTDeserializer( strings ); - deserializer.manufactureStrings(1, in ); - - assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" ); - } - - @Test - void testContinuationWithNoOverlap() throws IOException { - byte[] header = readSampleHexData("evencontinuation.txt", "header", FAKE_SID); - byte[] continueBytes = readSampleHexData("evencontinuation.txt", "continue1", ContinueRecord.sid); - RecordInputStream in = TestcaseRecordInputStream.create(concat(header, continueBytes)); - - IntMapper strings = new IntMapper<>(); - SSTDeserializer deserializer = new SSTDeserializer( strings ); - deserializer.manufactureStrings( 2, in); - - assertEquals( "At a dinner party or", strings.get( 0 ) + "" ); - assertEquals( "At a dinner party", strings.get( 1 ) + "" ); - } - - /** - * Strings can actually span across more than one continuation. - */ - @Test - void testStringAcross2Continuations() throws IOException { - byte[] header = readSampleHexData("stringacross2continuations.txt", "header", FAKE_SID); - byte[] continue1 = readSampleHexData("stringacross2continuations.txt", "continue1", ContinueRecord.sid); - byte[] continue2 = readSampleHexData("stringacross2continuations.txt", "continue2", ContinueRecord.sid); - - RecordInputStream in = TestcaseRecordInputStream.create(concat(header, concat(continue1, continue2))); - - IntMapper strings = new IntMapper<>(); - SSTDeserializer deserializer = new SSTDeserializer( strings ); - deserializer.manufactureStrings( 2, in); - - assertEquals( "At a dinner party or", strings.get( 0 ) + "" ); - assertEquals( "At a dinner partyAt a dinner party", strings.get( 1 ) + "" ); - } - - @Test - void testExtendedStrings() throws IOException { - byte[] header = readSampleHexData("extendedtextstrings.txt", "rich-header", FAKE_SID); - byte[] continueBytes = readSampleHexData("extendedtextstrings.txt", "rich-continue1", ContinueRecord.sid); - RecordInputStream in = TestcaseRecordInputStream.create(concat(header, continueBytes)); - - IntMapper strings = new IntMapper<>(); - SSTDeserializer deserializer = new SSTDeserializer( strings ); - deserializer.manufactureStrings( 1, in); - - assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" ); - - - header = readSampleHexData("extendedtextstrings.txt", "norich-header", FAKE_SID); - continueBytes = readSampleHexData("extendedtextstrings.txt", "norich-continue1", ContinueRecord.sid); - in = TestcaseRecordInputStream.create(concat(header, continueBytes)); - - strings = new IntMapper<>(); - deserializer = new SSTDeserializer( strings ); - 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 deleted file mode 100644 index b2206b86b7..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java +++ /dev/null @@ -1,416 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Arrays; -import java.util.Iterator; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.common.UnicodeString; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -final class TestSSTRecord { - - /** - * decodes hexdump files and concatenates the results - * @param hexDumpFileNames names of sample files in the hssf test data directory - */ - private static byte[] concatHexDumps(String... hexDumpFileNames) throws IOException { - int nFiles = hexDumpFileNames.length; - ByteArrayOutputStream baos = new ByteArrayOutputStream(nFiles * 8228); - for (String sampleFileName : hexDumpFileNames) { - try (InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName)) { - BufferedReader br = new BufferedReader(new InputStreamReader(is, LocaleUtil.CHARSET_1252)); - - while (true) { - String line = br.readLine(); - if (line == null) { - break; - } - baos.write(HexRead.readFromString(line)); - } - } - } - - return baos.toByteArray(); - } - - /** - * @param rawData serialization of one {@link SSTRecord} and zero or more {@link ContinueRecord}s - */ - private static SSTRecord createSSTFromRawData(byte[] rawData) { - RecordInputStream in = new RecordInputStream(new ByteArrayInputStream(rawData)); - in.nextRecord(); - SSTRecord result = new SSTRecord(in); - assertEquals(0, in.remaining()); - assertFalse(in.hasNextRecord()); - return result; - } - - /** - * SST is often split over several {@link ContinueRecord}s - */ - @Test - void testContinuedRecord() throws IOException { - byte[] origData; - SSTRecord record; - byte[] ser_output; - - origData = concatHexDumps("BigSSTRecord", "BigSSTRecordCR"); - record = createSSTFromRawData(origData); - assertEquals( 1464, record.getNumStrings() ); - assertEquals( 688, record.getNumUniqueStrings() ); - assertEquals( 688, record.countStrings() ); - ser_output = record.serialize(); - assertArrayEquals(origData, ser_output); - - // testing based on new bug report - origData = concatHexDumps("BigSSTRecord2", "BigSSTRecord2CR1", "BigSSTRecord2CR2", "BigSSTRecord2CR3", - "BigSSTRecord2CR4", "BigSSTRecord2CR5", "BigSSTRecord2CR6", "BigSSTRecord2CR7"); - record = createSSTFromRawData(origData); - - - assertEquals( 158642, record.getNumStrings() ); - assertEquals( 5249, record.getNumUniqueStrings() ); - assertEquals( 5249, record.countStrings() ); - ser_output = record.serialize(); -// if (false) { // set true to observe make sure areSameSSTs() is working -// ser_output[11000] = 'X'; -// } - - SSTRecord rec2 = createSSTFromRawData(ser_output); - assertRecordEquals(record, rec2); - -// if (false) { -// // TODO - trivial differences in ContinueRecord break locations -// // Sample data should be checked against what most recent Excel version produces. -// // maybe tweaks are required in ContinuableRecordOutput -// assertArrayEquals(origData, ser_output); -// } - } - - /** - * Test capability of handling mondo big strings - */ - @Test - void testHugeStrings() { - SSTRecord record = new SSTRecord(); - byte[][] bstrings = - { - new byte[9000], new byte[7433], new byte[9002], - new byte[16998] - }; - UnicodeString[] strings = new UnicodeString[bstrings.length]; - int total_length = 0; - - for ( int k = 0; k < bstrings.length; k++ ) - { - Arrays.fill( bstrings[k], (byte) ( 'a' + k ) ); - strings[k] = new UnicodeString( new String(bstrings[k], LocaleUtil.CHARSET_1252) ); - record.addString( strings[k] ); - total_length += 3 + bstrings[k].length; - } - - // add overhead of SST record - total_length += 8; - - // add overhead of broken strings - total_length += 4; - - // add overhead of six records - total_length += ( 6 * 4 ); - byte[] content = new byte[record.getRecordSize()]; - - record.serialize( 0, content ); - assertEquals( total_length, content.length ); - - //Deserialize the record. - RecordInputStream recStream = new RecordInputStream(new ByteArrayInputStream(content)); - recStream.nextRecord(); - record = new SSTRecord(recStream); - - assertEquals( strings.length, record.getNumStrings() ); - assertEquals( strings.length, record.getNumUniqueStrings() ); - assertEquals( strings.length, record.countStrings() ); - for ( int k = 0; k < strings.length; k++ ) - { - assertEquals( strings[k], record.getString( k ) ); - } - record = new SSTRecord(); - bstrings[1] = new byte[bstrings[1].length - 1]; - for ( int k = 0; k < bstrings.length; k++ ) - { - if ( ( bstrings[k].length % 2 ) == 1 ) - { - Arrays.fill( bstrings[k], (byte) ( 'a' + k ) ); - strings[k] = new UnicodeString( new String(bstrings[k], LocaleUtil.CHARSET_1252) ); - } - else - { - char[] data = new char[bstrings[k].length / 2]; - - Arrays.fill( data, (char) ( '\u2122' + k ) ); - strings[k] = new UnicodeString(new String( data )); - } - record.addString( strings[k] ); - } - content = new byte[record.getRecordSize()]; - record.serialize( 0, content ); - total_length--; - assertEquals( total_length, content.length ); - - recStream = new RecordInputStream(new ByteArrayInputStream(content)); - recStream.nextRecord(); - record = new SSTRecord(recStream); - - assertEquals( strings.length, record.getNumStrings() ); - assertEquals( strings.length, record.getNumUniqueStrings() ); - assertEquals( strings.length, record.countStrings() ); - for ( int k = 0; k < strings.length; k++ ) - { - assertEquals( strings[k], record.getString( k ) ); - } - } - - /** - * test SSTRecord boundary conditions - */ - @Test - 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(); - - // the record will start with two integers, then this string - // ... that will eat up 16 of the 8224 bytes that the record - // can hold - record.addString( new UnicodeString("Hello") ); - - // now we have an additional 8208 bytes, which is an exact - // multiple of 16 bytes - long testvalue = 1000000000000L; - - for ( int k = 0; k < 2000; k++ ) - { - record.addString( new UnicodeString(String.valueOf( testvalue++ )) ); - } - byte[] content = new byte[record.getRecordSize()]; - - record.serialize( 0, content ); - assertEquals(8224, LittleEndian.getShort(content, 2)); - assertEquals(ContinueRecord.sid, LittleEndian.getShort(content, 8228)); - assertEquals(8224, LittleEndian.getShort(content, 8228+2)); - assertEquals( (byte) 13, content[4 + 8228] ); - assertEquals(ContinueRecord.sid, LittleEndian.getShort(content, 2*8228)); - assertEquals(8224, LittleEndian.getShort(content, 8228*2+2)); - assertEquals( (byte) 13, content[4 + 8228 * 2] ); - assertEquals(ContinueRecord.sid, LittleEndian.getShort(content, 3*8228)); - assertEquals( (byte) 13, content[4 + 8228 * 3] ); - } - - /** - * test simple addString - */ - @Test - void testSimpleAddString() { - SSTRecord record = new SSTRecord(); - UnicodeString s1 = new UnicodeString("Hello world"); - - // \u2122 is the encoding of the trademark symbol ... - UnicodeString s2 = new UnicodeString("Hello world\u2122"); - - assertEquals( 0, record.addString( s1 ) ); - assertEquals( s1, record.getString( 0 ) ); - assertEquals( 1, record.countStrings() ); - assertEquals( 1, record.getNumStrings() ); - assertEquals( 1, record.getNumUniqueStrings() ); - assertEquals( 0, record.addString( s1 ) ); - assertEquals( s1, record.getString( 0 ) ); - assertEquals( 1, record.countStrings() ); - assertEquals( 2, record.getNumStrings() ); - assertEquals( 1, record.getNumUniqueStrings() ); - assertEquals( 1, record.addString( s2 ) ); - assertEquals( s2, record.getString( 1 ) ); - assertEquals( 2, record.countStrings() ); - assertEquals( 3, record.getNumStrings() ); - assertEquals( 2, record.getNumUniqueStrings() ); - Iterator iter = record.getStrings(); - - while ( iter.hasNext() ) { - UnicodeString ucs = iter.next(); - - if ( ucs.equals( s1 ) ) - { - assertEquals( (byte) 0, ucs.getOptionFlags() ); - } - else if ( ucs.equals( s2 ) ) - { - assertEquals( (byte) 1, ucs.getOptionFlags() ); - } - else - { - fail( "cannot match string: " + ucs.getString() ); - } - } - } - - /** - * test simple constructor - */ - @Test - void testSimpleConstructor() { - SSTRecord record = new SSTRecord(); - - assertEquals( 0, record.getNumStrings() ); - assertEquals( 0, record.getNumUniqueStrings() ); - assertEquals( 0, record.countStrings() ); - byte[] output = record.serialize(); - byte[] expected = { - (byte) record.getSid(), (byte) ( record.getSid() >> 8 ), - (byte) 8, (byte) 0, (byte) 0, (byte) 0, (byte) 0, - (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 - }; - - assertArrayEquals(expected, output); - } - - /** - * Tests that workbooks with rich text that duplicates a non rich text cell can be read and written. - */ - @Test - void testReadWriteDuplicatedRichText1() throws Exception { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("duprich1.xls")) { - HSSFSheet sheet = wb.getSheetAt(1); - assertEquals("01/05 (Wed)", sheet.getRow(0).getCell(8).getStringCellValue()); - assertEquals("01/05 (Wed)", sheet.getRow(1).getCell(8).getStringCellValue()); - - HSSFTestDataSamples.writeOutAndReadBack(wb).close(); - } - - // test the second file. - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("duprich2.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - int row = 0; - assertEquals("Testing", sheet.getRow(row++).getCell(0).getStringCellValue()); - assertEquals("rich", sheet.getRow(row++).getCell(0).getStringCellValue()); - assertEquals("text", sheet.getRow(row++).getCell(0).getStringCellValue()); - assertEquals("strings", sheet.getRow(row++).getCell(0).getStringCellValue()); - assertEquals("Testing", sheet.getRow(row++).getCell(0).getStringCellValue()); - assertEquals("Testing", sheet.getRow(row).getCell(0).getStringCellValue()); - - HSSFTestDataSamples.writeOutAndReadBack(wb).close(); - } - } - - - /** - * deep comparison of two SST records - */ - private static void assertRecordEquals(SSTRecord expected, SSTRecord actual){ - assertEquals(expected.getNumStrings(), actual.getNumStrings(), "number of strings"); - assertEquals(expected.getNumUniqueStrings(), actual.getNumUniqueStrings(), "number of unique strings"); - assertEquals(expected.countStrings(), actual.countStrings(), "count of strings"); - - Iterator iterA = expected.getStrings(); - Iterator iterB = actual.getStrings(); - while (iterA.hasNext()) { - assertEquals(iterA.next(), iterB.next()); - } - } - - @Test - void test50779_1() throws IOException { - byte[] bytes = RawDataUtil.decompress("H4sIAAAAAAAAAL3aO2gVQRQG4HO5XkEZ8AESi4DBKoXFP+8IVioSvahcLxKC" + - "iRIRc9FEUZExCL4IYnyQqIi9SEATFUHRTkSQaBFsrEQLG8EiFgGrCM6uIGiff5c5e3ZY9l8W9mt2FqSjoyEixTBSW5kPm7EV29CNHa" + - "hjJ3ajgSb2oge92Id+HMAADuEwWjiCoxjCMI7hOE7iNM7gLM7hPC7gIi5hFJdxBWO4imu4jhsYxy3cBqTYtVRESU28/NnqMFJZ/Fgj" + - "lBjLiXGcGM+JCZyYyInp4sRsZMTo8sshxGhODEUBzVFAcxTQHAU0RwHNUUBzFNAcBQxHAcNRwHAUMBwFDEcBw1HAcBQwHAUMRwHDUc" + - "ByFLAcBSxHActRwHIUsBwFLEcBy1HAchSwHAUcRwHHUcBxFHAcBRxHAcdRwHEUcBwFHEcBx1HAcxTwHAU8RwHPUcBzFPAcBTxHAc9R" + - "wHMU8BwFAkeBwFEgcBQIHAUCR4HAUSBwFAgcBQJHgcBRIHIUiBwFIkeByFEgchSIHAUiR4HIUSBmBdZJ7aWItDXTcHNiz925lkoP+u" + - "oHVRof+dmnUrXVOajSQs/YKZVODE7v+jWxpbl9VKX9I929n/tVSndmb6pUkWfl//Tl5ZN/whtM4T7eYRL38BBf8R1PMZ9nfuBt2X3E" + - "E7zAl7KfwWs8Lrvn+YpXf2cn8Qjfcp3ZJI1KvuZDOT+F95jO9yn6opstu+IvflWW5lEVVR5XybJc2/JZVdplRa7rZXWunbIm1w2yVp" + - "bkN9yee9Kyg5gp/HfZAW3FQ1ce/694+A14Ha5/eSEAAA=="); - - RecordInputStream in = TestcaseRecordInputStream.create(bytes); - assertEquals(SSTRecord.sid, in.getSid()); - SSTRecord src = new SSTRecord(in); - assertEquals(81, src.getNumStrings()); - - byte[] serialized = src.serialize(); - - in = TestcaseRecordInputStream.create(serialized); - assertEquals(SSTRecord.sid, in.getSid()); - SSTRecord dst = new SSTRecord(in); - assertEquals(81, dst.getNumStrings()); - - assertRecordEquals(src, dst); - } - - @Test - void test50779_2() throws IOException { - byte[] bytes = RawDataUtil.decompress("H4sIAAAAAAAAAL3Uu2sVQRjG4e9wOKKw4gUkKSyCVQqLd2d2ZhOwiiLqQSUe" + - "JIgRUcQc1ERUZBXBG0GMFxIiaC8S8I6FWIoIop2NlWBhI1hoIVhFcM6Cgn+Avx3m2+HbXd5hYJ9FGxgYNbPedNYY0SZt1hZtU1vbtV" + - "Oj6mi3xrRHe7VP+3VAh3RYXR3RUR3TpKZ0XCd1Wmd0Tud1QRd1SZc1rSu6qhld03Xd0E3Nal63JOuNnIlxTIxnYgomJjAxkYkpmZgh" + - "JmaYiMnrPweIQRTIGQVyRoGcUSBnFMgZBXJGgZxRIGcUcIwCjlHAMQo4RgHHKOAYBRyjgGMUcIwCjlHAMwp4RgHPKOAZBTyjgGcU8I" + - "wCnlHAMwp4RoGCUaBgFCgYBQpGgYJRoGAUKBgFCkaBglGgYBQIjAKBUSAwCgRGgcAoEBgFAqNAYBQIjAKBUSAyCkRGgcgoEBkFIqNA" + - "ZBSIjAKRUSAyCkRGgZJRoGQUKBkFSkaBklGgZBQoGQVKRoEyKdBvrdtm1tepJjtzu+5862bV/fH2wayaPftzPKua3cGJrFocmzmVVS" + - "cmHu34Nbexs3U6qxo2b6105kttfRof9VoPdU/vtKC7eqDP+qpn+pE63/WmXn3QU73Qp3r9Vq/0pF49T2+8/Ntd0GN9SbX3/H3dSxuz" + - "pi1Js2lZfV9ly1Lt22DLG6nTtLW2ItV1tjrVQVuTqrPWyvTZ/z+7YettoXcIfy4oeijNf6Pb+g0SIvVzNSEAAA=="); - - RecordInputStream in = TestcaseRecordInputStream.create(bytes); - assertEquals(SSTRecord.sid, in.getSid()); - SSTRecord src = new SSTRecord(in); - assertEquals(81, src.getNumStrings()); - - byte[] serialized = src.serialize(); - - in = TestcaseRecordInputStream.create(serialized); - assertEquals(SSTRecord.sid, in.getSid()); - SSTRecord dst = new SSTRecord(in); - assertEquals(81, dst.getNumStrings()); - - assertRecordEquals(src, dst); - } - - @Test - void test57456() { - byte[] bytes = HexRead.readFromString("FC, 00, 08, 00, 00, 00, 00, 00, E1, 06, 00, 00"); - RecordInputStream in = TestcaseRecordInputStream.create(bytes); - assertEquals(SSTRecord.sid, in.getSid()); - SSTRecord src = new SSTRecord(in); - assertEquals(0, src.getNumStrings()); - assertEquals(0, src.getNumUniqueStrings()); - - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java b/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java deleted file mode 100644 index db0593f344..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.common.UnicodeString; -import org.apache.poi.hssf.record.cont.ContinuableRecordOutput; -import org.apache.poi.util.IntMapper; -import org.apache.poi.util.LittleEndianConsts; -import org.junit.jupiter.api.Test; - -/** - * Tests that records size calculates correctly. - */ -final class TestSSTRecordSizeCalculator { - private static final String SMALL_STRING = "Small string"; - private static final int COMPRESSED_PLAIN_STRING_OVERHEAD = 3; - private static final int OPTION_FIELD_SIZE = 1; - - private final IntMapper strings = new IntMapper<>(); - - - /** standard record overhead: two shorts (record id plus data space size)*/ - private static final int STD_RECORD_OVERHEAD = 2 * LittleEndianConsts.SHORT_SIZE; - - /** SST overhead: the standard record overhead, plus the number of strings and the number of unique strings -- two ints */ - private static final int SST_RECORD_OVERHEAD = STD_RECORD_OVERHEAD + 2 * LittleEndianConsts.INT_SIZE; - - /** how much data can we stuff into an SST record? That would be _max minus the standard SST record overhead */ - private static final int MAX_DATA_SPACE = RecordInputStream.MAX_RECORD_DATA_SIZE - 8; - - - private void confirmSize(int expectedSize) { - ContinuableRecordOutput cro = ContinuableRecordOutput.createForCountingOnly(); - SSTSerializer ss = new SSTSerializer(strings, 0, 0); - ss.serialize(cro); - assertEquals(expectedSize, cro.getTotalSize()); - } - - @Test - void testBasic() { - strings.add(makeUnicodeString(SMALL_STRING)); - confirmSize(SST_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + SMALL_STRING.length()); - } - - @Test - void testBigStringAcrossUnicode() { - int bigString = MAX_DATA_SPACE + 100; - strings.add(makeUnicodeString(bigString)); - confirmSize(SST_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + MAX_DATA_SPACE - + STD_RECORD_OVERHEAD - + OPTION_FIELD_SIZE - + 100); - } - - @Test - void testPerfectFit() { - int perfectFit = MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD; - strings.add(makeUnicodeString(perfectFit)); - confirmSize(SST_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + perfectFit); - } - - @Test - void testJustOversized() { - int tooBig = MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD + 1; - strings.add(makeUnicodeString(tooBig)); - confirmSize(SST_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + tooBig - 1 - // continue record - + STD_RECORD_OVERHEAD - + OPTION_FIELD_SIZE + 1); - - } - - @Test - void testSecondStringStartsOnNewContinuation() { - int perfectFit = MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD; - strings.add(makeUnicodeString(perfectFit)); - strings.add(makeUnicodeString(SMALL_STRING)); - confirmSize(SST_RECORD_OVERHEAD - + MAX_DATA_SPACE - // second string - + STD_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + SMALL_STRING.length()); - } - - @Test - void testHeaderCrossesNormalContinuePoint() { - int almostPerfectFit = MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD - 2; - strings.add(makeUnicodeString(almostPerfectFit)); - String oneCharString = new String(new char[1]); - strings.add(makeUnicodeString(oneCharString)); - confirmSize(SST_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + almostPerfectFit - // second string - + STD_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + oneCharString.length()); - - } - - private static UnicodeString makeUnicodeString(int size) { - String s = new String(new char[size]); - return makeUnicodeString(s); - } - - private static UnicodeString makeUnicodeString(String s) { - UnicodeString st = new UnicodeString(s); - st.setOptionFlags((byte) 0); - return st; - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java deleted file mode 100644 index 17855c08de..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java +++ /dev/null @@ -1,245 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.util.stream.Stream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaRenderer; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.SharedFormula; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.util.LittleEndianInput; -import org.junit.jupiter.api.Test; - -final class TestSharedFormulaRecord { - - /** - * A sample spreadsheet known to have one sheet with 4 shared formula ranges - */ - private static final String SHARED_FORMULA_TEST_XLS = "SharedFormulaTest.xls"; - /** - * Binary data for an encoded formula. Taken from attachment 22062 (bugzilla 45123/45421). - * The shared formula is in Sheet1!C6:C21, with text "SUMPRODUCT(--(End_Acct=$C6),--(End_Bal))" - * This data is found at offset 0x1A4A (within the shared formula record). - * The critical thing about this formula is that it contains shared formula tokens (tRefN*, - * tAreaN*) with operand class 'array'. - */ - private static final byte[] SHARED_FORMULA_WITH_REF_ARRAYS_DATA = { - 0x1A, 0x00, - 0x63, 0x02, 0x00, 0x00, 0x00, - 0x6C, 0x00, 0x00, 0x02, (byte)0x80, // tRefNA - 0x0B, - 0x15, - 0x13, - 0x13, - 0x63, 0x03, 0x00, 0x00, 0x00, - 0x15, - 0x13, - 0x13, - 0x42, 0x02, (byte)0xE4, 0x00, - }; - - /** - * The method SharedFormulaRecord.convertSharedFormulas() converts formulas from - * 'shared formula' to 'single cell formula' format. It is important that token operand - * classes are preserved during this transformation, because Excel may not tolerate the - * incorrect encoding. The formula here is one such example (Excel displays #VALUE!). - */ - @Test - void testConvertSharedFormulasOperandClasses_bug45123() { - - LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(SHARED_FORMULA_WITH_REF_ARRAYS_DATA); - int encodedLen = in.readUShort(); - Ptg[] sharedFormula = Ptg.readTokens(encodedLen, in); - - SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97); - Ptg[] convertedFormula = sf.convertSharedFormulas(sharedFormula, 100, 200); - - RefPtg refPtg = (RefPtg) convertedFormula[1]; - assertEquals("$C101", refPtg.toFormulaString()); - assertNotEquals(Ptg.CLASS_REF, refPtg.getPtgClass(), "Identified bug 45123"); - confirmOperandClasses(sharedFormula, convertedFormula); - } - - private static void confirmOperandClasses(Ptg[] originalPtgs, Ptg[] convertedPtgs) { - int[] exp = Stream.of(originalPtgs).map(Ptg::getPtgClass).mapToInt(Byte::intValue).toArray(); - int[] act = Stream.of(convertedPtgs).map(Ptg::getPtgClass).mapToInt(Byte::intValue).toArray(); - assertArrayEquals(exp, act, "Different operand class"); - } - - @Test - void testConvertSharedFormulas() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFEvaluationWorkbook fpb = HSSFEvaluationWorkbook.create(wb); - Ptg[] sharedFormula, convertedFormula; - - SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97); - - sharedFormula = FormulaParser.parse("A2", fpb, FormulaType.CELL, -1); - convertedFormula = sf.convertSharedFormulas(sharedFormula, 0, 0); - confirmOperandClasses(sharedFormula, convertedFormula); - //conversion relative to [0,0] should return the original formula - assertEquals("A2", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - - convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 0); - confirmOperandClasses(sharedFormula, convertedFormula); - //one row down - assertEquals("A3", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - - convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 1); - confirmOperandClasses(sharedFormula, convertedFormula); - //one row down and one cell right - assertEquals("B3", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - - sharedFormula = FormulaParser.parse("SUM(A1:C1)", fpb, FormulaType.CELL, -1); - convertedFormula = sf.convertSharedFormulas(sharedFormula, 0, 0); - confirmOperandClasses(sharedFormula, convertedFormula); - assertEquals("SUM(A1:C1)", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - - convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 0); - confirmOperandClasses(sharedFormula, convertedFormula); - assertEquals("SUM(A2:C2)", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - - convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 1); - confirmOperandClasses(sharedFormula, convertedFormula); - assertEquals("SUM(B2:D2)", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - } - - /** - * Make sure that POI preserves {@link SharedFormulaRecord}s - */ - @Test - void testPreserveOnReserialize() { - HSSFWorkbook wb; - HSSFSheet sheet; - HSSFCell cellB32769; - HSSFCell cellC32769; - - // Reading directly from XLS file - wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS); - sheet = wb.getSheetAt(0); - cellB32769 = sheet.getRow(32768).getCell(1); - cellC32769 = sheet.getRow(32768).getCell(2); - // check reading of formulas which are shared (two cells from a 1R x 8C range) - assertEquals("B32770*2", cellB32769.getCellFormula()); - assertEquals("C32770*2", cellC32769.getCellFormula()); - confirmCellEvaluation(wb, cellB32769, 4); - confirmCellEvaluation(wb, cellC32769, 6); - // Confirm this example really does have SharedFormulas. - // there are 3 others besides the one at A32769:H32769 - assertEquals(4, countSharedFormulas(sheet)); - - - // Re-serialize and check again - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - cellB32769 = sheet.getRow(32768).getCell(1); - cellC32769 = sheet.getRow(32768).getCell(2); - assertEquals("B32770*2", cellB32769.getCellFormula()); - assertEquals("C32770*2", cellC32769.getCellFormula()); - confirmCellEvaluation(wb, cellB32769, 4); - assertEquals(4, countSharedFormulas(sheet)); - } - - @Test - void testUnshareFormulaDueToChangeFormula() { - HSSFWorkbook wb; - HSSFSheet sheet; - HSSFCell cellB32769; - HSSFCell cellC32769; - - wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS); - sheet = wb.getSheetAt(0); - cellB32769 = sheet.getRow(32768).getCell(1); - cellC32769 = sheet.getRow(32768).getCell(2); - - // Updating cell formula, causing it to become unshared - cellB32769.setCellFormula("1+1"); - confirmCellEvaluation(wb, cellB32769, 2); - // currently (Oct 2008) POI handles this by exploding the whole shared formula group - assertEquals(3, countSharedFormulas(sheet)); // one less now - // check that nearby cell of the same group still has the same formula - assertEquals("C32770*2", cellC32769.getCellFormula()); - confirmCellEvaluation(wb, cellC32769, 6); - } - - @Test - void testUnshareFormulaDueToDelete() { - HSSFWorkbook wb; - HSSFSheet sheet; - HSSFCell cell; - final int ROW_IX = 2; - - // changing shared formula cell to blank - wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS); - sheet = wb.getSheetAt(0); - - assertEquals("A$1*2", sheet.getRow(ROW_IX).getCell(1).getCellFormula()); - cell = sheet.getRow(ROW_IX).getCell(1); - cell.setBlank(); - assertEquals(3, countSharedFormulas(sheet)); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - assertEquals("A$1*2", sheet.getRow(ROW_IX+1).getCell(1).getCellFormula()); - - // deleting shared formula cell - wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS); - sheet = wb.getSheetAt(0); - - assertEquals("A$1*2", sheet.getRow(ROW_IX).getCell(1).getCellFormula()); - cell = sheet.getRow(ROW_IX).getCell(1); - sheet.getRow(ROW_IX).removeCell(cell); - assertEquals(3, countSharedFormulas(sheet)); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - assertEquals("A$1*2", sheet.getRow(ROW_IX+1).getCell(1).getCellFormula()); - } - - private static void confirmCellEvaluation(HSSFWorkbook wb, HSSFCell cell, double expectedValue) { - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue cv = fe.evaluate(cell); - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(expectedValue, cv.getNumberValue(), 0.0); - } - - /** - * @return the number of {@link SharedFormulaRecord}s encoded for the specified sheet - */ - private static int countSharedFormulas(HSSFSheet sheet) { - int[] count = { 0 }; - sheet.getSheet().visitContainedRecords(r -> count[0] += r instanceof SharedFormulaRecord ? 1 : 0, 0); - return count[0]; - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java b/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java deleted file mode 100644 index 18d345213e..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the StringRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestStringRecord { - private static final byte[] data = HexRead.readFromString( - "0B 00 " + // length - "00 " + // option - // string - "46 61 68 72 7A 65 75 67 74 79 70" - ); - - @Test - void testLoad() { - - StringRecord record = new StringRecord(TestcaseRecordInputStream.create(0x207, data)); - assertEquals( "Fahrzeugtyp", record.getString()); - - assertEquals( 18, record.getRecordSize() ); - } - - @Test - void testStore() { - StringRecord record = new StringRecord(); - record.setString("Fahrzeugtyp"); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) { - assertEquals(data[i], recordBytes[i+4], "At offset " + i); - } - } - - @Test - void testContinue() throws IOException { - int MAX_BIFF_DATA = RecordInputStream.MAX_RECORD_DATA_SIZE; - int TEXT_LEN = MAX_BIFF_DATA + 1000; // deliberately over-size - String textChunk = "ABCDEGGHIJKLMNOP"; // 16 chars - StringBuilder sb = new StringBuilder(16384); - while (sb.length() < TEXT_LEN) { - sb.append(textChunk); - } - sb.setLength(TEXT_LEN); - - StringRecord sr = new StringRecord(); - sr.setString(sb.toString()); - byte[] ser = sr.serialize(); - assertEquals(StringRecord.sid, LittleEndian.getUShort(ser, 0)); - assertTrue(LittleEndian.getUShort(ser, 2) <= MAX_BIFF_DATA, - "StringRecord should have been split with a continue record"); - // Confirm expected size of first record, and ushort strLen. - assertEquals(MAX_BIFF_DATA, LittleEndian.getUShort(ser, 2)); - assertEquals(TEXT_LEN, LittleEndian.getUShort(ser, 4)); - - // Confirm first few bytes of ContinueRecord - LittleEndianByteArrayInputStream crIn = new LittleEndianByteArrayInputStream(ser, (MAX_BIFF_DATA + 4)); - int nCharsInFirstRec = MAX_BIFF_DATA - (2 + 1); // strLen, optionFlags - int nCharsInSecondRec = TEXT_LEN - nCharsInFirstRec; - assertEquals(ContinueRecord.sid, crIn.readUShort()); - assertEquals(1 + nCharsInSecondRec, crIn.readUShort()); - assertEquals(0, crIn.readUByte()); - assertEquals('N', crIn.readUByte()); - assertEquals('O', crIn.readUByte()); - - // re-read and make sure string value is the same - RecordInputStream in = TestcaseRecordInputStream.create(ser); - StringRecord sr2 = new StringRecord(in); - assertEquals(sb.toString(), sr2.getString()); - crIn.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java b/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java deleted file mode 100644 index ed47560caf..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link StyleRecord} - */ -final class TestStyleRecord { - @Test - void testUnicodeReadName() { - byte[] data = HexRead.readFromString( - "11 00 09 00 01 38 5E C4 89 5F 00 53 00 68 00 65 00 65 00 74 00 31 00"); - RecordInputStream in = TestcaseRecordInputStream.create(StyleRecord.sid, data); - StyleRecord sr = new StyleRecord(in); - assertEquals("\u5E38\u89C4_Sheet1", sr.getName()); // "_Sheet1" - // bug 46385 - Incorrect number of bytes written - expected 27 but got 18 - byte[] ser = sr.serialize(); - confirmRecordEncoding(StyleRecord.sid, data, ser); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java deleted file mode 100644 index b10800d5a3..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java +++ /dev/null @@ -1,148 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.util.Arrays; - -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndian; -import org.junit.jupiter.api.Test; - -/** - * Tests Subrecord components of an OBJ record. Test data taken directly - * from a real Excel file. - */ -final class TestSubRecord { - /* - The following is a dump of the OBJ record corresponding to an auto-filter - drop-down list. The 3rd subrecord beginning at offset 0x002e (type=0x0013) - does not conform to the documentation, because the length field is 0x1fee, - which is longer than the entire OBJ record. - - 00000000 15 00 12 00 14 00 01 00 01 21 00 00 00 00 3C 13 .........!....<. Type=0x15 Len=0x0012 ftCmo - 00000010 F4 03 00 00 00 00 - 0C 00 14 00 00 00 00 00 00 00 ................ Type=0x0c Len=0x0014 ftSbs - 00000020 00 00 00 00 01 00 08 00 00 00 10 00 00 00 - 13 00 ................ Type=0x13 Len=0x1FEE ftLbsData - 00000030 EE 1F 00 00 08 00 08 00 01 03 00 00 0A 00 14 00 ................ - 00000040 6C 00 - 00 00 00 00 l..... Type=0x00 Len=0x0000 ftEnd - */ - - private static final byte[] dataAutoFilter - = HexRead.readFromString("" - + "5D 00 46 00 " // ObjRecord.sid, size=70 - // ftCmo - + "15 00 12 00 " - + "14 00 01 00 01 00 01 21 00 00 3C 13 F4 03 00 00 00 00 " - // ftSbs (currently UnknownSubrecord) - + "0C 00 14 00 " - + "00 00 00 00 00 00 00 00 00 00 01 00 08 00 00 00 10 00 00 00 " - // ftLbsData (currently UnknownSubrecord) - + "13 00 EE 1F 00 00 " - + "08 00 08 00 01 03 00 00 0A 00 14 00 6C 00 " - // ftEnd - + "00 00 00 00" - ); - - - /** - * Make sure that ftLbsData (which has abnormal size info) is parsed correctly. - * If the size field is interpreted incorrectly, the resulting ObjRecord becomes way too big. - * At the time of fixing (Oct-2008 svn r707447) {@link RecordInputStream} allowed buffer - * read overruns, so the bug was mostly silent. - */ - @Test - void testReadAll_bug45778() { - RecordInputStream in = TestcaseRecordInputStream.create(dataAutoFilter); - ObjRecord or = new ObjRecord(in); - byte[] data2 = or.serialize(); - assertNotEquals(8228, data2.length, "Identified bug 45778"); - assertEquals(74, data2.length); - assertArrayEquals(dataAutoFilter, data2); - } - - @Test - void testReadManualComboWithFormula() { - byte[] data = HexRead.readFromString("" - + "5D 00 66 00 " - + "15 00 12 00 14 00 02 00 11 20 00 00 00 00 " - + "20 44 C6 04 00 00 00 00 0C 00 14 00 04 F0 C6 04 " - + "00 00 00 00 00 00 01 00 06 00 00 00 10 00 00 00 " - + "0E 00 0C 00 05 00 80 44 C6 04 24 09 00 02 00 02 " - + "13 00 DE 1F 10 00 09 00 80 44 C6 04 25 0A 00 0F " - + "00 02 00 02 00 02 06 00 03 00 08 00 00 00 00 00 " - + "08 00 00 00 00 00 00 00 " // TODO sometimes last byte is non-zero - ); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - ObjRecord or = new ObjRecord(in); - byte[] data2 = or.serialize(); - assertNotEquals(8228, data2.length, "Identified bug 45778"); - assertEquals(data.length, data2.length, "Encoded length"); - assertArrayEquals(data, data2, "Encoded data differs"); - } - - /** - * Some versions of POI (e.g. 3.1 - prior to svn r707450 / bug 45778) interpreted the ftLbs - * subrecord second short (0x1FEE) as a length, and hence read lots of extra padding. This - * buffer-overrun in {@link RecordInputStream} happened silently due to problems later fixed - * in svn 707778. When the ObjRecord is written, the extra padding is written too, making the - * record 8224 bytes long instead of 70. - * (An aside: It seems more than a coincidence that this problem creates a record of exactly - * {@link RecordInputStream#MAX_RECORD_DATA_SIZE} but not enough is understood about - * subrecords to explain this.)
- * - * Excel reads files with this excessive padding OK. It also truncates the over-sized - * ObjRecord back to the proper size. POI should do the same. - */ - @Test - void testWayTooMuchPadding_bug46545() { - byte[] data = HexRead.readFromString("" - + "15 00 12 00 14 00 13 00 01 21 00 00 00" - + "00 98 0B 5B 09 00 00 00 00 0C 00 14 00 00 00 00 00 00 00 00" - + "00 00 00 01 00 01 00 00 00 10 00 00 00 " - // ftLbs - + "13 00 EE 1F 00 00 " - + "01 00 00 00 01 06 00 00 02 00 08 00 75 00 " - // ftEnd - + "00 00 00 00" - ); - final int LBS_START_POS = 0x002E; - final int WRONG_LBS_SIZE = 0x1FEE; - assertEquals(0x0013, LittleEndian.getShort(data, LBS_START_POS)); - assertEquals(WRONG_LBS_SIZE, LittleEndian.getShort(data, LBS_START_POS+2)); - int wrongTotalSize = LBS_START_POS + 4 + WRONG_LBS_SIZE; - byte[] wrongData = Arrays.copyOf(data, wrongTotalSize); - // wrongData has the ObjRecord data as would have been written by v3.1 - - RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, wrongData); - // bug 46545 - Leftover 8154 bytes in subrecord data - ObjRecord or = new ObjRecord(in); - // make sure POI properly truncates the ObjRecord data - byte[] data2 = or.serialize(); - confirmRecordEncoding(ObjRecord.sid, data, data2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java deleted file mode 100644 index 1766c514dd..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.apache.poi.hssf.record.SupBookRecord.CH_ALT_STARTUP_DIR; -import static org.apache.poi.hssf.record.SupBookRecord.CH_DOWN_DIR; -import static org.apache.poi.hssf.record.SupBookRecord.CH_LIB_DIR; -import static org.apache.poi.hssf.record.SupBookRecord.CH_SAME_VOLUME; -import static org.apache.poi.hssf.record.SupBookRecord.CH_STARTUP_DIR; -import static org.apache.poi.hssf.record.SupBookRecord.CH_UP_DIR; -import static org.apache.poi.hssf.record.SupBookRecord.CH_VOLUME; -import static org.apache.poi.hssf.record.SupBookRecord.PATH_SEPERATOR; -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the SupBook record - * class works correctly. - */ -final class TestSupBookRecord { - /** - * This contains a fake data section of a SubBookRecord - */ - byte[] dataIR = new byte[] { - (byte)0x04,(byte)0x00,(byte)0x01,(byte)0x04, - }; - byte[] dataAIF = new byte[] { - (byte)0x01,(byte)0x00,(byte)0x01,(byte)0x3A, - }; - byte[] dataER = new byte[] { - (byte)0x02,(byte)0x00, - (byte)0x07,(byte)0x00, (byte)0x00, - (byte)'t', (byte)'e', (byte)'s', (byte)'t', (byte)'U', (byte)'R', (byte)'L', - (byte)0x06,(byte)0x00, (byte)0x00, - (byte)'S', (byte)'h', (byte)'e', (byte)'e', (byte)'t', (byte)'1', - (byte)0x06,(byte)0x00, (byte)0x00, - (byte)'S', (byte)'h', (byte)'e', (byte)'e', (byte)'t', (byte)'2', - }; - - /** - * tests that we can load the record - */ - @Test - void testLoadIR() { - SupBookRecord record = new SupBookRecord(TestcaseRecordInputStream.create(0x01AE, dataIR)); - assertTrue( record.isInternalReferences() ); //expected flag - assertEquals( 0x4, record.getNumberOfSheets() ); //expected # of sheets - - assertEquals( 8, record.getRecordSize() ); //sid+size+data - } - - /** - * tests that we can load the record - */ - @Test - void testLoadER() { - SupBookRecord record = new SupBookRecord(TestcaseRecordInputStream.create(0x01AE, dataER)); - assertTrue( record.isExternalReferences() ); //expected flag - assertEquals( 0x2, record.getNumberOfSheets() ); //expected # of sheets - - assertEquals( 34, record.getRecordSize() ); //sid+size+data - - assertEquals("testURL", record.getURL()); - String[] sheetNames = record.getSheetNames(); - assertEquals(2, sheetNames.length); - assertEquals("Sheet1", sheetNames[0]); - assertEquals("Sheet2", sheetNames[1]); - } - - /** - * tests that we can load the record - */ - @Test - void testLoadAIF() { - SupBookRecord record = new SupBookRecord(TestcaseRecordInputStream.create(0x01AE, dataAIF)); - assertTrue( record.isAddInFunctions() ); //expected flag - assertEquals( 0x1, record.getNumberOfSheets() ); //expected # of sheets - assertEquals( 8, record.getRecordSize() ); //sid+size+data - } - - /** - * Tests that we can store the record - */ - @SuppressWarnings("squid:S2699") - @Test - void testStoreIR() { - SupBookRecord record = SupBookRecord.createInternalReferences((short)4); - - confirmRecordEncoding(0x01AE, dataIR, record.serialize()); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStoreER() { - String url = "testURL"; - String[] sheetNames = { "Sheet1", "Sheet2", }; - SupBookRecord record = SupBookRecord.createExternalReferences(url, sheetNames); - - confirmRecordEncoding(0x01AE, dataER, record.serialize()); - } - - @Test - void testStoreAIF() { - SupBookRecord record = SupBookRecord.createAddInFunctions(); - assertEquals(1, record.getNumberOfSheets()); - assertTrue(record.isAddInFunctions()); - confirmRecordEncoding(0x01AE, dataAIF, record.serialize()); - } - - @Test - void testExternalReferenceUrl() { - String[] sheetNames = new String[]{"SampleSheet"}; - final char startMarker = (char)1; - - SupBookRecord record; - - record = new SupBookRecord(startMarker + "test.xls", sheetNames); - assertEquals("test.xls", record.getURL()); - - //UNC path notation - record = new SupBookRecord(startMarker + "" + CH_VOLUME + "@servername" + CH_DOWN_DIR + "test.xls", sheetNames); - assertEquals("\\\\servername" + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Absolute path notation - different device - record = new SupBookRecord(startMarker + "" + CH_VOLUME + "D" + CH_DOWN_DIR + "test.xls", sheetNames); - assertEquals("D:" + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Absolute path notation - same device - record = new SupBookRecord(startMarker + "" + CH_SAME_VOLUME + "folder" + CH_DOWN_DIR + "test.xls", sheetNames); - assertEquals(PATH_SEPERATOR + "folder" + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Relative path notation - down - record = new SupBookRecord(startMarker + "folder" + CH_DOWN_DIR + "test.xls", sheetNames); - assertEquals("folder" + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Relative path notation - up - record = new SupBookRecord(startMarker +""+ CH_UP_DIR + "test.xls", sheetNames); - assertEquals(".." + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Relative path notation - for EXCEL.exe - fallback - record = new SupBookRecord(startMarker +""+ CH_STARTUP_DIR + "test.xls", sheetNames); - assertEquals("." + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Relative path notation - for EXCEL lib folder - fallback - record = new SupBookRecord(startMarker +""+ CH_LIB_DIR + "test.xls", sheetNames); - assertEquals("." + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Relative path notation - for alternative EXCEL.exe - fallback - record = new SupBookRecord(startMarker +""+ CH_ALT_STARTUP_DIR+ "test.xls", sheetNames); - assertEquals("." + PATH_SEPERATOR + "test.xls", record.getURL()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java deleted file mode 100644 index 58cd682df2..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java +++ /dev/null @@ -1,97 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.util.CellRangeAddress8Bit; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the TableRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestTableRecord { - byte[] header = new byte[] { - 0x36, 02, 0x10, 00, // sid=x236, 16 bytes long - }; - byte[] data = new byte[] { - 03, 00, // from row 3 - 8, 00, // to row 8 - 04, // from col 4 - 06, // to col 6 - 00, 00, // no flags set - 04, 00, // row inp row 4 - 01, 00, // col inp row 1 - 0x76, 0x40, // row inp col 0x4076 (!) - 00, 00 // col inp col 0 - }; - - @Test - void testLoad() { - - TableRecord record = new TableRecord(TestcaseRecordInputStream.create(0x236, data)); - - CellRangeAddress8Bit range = record.getRange(); - assertEquals(3, range.getFirstRow()); - assertEquals(8, range.getLastRow()); - assertEquals(4, range.getFirstColumn()); - assertEquals(6, range.getLastColumn()); - assertEquals(0, record.getFlags()); - assertEquals(4, record.getRowInputRow()); - assertEquals(1, record.getColInputRow()); - assertEquals(0x4076, record.getRowInputCol()); - assertEquals(0, record.getColInputCol()); - - assertEquals( 16 + 4, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() - { -// Offset 0x3bd9 (15321) -// recordid = 0x236, size = 16 -// [TABLE] -// .row from = 3 -// .row to = 8 -// .column from = 4 -// .column to = 6 -// .flags = 0 -// .always calc =false -// .reserved = 0 -// .row input row = 4 -// .col input row = 1 -// .row input col = 4076 -// .col input col = 0 -// [/TABLE] - - CellRangeAddress8Bit crab = new CellRangeAddress8Bit(3, 8, 4, 6); - TableRecord record = new TableRecord(crab); - record.setFlags((byte)0); - record.setRowInputRow(4); - record.setColInputRow(1); - record.setRowInputCol(0x4076); - record.setColInputCol(0); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(TableRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java deleted file mode 100644 index 6af2622dcb..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java +++ /dev/null @@ -1,85 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the TextObjectBaseRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestTextObjectBaseRecord { - /** data for one TXO rec and two continue recs */ - private static final byte[] data = HexRead.readFromString( - "B6 01 " + // TextObjectRecord.sid - "12 00 " + // size 18 - "44 02 02 00 00 00 00 00" + - "00 00 " + - "02 00 " + // strLen 2 - "10 00 " + // 16 bytes for 2 format runs - "00 00" + - "00 00 " + - "3C 00 " + // ContinueRecord.sid - "03 00 " + // size 3 - "00 " + // unicode compressed - "41 42 " + // 'AB' - "3C 00 " + // ContinueRecord.sid - "10 00 " + // size 16 - "00 00 18 00 00 00 00 00 " + - "02 00 00 00 00 00 00 00 " - ); - - @Test - void testLoad() { - RecordInputStream in = TestcaseRecordInputStream.create(data); - TextObjectRecord record = new TextObjectRecord(in); - - assertEquals(TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_CENTERED, record.getHorizontalTextAlignment()); - assertEquals(TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_JUSTIFY, record.getVerticalTextAlignment()); - assertTrue(record.isTextLocked()); - assertEquals(TextObjectRecord.TEXT_ORIENTATION_ROT_RIGHT, record.getTextOrientation()); - - assertEquals(49, record.getRecordSize() ); - } - - @Test - void testStore() { - TextObjectRecord record = new TextObjectRecord(); - - HSSFRichTextString str = new HSSFRichTextString("AB"); - str.applyFont(0, 2, (short)0x0018); - str.applyFont(2, 2, (short)0x0320); - - record.setHorizontalTextAlignment(TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_CENTERED); - record.setVerticalTextAlignment(TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_JUSTIFY); - record.setTextLocked(true); - record.setTextOrientation(TextObjectRecord.TEXT_ORIENTATION_ROT_RIGHT); - record.setStr(str); - - byte [] recordBytes = record.serialize(); - assertArrayEquals(data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java deleted file mode 100644 index 272b1802e1..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java +++ /dev/null @@ -1,201 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.ByteArrayInputStream; - -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndian; -import org.junit.jupiter.api.Test; - -/** - * Tests that serialization and deserialization of the TextObjectRecord . - * Test data taken directly from a real Excel file. - * - * @author Yegor Kozlov - */ -final class TestTextObjectRecord { - - private static final byte[] simpleData = HexRead.readFromString( - "B6 01 12 00 " + - "12 02 00 00 00 00 00 00" + - "00 00 0D 00 08 00 00 00" + - "00 00 " + - "3C 00 0E 00 " + - "00 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 " + - "3C 00 08 " + - "00 0D 00 00 00 00 00 00 00" - ); - - @Test - void testRead() { - - RecordInputStream is =TestcaseRecordInputStream.create(simpleData); - TextObjectRecord record = new TextObjectRecord(is); - - assertEquals(TextObjectRecord.sid, record.getSid()); - assertEquals(TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED, record.getHorizontalTextAlignment()); - assertEquals(TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_TOP, record.getVerticalTextAlignment()); - assertEquals(TextObjectRecord.TEXT_ORIENTATION_NONE, record.getTextOrientation()); - assertEquals("Hello, World!", record.getStr().getString()); - } - - @Test - void testWrite() { - HSSFRichTextString str = new HSSFRichTextString("Hello, World!"); - - TextObjectRecord record = new TextObjectRecord(); - record.setStr(str); - record.setHorizontalTextAlignment( TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED ); - record.setVerticalTextAlignment( TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_TOP ); - record.setTextLocked( true ); - record.setTextOrientation( TextObjectRecord.TEXT_ORIENTATION_NONE ); - - byte [] ser = record.serialize(); - assertEquals(ser.length , simpleData.length); - - assertArrayEquals(simpleData, ser); - - //read again - RecordInputStream is = TestcaseRecordInputStream.create(simpleData); - record = new TextObjectRecord(is); - assertNotNull(record); - } - - /** - * Zero {@link ContinueRecord}s follow a {@link TextObjectRecord} if the text is empty - */ - @Test - void testWriteEmpty() { - HSSFRichTextString str = new HSSFRichTextString(""); - - TextObjectRecord record = new TextObjectRecord(); - record.setStr(str); - - byte [] ser = record.serialize(); - - int formatDataLen = LittleEndian.getUShort(ser, 16); - assertEquals(0, formatDataLen, "formatDataLength"); - - assertEquals(22, ser.length); // just the TXO record - - //read again - RecordInputStream is = TestcaseRecordInputStream.create(ser); - record = new TextObjectRecord(is); - assertEquals(0, record.getStr().length()); - } - - /** - * Test that TextObjectRecord serializes logs records properly. - */ - @Test - void testLongRecords() { - int[] lengths = {1024, 2048, 4096, 8192, 16384}; //test against strings of different length - for (int length : lengths) { - StringBuilder buff = new StringBuilder(length); - for (int j = 0; j < length; j++) { - buff.append("x"); - } - HSSFRichTextString str = new HSSFRichTextString(buff.toString()); - - TextObjectRecord obj = new TextObjectRecord(); - obj.setStr(str); - - byte [] data = obj.serialize(); - RecordInputStream is = new RecordInputStream(new ByteArrayInputStream(data)); - is.nextRecord(); - TextObjectRecord record = new TextObjectRecord(is); - str = record.getStr(); - - assertEquals(buff.length(), str.length()); - assertEquals(buff.toString(), str.getString()); - } - } - - /** - * Test cloning - */ - @Test - void testClone() { - String text = "Hello, World"; - HSSFRichTextString str = new HSSFRichTextString(text); - - TextObjectRecord obj = new TextObjectRecord(); - obj.setStr( str ); - - - TextObjectRecord cloned = obj.copy(); - assertEquals(obj.getRecordSize(), cloned.getRecordSize()); - assertEquals(obj.getHorizontalTextAlignment(), cloned.getHorizontalTextAlignment()); - assertEquals(obj.getStr().getString(), cloned.getStr().getString()); - - //finally check that the serialized data is the same - byte[] src = obj.serialize(); - byte[] cln = cloned.serialize(); - assertArrayEquals(src, cln); - } - - /** similar to {@link #simpleData} but with link formula at end of TXO rec*/ - private static final byte[] linkData = HexRead.readFromString( - "B6 01 " + // TextObjectRecord.sid - "1E 00 " + // size 18 - "44 02 02 00 00 00 00 00" + - "00 00 " + - "02 00 " + // strLen 2 - "10 00 " + // 16 bytes for 2 format runs - "00 00 00 00 " + - - "05 00 " + // formula size - "D4 F0 8A 03 " + // unknownInt - "24 01 00 13 C0 " + //tRef(T2) - "13 " + // ?? - - "3C 00 " + // ContinueRecord.sid - "03 00 " + // size 3 - "00 " + // unicode compressed - "41 42 " + // 'AB' - "3C 00 " + // ContinueRecord.sid - "10 00 " + // size 16 - "00 00 18 00 00 00 00 00 " + - "02 00 00 00 00 00 00 00 " - ); - - @Test - void testLinkFormula() { - RecordInputStream is = new RecordInputStream(new ByteArrayInputStream(linkData)); - is.nextRecord(); - TextObjectRecord rec = new TextObjectRecord(is); - - Ptg ptg = rec.getLinkRefPtg(); - assertNotNull(ptg); - assertEquals(RefPtg.class, ptg.getClass()); - RefPtg rptg = (RefPtg) ptg; - assertEquals("T2", rptg.toFormulaString()); - - byte [] data2 = rec.serialize(); - assertEquals(linkData.length, data2.length); - assertArrayEquals(linkData, data2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java deleted file mode 100644 index 773b8666c1..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - 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.record; - - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -final class TestUnicodeNameRecord { - - @Test - void testReadBook() throws IOException { - // This bit used to crash - try (HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("unicodeNameRecord.xls")) { - HSSFSheet sheet = book.getSheetAt(0); - assertNotNull(sheet); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java b/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java deleted file mode 100644 index 364e478932..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link WriteAccessRecord} - */ -final class TestWriteAccessRecord { - - private static final String HEX_SIXTYFOUR_SPACES = "" - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20"; - - @Test - void testMissingStringHeader_bug47001a() { - /* - * Data taken from offset 0x0224 in - * attachment 23468 from bugzilla 47001 - */ - byte[] data = HexRead.readFromString("" - + "5C 00 70 00 " - + "4A 61 76 61 20 45 78 63 65 6C 20 41 50 49 20 76 " - + "32 2E 36 2E 34" - + "20 20 20 20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " - + HEX_SIXTYFOUR_SPACES); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - - // bug 47001a - Not enough data (0) to read requested (1) bytes - WriteAccessRecord rec = new WriteAccessRecord(in); - assertEquals("Java Excel API v2.6.4", rec.getUsername()); - - - byte[] expectedEncoding = HexRead.readFromString("" - + "15 00 00 4A 61 76 61 20 45 78 63 65 6C 20 41 50 " - + "49 20 76 32 2E 36 2E 34" - + "20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " - + HEX_SIXTYFOUR_SPACES); - - confirmRecordEncoding(WriteAccessRecord.sid, expectedEncoding, rec.serialize()); - } - - @Test - void testShortRecordWrittenByMSAccess() { - /* - * Data taken from two example files - * ex42564-21435.xls - * bug_42794.xls (from bug 42794 attachment 20429) - * In both cases, this data is found at offset 0x0C1C. - */ - byte[] data = HexRead.readFromString("" - + "5C 00 39 00 " - + "36 00 00 41 20 73 61 74 69 73 66 69 65 64 20 4D " - + "69 63 72 6F 73 6F 66 74 20 4F 66 66 69 63 65 39 " - + "20 55 73 65 72" - + "20 20 20 20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20"); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - WriteAccessRecord rec = new WriteAccessRecord(in); - assertEquals("A satisfied Microsoft Office9 User", rec.getUsername()); - byte[] expectedEncoding = HexRead.readFromString("" - + "22 00 00 41 20 73 61 74 69 73 66 69 65 64 20 4D " - + "69 63 72 6F 73 6F 66 74 20 4F 66 66 69 63 65 39 " - + "20 55 73 65 72" - + "20 20 20 20 20 20 20 20 20 20 20 " - + HEX_SIXTYFOUR_SPACES); - - confirmRecordEncoding(WriteAccessRecord.sid, expectedEncoding, rec.serialize()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java deleted file mode 100644 index 93c62912a9..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java +++ /dev/null @@ -1,101 +0,0 @@ -/* ==================================================================== - 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.record; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.Arrays; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.apache.poi.util.LittleEndianInput; - -/** - * A Record Input Stream derivative that makes access to byte arrays used in the - * test cases work a bit easier. - *

Creates the stream and moves to the first record. - * - * @author Jason Height (jheight at apache.org) - */ -public final class TestcaseRecordInputStream { - - private TestcaseRecordInputStream() { - // no instances of this class - } - - /** - * Prepends a mock record identifier to the supplied data and opens a record input stream - */ - public static LittleEndianInput createLittleEndian(byte[] data) { - return new LittleEndianByteArrayInputStream(data); - - } - public static RecordInputStream create(int sid, byte[] data) { - return create(mergeDataAndSid(sid, data.length, data)); - } - /** - * First 4 bytes of data are assumed to be record identifier and length. The supplied - * data can contain multiple records (sequentially encoded in the same way) - */ - public static RecordInputStream create(byte[] data) { - InputStream is = new ByteArrayInputStream(data); - RecordInputStream result = new RecordInputStream(is); - result.nextRecord(); - return result; - } - - public static byte[] mergeDataAndSid(int sid, int length, byte[] data) { - byte[] result = new byte[data.length + 4]; - LittleEndian.putUShort(result, 0, sid); - LittleEndian.putUShort(result, 2, length); - System.arraycopy(data, 0, result, 4, data.length); - return result; - } - /** - * Confirms data sections are equal - * @param expectedData - just raw data (without sid or size short ints) - * @param actualRecordBytes this includes 4 prefix bytes (sid & size) - */ - public static void confirmRecordEncoding(int expectedSid, byte[] expectedData, byte[] actualRecordBytes) { - confirmRecordEncoding(null, expectedSid, expectedData, actualRecordBytes); - } - /** - * Confirms data sections are equal - * @param msgPrefix message prefix to be displayed in case of failure - * @param expectedData - just raw data (without ushort sid, ushort size) - * @param actualRecordBytes this includes 4 prefix bytes (sid & size) - */ - public static void confirmRecordEncoding(String msgPrefix, int expectedSid, byte[] expectedData, byte[] actualRecordBytes) { - int expectedDataSize = expectedData.length; - assertEquals(actualRecordBytes.length - 4, expectedDataSize, "Size of encode data mismatch"); - assertEquals(expectedSid, LittleEndian.getShort(actualRecordBytes, 0)); - assertEquals(expectedDataSize, LittleEndian.getShort(actualRecordBytes, 2)); - assertArrayEquals(expectedData, cut(actualRecordBytes, 4)); - } - - public static byte[] cut( byte[] data, int fromInclusive ) { - return cut(data, fromInclusive, data.length); - } - - public static byte[] cut(byte[] data, int fromInclusive, int toExclusive) { - return Arrays.copyOfRange(data, fromInclusive, toExclusive); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java deleted file mode 100644 index b400b76c24..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java +++ /dev/null @@ -1,168 +0,0 @@ -/* ==================================================================== - 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.record.aggregates; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hssf.model.RecordStream; -import org.apache.poi.hssf.record.CFHeaderBase; -import org.apache.poi.hssf.record.CFHeaderRecord; -import org.apache.poi.hssf.record.CFRule12Record; -import org.apache.poi.hssf.record.CFRuleBase; -import org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator; -import org.apache.poi.hssf.record.CFRuleRecord; -import org.apache.poi.hssf.record.RecordFactory; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.LittleEndian; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the CFRecordsAggregate - * class works correctly. - */ -@SuppressWarnings("resource") -final class TestCFRecordsAggregate { - @Test - void testCFRecordsAggregate() { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - - List recs = new ArrayList<>(); - CFHeaderBase header = new CFHeaderRecord(); - CFRuleBase rule1 = CFRuleRecord.create(sheet, "7"); - CFRuleBase rule2 = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5"); - CFRuleBase rule3 = CFRuleRecord.create(sheet, ComparisonOperator.GE, "100", null); - header.setNumberOfConditionalFormats(3); - CellRangeAddress[] cellRanges = { - new CellRangeAddress(0,1,0,0), - new CellRangeAddress(0,1,2,2), - }; - header.setCellRanges(cellRanges); - recs.add(header); - recs.add(rule1); - recs.add(rule2); - recs.add(rule3); - CFRecordsAggregate record = CFRecordsAggregate.createCFAggregate(new RecordStream(recs, 0)); - - // Serialize - byte [] serializedRecord = new byte[record.getRecordSize()]; - record.serialize(0, serializedRecord); - InputStream in = new ByteArrayInputStream(serializedRecord); - - //Parse - recs = RecordFactory.createRecords(in); - - // Verify - assertNotNull(recs); - assertEquals(4, recs.size()); - - header = (CFHeaderRecord)recs.get(0); - rule1 = (CFRuleRecord)recs.get(1); - assertNotNull(rule1); - rule2 = (CFRuleRecord)recs.get(2); - assertNotNull(rule2); - rule3 = (CFRuleRecord)recs.get(3); - assertNotNull(rule3); - cellRanges = header.getCellRanges(); - - assertEquals(2, cellRanges.length); - assertEquals(3, header.getNumberOfConditionalFormats()); - assertFalse(header.getNeedRecalculation()); - - record = CFRecordsAggregate.createCFAggregate(new RecordStream(recs, 0)); - - record = record.cloneCFAggregate(); - - assertNotNull(record.getHeader()); - assertEquals(3,record.getNumberOfRules()); - - header = record.getHeader(); - rule1 = record.getRule(0); - assertNotNull(rule1); - rule2 = record.getRule(1); - assertNotNull(rule2); - rule3 = record.getRule(2); - assertNotNull(rule3); - cellRanges = header.getCellRanges(); - - assertEquals(2, cellRanges.length); - assertEquals(3, header.getNumberOfConditionalFormats()); - assertFalse(header.getNeedRecalculation()); - } - - /** - * Make sure that the CF Header record is properly updated with the number of rules - */ - @Test - void testNRules() { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - CellRangeAddress[] cellRanges = { - new CellRangeAddress(0,1,0,0), - new CellRangeAddress(0,1,2,2), - }; - CFRuleRecord[] rules = { - CFRuleRecord.create(sheet, "7"), - CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5"), - }; - CFRecordsAggregate agg = new CFRecordsAggregate(cellRanges, rules); - byte[] serializedRecord = new byte[agg.getRecordSize()]; - agg.serialize(0, serializedRecord); - - int nRules = LittleEndian.getUShort(serializedRecord, 4); - assertNotEquals(0, nRules, "Identified bug 45682 b"); - assertEquals(rules.length, nRules); - } - - @Test - void testCantMixTypes() { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - CellRangeAddress[] cellRanges = { - new CellRangeAddress(0,1,0,0), - new CellRangeAddress(0,1,2,2), - }; - CFRuleBase[] rules1 = { - CFRuleRecord.create(sheet, "7"), - CFRule12Record.create(sheet, ComparisonOperator.BETWEEN, "2", "5"), - }; - - assertThrows(IllegalArgumentException.class, () -> new CFRecordsAggregate(cellRanges, rules1), - "Shouldn't be able to mix between types"); - - - CFRuleBase[] rules2 = { CFRuleRecord.create(sheet, "7") }; - CFRecordsAggregate agg = new CFRecordsAggregate(cellRanges, rules2); - assertTrue(agg.getHeader().getNeedRecalculation()); - - assertThrows(IllegalArgumentException.class, () -> agg.addRule(CFRule12Record.create(sheet, "7")), - "Shouldn't be able to mix between types"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.java deleted file mode 100644 index 6fae73f041..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - 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.record.aggregates; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hssf.record.ColumnInfoRecord; -import org.apache.poi.hssf.record.RecordBase; -import org.junit.jupiter.api.Test; - -final class TestColumnInfoRecordsAggregate { - - @Test - void testGetRecordSize() { - ColumnInfoRecordsAggregate agg = new ColumnInfoRecordsAggregate(); - agg.insertColumn(createColInfo(1, 3)); - agg.insertColumn(createColInfo(4, 7)); - agg.insertColumn(createColInfo(8, 8)); - agg.groupColumnRange((short) 2, (short) 5, true); - assertEquals(4, agg.getNumColumns()); - - confirmSerializedSize(agg); - - agg = new ColumnInfoRecordsAggregate(); - agg.groupColumnRange((short) 3, (short) 6, true); - confirmSerializedSize(agg); - } - - private static void confirmSerializedSize(RecordBase cirAgg) { - int estimatedSize = cirAgg.getRecordSize(); - byte[] buf = new byte[estimatedSize]; - int serializedSize = cirAgg.serialize(0, buf); - assertEquals(estimatedSize, serializedSize); - } - - private static ColumnInfoRecord createColInfo(int firstCol, int lastCol) { - ColumnInfoRecord columnInfoRecord = new ColumnInfoRecord(); - columnInfoRecord.setFirstColumn((short) firstCol); - columnInfoRecord.setLastColumn((short) lastCol); - return columnInfoRecord; - } - - @Test - void testGroupColumns_bug45639() { - ColumnInfoRecordsAggregate agg = new ColumnInfoRecordsAggregate(); - agg.groupColumnRange( 7, 9, true); - agg.groupColumnRange( 4, 12, true); - - // bug 45639 - ArrayIndexOutOfBoundsException - agg.groupColumnRange( 1, 15, true); - - List cirs = new ArrayList<>(); - agg.visitContainedRecords(cirs::add); - - assertEquals(5, cirs.size()); - confirmCIR(cirs, 0, 1, 3, 1, false, false); - confirmCIR(cirs, 1, 4, 6, 2, false, false); - confirmCIR(cirs, 2, 7, 9, 3, false, false); - confirmCIR(cirs, 3, 10, 12, 2, false, false); - confirmCIR(cirs, 4, 13, 15, 1, false, false); - } - - /** - * Check that an inner group remains hidden - */ - @Test - void testHiddenAfterExpanding() { - ColumnInfoRecordsAggregate agg = new ColumnInfoRecordsAggregate(); - agg.groupColumnRange(1, 15, true); - agg.groupColumnRange(4, 12, true); - - List cirs = new ArrayList<>(); - - // collapse both inner and outer groups - agg.collapseColumn(6); - agg.collapseColumn(3); - - agg.visitContainedRecords(cirs::add); - assertEquals(5, cirs.size()); - confirmCIR(cirs, 0, 1, 3, 1, true, false); - confirmCIR(cirs, 1, 4, 12, 2, true, false); - confirmCIR(cirs, 2, 13, 13, 1, true, true); - confirmCIR(cirs, 3, 14, 15, 1, true, false); - confirmCIR(cirs, 4, 16, 16, 0, false, true); - - // just expand the inner group - agg.expandColumn(6); - - cirs.clear(); - agg.visitContainedRecords(cirs::add); - assertEquals(4, cirs.size()); - assertTrue(((ColumnInfoRecord)cirs.get(1)).getHidden(), "Inner group should still be hidden"); - confirmCIR(cirs, 0, 1, 3, 1, true, false); - confirmCIR(cirs, 1, 4, 12, 2, true, false); - confirmCIR(cirs, 2, 13, 15, 1, true, false); - confirmCIR(cirs, 3, 16, 16, 0, false, true); - } - - private static void confirmCIR(List cirs, int ix, int startColIx, int endColIx, int level, boolean isHidden, boolean isCollapsed) { - assertTrue(cirs.get(ix) instanceof ColumnInfoRecord); - ColumnInfoRecord cir = (ColumnInfoRecord)cirs.get(ix); - assertEquals(startColIx, cir.getFirstColumn(), "startColIx"); - assertEquals(endColIx, cir.getLastColumn(), "endColIx"); - assertEquals(level, cir.getOutlineLevel(), "level"); - assertEquals(isHidden, cir.getHidden(), "hidden"); - assertEquals(isCollapsed, cir.getCollapsed(), "collapsed"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.java deleted file mode 100644 index 8bfc6576c2..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.java +++ /dev/null @@ -1,99 +0,0 @@ -/* ==================================================================== - 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.record.aggregates; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.StringRecord; -import org.apache.poi.ss.formula.FormulaRenderer; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.ExpPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Test; - -final class TestFormulaRecordAggregate { - - @Test - void testBasic() { - FormulaRecord f = new FormulaRecord(); - f.setCachedResultTypeString(); - StringRecord s = new StringRecord(); - s.setString("abc"); - FormulaRecordAggregate fagg = new FormulaRecordAggregate(f, s, SharedValueManager.createEmpty()); - assertEquals("abc", fagg.getStringValue()); - assertFalse(fagg.isPartOfArrayFormula()); - } - - /** - * Sometimes a {@link StringRecord} appears after a {@link FormulaRecord} even though the - * formula has evaluated to a text value. This might be more likely to occur when the formula - * can evaluate to a text value.
- * Bug 46213 attachment 22874 has such an extra {@link StringRecord} at stream offset 0x5765. - * This file seems to open in Excel (2007) with no trouble. When it is re-saved, Excel omits - * the extra record. POI should do the same. - */ - @Test - void testExtraStringRecord_bug46213() { - FormulaRecord fr = new FormulaRecord(); - fr.setValue(2.0); - StringRecord sr = new StringRecord(); - sr.setString("NA"); - SharedValueManager svm = SharedValueManager.createEmpty(); - // bug 46213 -> String record was supplied but formula record flag is not set - FormulaRecordAggregate fra = new FormulaRecordAggregate(fr, sr, svm); - List vraRecs = new ArrayList<>(); - fra.visitContainedRecords(vraRecs::add); - assertEquals(1, vraRecs.size()); - assertEquals(fr, vraRecs.get(0)); - } - - @Test - void testArrayFormulas() { - int rownum = 4; - int colnum = 4; - - FormulaRecord fr = new FormulaRecord(); - fr.setRow(rownum); - fr.setColumn((short)colnum); - - FormulaRecordAggregate agg = new FormulaRecordAggregate(fr, null, SharedValueManager.createEmpty()); - Ptg[] ptgsForCell = {new ExpPtg(rownum, colnum)}; - agg.setParsedExpression(ptgsForCell); - - String formula = "SUM(A1:A3*B1:B3)"; - Ptg[] ptgs = HSSFFormulaParser.parse(formula, null, FormulaType.ARRAY, 0); - agg.setArrayFormula(new CellRangeAddress(rownum, rownum, colnum, colnum), ptgs); - - assertTrue(agg.isPartOfArrayFormula()); - assertEquals("E5", agg.getArrayFormulaRange().formatAsString()); - Ptg[] ptg = agg.getFormulaTokens(); - String fmlaSer = FormulaRenderer.toFormulaString(null, ptg); - assertEquals(formula, fmlaSer); - - agg.removeArrayFormula(rownum, colnum); - assertFalse(agg.isPartOfArrayFormula()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java deleted file mode 100644 index 243e1adc2e..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java +++ /dev/null @@ -1,425 +0,0 @@ -/* ==================================================================== - 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.record.aggregates; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Stream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.RecordStream; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.BottomMarginRecord; -import org.apache.poi.hssf.record.ContinueRecord; -import org.apache.poi.hssf.record.DimensionsRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.FooterRecord; -import org.apache.poi.hssf.record.HCenterRecord; -import org.apache.poi.hssf.record.HeaderFooterRecord; -import org.apache.poi.hssf.record.HeaderRecord; -import org.apache.poi.hssf.record.IndexRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.SelectionRecord; -import org.apache.poi.hssf.record.UnknownRecord; -import org.apache.poi.hssf.record.UserSViewBegin; -import org.apache.poi.hssf.record.UserSViewEnd; -import org.apache.poi.hssf.record.VCenterRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.usermodel.HSSFPrintSetup; -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.RecordFormatException; -import org.junit.jupiter.api.Test; - -/** - * Tess for {@link PageSettingsBlock} - */ -final class TestPageSettingsBlock { - @Test - void testPrintSetup_bug46548() { - // PageSettingBlock in this file contains PLS (sid=x004D) record - // followed by ContinueRecord (sid=x003C) - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex46548-23133.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFPrintSetup ps = sheet.getPrintSetup(); - - // bug 46548: PageSettingBlock missing PrintSetupRecord record - assertEquals(1, ps.getCopies()); - } - - /** - * Bug 46840 occurred because POI failed to recognise HEADERFOOTER as part of the - * {@link PageSettingsBlock}. - */ - @Test - void testHeaderFooter_bug46840() { - - int rowIx = 5; - int colIx = 6; - NumberRecord nr = new NumberRecord(); - nr.setRow(rowIx); - nr.setColumn((short) colIx); - nr.setValue(3.0); - - org.apache.poi.hssf.record.Record[] recs = { - BOFRecord.createSheetBOF(), - new HeaderRecord("&LSales Figures"), - new FooterRecord("&LJanuary"), - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 C4 60 00 00 00 00 00 00 00 00")), - new DimensionsRecord(), - new WindowTwoRecord(), - new UserSViewBegin(HexRead.readFromString("ED 77 3B 86 BC 3F 37 4C A9 58 60 23 43 68 54 4B 01 00 00 00 64 00 00 00 40 00 00 00 02 00 00 00 3D 80 04 00 00 00 00 00 00 00 0C 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 F0 3F FF FF 01 00")), - new HeaderRecord("&LSales Figures"), - new FooterRecord("&LJanuary"), - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 C4 60 00 00 00 00 00 00 00 00")), - new UserSViewEnd(HexRead.readFromString("01, 00")), - - EOFRecord.instance, - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - // bug 46480- two Page Settings Blocks found in the same sheet - InternalSheet sheet = InternalSheet.createSheet(rs); - - List outRecs = new ArrayList<>(); - sheet.visitContainedRecords(outRecs::add, rowIx); - assertEquals(13, outRecs.size()); - } - - /** - * Bug 46953 occurred because POI didn't handle late PSB records properly. - */ - @Test - void testLateHeaderFooter_bug46953() { - - int rowIx = 5; - int colIx = 6; - NumberRecord nr = new NumberRecord(); - nr.setRow(rowIx); - nr.setColumn((short) colIx); - nr.setValue(3.0); - - org.apache.poi.hssf.record.Record[] recs = { - BOFRecord.createSheetBOF(), - new HeaderRecord("&LSales Figures"), - new FooterRecord("&LJanuary"), - new DimensionsRecord(), - new WindowTwoRecord(), - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 C4 60 00 00 00 00 00 00 00 00")), - EOFRecord.instance, - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - InternalSheet sheet = InternalSheet.createSheet(rs); - - List outRecs = new ArrayList<>(); - sheet.visitContainedRecords(outRecs::add, 0); - // Identified bug 46953 - EOF incorrectly appended to PSB - assertNotEquals(EOFRecord.instance, outRecs.get(4)); - assertEquals(recs.length+1, outRecs.size()); // +1 for index record - - Class[] act = outRecs.stream().map(Object::getClass).toArray(Class[]::new); - Class[] exp = { BOFRecord.class, IndexRecord.class, HeaderRecord.class, FooterRecord.class, - HeaderFooterRecord.class, DimensionsRecord.class, WindowTwoRecord.class, EOFRecord.class }; - assertArrayEquals(exp, act); - } - /** - * Bug 47199 was due to the margin records being located well after the initial PSB records. - * The example file supplied (attachment 23710) had three non-PSB record types - * between the PRINTSETUP record and first MARGIN record: - *

    - *
  • PRINTSETUP(0x00A1)
  • - *
  • DEFAULTCOLWIDTH(0x0055)
  • - *
  • COLINFO(0x007D)
  • - *
  • DIMENSIONS(0x0200)
  • - *
  • BottomMargin(0x0029)
  • - *
- */ - @Test - void testLateMargins_bug47199() { - - BottomMarginRecord bottomMargin = new BottomMarginRecord(); - bottomMargin.setMargin(0.787F); - - org.apache.poi.hssf.record.Record[] recs = { - BOFRecord.createSheetBOF(), - new HeaderRecord("&LSales Figures"), - new FooterRecord("&LJanuary"), - new DimensionsRecord(), - bottomMargin, - new WindowTwoRecord(), - EOFRecord.instance, - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - - // bug 47199a - failed to process late margins records - InternalSheet sheet = InternalSheet.createSheet(rs); - - List outRecs = new ArrayList<>(); - sheet.visitContainedRecords(outRecs::add, 0); - assertEquals(recs.length+1, outRecs.size()); // +1 for index record - - Class[] act = outRecs.stream().map(Object::getClass).toArray(Class[]::new); - Class[] exp = { BOFRecord.class, IndexRecord.class, HeaderRecord.class, FooterRecord.class, - BottomMarginRecord.class, DimensionsRecord.class, WindowTwoRecord.class, EOFRecord.class }; - assertArrayEquals(exp, act); - } - - /** - * The PageSettingsBlock should not allow multiple copies of the same record. This extra assertion - * was added while fixing bug 47199. All existing POI test samples comply with this requirement. - */ - @Test - void testDuplicatePSBRecord_bug47199() { - // Hypothetical setup of PSB records which should cause POI to crash - org.apache.poi.hssf.record.Record[] recs = { - new HeaderRecord("&LSales Figures"), - new HeaderRecord("&LInventory"), - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - - RecordFormatException ex = assertThrows( - RecordFormatException.class, - () -> new PageSettingsBlock(rs) - ); - assertEquals("Duplicate PageSettingsBlock record (sid=0x14)", ex.getMessage()); - } - - /** - * Excel tolerates missing header / footer records, but adds them (empty) in when re-saving. - * This is not critical functionality but it has been decided to keep POI consistent with - * Excel in this regard. - */ - @Test - void testMissingHeaderFooter() { - // initialise PSB with some records, but not the header / footer - org.apache.poi.hssf.record.Record[] recs = { - new HCenterRecord(), - new VCenterRecord(), - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - PageSettingsBlock psb = new PageSettingsBlock(rs); - - // serialize the PSB to see what records come out - List outRecs = new ArrayList<>(); - psb.visitContainedRecords(outRecs::add); - - assertNotEquals(2, outRecs.size(), "PageSettingsBlock didn't add missing header/footer records"); - - Class[] act = outRecs.stream().map(Object::getClass).toArray(Class[]::new); - Class[] exp = { HeaderRecord.class, FooterRecord.class, HCenterRecord.class, VCenterRecord.class}; - assertArrayEquals(exp, act); - - // make sure the added header / footer records are empty - HeaderRecord hr = (HeaderRecord) outRecs.get(0); - assertEquals("", hr.getText()); - FooterRecord fr = (FooterRecord) outRecs.get(1); - assertEquals("", fr.getText()); - } - - /** - * Apparently it's OK to have more than one PLS record. - * Attachment 23866 from bug 47415 had a PageSettingsBlock with two PLS records. This file - * seems to open OK in Excel(2007) but both PLS records are removed (perhaps because the - * specified printers were not available on the testing machine). Since the example file does - * not upset Excel, POI will preserve multiple PLS records.

- * - * As of June 2009, PLS is still uninterpreted by POI - */ - @Test - void testDuplicatePLS_bug47415() { - Record plsA = new UnknownRecord(UnknownRecord.PLS_004D, HexRead.readFromString("BA AD F0 0D")); - Record plsB = new UnknownRecord(UnknownRecord.PLS_004D, HexRead.readFromString("DE AD BE EF")); - Record contB1 = new ContinueRecord(HexRead.readFromString("FE ED")); - Record contB2 = new ContinueRecord(HexRead.readFromString("FA CE")); - org.apache.poi.hssf.record.Record[] recs = { - new HeaderRecord("&LSales Figures"), - new FooterRecord("&LInventory"), - new HCenterRecord(), - new VCenterRecord(), - plsA, - plsB, contB1, contB2, // make sure continuing PLS is still OK - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - // bug 47415 - Duplicate PageSettingsBlock record (sid=0x4d) - PageSettingsBlock psb = new PageSettingsBlock(rs); - - // serialize the PSB to see what records come out - List outRecs = new ArrayList<>(); - psb.visitContainedRecords(outRecs::add); - - // records were assembled in standard order, so this simple check is OK - assertArrayEquals(recs, outRecs.toArray(new Record[0])); - } - - @Test - void testDuplicateHeaderFooter_bug48026() { - - org.apache.poi.hssf.record.Record[] recs = { - BOFRecord.createSheetBOF(), - new IndexRecord(), - - //PageSettingsBlock - new HeaderRecord("&LDecember"), - new FooterRecord("&LJanuary"), - new DimensionsRecord(), - - new WindowTwoRecord(), - - //CustomViewSettingsRecordAggregate - new UserSViewBegin(HexRead.readFromString("53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 01 00 00 00 64 00 00 00 40 00 00 00 03 00 00 00 7D 00 00 20 00 00 34 00 00 00 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF FF FF")), - new SelectionRecord(0, 0), - new UserSViewEnd(HexRead.readFromString("01 00")), - - // two HeaderFooterRecord records, the first one has zero GUID (16 bytes at offset 12) and belongs to the PSB, - // the other is matched with a CustomViewSettingsRecordAggregate having UserSViewBegin with the same GUID - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 34 33 00 00 00 00 00 00 00 00")), - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 34 33 00 00 00 00 00 00 00 00")), - - EOFRecord.instance, - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - // bug 48026 - Duplicate PageSettingsBlock record (sid=0x89c) - InternalSheet sheet = InternalSheet.createSheet(rs); - - List outRecs = new ArrayList<>(); - sheet.visitContainedRecords(outRecs::add, 0); - - assertEquals(recs.length, outRecs.size()); - //expected order of records: - Record[] expectedRecs = { - recs[0], //BOFRecord - recs[1], //IndexRecord - - //PageSettingsBlock - recs[2], //HeaderRecord - recs[3], //FooterRecord - recs[9], //HeaderFooterRecord - recs[4], // DimensionsRecord - recs[5], // WindowTwoRecord - - //CustomViewSettingsRecordAggregate - recs[6], // UserSViewBegin - recs[7], // SelectionRecord - recs[10], // HeaderFooterRecord - recs[8], // UserSViewEnd - - recs[11], //EOFRecord - }; - - assertArrayEquals( - Stream.of(expectedRecs).map(Object::getClass).toArray(Class[]::new), - outRecs.stream().map(Object::getClass).toArray(Class[]::new) - ); - - HeaderFooterRecord hd1 = (HeaderFooterRecord)expectedRecs[4]; - //GUID is zero - assertArrayEquals(new byte[16], hd1.getGuid()); - assertTrue(hd1.isCurrentSheet()); - - UserSViewBegin svb = (UserSViewBegin)expectedRecs[7]; - HeaderFooterRecord hd2 = (HeaderFooterRecord)expectedRecs[9]; - assertFalse(hd2.isCurrentSheet()); - //GUIDs of HeaderFooterRecord and UserSViewBegin must be the same - assertArrayEquals(svb.getGuid(), hd2.getGuid()); - } - - @Test - void testDuplicateHeaderFooterInside_bug48026() { - - Record[] recs = { - BOFRecord.createSheetBOF(), - new IndexRecord(), - - //PageSettingsBlock - new HeaderRecord("&LDecember"), - new FooterRecord("&LJanuary"), - new DimensionsRecord(), - - new WindowTwoRecord(), - - //CustomViewSettingsRecordAggregate - new UserSViewBegin(HexRead.readFromString("53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 01 00 00 00 64 00 00 00 40 00 00 00 03 00 00 00 7D 00 00 20 00 00 34 00 00 00 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF FF FF")), - new SelectionRecord(0, 0), - - // two HeaderFooterRecord records, the first one has zero GUID (16 bytes at offset 12) and belongs to the PSB, - // the other is matched with a CustomViewSettingsRecordAggregate having UserSViewBegin with the same GUID - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 34 33 00 00 00 00 00 00 00 00")), - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 34 33 00 00 00 00 00 00 00 00")), - - new UserSViewEnd(HexRead.readFromString("01 00")), - - EOFRecord.instance, - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - // Bug 48026 : Duplicate PageSettingsBlock record (sid=0x89c) - InternalSheet sheet = InternalSheet.createSheet(rs); - - List outRecs = new ArrayList<>(); - sheet.visitContainedRecords(outRecs::add, 0); - - assertEquals(recs.length+1, outRecs.size()); - //expected order of records: - Record[] expectedRecs = { - recs[0], //BOFRecord - recs[1], //IndexRecord - - //PageSettingsBlock - recs[2], //HeaderRecord - recs[3], //FooterRecord - recs[4], // DimensionsRecord - recs[5], // WindowTwoRecord - - //CustomViewSettingsRecordAggregate - recs[6], // UserSViewBegin - recs[7], // SelectionRecord - recs[2], //HeaderRecord - recs[3], //FooterRecord - recs[8], // HeaderFooterRecord -// recs[9], //HeaderFooterRecord - recs[10], // UserSViewEnd - - recs[11], //EOFRecord - }; - - assertArrayEquals( - Stream.of(expectedRecs).map(Object::getClass).toArray(Class[]::new), - outRecs.stream().map(Object::getClass).toArray(Class[]::new) - ); - - HeaderFooterRecord hd1 = (HeaderFooterRecord)expectedRecs[10]; - //GUID is zero - assertArrayEquals(new byte[16], hd1.getGuid()); - assertTrue(hd1.isCurrentSheet()); - - UserSViewBegin svb = (UserSViewBegin)expectedRecs[6]; - HeaderFooterRecord hd2 = (HeaderFooterRecord)recs[9]; - assertFalse(hd2.isCurrentSheet()); - //GUIDs of HeaderFooterRecord and UserSViewBegin must be the same - assertArrayEquals(svb.getGuid(), hd2.getGuid()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java deleted file mode 100644 index 41ad8fbcb5..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java +++ /dev/null @@ -1,159 +0,0 @@ -/* ==================================================================== - 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.record.aggregates; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.RecordStream; -import org.apache.poi.hssf.record.ArrayRecord; -import org.apache.poi.hssf.record.ContinueRecord; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RowRecord; -import org.apache.poi.hssf.record.SharedFormulaRecord; -import org.apache.poi.hssf.record.SharedValueRecordBase; -import org.apache.poi.hssf.record.TableRecord; -import org.apache.poi.hssf.record.UnknownRecord; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.CellRangeAddress8Bit; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link RowRecordsAggregate} - */ -final class TestRowRecordsAggregate { - - @Test - void testRowGet() { - RowRecordsAggregate rra = new RowRecordsAggregate(); - RowRecord rr = new RowRecord(4); - rra.insertRow(rr); - rra.insertRow(new RowRecord(1)); - - RowRecord rr1 = rra.getRow(4); - - assertNotNull(rr1); - assertEquals(4, rr1.getRowNumber(), "Row number is 1"); - assertSame(rr1, rr, "Row record retrieved is identical "); - } - - /** - * Prior to Aug 2008, POI would re-serialize spreadsheets with {@link ArrayRecord}s or - * {@link TableRecord}s with those records out of order. Similar to - * {@link SharedFormulaRecord}s, these records should appear immediately after the first - * {@link FormulaRecord}s that they apply to (and only once).
- */ - @Test - void testArraysAndTables() throws Exception { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testArraysAndTables.xls")) { - final List sheetRecs = new ArrayList<>(); - wb.getSheetAt(0).getSheet().visitContainedRecords(sheetRecs::add, 0); - - int countArrayFormulas = verifySharedValues(sheetRecs, ArrayRecord.class); - assertEquals(5, countArrayFormulas); - int countTableFormulas = verifySharedValues(sheetRecs, TableRecord.class); - assertEquals(3, countTableFormulas); - - // Note - SharedFormulaRecords are currently not re-serialized by POI (each is extracted - // into many non-shared formulas), but if they ever were, the same rules would apply. - int countSharedFormulas = verifySharedValues(sheetRecs, SharedFormulaRecord.class); - assertEquals(0, countSharedFormulas); - - -// if (false) { // set true to observe re-serialized file -// File f = new File(System.getProperty("java.io.tmpdir") + "/testArraysAndTables-out.xls"); -// try { -// OutputStream os = new FileOutputStream(f); -// wb.write(os); -// os.close(); -// } catch (IOException e) { -// throw new RuntimeException(e); -// } -// System.out.println("Output file to " + f.getAbsolutePath()); -// } - - } - } - - private static int verifySharedValues(List recs, Class shfClass) { - - int result =0; - for(int i=0; i - * The functionality change being tested here is actually not critical to the overall fix - * for bug 46280, since the fix involved making sure the that offending PivotTable - * records do not get into {@link RowRecordsAggregate}.
- * This fix in {@link RowRecordsAggregate} was implemented anyway since any {@link - * UnknownRecord} has the potential of being 'continued'. - */ - @Test - void testUnknownContinue_bug46280() { - org.apache.poi.hssf.record.Record[] inRecs = { - new RowRecord(0), - new NumberRecord(), - new UnknownRecord(0x5555, "dummydata".getBytes(LocaleUtil.CHARSET_1252)), - new ContinueRecord("moredummydata".getBytes(LocaleUtil.CHARSET_1252)), - }; - RecordStream rs = new RecordStream(Arrays.asList(inRecs), 0); - RowRecordsAggregate rra; - try { - rra = new RowRecordsAggregate(rs, SharedValueManager.createEmpty()); - } catch (RuntimeException e) { - if (e.getMessage().startsWith("Unexpected record type")) { - fail("Identified bug 46280a"); - } - throw e; - } - - List outRecs = new ArrayList<>(); - rra.visitContainedRecords(outRecs::add); - assertEquals(5, outRecs.size()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java deleted file mode 100644 index 31b4f92548..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java +++ /dev/null @@ -1,163 +0,0 @@ -/* ==================================================================== - 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.record.aggregates; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.util.Collection; -import java.util.HashMap; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.SharedFormulaRecord; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link SharedValueManager} - */ -final class TestSharedValueManager { - - /** - * This Excel workbook contains two sheets that each have a pair of overlapping shared formula - * ranges. The first sheet has one row and one column shared formula ranges which intersect. - * The second sheet has two column shared formula ranges - one contained within the other. - * These shared formula ranges were created by fill-dragging a single cell formula across the - * desired region. The larger shared formula ranges were placed first.
- * - * There are probably many ways to produce similar effects, but it should be noted that Excel - * is quite temperamental in this regard. Slight variations in technique can cause the shared - * formulas to spill out into plain formula records (which would make these tests pointless). - * - */ - private static final String SAMPLE_FILE_NAME = "overlapSharedFormula.xls"; - /** - * Some of these bugs are intermittent, and the test author couldn't think of a way to write - * test code to hit them bug deterministically. The reason for the unpredictability is that - * the bugs depended on the {@link SharedFormulaRecord}s being searched in a particular order. - * At the time of writing of the test, the order was being determined by the call to {@link - * Collection#toArray(Object[])} on {@link HashMap#values()} where the items in the map were - * using default {@link Object#hashCode()}
- */ - private static final int MAX_ATTEMPTS=5; - - /** - * This bug happened when there were two or more shared formula ranges that overlapped. POI - * would sometimes associate formulas in the overlapping region with the wrong shared formula - */ - @Test - void testPartiallyOverlappingRanges() { - - - for (int attempt=1; attempt < MAX_ATTEMPTS; attempt++) { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_FILE_NAME); - - HSSFSheet sheet = wb.getSheetAt(0); - assertEquals("1+1", sheet.getRow(2).getCell(0).getCellFormula()); - String act = sheet.getRow(3).getCell(0).getCellFormula(); - assertNotEquals("wrong shared formula record chosen", "1+1", act); - act = sheet.getRow(3).getCell(0).getCellFormula(); - assertEquals("2+2", act); - - int[] count = { 0 }; - sheet.getSheet().visitContainedRecords(r -> count[0] += r instanceof SharedFormulaRecord ? 1 : 0, 0); - assertEquals(2, count[0]); - } - } - - /** - * This bug occurs for similar reasons to the bug in {@link #testPartiallyOverlappingRanges()} - * but the symptoms are much uglier - serialization fails with {@link NullPointerException}.
- */ - @Test - void testCompletelyOverlappedRanges() { - for (int attempt=1; attempt < MAX_ATTEMPTS; attempt++) { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_FILE_NAME); - - HSSFSheet sheet = wb.getSheetAt(1); - - int[] count = { 0 }; - - // NullPointerException -> cannot reserialize completely overlapped shared formula - sheet.getSheet().visitContainedRecords(r -> count[0] += r instanceof SharedFormulaRecord ? 1 : 0, 0); - assertEquals(2, count[0]); - } - } - - /** - * Tests fix for a bug in the way shared formula cells are associated with shared formula - * records. Prior to this fix, POI would attempt to use the upper left corner of the - * shared formula range as the locator cell. The correct cell to use is the 'first cell' - * in the shared formula group which is not always the top left cell. This is possible - * because shared formula groups may be sparse and may overlap.
- * - * Two existing sample files (15228.xls and ex45046-21984.xls) had similar issues. - * These were not explored fully, but seem to be fixed now. - */ - @Test - void testRecalculateFormulas47747() { - - /* - * ex47747-sharedFormula.xls is a heavily cut-down version of the spreadsheet from - * the attachment (id=24176) in Bugzilla 47747. This was done to make the sample - * file smaller, which hopefully allows the special data encoding condition to be - * seen more easily. Care must be taken when modifying this file since the - * special conditions are easily destroyed (which would make this test useless). - * It seems that removing the worksheet protection has made this more so - if the - * current file is re-saved in Excel(2007) the bug condition disappears. - * - * - * Using BiffViewer, one can see that there are two shared formula groups representing - * the essentially same formula over ~20 cells. The shared group ranges overlap and - * are A12:Q20 and A20:Q27. The locator cell ('first cell') for the second group is - * Q20 which is not the top left cell of the enclosing range. It is this specific - * condition which caused the bug to occur - */ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex47747-sharedFormula.xls"); - - // pick out a cell from within the second shared formula group - HSSFCell cell = wb.getSheetAt(0).getRow(23).getCell(0); - // bug occurs if the formula record has been associated - // with the first (and not the second) shared formula group - String formulaText = cell.getCellFormula(); - assertEquals("$AF24*A$7", formulaText); - } - - @Test - void testBug52527() { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("52527.xls"); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - assertEquals("IF(H3,LINEST(N9:N14,K9:M14,FALSE),LINEST(N8:N14,K8:M14,FALSE))", - wb1.getSheetAt(0).getRow(4).getCell(11).getCellFormula()); - assertEquals("IF(H3,LINEST(N9:N14,K9:M14,FALSE),LINEST(N8:N14,K8:M14,FALSE))", - wb2.getSheetAt(0).getRow(4).getCell(11).getCellFormula()); - - assertEquals("1/SQRT(J9)", - wb1.getSheetAt(0).getRow(8).getCell(10).getCellFormula()); - assertEquals("1/SQRT(J9)", - wb2.getSheetAt(0).getRow(8).getCell(10).getCellFormula()); - - assertEquals("1/SQRT(J26)", - wb1.getSheetAt(0).getRow(25).getCell(10).getCellFormula()); - assertEquals("1/SQRT(J26)", - wb2.getSheetAt(0).getRow(25).getCell(10).getCellFormula()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java deleted file mode 100644 index 38018f3627..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java +++ /dev/null @@ -1,411 +0,0 @@ -/* ==================================================================== - 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.record.aggregates; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.zip.CRC32; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.RecordStream; -import org.apache.poi.hssf.model.RowBlocksReader; -import org.apache.poi.hssf.record.BlankRecord; -import org.apache.poi.hssf.record.CellValueRecordInterface; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.MulBlankRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.SharedFormulaRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link ValueRecordsAggregate} - */ -final class TestValueRecordsAggregate { - private static final String ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE = "AbnormalSharedFormulaFlag.xls"; - private final ValueRecordsAggregate valueRecord = new ValueRecordsAggregate(); - - private List getValueRecords() { - List list = new ArrayList<>(); - for ( CellValueRecordInterface rec : valueRecord ) { - list.add(rec); - } - return Collections.unmodifiableList(list); - } - - /** - * Make sure the shared formula DOESNT makes it to the FormulaRecordAggregate when being parsed - * as part of the value records - */ - @Test - void testSharedFormula() { - List records = new ArrayList<>(); - records.add(new FormulaRecord()); - records.add(new SharedFormulaRecord()); - records.add(new WindowTwoRecord()); - - constructValueRecord(records); - List cvrs = getValueRecords(); - //Ensure that the SharedFormulaRecord has been converted - assertEquals(1, cvrs.size()); - - CellValueRecordInterface record = cvrs.get(0); - assertNotNull( record, "Row contains a value" ); - assertTrue( ( record instanceof FormulaRecordAggregate ), "First record is a FormulaRecordsAggregate"); - } - - private void constructValueRecord(List records) { - RowBlocksReader rbr = new RowBlocksReader(new RecordStream(records, 0)); - SharedValueManager sfrh = rbr.getSharedFormulaManager(); - RecordStream rs = rbr.getPlainRecordStream(); - while(rs.hasNext()) { - Record rec = rs.getNext(); - valueRecord.construct((CellValueRecordInterface)rec, rs, sfrh); - } - } - - private static List testData() { - List records = new ArrayList<>(); - FormulaRecord formulaRecord = new FormulaRecord(); - BlankRecord blankRecord = new BlankRecord(); - formulaRecord.setRow(1); - formulaRecord.setColumn((short) 1); - blankRecord.setRow(2); - blankRecord.setColumn((short) 2); - records.add(formulaRecord); - records.add(blankRecord); - records.add(new WindowTwoRecord()); - return records; - } - - @Test - void testInsertCell() { - assertEquals(0, getValueRecords().size()); - - BlankRecord blankRecord = newBlankRecord(); - valueRecord.insertCell( blankRecord ); - assertEquals(1, getValueRecords().size()); - } - - @Test - void testRemoveCell() { - BlankRecord blankRecord1 = newBlankRecord(); - valueRecord.insertCell( blankRecord1 ); - BlankRecord blankRecord2 = newBlankRecord(); - valueRecord.removeCell( blankRecord2 ); - assertEquals(0, getValueRecords().size()); - - // removing an already empty cell just falls through - valueRecord.removeCell( blankRecord2 ); - } - - @Test - void testGetPhysicalNumberOfCells() { - assertEquals(0, valueRecord.getPhysicalNumberOfCells()); - BlankRecord blankRecord1 = newBlankRecord(); - valueRecord.insertCell( blankRecord1 ); - assertEquals(1, valueRecord.getPhysicalNumberOfCells()); - valueRecord.removeCell( blankRecord1 ); - assertEquals(0, valueRecord.getPhysicalNumberOfCells()); - } - - @Test - void testGetFirstCellNum() { - assertEquals( -1, valueRecord.getFirstCellNum() ); - valueRecord.insertCell( newBlankRecord( 2, 2 ) ); - assertEquals( 2, valueRecord.getFirstCellNum() ); - valueRecord.insertCell( newBlankRecord( 3, 3 ) ); - assertEquals( 2, valueRecord.getFirstCellNum() ); - - // Note: Removal doesn't currently reset the first column. It probably should but it doesn't. - valueRecord.removeCell( newBlankRecord( 2, 2 ) ); - assertEquals( 2, valueRecord.getFirstCellNum() ); - } - - @Test - void testGetLastCellNum() { - assertEquals( -1, valueRecord.getLastCellNum() ); - valueRecord.insertCell( newBlankRecord( 2, 2 ) ); - assertEquals( 2, valueRecord.getLastCellNum() ); - valueRecord.insertCell( newBlankRecord( 3, 3 ) ); - assertEquals( 3, valueRecord.getLastCellNum() ); - - // Note: Removal doesn't currently reset the last column. It probably should but it doesn't. - valueRecord.removeCell( newBlankRecord( 3, 3 ) ); - assertEquals( 3, valueRecord.getLastCellNum() ); - - } - - - private static final class SerializerVisitor implements RecordVisitor { - private final byte[] _buf; - private int _writeIndex; - public SerializerVisitor(byte[] buf) { - _buf = buf; - _writeIndex = 0; - - } - @Override - public void visitRecord(org.apache.poi.hssf.record.Record r) { - r.serialize(_writeIndex, _buf); - _writeIndex += r.getRecordSize(); - } - public int getWriteIndex() { - return _writeIndex; - } - } - - @Test - void testSerialize() { - byte[] expectedArray = HexRead.readFromString("" - + "06 00 16 00 " // Formula - + "01 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 " - + "01 02 06 00 " // Blank - + "02 00 02 00 00 00"); - byte[] actualArray = new byte[expectedArray.length]; - List records = testData(); - constructValueRecord(records); - - SerializerVisitor sv = new SerializerVisitor(actualArray); - valueRecord.visitCellsForRow(1, sv); - valueRecord.visitCellsForRow(2, sv); - assertEquals(actualArray.length, sv.getWriteIndex()); - assertArrayEquals(expectedArray, actualArray); - } - - private static BlankRecord newBlankRecord() { - return newBlankRecord( 2, 2 ); - } - - private static BlankRecord newBlankRecord(int col, int row) { - BlankRecord blankRecord = new BlankRecord(); - blankRecord.setRow( row ); - blankRecord.setColumn( (short) col ); - return blankRecord; - } - - /** - * Sometimes the 'shared formula' flag (FormulaRecord.isSharedFormula()) is set when - * there is no corresponding SharedFormulaRecord available. SharedFormulaRecord definitions do - * not span multiple sheets. They are are only defined within a sheet, and thus they do not - * have a sheet index field (only row and column range fields).
- * So it is important that the code which locates the SharedFormulaRecord for each - * FormulaRecord does not allow matches across sheets.
- * - * Prior to bugzilla 44449 (Feb 2008), POI ValueRecordsAggregate.construct(int, List) - * allowed SharedFormulaRecords to be erroneously used across sheets. That incorrect - * behaviour is shown by this test.

- * - * Notes on how to produce the test spreadsheet:

- * The setup for this test (AbnormalSharedFormulaFlag.xls) is rather fragile, insomuchas - * re-saving the file (either with Excel or POI) clears the flag.
- *
    - *
  1. A new spreadsheet was created in Excel (File | New | Blank Workbook).
  2. - *
  3. Sheet3 was deleted.
  4. - *
  5. Sheet2!A1 formula was set to '="second formula"', and fill-dragged through A1:A8.
  6. - *
  7. Sheet1!A1 formula was set to '="first formula"', and also fill-dragged through A1:A8.
  8. - *
  9. Four rows on Sheet1 "5" through "8" were deleted ('delete rows' alt-E D, not 'clear' Del).
  10. - *
  11. The spreadsheet was saved as AbnormalSharedFormulaFlag.xls.
  12. - *
- * Prior to the row delete action the spreadsheet has two SharedFormulaRecords. One - * for each sheet. To expose the bug, the shared formulas have been made to overlap.
- * The row delete action (as described here) seems to to delete the - * SharedFormulaRecord from Sheet1 (but not clear the 'shared formula' flags.
- * There are other variations on this theme to create the same effect. - * - */ - @Test - void testSpuriousSharedFormulaFlag() throws Exception { - - 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 = HSSFTestDataSamples.openSampleWorkbook(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE); - - HSSFSheet s = wb.getSheetAt(0); // Sheet1 - - String cellFormula; - cellFormula = getFormulaFromFirstCell(s, 0); // row "1" - // the problem is not observable in the first row of the shared formula - assertEquals("\"first formula\"", cellFormula, "Something else wrong with this test case"); - - // but the problem is observable in rows 2,3,4 - cellFormula = getFormulaFromFirstCell(s, 1); // row "2" - assertNotEquals("\"second formula\"", cellFormula, "found bug 44449 (Wrong SharedFormulaRecord was used)."); - - assertEquals("\"first formula\"", cellFormula, "Something else wrong with this test case"); - - wb.close(); - } - private static String getFormulaFromFirstCell(HSSFSheet s, int rowIx) { - return s.getRow(rowIx).getCell(0).getCellFormula(); - } - - /** - * If someone opened this particular test file in Excel and saved it, the peculiar condition - * which causes the target bug would probably disappear. This test would then just succeed - * regardless of whether the fix was present. So a CRC check is performed to make it less easy - * for that to occur. - */ - private static RuntimeException failUnexpectedTestFileChange() { - String msg = "Test file '" + ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE + "' has changed. " - + "This junit may not be properly testing for the target bug. " - + "Either revert the test file or ensure that the new version " - + "has the right characteristics to test the target bug."; - // A breakpoint in ValueRecordsAggregate.handleMissingSharedFormulaRecord(FormulaRecord) - // should get hit during parsing of Sheet1. - // If the test spreadsheet is created as directed, this condition should occur. - // It is easy to upset the test spreadsheet (for example re-saving will destroy the - // peculiar condition we are testing for). - throw new RuntimeException(msg); - } - - /** - * gets a CRC checksum for the content of a file - */ - private static long getFileCRC(InputStream is) { - CRC32 crc = new CRC32(); - byte[] buf = new byte[2048]; - try { - while(true) { - int bytesRead = is.read(buf); - if(bytesRead < 1) { - break; - } - crc.update(buf, 0, bytesRead); - } - is.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - - return crc.getValue(); - } - - @Test - void testRemoveNewRow_bug46312() throws IOException { - // To make bug occur, rowIndex needs to be >= ValueRecordsAggregate.records.length - int rowIndex = 30; - - ValueRecordsAggregate vra = new ValueRecordsAggregate(); - // bug 46312 - Specified rowIndex 30 is outside the allowable range (0..30) - assertDoesNotThrow(() -> vra.removeAllCellsValuesForRow(rowIndex)); - - // same bug as demonstrated through usermodel API - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - HSSFRow row = sheet.createRow(rowIndex); - - // must not add any cells to the new row if we want to see the bug - // row.createCell(0); // this causes ValueRecordsAggregate.records to auto-extend - assertDoesNotThrow(() -> sheet.createRow(rowIndex)); - } - } - - /** - * Tests various manipulations of blank cells, to make sure that {@link MulBlankRecord}s - * are use appropriately - */ - @Test - void testMultipleBlanks() { - BlankRecord brA2 = newBlankRecord(0, 1); - BlankRecord brB2 = newBlankRecord(1, 1); - BlankRecord brC2 = newBlankRecord(2, 1); - BlankRecord brD2 = newBlankRecord(3, 1); - BlankRecord brE2 = newBlankRecord(4, 1); - BlankRecord brB3 = newBlankRecord(1, 2); - BlankRecord brC3 = newBlankRecord(2, 2); - - valueRecord.insertCell(brA2); - valueRecord.insertCell(brB2); - valueRecord.insertCell(brD2); - confirmMulBlank(3, 1, 1); - - valueRecord.insertCell(brC3); - confirmMulBlank(4, 1, 2); - - valueRecord.insertCell(brB3); - valueRecord.insertCell(brE2); - confirmMulBlank(6, 3, 0); - - valueRecord.insertCell(brC2); - confirmMulBlank(7, 2, 0); - - valueRecord.removeCell(brA2); - confirmMulBlank(6, 2, 0); - - valueRecord.removeCell(brC2); - confirmMulBlank(5, 2, 1); - - valueRecord.removeCell(brC3); - confirmMulBlank(4, 1, 2); - } - - private void confirmMulBlank(int expectedTotalBlankCells, - int expectedNumberOfMulBlankRecords, int expectedNumberOfSingleBlankRecords) { - // assumed row ranges set-up by caller: - final int firstRow = 1; - final int lastRow = 2; - - - final class BlankStats { - public int countBlankCells; - public int countMulBlankRecords; - public int countSingleBlankRecords; - } - - final BlankStats bs = new BlankStats(); - RecordVisitor rv = r -> { - if (r instanceof MulBlankRecord) { - MulBlankRecord mbr = (MulBlankRecord) r; - bs.countMulBlankRecords++; - bs.countBlankCells += mbr.getNumColumns(); - } else if (r instanceof BlankRecord) { - bs.countSingleBlankRecords++; - bs.countBlankCells++; - } - }; - - for (int rowIx = firstRow; rowIx <=lastRow; rowIx++) { - if (valueRecord.rowHasCells(rowIx)) { - valueRecord.visitCellsForRow(rowIx, rv); - } - } - assertEquals(expectedTotalBlankCells, bs.countBlankCells); - assertEquals(expectedNumberOfMulBlankRecords, bs.countMulBlankRecords); - assertEquals(expectedNumberOfSingleBlankRecords, bs.countSingleBlankRecords); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java b/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java deleted file mode 100644 index cb0a6a548b..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java +++ /dev/null @@ -1,274 +0,0 @@ -/* ==================================================================== -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.record.cf; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Arrays; - -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeUtil; -import org.junit.jupiter.api.Test; - -/** - * Tests CellRange operations. - */ -final class TestCellRange { - private static final CellRangeAddress biggest = createCR( 0, -1, 0,-1); - private static final CellRangeAddress tenthColumn = createCR( 0, -1,10,10); - private static final CellRangeAddress tenthRow = createCR(10, 10, 0,-1); - private static final CellRangeAddress box10x10 = createCR( 0, 10, 0,10); - private static final CellRangeAddress box9x9 = createCR( 0, 9, 0, 9); - private static final CellRangeAddress box10to20c = createCR( 0, 10,10,20); - private static final CellRangeAddress oneCell = createCR(10, 10,10,10); - - private static final CellRangeAddress[] sampleRanges = { - biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell, - }; - - /** cross-reference of contains() operations for sampleRanges against itself */ - private static final boolean [][] containsExpectedResults = - { - // biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell - /*biggest */ {true, true , true , true , true , true , true}, - /*tenthColumn*/ {false, true , false, false, false, false, true}, - /*tenthRow */ {false, false, true , false, false, false, true}, - /*box10x10 */ {false, false, false, true , true , false, true}, - /*box9x9 */ {false, false, false, false, true , false, false}, - /*box10to20c */ {false, false, false, false, false, true , true}, - /*oneCell */ {false, false, false, false, false, false, true}, - } ; - - /** - * @param lastRow pass -1 for max row index - * @param lastCol pass -1 for max col index - */ - private static CellRangeAddress createCR(int firstRow, int lastRow, int firstCol, int lastCol) { - // max row & max col limit as per BIFF8 - return new CellRangeAddress( - firstRow, - lastRow == -1 ? 0xFFFF : lastRow, - firstCol, - lastCol == -1 ? 0x00FF : lastCol); - } - - @Test - void testContainsMethod() - { - CellRangeAddress [] ranges = sampleRanges; - for(int i=0; i!=ranges.length;i++) - { - for(int j=0; j!=ranges.length;j++) - { - boolean expectedResult = containsExpectedResults[i][j]; - assertEquals(expectedResult, CellRangeUtil.contains(ranges[i], ranges[j]), "("+i+","+j+"): "); - } - } - } - - private static final CellRangeAddress col1 = createCR( 0, -1, 1,1); - private static final CellRangeAddress col2 = createCR( 0, -1, 2,2); - private static final CellRangeAddress row1 = createCR( 1, 1, 0,-1); - private static final CellRangeAddress row2 = createCR( 2, 2, 0,-1); - - private static final CellRangeAddress box0 = createCR( 0, 2, 0,2); - private static final CellRangeAddress box1 = createCR( 0, 1, 0,1); - private static final CellRangeAddress box2 = createCR( 0, 1, 2,3); - private static final CellRangeAddress box3 = createCR( 2, 3, 0,1); - private static final CellRangeAddress box4 = createCR( 2, 3, 2,3); - private static final CellRangeAddress box5 = createCR( 1, 3, 1,3); - - @Test - void testHasSharedBorderMethod() { - assertFalse(CellRangeUtil.hasExactSharedBorder(col1, col1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(col2, col2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(col1, col2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(col2, col1)); - - assertFalse(CellRangeUtil.hasExactSharedBorder(row1, row1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(row2, row2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(row1, row2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(row2, row1)); - - assertFalse(CellRangeUtil.hasExactSharedBorder(row1, col1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(row1, col2)); - assertFalse(CellRangeUtil.hasExactSharedBorder(col1, row1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(col2, row1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(row2, col1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(row2, col2)); - assertFalse(CellRangeUtil.hasExactSharedBorder(col1, row2)); - assertFalse(CellRangeUtil.hasExactSharedBorder(col2, row2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(col2, col1)); - - assertFalse(CellRangeUtil.hasExactSharedBorder(box1, box1)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box1, box2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box1, box3)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box1, box4)); - - assertTrue(CellRangeUtil.hasExactSharedBorder(box2, box1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box2, box2)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box2, box3)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box2, box4)); - - assertTrue(CellRangeUtil.hasExactSharedBorder(box3, box1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box3, box2)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box3, box3)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box3, box4)); - - assertFalse(CellRangeUtil.hasExactSharedBorder(box4, box1)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box4, box2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box4, box3)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box4, box4)); - } - - @Test - void testIntersectMethod() { - assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(box0, box5)); - assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(box5, box0)); - assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box1, box4)); - assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box4, box1)); - assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box2, box3)); - assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box3, box2)); - assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(box0, box1)); - assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(box0, box0)); - assertEquals(CellRangeUtil.ENCLOSES, CellRangeUtil.intersect(box1, box0)); - assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(tenthColumn, oneCell)); - assertEquals(CellRangeUtil.ENCLOSES, CellRangeUtil.intersect(oneCell, tenthColumn)); - assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(tenthColumn, tenthRow)); - assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(tenthRow, tenthColumn)); - assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(tenthColumn, tenthColumn)); - assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(tenthRow, tenthRow)); - - // Bug 55380 - assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect( - CellRangeAddress.valueOf("C1:D2"), CellRangeAddress.valueOf("C2:C3"))); - } - - /** - * Cell ranges like the following are valid - * =$C:$IV,$B$1:$B$8,$B$10:$B$65536,$A:$A - */ - @Test - void testCreate() { - CellRangeAddress cr = createCR(0, -1, 2, 255); // $C:$IV - - assertFalse(cr.isFullRowRange(), "isFullRowRange"); - assertTrue(cr.isFullColumnRange(), "isFullColumnRange"); - - createCR(0, 7, 1, 1); // $B$1:$B$8 - - // bug 44739 - invalid cell range - createCR(9, -1, 1, 1); // $B$65536 - - createCR(0, -1, 0, 0); // $A:$A - } - - @Test - void testNumberOfCells() { - assertEquals(1, oneCell.getNumberOfCells()); - assertEquals(100, box9x9.getNumberOfCells()); - assertEquals(121, box10to20c.getNumberOfCells()); - } - - @SuppressWarnings("RedundantArrayCreation") - @Test - void testMergeCellRanges() { - // no result on empty - cellRangeTest(new String[]{ }); - - // various cases with two ranges - cellRangeTest(new String[]{"A1:B1", "A2:B2"}, "A1:B2"); - cellRangeTest(new String[]{"A1:B1" }, "A1:B1"); - cellRangeTest(new String[]{"A1:B2", "A2:B2"}, "A1:B2"); - cellRangeTest(new String[]{"A1:B3", "A2:B2"}, "A1:B3"); - cellRangeTest(new String[]{"A1:C1", "A2:B2"}, new String[] {"A1:C1", "A2:B2"}); - - // cases with three ranges - cellRangeTest(new String[]{"A1:A1", "A2:B2", "A1:C1"}, new String[] {"A1:C1", "A2:B2"}); - cellRangeTest(new String[]{"A1:C1", "A2:B2", "A1:A1"}, new String[] {"A1:C1", "A2:B2"}); - - // "standard" cases - // enclose - cellRangeTest(new String[]{"A1:D4", "B2:C3"}, new String[] {"A1:D4"}); - // inside - cellRangeTest(new String[]{"B2:C3", "A1:D4"}, new String[] {"A1:D4"}); - cellRangeTest(new String[]{"B2:C3", "A1:D4"}, new String[] {"A1:D4"}); - // disjunct - cellRangeTest(new String[]{"A1:B2", "C3:D4"}, new String[] {"A1:B2", "C3:D4"}); - cellRangeTest(new String[]{"A1:B2", "A3:D4"}, new String[] {"A1:B2", "A3:D4"}); - // overlap that cannot be merged - cellRangeTest(new String[]{"C1:D2", "C2:C3"}, new String[] {"C1:D2", "C2:C3"}); - // overlap which could theoretically be merged, but isn't because the implementation was buggy and therefore was removed - cellRangeTest(new String[]{"A1:C3", "B1:D3"}, new String[] {"A1:C3", "B1:D3"}); // could be one region "A1:D3" - cellRangeTest(new String[]{"A1:C3", "B1:D1"}, new String[] {"A1:C3", "B1:D1"}); // could be one region "A1:D3" - } - - @SuppressWarnings("RedundantArrayCreation") - @Test - void testMergeCellRanges55380() { - cellRangeTest(new String[]{"C1:D2", "C2:C3"}, new String[] {"C1:D2", "C2:C3"}); - cellRangeTest(new String[]{"A1:C3", "B2:D2"}, new String[] {"A1:C3", "B2:D2"}); - cellRangeTest(new String[]{"C9:D30", "C7:C31"}, new String[] {"C9:D30", "C7:C31"}); - } - -// void testResolveRangeOverlap() { -// resolveRangeOverlapTest("C1:D2", "C2:C3"); -// } - - private void cellRangeTest(String[] input, String... expectedOutput) { - CellRangeAddress[] inputArr = new CellRangeAddress[input.length]; - for(int i = 0;i < input.length;i++) { - inputArr[i] = CellRangeAddress.valueOf(input[i]); - } - CellRangeAddress[] result = CellRangeUtil.mergeCellRanges(inputArr); - verifyExpectedResult(result, expectedOutput); - } - -// private void resolveRangeOverlapTest(String a, String b, String...expectedOutput) { -// CellRangeAddress rangeA = CellRangeAddress.valueOf(a); -// CellRangeAddress rangeB = CellRangeAddress.valueOf(b); -// CellRangeAddress[] result = CellRangeUtil.resolveRangeOverlap(rangeA, rangeB); -// verifyExpectedResult(result, expectedOutput); -// } - - private void verifyExpectedResult(CellRangeAddress[] result, String... expectedOutput) { - assertEquals(expectedOutput.length, result.length, - "\nExpected: " + Arrays.toString(expectedOutput) + "\nHad: " + Arrays.toString(result)); - for(int i = 0;i < expectedOutput.length;i++) { - assertEquals(expectedOutput[i], result[i].formatAsString(), - "\nExpected: " + Arrays.toString(expectedOutput) + "\nHad: " + Arrays.toString(result)); - } - } - - @Test - void testValueOf() { - CellRangeAddress cr1 = CellRangeAddress.valueOf("A1:B1"); - assertEquals(0, cr1.getFirstColumn()); - assertEquals(0, cr1.getFirstRow()); - assertEquals(1, cr1.getLastColumn()); - assertEquals(0, cr1.getLastRow()); - - CellRangeAddress cr2 = CellRangeAddress.valueOf("B1"); - assertEquals(1, cr2.getFirstColumn()); - assertEquals(0, cr2.getFirstRow()); - assertEquals(1, cr2.getLastColumn()); - assertEquals(0, cr2.getLastRow()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java deleted file mode 100644 index c0cb666800..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the AreaFormatRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestAreaFormatRecord { - byte[] data = new byte[] { - (byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0x00, // forecolor - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // backcolor - (byte)0x01,(byte)0x00, // pattern - (byte)0x01,(byte)0x00, // format - (byte)0x4E,(byte)0x00, // forecolor index - (byte)0x4D,(byte)0x00 // backcolor index - - }; - - @Test - void testLoad() { - AreaFormatRecord record = new AreaFormatRecord(TestcaseRecordInputStream.create(0x100a, data)); - assertEquals( 0xFFFFFF, record.getForegroundColor()); - assertEquals( 0x000000, record.getBackgroundColor()); - assertEquals( 1, record.getPattern()); - assertEquals( 1, record.getFormatFlags()); - assertTrue(record.isAutomatic()); - assertFalse(record.isInvert()); - assertEquals( 0x4e, record.getForecolorIndex()); - assertEquals( 0x4d, record.getBackcolorIndex()); - - - assertEquals( 20, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - AreaFormatRecord record = new AreaFormatRecord(); - record.setForegroundColor( 0xFFFFFF ); - record.setBackgroundColor( 0x000000 ); - record.setPattern( (short)1 ); - record.setAutomatic( true ); - record.setInvert( false ); - record.setForecolorIndex( (short)0x4e ); - record.setBackcolorIndex( (short)0x4d ); - - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(AreaFormatRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java deleted file mode 100644 index 638b32635c..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the AreaRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestAreaRecord { - byte[] data = new byte[] { - (byte)0x02,(byte)0x00 // format flags - }; - - @Test - void testLoad() { - - AreaRecord record = new AreaRecord(TestcaseRecordInputStream.create(0x101A, data)); - assertEquals( 2, record.getFormatFlags()); - assertFalse(record.isStacked()); - assertTrue(record.isDisplayAsPercentage()); - assertFalse(record.isShadow()); - - assertEquals( 6, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - AreaRecord record = new AreaRecord(); - record.setStacked( false ); - record.setDisplayAsPercentage( true ); - record.setShadow( false ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(AreaRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java deleted file mode 100644 index 7e1a07f651..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the AxisLineFormatRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestAxisLineFormatRecord { - byte[] data = new byte[] { - (byte)0x01,(byte)0x00 - }; - - @Test - void testLoad() { - AxisLineFormatRecord record = new AxisLineFormatRecord(TestcaseRecordInputStream.create(0x1021, data)); - assertEquals( AxisLineFormatRecord.AXIS_TYPE_MAJOR_GRID_LINE, record.getAxisType()); - - assertEquals( 6, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - AxisLineFormatRecord record = new AxisLineFormatRecord(); - record.setAxisType( AxisLineFormatRecord.AXIS_TYPE_MAJOR_GRID_LINE ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(AxisLineFormatRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java deleted file mode 100644 index 06c03ee0ca..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the AxisOptionsRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestAxisOptionsRecord { - private static final byte[] data = { - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01,(byte)0x00, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0xEF,(byte)0x00 - }; - - @Test - void testLoad() { - AxisOptionsRecord record = new AxisOptionsRecord(TestcaseRecordInputStream.create(0x1062, data)); - assertEquals( 0, record.getMinimumCategory()); - assertEquals( 0, record.getMaximumCategory()); - assertEquals( 1, record.getMajorUnitValue()); - assertEquals( 0, record.getMajorUnit()); - assertEquals( 1, record.getMinorUnitValue()); - assertEquals( 0, record.getMinorUnit()); - assertEquals( 0, record.getBaseUnit()); - assertEquals( 0, record.getCrossingPoint()); - assertEquals( 239, record.getOptions()); - assertTrue(record.isDefaultMinimum()); - assertTrue(record.isDefaultMaximum()); - assertTrue(record.isDefaultMajor()); - assertTrue(record.isDefaultMinorUnit()); - assertFalse(record.isIsDate()); - assertTrue(record.isDefaultBase()); - assertTrue(record.isDefaultCross()); - assertTrue(record.isDefaultDateSettings()); - - assertEquals( 22, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - AxisOptionsRecord record = new AxisOptionsRecord(); - record.setMinimumCategory( (short)0 ); - record.setMaximumCategory( (short)0 ); - record.setMajorUnitValue( (short)1 ); - record.setMajorUnit( (short)0 ); - record.setMinorUnitValue( (short)1 ); - record.setMinorUnit( (short)0 ); - record.setBaseUnit( (short)0 ); - record.setCrossingPoint( (short)0 ); - record.setOptions( (short)239 ); - record.setDefaultMinimum( true ); - record.setDefaultMaximum( true ); - record.setDefaultMajor( true ); - record.setDefaultMinorUnit( true ); - record.setIsDate( false ); - record.setDefaultBase( true ); - record.setDefaultCross( true ); - record.setDefaultDateSettings( true ); - - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(AxisOptionsRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java deleted file mode 100644 index 0c77fbcf2d..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the AxisParentRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestAxisParentRecord { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00, // axis type - (byte)0x1D,(byte)0x02,(byte)0x00,(byte)0x00, // x - (byte)0xDD,(byte)0x00,(byte)0x00,(byte)0x00, // y - (byte)0x31,(byte)0x0B,(byte)0x00,(byte)0x00, // width - (byte)0x56,(byte)0x0B,(byte)0x00,(byte)0x00 // height - }; - - @Test - void testLoad() { - AxisParentRecord record = new AxisParentRecord(TestcaseRecordInputStream.create(0x1041, data)); - assertEquals( AxisParentRecord.AXIS_TYPE_MAIN, record.getAxisType()); - assertEquals( 0x021d, record.getX()); - assertEquals( 0xdd, record.getY()); - assertEquals( 0x0b31, record.getWidth()); - assertEquals( 0x0b56, record.getHeight()); - - assertEquals( 22, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - AxisParentRecord record = new AxisParentRecord(); - record.setAxisType( AxisParentRecord.AXIS_TYPE_MAIN ); - record.setX( 0x021d ); - record.setY( 0xdd ); - record.setWidth( 0x0b31 ); - record.setHeight( 0x0b56 ); - - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(AxisParentRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java deleted file mode 100644 index 70b504c6ac..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the AxisRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestAxisRecord { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00, // type - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00 - }; - - @Test - void testLoad() { - AxisRecord record = new AxisRecord(TestcaseRecordInputStream.create(0x101d, data)); - assertEquals( AxisRecord.AXIS_TYPE_CATEGORY_OR_X_AXIS, record.getAxisType()); - assertEquals( 0, record.getReserved1()); - assertEquals( 0, record.getReserved2()); - assertEquals( 0, record.getReserved3()); - assertEquals( 0, record.getReserved4()); - - assertEquals( 4 + 18, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - AxisRecord record = new AxisRecord(); - record.setAxisType( AxisRecord.AXIS_TYPE_CATEGORY_OR_X_AXIS ); - record.setReserved1( 0 ); - record.setReserved2( 0 ); - record.setReserved3( 0 ); - record.setReserved4( 0 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(AxisRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java deleted file mode 100644 index 4a494d2f8b..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the AxisUsedRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestAxisUsedRecord { - byte[] data = new byte[] { - (byte)0x01,(byte)0x00, - }; - - @Test - void testLoad() { - AxisUsedRecord record = new AxisUsedRecord(TestcaseRecordInputStream.create(0x1046, data)); - assertEquals( 1, record.getNumAxis()); - - assertEquals( 6, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - AxisUsedRecord record = new AxisUsedRecord(); - record.setNumAxis( (short)1 ); - - byte[] recordBytes = record.serialize(); - confirmRecordEncoding(AxisUsedRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java deleted file mode 100644 index 975f6c998f..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the BarRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestBarRecord { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00, // bar space - (byte)0x96,(byte)0x00, // category space - (byte)0x00,(byte)0x00 // format flags - }; - - @Test - void testLoad() { - BarRecord record = new BarRecord(TestcaseRecordInputStream.create(0x1017, data)); - assertEquals( 0, record.getBarSpace()); - assertEquals( 0x96, record.getCategorySpace()); - assertEquals( 0, record.getFormatFlags()); - assertFalse(record.isHorizontal()); - assertFalse(record.isStacked()); - assertFalse(record.isDisplayAsPercentage()); - assertFalse(record.isShadow()); - - assertEquals( 10, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - BarRecord record = new BarRecord(); - record.setBarSpace( (short)0 ); - record.setCategorySpace( (short)0x96 ); - record.setHorizontal( false ); - record.setStacked( false ); - record.setDisplayAsPercentage( false ); - record.setShadow( false ); - - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(BarRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java deleted file mode 100644 index 87f020479b..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the CategorySeriesAxisRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestCategorySeriesAxisRecord { - byte[] data = new byte[] { - (byte)0x01,(byte)0x00, // crossing point - (byte)0x01,(byte)0x00, // label frequency - (byte)0x01,(byte)0x00, // tick mark frequency - (byte)0x01,(byte)0x00 // options - }; - - @Test - void testLoad() { - CategorySeriesAxisRecord record = new CategorySeriesAxisRecord(TestcaseRecordInputStream.create(0x1020, data)); - assertEquals( 1, record.getCrossingPoint()); - assertEquals( 1, record.getLabelFrequency()); - assertEquals( 1, record.getTickMarkFrequency()); - assertEquals( 1, record.getOptions()); - assertTrue(record.isValueAxisCrossing()); - assertFalse(record.isCrossesFarRight()); - assertFalse(record.isReversed()); - - assertEquals( 4 + 8, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - CategorySeriesAxisRecord record = new CategorySeriesAxisRecord(); - record.setCrossingPoint( (short)1 ); - record.setLabelFrequency( (short)1 ); - record.setTickMarkFrequency( (short)1 ); - record.setValueAxisCrossing( true ); - record.setCrossesFarRight( false ); - record.setReversed( false ); - - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(CategorySeriesAxisRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java deleted file mode 100644 index 1341bce4b8..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - 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.record.chart; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link ChartFormatRecord} Test data taken directly from a real - * Excel file. - */ -final class TestChartFormatRecord { - /** - * This rather uninteresting data came from attachment 23347 of bug 46693 at - * offsets 0x6BB2 and 0x7BAF - */ - private static final byte[] data = HexRead.readFromString( - "14 10 14 00 " // BIFF header - + "00 00 00 00 00 00 00 00 " - + "00 00 00 00 00 00 00 00 " - + "00 00 00 00"); - - /** - * The correct size of a {@link ChartFormatRecord} is 20 bytes (not including header). - */ - @Test - void testLoad() { - RecordInputStream in = TestcaseRecordInputStream.create(data); - ChartFormatRecord record = new ChartFormatRecord(in); - assertNotEquals(2, in.remaining(), "Identified bug 44693d"); - assertEquals(0, in.remaining()); - assertEquals(24, record.getRecordSize()); - - byte[] data2 = record.serialize(); - assertArrayEquals(data, data2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java deleted file mode 100644 index a2eaa8fa43..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the ChartRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestChartRecord { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0xE8,(byte)0xFF,(byte)0xD0,(byte)0x01, - (byte)0xC8,(byte)0xCC,(byte)0xE5,(byte)0x00 - }; - - @Test - void testLoad() { - ChartRecord record = new ChartRecord(TestcaseRecordInputStream.create(0x1002, data)); - assertEquals( 0, record.getX()); - assertEquals( 0, record.getY()); - assertEquals( 30474216, record.getWidth()); - assertEquals( 15060168, record.getHeight()); - - assertEquals( 20, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - ChartRecord record = new ChartRecord(); - record.setX( 0 ); - record.setY( 0 ); - record.setWidth( 30474216 ); - record.setHeight( 15060168 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(ChartRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java deleted file mode 100644 index e719910ddf..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - 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.record.chart; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -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.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.Test; - -final class TestChartTitleFormatRecord { - - @Test - void testRecord() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem( - HSSFTestDataSamples.getSampleFile("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 = grabber.chartTitleFormatRecords.get(0); - assertEquals(3, r.getFormatCount()); - - hssf.close(); - fs.close(); - - } - - private static final class ChartTitleFormatRecordGrabber implements HSSFListener { - private final List chartTitleFormatRecords; - - ChartTitleFormatRecordGrabber() { - chartTitleFormatRecords = new ArrayList<>(); - } - - @Override - public void processRecord(org.apache.poi.hssf.record.Record record) { - if(record instanceof ChartTitleFormatRecord) { - chartTitleFormatRecords.add((ChartTitleFormatRecord)record); - } - } - - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.java deleted file mode 100644 index 8511d1cdf5..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the DatRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestDatRecord { - byte[] data = new byte[] { - (byte)0x0D,(byte)0x00 // options - }; - - @Test - void testLoad() { - DatRecord record = new DatRecord(TestcaseRecordInputStream.create(0x1063, data)); - assertEquals( 0xD, record.getOptions()); - assertTrue(record.isHorizontalBorder()); - assertFalse(record.isVerticalBorder()); - assertTrue(record.isBorder()); - assertTrue(record.isShowSeriesKey()); - - assertEquals( 6, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - DatRecord record = new DatRecord(); - record.setHorizontalBorder( true ); - record.setVerticalBorder( false ); - record.setBorder( true ); - record.setShowSeriesKey( true ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(DatRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java deleted file mode 100644 index a146408400..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the DataFormatRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestDataFormatRecord { - byte[] data = new byte[] { - (byte)0xFF,(byte)0xFF, // point number - (byte)0x00,(byte)0x00, // series index - (byte)0x00,(byte)0x00, // series number - (byte)0x00,(byte)0x00 // format flags - }; - - @Test - void testLoad() { - DataFormatRecord record = new DataFormatRecord(TestcaseRecordInputStream.create(0x1006, data)); - assertEquals( (short)0xFFFF, record.getPointNumber()); - assertEquals( 0, record.getSeriesIndex()); - assertEquals( 0, record.getSeriesNumber()); - assertEquals( 0, record.getFormatFlags()); - assertFalse(record.isUseExcel4Colors()); - - assertEquals( 12, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - DataFormatRecord record = new DataFormatRecord(); - record.setPointNumber( (short)0xFFFF ); - record.setSeriesIndex( (short)0 ); - record.setSeriesNumber( (short)0 ); - record.setFormatFlags( (short)0 ); - record.setUseExcel4Colors( false ); - - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(DataFormatRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java deleted file mode 100644 index 6ebf3a6191..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the DefaultDataLabelTextPropertiesRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestDefaultDataLabelTextPropertiesRecord { - byte[] data = new byte[] { - (byte)0x02,(byte)0x00 - }; - - @Test - void testLoad() { - - DefaultDataLabelTextPropertiesRecord record = new DefaultDataLabelTextPropertiesRecord(TestcaseRecordInputStream.create(0x1024, data)); - assertEquals( 2, record.getCategoryDataType()); - - assertEquals( 6, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - DefaultDataLabelTextPropertiesRecord record = new DefaultDataLabelTextPropertiesRecord(); - record.setCategoryDataType( (short)2 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(DefaultDataLabelTextPropertiesRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java deleted file mode 100644 index 5042e5663d..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the FontBasisRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestFontBasisRecord { - byte[] data = new byte[] { - (byte)0x28,(byte)0x1A, // x basis - (byte)0x9C,(byte)0x0F, // y basis - (byte)0xC8,(byte)0x00, // height basis - (byte)0x00,(byte)0x00, // scale - (byte)0x05,(byte)0x00 // index to font table - }; - - @Test - void testLoad() { - FontBasisRecord record = new FontBasisRecord(TestcaseRecordInputStream.create(0x1060, data)); - assertEquals( 0x1a28, record.getXBasis()); - assertEquals( 0x0f9c, record.getYBasis()); - assertEquals( 0xc8, record.getHeightBasis()); - assertEquals( 0x00, record.getScale()); - assertEquals( 0x05, record.getIndexToFontTable()); - - assertEquals( 14, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - FontBasisRecord record = new FontBasisRecord(); - record.setXBasis( (short)0x1a28 ); - record.setYBasis( (short)0x0f9c ); - record.setHeightBasis( (short)0xc8 ); - record.setScale( (short)0x00 ); - record.setIndexToFontTable( (short)0x05 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(FontBasisRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java deleted file mode 100644 index ca92378c8c..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the FontIndexRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestFontIndexRecord { - byte[] data = new byte[] { - (byte)0x05,(byte)0x00 - }; - - @Test - void testLoad() { - - FontIndexRecord record = new FontIndexRecord(TestcaseRecordInputStream.create(0x1026, data)); - assertEquals( 5, record.getFontIndex()); - - assertEquals( 6, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - FontIndexRecord record = new FontIndexRecord(); - record.setFontIndex( (short)5 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(FontIndexRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java deleted file mode 100644 index ca8ec3ca9b..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the FrameRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestFrameRecord { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00, // border type - (byte)0x02,(byte)0x00 // options - }; - - @Test - void testLoad() { - FrameRecord record = new FrameRecord(TestcaseRecordInputStream.create(0x1032, data)); - assertEquals( FrameRecord.BORDER_TYPE_REGULAR, record.getBorderType()); - assertEquals( 2, record.getOptions()); - assertFalse(record.isAutoSize()); - assertTrue(record.isAutoPosition()); - - assertEquals( 8, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - FrameRecord record = new FrameRecord(); - record.setBorderType( FrameRecord.BORDER_TYPE_REGULAR ); - record.setOptions( (short)2 ); - record.setAutoSize( false ); - record.setAutoPosition( true ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(FrameRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java deleted file mode 100644 index d5c995fd5b..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - 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.record.chart; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the LegendRecord class works - * correctly. Test data taken directly from a real Excel file. - */ -final class TestLegendRecord { - byte[] data = new byte[] { (byte) 0x76, (byte) 0x0E, (byte) 0x00, (byte) 0x00, (byte) 0x86, - (byte) 0x07, (byte) 0x00, (byte) 0x00, (byte) 0x19, (byte) 0x01, (byte) 0x00, - (byte) 0x00, (byte) 0x8B, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, - (byte) 0x01, (byte) 0x1F, (byte) 0x00 }; - - @Test - void testLoad() { - LegendRecord record = new LegendRecord(TestcaseRecordInputStream.create(0x1015, data)); - - assertEquals(0xe76, record.getXAxisUpperLeft()); - - assertEquals(0x786, record.getYAxisUpperLeft()); - - assertEquals(0x119, record.getXSize()); - - assertEquals(0x8b, record.getYSize()); - - assertEquals((byte) 0x3, record.getType()); - - assertEquals((byte) 0x1, record.getSpacing()); - - assertEquals((short) 0x1f, record.getOptions()); - assertTrue(record.isAutoPosition()); - assertTrue(record.isAutoSeries()); - assertTrue(record.isAutoXPositioning()); - assertTrue(record.isAutoYPositioning()); - assertTrue(record.isVertical()); - assertFalse(record.isDataTable()); - - assertEquals(24, record.getRecordSize()); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - LegendRecord record = new LegendRecord(); - - record.setXAxisUpperLeft(0xe76); - record.setYAxisUpperLeft(0x786); - record.setXSize(0x119); - record.setYSize(0x8b); - record.setType((byte) 0x3); - record.setSpacing((byte) 0x1); - record.setOptions((short) 0x1f); - record.setAutoPosition(true); - record.setAutoSeries(true); - record.setAutoXPositioning(true); - record.setAutoYPositioning(true); - record.setVertical(true); - record.setDataTable(false); - - byte[] recordBytes = record.serialize(); - confirmRecordEncoding(LegendRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java deleted file mode 100644 index 89fd5e48e4..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the LineFormatRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestLineFormatRecord { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // colour - (byte)0x00,(byte)0x00, // pattern - (byte)0x00,(byte)0x00, // weight - (byte)0x01,(byte)0x00, // format - (byte)0x4D,(byte)0x00 // index - }; - - @Test - void testLoad() { - LineFormatRecord record = new LineFormatRecord(TestcaseRecordInputStream.create(0x1007, data)); - assertEquals( 0, record.getLineColor()); - assertEquals( 0, record.getLinePattern()); - assertEquals( 0, record.getWeight()); - assertEquals( 1, record.getFormat()); - assertTrue(record.isAuto()); - assertFalse(record.isDrawTicks()); - assertEquals( 0x4d, record.getColourPaletteIndex()); - - assertEquals( 16, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - LineFormatRecord record = new LineFormatRecord(); - record.setLineColor( 0 ); - record.setLinePattern( (short)0 ); - record.setWeight( (short)0 ); - record.setAuto( true ); - record.setDrawTicks( false ); - record.setColourPaletteIndex( (short)0x4d ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(LineFormatRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java deleted file mode 100644 index b21fd2d71d..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java +++ /dev/null @@ -1,194 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the LinkedDataRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestLinkedDataRecord { - -/* - The records below are records that would appear in a simple bar chart - - The first record links to the series title (linkType = 0). It's - reference type is 1 which means that it links directly to data entered - into the forumula bar. There seems to be no reference to any data - however. The formulaOfLink field contains two 0 bytes. This probably - means that there is no particular heading set. - - -============================================ -Offset 0xf9c (3996) -rectype = 0x1051, recsize = 0x8 --BEGIN DUMP--------------------------------- -00000000 00 01 00 00 00 00 00 00 ........ --END DUMP----------------------------------- -recordid = 0x1051, size =8 -[AI] -.linkType = 0x00 (0 ) -.referenceType = 0x01 (1 ) -.options = 0x0000 (0 ) - .customNumberFormat = false -.indexNumberFmtRecord = 0x0000 (0 ) -.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@95fd19 ) -[/AI] - - - The second record links to the series data (linkType=1). The - referenceType = 2 which means it's linked to the worksheet. - It links using a formula. The formula value is - 0B 00 3B 00 00 00 00 1E 00 01 00 01 00. - - 0B 00 11 bytes length - 3B (tArea3d) Rectangular area - 00 00 index to REF entry in extern sheet - 00 00 index to first row - 1E 00 index to last row - 01 00 index to first column and relative flags - 01 00 index to last column and relative flags - -============================================ -Offset 0xfa8 (4008) -rectype = 0x1051, recsize = 0x13 --BEGIN DUMP--------------------------------- -00000000 01 02 00 00 00 00 0B 00 3B 00 00 00 00 1E 00 01 ........;....... -00000010 00 01 00 ... --END DUMP----------------------------------- -recordid = 0x1051, size =19 -[AI] -.linkType = 0x01 (1 ) -.referenceType = 0x02 (2 ) -.options = 0x0000 (0 ) - .customNumberFormat = false -.indexNumberFmtRecord = 0x0000 (0 ) -.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@11b9fb1 ) -[/AI] - - The third record links to the series categories (linkType=2). The - reference type of 2 means that it's linked to the worksheet. - It links using a formula. The formula value is - 0B 00 3B 00 00 00 00 1E 00 01 00 01 00 - - 0B 00 11 bytes in length - 3B (tArea3d) Rectangular area - 00 00 index to REF entry in extern sheet - 00 00 index to first row - 00 1F index to last row - 00 00 index to first column and relative flags - 00 00 index to last column and relative flags - - -============================================ -Offset 0xfbf (4031) -rectype = 0x1051, recsize = 0x13 --BEGIN DUMP--------------------------------- -00000000 02 02 00 00 69 01 0B 00 3B 00 00 00 00 1F 00 00 ....i...;....... -00000010 00 00 00 ... --END DUMP----------------------------------- -recordid = 0x1051, size =19 -[AI] -.linkType = 0x02 (2 ) -.referenceType = 0x02 (2 ) -.options = 0x0000 (0 ) - .customNumberFormat = false -.indexNumberFmtRecord = 0x0169 (361 ) -.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@913fe2 ) -[/AI] - -This third link type does not seem to be documented and does not appear to -contain any useful information anyway. - -============================================ -Offset 0xfd6 (4054) -rectype = 0x1051, recsize = 0x8 --BEGIN DUMP--------------------------------- -00000000 03 01 00 00 00 00 00 00 ........ --END DUMP----------------------------------- -recordid = 0x1051, size =8 -[AI] -.linkType = 0x03 (3 ) -.referenceType = 0x01 (1 ) -.options = 0x0000 (0 ) - .customNumberFormat = false -.indexNumberFmtRecord = 0x0000 (0 ) -.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@1f934ad ) -[/AI] - -*/ - - byte[] data = new byte[]{ - (byte)0x01, // link type - (byte)0x02, // reference type - (byte)0x00,(byte)0x00, // options - (byte)0x00,(byte)0x00, // index number format record - (byte)0x0B,(byte)0x00, // 11 bytes length - (byte)0x3B, // formula of link - (byte)0x00,(byte)0x00, // index to ref entry in extern sheet - (byte)0x00,(byte)0x00, // index to first row - (byte)0x00,(byte)0x1F, // index to last row - (byte)0x00,(byte)0x00, // index to first column and relative flags - (byte)0x00,(byte)0x00, // index to last column and relative flags - }; - - @Test - void testLoad() { - LinkedDataRecord record = new LinkedDataRecord(TestcaseRecordInputStream.create(0x1051, data)); - assertEquals( LinkedDataRecord.LINK_TYPE_VALUES, record.getLinkType()); - assertEquals( LinkedDataRecord.REFERENCE_TYPE_WORKSHEET, record.getReferenceType()); - assertEquals( 0, record.getOptions()); - assertFalse(record.isCustomNumberFormat()); - assertEquals( 0, record.getIndexNumberFmtRecord()); - - Area3DPtg ptgExpected = new Area3DPtg(0, 7936, 0, 0, - false, false, false, false, 0); - - Ptg ptgActual = record.getFormulaOfLink()[0]; - assertEquals(ptgExpected.toString(), ptgActual.toString()); - - assertEquals( data.length + 4, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - LinkedDataRecord record = new LinkedDataRecord(); - record.setLinkType( LinkedDataRecord.LINK_TYPE_VALUES ); - record.setReferenceType( LinkedDataRecord.REFERENCE_TYPE_WORKSHEET ); - record.setOptions( (short)0 ); - record.setCustomNumberFormat( false ); - record.setIndexNumberFmtRecord( (short)0 ); - Area3DPtg ptg = new Area3DPtg(0, 7936, 0, 0, - false, false, false, false, 0); - record.setFormulaOfLink(new Ptg[] { ptg, } ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(LinkedDataRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java deleted file mode 100644 index 12c7cc7342..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the NumberFormatIndexRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestNumberFormatIndexRecord { - byte[] data = new byte[] { - 0x05,0x00 - }; - - @Test - void testLoad() { - NumberFormatIndexRecord record = new NumberFormatIndexRecord(TestcaseRecordInputStream.create(0x104e, data)); - assertEquals( 5, record.getFormatIndex()); - - assertEquals( 6, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - NumberFormatIndexRecord record = new NumberFormatIndexRecord(); - record.setFormatIndex( (short)5 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(NumberFormatIndexRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java deleted file mode 100644 index cd0b87bbc8..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the ObjectLinkRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestObjectLinkRecord { - byte[] data = new byte[] { - (byte)0x03,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00 - }; - - @Test - void testLoad() { - ObjectLinkRecord record = new ObjectLinkRecord(TestcaseRecordInputStream.create(0x1027, data)); - - assertEquals( (short)3, record.getAnchorId()); - assertEquals( (short)0x00, record.getLink1()); - assertEquals( (short)0x00, record.getLink2()); - - assertEquals( 10, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - ObjectLinkRecord record = new ObjectLinkRecord(); - - record.setAnchorId( (short)3 ); - record.setLink1( (short)0x00 ); - record.setLink2( (short)0x00 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(ObjectLinkRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java deleted file mode 100644 index 2c9d42a8dc..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the PlotAreaRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestPlotAreaRecord { - byte[] data = new byte[] { - - }; - - @Test - void testLoad() { - PlotAreaRecord record = new PlotAreaRecord(TestcaseRecordInputStream.create(0x1035, data)); - - assertEquals( 4, record.getRecordSize() ); - } - - @Test - void testStore() { - PlotAreaRecord record = new PlotAreaRecord(); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java deleted file mode 100644 index 30435c76b7..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the PlotGrowthRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestPlotGrowthRecord { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00,(byte)0x01,(byte)0x00, // horizontal - (byte)0x00,(byte)0x00,(byte)0x01,(byte)0x00 // vertical - }; - - @Test - void testLoad() { - - PlotGrowthRecord record = new PlotGrowthRecord(TestcaseRecordInputStream.create(0x1064, data)); - assertEquals( 65536, record.getHorizontalScale()); - assertEquals( 65536, record.getVerticalScale()); - - assertEquals( 12, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - PlotGrowthRecord record = new PlotGrowthRecord(); - record.setHorizontalScale( 65536 ); - record.setVerticalScale( 65536 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(PlotGrowthRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java deleted file mode 100644 index 1c6e886c90..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the SeriesChartGroupIndexRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestSeriesChartGroupIndexRecord { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00 - }; - - @Test - void testLoad() { - SeriesChartGroupIndexRecord record = new SeriesChartGroupIndexRecord(TestcaseRecordInputStream.create(0x1045, data)); - assertEquals( 0, record.getChartGroupIndex()); - - assertEquals( 6, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - SeriesChartGroupIndexRecord record = new SeriesChartGroupIndexRecord(); - record.setChartGroupIndex( (short)0 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(SeriesChartGroupIndexRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java deleted file mode 100644 index b4bad1d191..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the SeriesIndexRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestSeriesIndexRecord { - byte[] data = new byte[] { - (byte)0x03,(byte)0x00 - }; - - @Test - void testLoad() { - SeriesIndexRecord record = new SeriesIndexRecord(TestcaseRecordInputStream.create(0x1065, data)); - - assertEquals( (short)3, record.getIndex()); - assertEquals( 6, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - SeriesIndexRecord record = new SeriesIndexRecord(); - record.setIndex( (short)3 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(SeriesIndexRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java deleted file mode 100644 index f20184d3ba..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the SeriesLabelsRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestSeriesLabelsRecord { - byte[] data = new byte[] { - (byte)0x03,(byte)0x00 - }; - - @Test - void testLoad() { - SeriesLabelsRecord record = new SeriesLabelsRecord(TestcaseRecordInputStream.create(0x100c, data)); - assertEquals( 3, record.getFormatFlags()); - assertTrue(record.isShowActual()); - assertTrue(record.isShowPercent()); - assertFalse(record.isLabelAsPercentage()); - assertFalse(record.isSmoothedLine()); - assertFalse(record.isShowLabel()); - assertFalse(record.isShowBubbleSizes()); - - assertEquals( 2+4, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - SeriesLabelsRecord record = new SeriesLabelsRecord(); - record.setShowActual( true ); - record.setShowPercent( true ); - record.setLabelAsPercentage( false ); - record.setSmoothedLine( false ); - record.setShowLabel( false ); - record.setShowBubbleSizes( false ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(SeriesLabelsRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java deleted file mode 100644 index b75c579147..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the SeriesListRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestSeriesListRecord { - private static final byte[] data = { - (byte)0x02,(byte)0x00,(byte)0x01,(byte)0x20,(byte)0xff,(byte)0xf0 - }; - - @Test - void testLoad() { - - SeriesListRecord record = new SeriesListRecord(TestcaseRecordInputStream.create(0x1016, data)); - assertEquals( (short)0x2001, record.getSeriesNumbers()[0]); - assertEquals( (short)0xf0ff, record.getSeriesNumbers()[1]); - assertEquals( 2, record.getSeriesNumbers().length); - - assertEquals( 4 + 6, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - SeriesListRecord record = new SeriesListRecord(new short[] { (short)0x2001, (short)0xf0ff } ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(SeriesListRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java deleted file mode 100644 index 8aac948d0c..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the SeriesRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestSeriesRecord { - byte[] data = new byte[] { - (byte)0x01,(byte)0x00, // category data type - (byte)0x01,(byte)0x00, // values data type - (byte)0x1B,(byte)0x00, // num categories - (byte)0x1B,(byte)0x00, // num values - (byte)0x01,(byte)0x00, // bubble series type - (byte)0x00,(byte)0x00 // num bubble values - }; - - @Test - void testLoad() { - SeriesRecord record = new SeriesRecord(TestcaseRecordInputStream.create(0x1003, data)); - assertEquals( SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC, record.getCategoryDataType()); - assertEquals( SeriesRecord.VALUES_DATA_TYPE_NUMERIC, record.getValuesDataType()); - assertEquals( 27, record.getNumCategories()); - assertEquals( 27, record.getNumValues()); - assertEquals( SeriesRecord.BUBBLE_SERIES_TYPE_NUMERIC, record.getBubbleSeriesType()); - assertEquals( 0, record.getNumBubbleValues()); - - - assertEquals( 16, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - SeriesRecord record = new SeriesRecord(); - record.setCategoryDataType( SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC ); - record.setValuesDataType( SeriesRecord.VALUES_DATA_TYPE_NUMERIC ); - record.setNumCategories( (short)27 ); - record.setNumValues( (short)27 ); - record.setBubbleSeriesType( SeriesRecord.BUBBLE_SERIES_TYPE_NUMERIC ); - record.setNumBubbleValues( (short)0 ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(SeriesRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java deleted file mode 100644 index 6e56904996..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - 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.record.chart; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the SeriesTextRecord class - * works correctly. Test data taken directly from a real Excel file. - */ -final class TestSeriesTextRecord { - private static final byte[] SIMPLE_DATA = HexRead - .readFromString("00 00 0C 00 56 61 6C 75 65 20 4E 75 6D 62 65 72"); - - @Test - void testLoad() { - SeriesTextRecord record = new SeriesTextRecord(TestcaseRecordInputStream.create(0x100d, SIMPLE_DATA)); - - assertEquals((short) 0, record.getId()); - assertEquals("Value Number", record.getText()); - - assertEquals(SIMPLE_DATA.length + 4, record.getRecordSize()); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - SeriesTextRecord record = new SeriesTextRecord(); - - record.setId(0); - record.setText("Value Number"); - - byte[] recordBytes = record.serialize(); - confirmRecordEncoding(SeriesTextRecord.sid, SIMPLE_DATA, recordBytes); - } - - @Test - void testReserializeLongTitle() { - // Hex dump from bug 45784 attachment 22560 streamOffset=0x0CD1 - byte[] data = HexRead.readFromString( - "00 00, " - + "82 " - + "01 " - + "50 00 6C 00 61 00 73 00 6D 00 61 00 20 00 4C 00 " - + "65 00 76 00 65 00 6C 00 73 00 20 00 6F 00 66 00 " - + "20 00 4C 00 2D 00 30 00 30 00 30 00 31 00 31 00 " - + "31 00 32 00 32 00 32 00 2D 00 33 00 33 00 33 00 " - + "58 00 34 00 34 00 34 00 20 00 69 00 6E 00 20 00 " - + "53 00 44 00 20 00 72 00 61 00 74 00 0A 00 50 00 " - + "4F 00 20 00 33 00 2E 00 30 00 20 00 6D 00 67 00 " - + "2F 00 6B 00 67 00 20 00 28 00 35 00 2E 00 30 00 " - + "20 00 6D 00 4C 00 2F 00 6B 00 67 00 29 00 20 00 " - + "69 00 6E 00 20 00 4D 00 65 00 74 00 68 00 6F 00 " - + "63 00 65 00 6C 00 0A 00 49 00 56 00 20 00 30 00 " - + "2E 00 35 00 20 00 6D 00 67 00 2F 00 6B 00 67 00 " - + "20 00 28 00 31 00 2E 00 30 00 20 00 6D 00 4C 00 " - + "2F 00 6B 00 67 00 29 00 20 00 69 00 6E 00 20 00 " - + "36 00 30 00 25 00 20 00 50 00 45 00 47 00 20 00 " - + "32 00 30 00 30 00 0A 00 46 00 20 00 3D 00 61 00 " - + "62 00 63 00"); - - RecordInputStream in = TestcaseRecordInputStream.create(SeriesTextRecord.sid, data); - // Identified bug 45784a - // 'would be' error msg changed at svn r703620 - // "Illegal length - asked for -126 but only 130 left!" - // "Bad requested string length (-126)" - SeriesTextRecord str = new SeriesTextRecord(in); - - assertTrue(str.getRecordSize() >= 0, "Identified bug 45784b"); - byte[] ser = str.serialize(); - confirmRecordEncoding(SeriesTextRecord.sid, data, ser); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.java deleted file mode 100644 index 21f03302c6..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link SheetPropertiesRecord} - * Test data taken directly from a real Excel file. - */ -final class TestSheetPropertiesRecord { - private static final byte[] data = { - (byte)0x0A,(byte)0x00, - (byte)0x00, - (byte)0x00, // not sure where that last byte comes from - }; - - @Test - void testLoad() { - RecordInputStream in = TestcaseRecordInputStream.create(0x1044, data); - SheetPropertiesRecord record = new SheetPropertiesRecord(in); - assertNotEquals(1, in.remaining(), "Identified bug 44693c"); - assertEquals(0, in.remaining()); - assertEquals( 10, record.getFlags()); - assertFalse(record.isChartTypeManuallyFormatted()); - assertTrue(record.isPlotVisibleOnly()); - assertFalse(record.isDoNotSizeWithWindow()); - assertTrue(record.isDefaultPlotDimensions()); - assertFalse(record.isAutoPlotArea()); - assertEquals( 0, record.getEmpty()); - - assertEquals( 8, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - SheetPropertiesRecord record = new SheetPropertiesRecord(); - record.setChartTypeManuallyFormatted( false ); - record.setPlotVisibleOnly( true ); - record.setDoNotSizeWithWindow( false ); - record.setDefaultPlotDimensions( true ); - record.setAutoPlotArea( false ); - record.setEmpty( (byte)0 ); - - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(SheetPropertiesRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java deleted file mode 100644 index 7628d9ce4f..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the TextRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestTextRecord { - byte[] data = new byte[] { - (byte)0x02, // horiz align - (byte)0x02, // vert align - (byte)0x01,(byte)0x00, // display mode - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // rgb color - (byte)0xD6,(byte)0xFF,(byte)0xFF,(byte)0xFF, // x - (byte)0xC4,(byte)0xFF,(byte)0xFF,(byte)0xFF, // y - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // width - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // height - (byte)0xB1,(byte)0x00, // options 1 - (byte)0x4D,(byte)0x00, // index of color value - (byte)0x50,(byte)0x2B, // options 2 -- strange upper bits supposed to be 0'd - (byte)0x00,(byte)0x00 // text rotation - }; - - @Test - void testLoad() { - TextRecord record = new TextRecord(TestcaseRecordInputStream.create(0x1025, data)); - assertEquals( TextRecord.HORIZONTAL_ALIGNMENT_CENTER, record.getHorizontalAlignment()); - assertEquals( TextRecord.VERTICAL_ALIGNMENT_CENTER, record.getVerticalAlignment()); - assertEquals( TextRecord.DISPLAY_MODE_TRANSPARENT, record.getDisplayMode()); - assertEquals( 0, record.getRgbColor()); - assertEquals( -42, record.getX()); - assertEquals( -60, record.getY()); - assertEquals( 0, record.getWidth()); - assertEquals( 0, record.getHeight()); - assertEquals( 177, record.getOptions1()); - assertTrue(record.isAutoColor()); - assertFalse(record.isShowKey()); - assertFalse(record.isShowValue()); - assertFalse(record.isVertical()); - assertTrue(record.isAutoGeneratedText()); - assertTrue(record.isGenerated()); - assertFalse(record.isAutoLabelDeleted()); - assertTrue(record.isAutoBackground()); - assertEquals( TextRecord.ROTATION_NONE, record.getRotation() ); - assertFalse(record.isShowCategoryLabelAsPercentage()); - assertFalse(record.isShowValueAsPercentage()); - assertFalse(record.isShowBubbleSizes()); - assertFalse(record.isShowLabel()); - assertEquals( 77, record.getIndexOfColorValue()); - assertEquals( 11088, record.getOptions2()); - assertEquals( 0, record.getDataLabelPlacement() ); - assertEquals( 0, record.getTextRotation()); - - - assertEquals( 36, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - TextRecord record = new TextRecord(); - record.setHorizontalAlignment( TextRecord.HORIZONTAL_ALIGNMENT_CENTER ); - record.setVerticalAlignment( TextRecord.VERTICAL_ALIGNMENT_CENTER ); - record.setDisplayMode( TextRecord.DISPLAY_MODE_TRANSPARENT ); - record.setRgbColor( 0 ); - record.setX( -42 ); - record.setY( -60 ); - record.setWidth( 0 ); - record.setHeight( 0 ); - record.setAutoColor( true ); - record.setShowKey( false ); - record.setShowValue( false ); - record.setVertical( false ); - record.setAutoGeneratedText( true ); - record.setGenerated( true ); - record.setAutoLabelDeleted( false ); - record.setAutoBackground( true ); - record.setRotation( TextRecord.ROTATION_NONE ); - record.setShowCategoryLabelAsPercentage( false ); - record.setShowValueAsPercentage( false ); - record.setShowBubbleSizes( false ); - record.setShowLabel( false ); - record.setIndexOfColorValue( (short)77 ); - record.setOptions2( (short)0x2b50 ); -// record.setDataLabelPlacement( (short)0x2b50 ); - record.setTextRotation( (short)0 ); - - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(TextRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java deleted file mode 100644 index dc1a0405bd..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the TickRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestTickRecord { - private static final byte[] data = { - (byte)0x02, (byte)0x00, (byte)0x03, (byte)0x01, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x23, (byte)0x00, - (byte)0x4D, (byte)0x00, (byte)0x00, (byte)0x00 - }; - - @Test - void testLoad() { - TickRecord record = new TickRecord(TestcaseRecordInputStream.create(0x101e, data)); - assertEquals( (byte)2, record.getMajorTickType()); - assertEquals( (byte)0, record.getMinorTickType()); - assertEquals( (byte)3, record.getLabelPosition()); - assertEquals( (short)1, record.getBackground()); - assertEquals( 0, record.getLabelColorRgb()); - assertEquals( (short)0, record.getZero1()); - assertEquals( (short)0, record.getZero2()); - assertEquals( (short)35, record.getOptions()); - assertTrue(record.isAutoTextColor()); - assertTrue(record.isAutoTextBackground()); - assertEquals( (short)0x0, record.getRotation() ); - assertTrue(record.isAutorotate()); - assertEquals( (short)77, record.getTickColor()); - assertEquals( (short)0x0, record.getZero3()); - - - assertEquals( 34, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - TickRecord record = new TickRecord(); - record.setMajorTickType( (byte)2 ); - record.setMinorTickType( (byte)0 ); - record.setLabelPosition( (byte)3 ); - record.setBackground( (byte)1 ); - record.setLabelColorRgb( 0 ); - record.setZero1( (short)0 ); - record.setZero2( (short)0 ); - record.setOptions( (short)35 ); - record.setAutoTextColor( true ); - record.setAutoTextBackground( true ); - record.setRotation( (short)0 ); - record.setAutorotate( true ); - record.setTickColor( (short)77 ); - record.setZero3( (short)0 ); - - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(TickRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java deleted file mode 100644 index 8d1294fa9b..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the UnitsRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestUnitsRecord { - byte[] data = new byte[] { - (byte)0x00, (byte)0x00 - }; - - @Test - void testLoad() { - - UnitsRecord record = new UnitsRecord(TestcaseRecordInputStream.create(0x1001, data)); - assertEquals( 0, record.getUnits()); - - assertEquals( 6, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - UnitsRecord record = new UnitsRecord(); - record.setUnits( (short)0 ); - - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(UnitsRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java deleted file mode 100644 index 0dc470d417..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - 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.record.chart; - - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Tests the serialization and deserialization of the ValueRangeRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -final class TestValueRangeRecord { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // min axis value - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // max axis value - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // major increment - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // minor increment - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // cross over - (byte)0x1F,(byte)0x01 // options - }; - - @Test - void testLoad() { - - ValueRangeRecord record = new ValueRangeRecord(TestcaseRecordInputStream.create(0x101f, data)); - assertEquals( 0.0, record.getMinimumAxisValue(), 0.001); - assertEquals( 0.0, record.getMaximumAxisValue(), 0.001); - assertEquals( 0.0, record.getMajorIncrement(), 0.001); - assertEquals( 0.0, record.getMinorIncrement(), 0.001); - assertEquals( 0.0, record.getCategoryAxisCross(), 0.001); - assertEquals( 0x011f, record.getOptions()); - assertTrue(record.isAutomaticMinimum()); - assertTrue(record.isAutomaticMaximum()); - assertTrue(record.isAutomaticMajor()); - assertTrue(record.isAutomaticMinor()); - assertTrue(record.isAutomaticCategoryCrossing()); - assertFalse(record.isLogarithmicScale()); - assertFalse(record.isValuesInReverse()); - assertFalse(record.isCrossCategoryAxisAtMaximum()); - assertTrue(record.isReserved()); - - assertEquals( 42+4, record.getRecordSize() ); - } - - @SuppressWarnings("squid:S2699") - @Test - void testStore() { - ValueRangeRecord record = new ValueRangeRecord(); - record.setMinimumAxisValue( 0 ); - record.setMaximumAxisValue( 0 ); - record.setMajorIncrement( 0 ); - record.setMinorIncrement( 0 ); - record.setCategoryAxisCross( 0 ); - record.setAutomaticMinimum( true ); - record.setAutomaticMaximum( true ); - record.setAutomaticMajor( true ); - record.setAutomaticMinor( true ); - record.setAutomaticCategoryCrossing( true ); - record.setLogarithmicScale( false ); - record.setValuesInReverse( false ); - record.setCrossCategoryAxisAtMaximum( false ); - record.setReserved( true ); - - byte [] recordBytes = record.serialize(); - confirmRecordEncoding(ValueRangeRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java b/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java deleted file mode 100644 index 45151b90ff..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java +++ /dev/null @@ -1,447 +0,0 @@ -/* ==================================================================== - 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.record.common; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.hssf.record.ContinueRecord; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.SSTRecord; -import org.apache.poi.hssf.record.cont.ContinuableRecordOutput; -import org.apache.poi.hssf.usermodel.HSSFOptimiser; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; -import org.apache.poi.util.LittleEndianConsts; -import org.apache.poi.util.LittleEndianInput; -import org.apache.poi.util.LittleEndianInputStream; -import org.apache.poi.util.LittleEndianOutputStream; -import org.apache.poi.util.StringUtil; -import org.junit.jupiter.api.Test; - -/** - * Tests that {@link UnicodeString} record size calculates correctly. The record size - * is used when serializing {@link SSTRecord}s. - * - * @author Jason Height (jheight at apache.org) - */ -final class TestUnicodeString { - private static final int MAX_DATA_SIZE = RecordInputStream.MAX_RECORD_DATA_SIZE; - - /** a 4 character string requiring 16 bit encoding */ - private static final String STR_16_BIT = "A\u591A\u8A00\u8A9E"; - - private static void confirmSize(int expectedSize, UnicodeString s) { - confirmSize(expectedSize, s, 0); - } - - /** - * Note - a value of zero for amountUsedInCurrentRecord would only ever occur just - * after a {@link ContinueRecord} had been started. In the initial {@link SSTRecord} this - * value starts at 8 (for the first {@link UnicodeString} written). In general, it can be - * any value between 0 and {@link #MAX_DATA_SIZE} - */ - private static void confirmSize(int expectedSize, UnicodeString s, int amountUsedInCurrentRecord) { - ContinuableRecordOutput out = ContinuableRecordOutput.createForCountingOnly(); - out.writeContinue(); - for(int i=amountUsedInCurrentRecord; i>0; i--) { - out.writeByte(0); - } - int size0 = out.getTotalSize(); - s.serialize(out); - int size1 = out.getTotalSize(); - int actualSize = size1-size0; - assertEquals(expectedSize, actualSize); - } - - @Test - void smallStringSize() { - //Test a basic string - UnicodeString s = makeUnicodeString("Test"); - confirmSize(7, s); - - //Test a small string that is uncompressed - s = makeUnicodeString(STR_16_BIT); - s.setOptionFlags((byte)0x01); - confirmSize(11, s); - - //Test a compressed small string that has rich text formatting - s.setString("Test"); - s.setOptionFlags((byte)0x8); - FormatRun r = new FormatRun((short)0,(short)1); - s.addFormatRun(r); - FormatRun r2 = new FormatRun((short)2,(short)2); - s.addFormatRun(r2); - confirmSize(17, s); - - //Test a uncompressed small string that has rich text formatting - s.setString(STR_16_BIT); - s.setOptionFlags((byte)0x9); - confirmSize(21, s); - - //Test a compressed small string that has rich text and extended text - s.setString("Test"); - s.setOptionFlags((byte)0xC); - confirmSize(17, s); - - // Extended phonetics data - // Minimum size is 14 - // Also adds 4 bytes to hold the length - s.setExtendedRst( - new ExtRst() - ); - confirmSize(35, s); - - //Test a uncompressed small string that has rich text and extended text - s.setString(STR_16_BIT); - s.setOptionFlags((byte)0xD); - confirmSize(39, s); - - s.setExtendedRst(null); - confirmSize(21, s); - } - - @Test - void perfectStringSize() { - //Test a basic string - UnicodeString s = makeUnicodeString(MAX_DATA_SIZE-2-1); - confirmSize(MAX_DATA_SIZE, s); - - //Test an uncompressed string - //Note that we can only ever get to a maximim size of 8227 since an uncompressed - //string is writing double bytes. - s = makeUnicodeString((MAX_DATA_SIZE-2-1)/2, true); - s.setOptionFlags((byte)0x1); - confirmSize(MAX_DATA_SIZE-1, s); - } - - @Test - void perfectRichStringSize() { - //Test a rich text string - UnicodeString s = makeUnicodeString(MAX_DATA_SIZE-2-1-8-2); - s.addFormatRun(new FormatRun((short)1,(short)0)); - s.addFormatRun(new FormatRun((short)2,(short)1)); - s.setOptionFlags((byte)0x8); - confirmSize(MAX_DATA_SIZE, s); - - //Test an uncompressed rich text string - //Note that we can only ever get to a maximum size of 8227 since an uncompressed - //string is writing double bytes. - s = makeUnicodeString((MAX_DATA_SIZE-2-1-8-2)/2, true); - s.addFormatRun(new FormatRun((short)1,(short)0)); - s.addFormatRun(new FormatRun((short)2,(short)1)); - s.setOptionFlags((byte)0x9); - confirmSize(MAX_DATA_SIZE-1, s); - } - - @Test - void continuedStringSize() { - //Test a basic string - UnicodeString s = makeUnicodeString(MAX_DATA_SIZE-2-1+20); - confirmSize(MAX_DATA_SIZE+4+1+20, s); - } - - /** Tests that a string size calculation that fits neatly in two records, the second being a continue*/ - @Test - void perfectContinuedStringSize() { - //Test a basic string - int strSize = MAX_DATA_SIZE*2; - //String overhead - strSize -= 3; - //Continue Record overhead - strSize -= 4; - //Continue Record additional byte overhead - strSize -= 1; - UnicodeString s = makeUnicodeString(strSize); - confirmSize(MAX_DATA_SIZE*2, s); - } - - @Test - void formatRun() { - FormatRun fr = new FormatRun((short)4, (short)0x15c); - assertEquals(4, fr.getCharacterPos()); - assertEquals(0x15c, fr.getFontIndex()); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - LittleEndianOutputStream out = new LittleEndianOutputStream(baos); - - fr.serialize(out); - - byte[] b = baos.toByteArray(); - assertEquals(4, b.length); - assertEquals(4, b[0]); - assertEquals(0, b[1]); - assertEquals(0x5c, b[2]); - assertEquals(0x01, b[3]); - - LittleEndianInputStream inp = new LittleEndianInputStream( - new ByteArrayInputStream(b) - ); - fr = new FormatRun(inp); - assertEquals(4, fr.getCharacterPos()); - assertEquals(0x15c, fr.getFontIndex()); - } - - @Test - void extRstFromEmpty() { - ExtRst ext = new ExtRst(); - - assertEquals(0, ext.getNumberOfRuns()); - assertEquals(0, ext.getFormattingFontIndex()); - assertEquals(0, ext.getFormattingOptions()); - assertEquals("", ext.getPhoneticText()); - assertEquals(0, ext.getPhRuns().length); - assertEquals(10, ext.getDataSize()); // Excludes 4 byte header - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - LittleEndianOutputStream out = new LittleEndianOutputStream(baos); - ContinuableRecordOutput cout = new ContinuableRecordOutput(out, 0xffff); - - ext.serialize(cout); - cout.writeContinue(); - - byte[] b = baos.toByteArray(); - assertEquals(20, b.length); - - // First 4 bytes from the outputstream - assertEquals(-1, b[0]); - assertEquals(-1, b[1]); - assertEquals(14, b[2]); - assertEquals(0, b[3]); - - // Reserved - assertEquals(1, b[4]); - assertEquals(0, b[5]); - // Data size - assertEquals(10, b[6]); - assertEquals(0, b[7]); - // Font*2 - assertEquals(0, b[8]); - assertEquals(0, b[9]); - assertEquals(0, b[10]); - assertEquals(0, b[11]); - // 0 Runs - assertEquals(0, b[12]); - assertEquals(0, b[13]); - // Size=0, *2 - assertEquals(0, b[14]); - assertEquals(0, b[15]); - assertEquals(0, b[16]); - assertEquals(0, b[17]); - - // Last 2 bytes from the outputstream - assertEquals(ContinueRecord.sid, b[18]); - assertEquals(0, b[19]); - - - // Load in again and re-test - byte[] data = Arrays.copyOfRange(b, 4, 4+14); - LittleEndianInputStream inp = new LittleEndianInputStream(new ByteArrayInputStream(data)); - ext = new ExtRst(inp, data.length); - - assertEquals(0, ext.getNumberOfRuns()); - assertEquals(0, ext.getFormattingFontIndex()); - assertEquals(0, ext.getFormattingOptions()); - assertEquals("", ext.getPhoneticText()); - assertEquals(0, ext.getPhRuns().length); - } - - @Test - void extRstFromData() { - byte[] data = new byte[] { - 1, 0, 0x0C, 0, - 0, 0, 0x37, 0, - 0, 0, - 0, 0, 0, 0, - 0, 0 // Cruft at the end, as found from real files - }; - assertEquals(16, data.length); - - LittleEndianInputStream inp = new LittleEndianInputStream( - new ByteArrayInputStream(data) - ); - ExtRst ext = new ExtRst(inp, data.length); - assertEquals(0x0c, ext.getDataSize()); // Excludes 4 byte header - - assertEquals(0, ext.getNumberOfRuns()); - assertEquals(0x37, ext.getFormattingOptions()); - assertEquals(0, ext.getFormattingFontIndex()); - assertEquals("", ext.getPhoneticText()); - assertEquals(0, ext.getPhRuns().length); - } - - @Test - void corruptExtRstDetection() { - byte[] data = new byte[] { - 0x79, 0x79, 0x11, 0x11, - 0x22, 0x22, 0x33, 0x33, - }; - assertEquals(8, data.length); - - LittleEndianInputStream inp = new LittleEndianInputStream( - new ByteArrayInputStream(data) - ); - ExtRst ext = new ExtRst(inp, data.length); - - // Will be empty - assertEquals(ext, new ExtRst()); - - // If written, will be the usual size - assertEquals(10, ext.getDataSize()); // Excludes 4 byte header - - // Is empty - assertEquals(0, ext.getNumberOfRuns()); - assertEquals(0, ext.getFormattingOptions()); - assertEquals(0, ext.getFormattingFontIndex()); - assertEquals("", ext.getPhoneticText()); - assertEquals(0, ext.getPhRuns().length); - } - - @Test - void extRstEqualsAndHashCode() { - byte[] buf = new byte[200]; - LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(buf, 0); - String str = "\u1d02\u1d12\u1d22"; - bos.writeShort(1); - bos.writeShort(5*LittleEndianConsts.SHORT_SIZE+str.length()*2+3*LittleEndianConsts.SHORT_SIZE+2); // data size - bos.writeShort(0x4711); - bos.writeShort(0x0815); - bos.writeShort(1); - bos.writeShort(str.length()); - bos.writeShort(str.length()); - StringUtil.putUnicodeLE(str, bos); - bos.writeShort(1); - bos.writeShort(1); - bos.writeShort(3); - bos.writeShort(42); - - LittleEndianInput in = new LittleEndianByteArrayInputStream(buf, 0, bos.getWriteIndex()); - ExtRst extRst1 = new ExtRst(in, bos.getWriteIndex()); - in = new LittleEndianByteArrayInputStream(buf, 0, bos.getWriteIndex()); - ExtRst extRst2 = new ExtRst(in, bos.getWriteIndex()); - - assertEquals(extRst1, extRst2); - assertEquals(extRst1.hashCode(), extRst2.hashCode()); - } - - @Test - void unicodeStringsNullPointer() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - - Sheet sheet = wb.createSheet("styles"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellStyle style = wb.createCellStyle(); - style.setFont(wb.createFont()); - cell.setCellStyle(style); - - cell.setCellValue("test"); - - assertDoesNotThrow(() -> HSSFOptimiser.optimiseFonts(wb)); - } - } - - @Test - void copyExtRst() { - ExtRst ext = new ExtRst(); - - assertEquals(0, ext.getNumberOfRuns()); - assertEquals(0, ext.getFormattingFontIndex()); - assertEquals(0, ext.getFormattingOptions()); - assertEquals("", ext.getPhoneticText()); - assertEquals(0, ext.getPhRuns().length); - assertEquals(10, ext.getDataSize()); // Excludes 4 byte header - - ExtRst copied = ext.copy(); - - assertEquals(0, copied.getNumberOfRuns()); - assertEquals(0, copied.getFormattingFontIndex()); - assertEquals(0, copied.getFormattingOptions()); - assertEquals("", copied.getPhoneticText()); - assertEquals(0, copied.getPhRuns().length); - assertEquals(10, copied.getDataSize()); - } - - @Test - void copyExtRstFromData() { - byte[] data = new byte[]{ - 1, 0, 0x0C, 0, - 0, 0, 0x37, 0, - 0, 0, - 0, 0, 0, 0, - 0, 0 // Cruft at the end, as found from real files - }; - assertEquals(16, data.length); - - LittleEndianInputStream inp = new LittleEndianInputStream( - new ByteArrayInputStream(data) - ); - ExtRst ext = new ExtRst(inp, data.length); - assertEquals(0x0c, ext.getDataSize()); // Excludes 4 byte header - - assertEquals(0, ext.getNumberOfRuns()); - assertEquals(0x37, ext.getFormattingOptions()); - assertEquals(0, ext.getFormattingFontIndex()); - assertEquals("", ext.getPhoneticText()); - assertEquals(0, ext.getPhRuns().length); - - ExtRst copied = ext.copy(); - assertEquals(10, copied.getDataSize()); // Excludes 4 byte header - - assertEquals(0, copied.getNumberOfRuns()); - assertEquals(0x37, copied.getFormattingOptions()); - assertEquals(0, copied.getFormattingFontIndex()); - assertEquals("", copied.getPhoneticText()); - assertEquals(0, copied.getPhRuns().length); - } - - private static UnicodeString makeUnicodeString(String s) { - UnicodeString st = new UnicodeString(s); - st.setOptionFlags((byte)0); - return st; - } - - private static UnicodeString makeUnicodeString(int numChars) { - return makeUnicodeString(numChars, false); - } - - /** - * @param is16Bit if true the created string will have characters > 0x00FF - * @return a string of the specified number of characters - */ - private static UnicodeString makeUnicodeString(int numChars, boolean is16Bit) { - StringBuilder b = new StringBuilder(numChars); - int charBase = is16Bit ? 0x8A00 : 'A'; - for (int i = 0; i < numChars; i++) { - char ch = (char) ((i % 16) + charBase); - b.append(ch); - } - return makeUnicodeString(b.toString()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java deleted file mode 100644 index 3cfe1dc277..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - 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.record.pivot; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.record.pivottable.ExtendedPivotTableViewFieldsRecord; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link ExtendedPivotTableViewFieldsRecord} - */ -final class TestExtendedPivotTableViewFieldsRecord { - - @Test - void testSubNameNotPresent_bug46693() { - // This data came from attachment 23347 of bug 46693 at offset 0xAA43 - byte[] data = HexRead.readFromString( - "00 01 14 00" + // BIFF header - "1E 14 00 0A FF FF FF FF 00 00 FF FF 00 00 00 00 00 00 00 00"); - RecordInputStream in = TestcaseRecordInputStream.create(data); - // bug 46693a - Expected to find a ContinueRecord in order to read remaining 65535 of 65535 chars - ExtendedPivotTableViewFieldsRecord rec = new ExtendedPivotTableViewFieldsRecord(in); - - assertEquals(data.length, rec.getRecordSize()); - } - - @SuppressWarnings("squid:S2699") - @Test - void testOlderFormat_bug46918() { - // There are 10 SXVDEX records in the file (not uploaded) that originated bugzilla 46918 - // They all had the following hex encoding: - byte[] data = HexRead.readFromString("00 01 0A 00 1E 14 00 0A FF FF FF FF 00 00"); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - // bug 46918 - Not enough data (0) to read requested (2) bytes - ExtendedPivotTableViewFieldsRecord rec = new ExtendedPivotTableViewFieldsRecord(in); - - byte[] expReserData = HexRead.readFromString("1E 14 00 0A FF FF FF FF 00 00" + - "FF FF 00 00 00 00 00 00 00 00"); - - confirmRecordEncoding(ExtendedPivotTableViewFieldsRecord.sid, expReserData, rec.serialize()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java deleted file mode 100644 index ff6ac5d019..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - 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.record.pivot; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.record.pivottable.PageItemRecord; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link PageItemRecord} - */ -final class TestPageItemRecord { - @Test - void testMoreThanOneInfoItem_bug46917() { - byte[] data = HexRead.readFromString("01 02 03 04 05 06 07 08 09 0A 0B 0C"); - RecordInputStream in = TestcaseRecordInputStream.create(PageItemRecord.sid, data); - PageItemRecord rec = new PageItemRecord(in); - assertNotEquals(6, in.remaining(), "Identified bug 46917"); - assertEquals(0, in.remaining()); - - assertEquals(4+data.length, rec.getRecordSize()); - } - - @Test - void testSerialize() { - confirmSerialize("01 02 03 04 05 06"); - confirmSerialize("01 02 03 04 05 06 07 08 09 0A 0B 0C"); - confirmSerialize("01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12"); - } - - private static void confirmSerialize(String hexDump) { - byte[] data = HexRead.readFromString(hexDump); - RecordInputStream in = TestcaseRecordInputStream.create(PageItemRecord.sid, data); - PageItemRecord rec = new PageItemRecord(in); - assertEquals(0, in.remaining()); - assertEquals(4+data.length, rec.getRecordSize()); - byte[] data2 = rec.serialize(); - confirmRecordEncoding(PageItemRecord.sid, data, data2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java deleted file mode 100644 index ee05e1a4f4..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - 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.record.pivot; - -import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.record.pivottable.ViewFieldsRecord; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link ViewFieldsRecord} - */ -final class TestViewFieldsRecord { - - @Test - void testUnicodeFlag_bug46693() { - byte[] data = HexRead.readFromString("01 00 01 00 01 00 04 00 05 00 00 6D 61 72 63 6F"); - RecordInputStream in = TestcaseRecordInputStream.create(ViewFieldsRecord.sid, data); - ViewFieldsRecord rec = new ViewFieldsRecord(in); - assertNotEquals(1, in.remaining(), "Identified bug 46693b"); - assertEquals(0, in.remaining()); - assertEquals(4+data.length, rec.getRecordSize()); - } - - @Test - void testSerialize() { - // This hex data was produced by changing the 'Custom Name' property, - // available under 'Field Settings' from the 'PivotTable Field List' (Excel 2007) - confirmSerialize("00 00 01 00 01 00 00 00 FF FF"); - confirmSerialize("01 00 01 00 01 00 04 00 05 00 00 6D 61 72 63 6F"); - confirmSerialize("01 00 01 00 01 00 04 00 0A 00 01 48 00 69 00 73 00 74 00 6F 00 72 00 79 00 2D 00 82 69 81 89"); - } - - private static void confirmSerialize(String hexDump) { - byte[] data = HexRead.readFromString(hexDump); - RecordInputStream in = TestcaseRecordInputStream.create(ViewFieldsRecord.sid, data); - ViewFieldsRecord rec = new ViewFieldsRecord(in); - assertEquals(0, in.remaining()); - assertEquals(4+data.length, rec.getRecordSize()); - byte[] data2 = rec.serialize(); - confirmRecordEncoding(ViewFieldsRecord.sid, data, data2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/FormulaExtractor.java b/src/testcases/org/apache/poi/hssf/usermodel/FormulaExtractor.java deleted file mode 100644 index c44b3c0c7b..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/FormulaExtractor.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.record.CellValueRecordInterface; -import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; -import org.apache.poi.ss.formula.ptg.Ptg; - -/** - * Test utility class to get Ptg arrays out of formula cells - * - * @author Josh Micich - */ -public final class FormulaExtractor { - - private FormulaExtractor() { - // no instances of this class - } - - public static Ptg[] getPtgs(HSSFCell cell) { - CellValueRecordInterface vr = cell.getCellValueRecord(); - if (!(vr instanceof FormulaRecordAggregate)) { - throw new IllegalArgumentException("Not a formula cell"); - } - FormulaRecordAggregate fra = (FormulaRecordAggregate) vr; - return fra.getFormulaRecord().getParsedExpression(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/HSSFEvaluationTestHelper.java b/src/testcases/org/apache/poi/hssf/usermodel/HSSFEvaluationTestHelper.java deleted file mode 100644 index 96196c146e..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/HSSFEvaluationTestHelper.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.ss.formula.EvaluationCell; - -/** - * Raises visibility of some internal functionality for test purposes - * - * @author Josh Micich - */ -public final class HSSFEvaluationTestHelper { - - public static EvaluationCell wrapCell(HSSFCell cell) { - return new HSSFEvaluationCell(cell); - } - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/HSSFTestHelper.java b/src/testcases/org/apache/poi/hssf/usermodel/HSSFTestHelper.java deleted file mode 100644 index 20a55c32ab..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/HSSFTestHelper.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.ddf.*; -import org.apache.poi.hssf.model.DrawingManager2; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.record.TextObjectRecord; - -/** - * Helper class for HSSF tests that aren't within the - * HSSF UserModel package, but need to do internal - * UserModel things. - */ -public class HSSFTestHelper { - - public static class MockDrawingManager extends DrawingManager2 { - - public MockDrawingManager (){ - super(null); - } - - @Override - public int allocateShapeId(EscherDgRecord dg) { - return 1025; - } - - @Override - public EscherDgRecord createDgRecord() - { - EscherDgRecord dg = new EscherDgRecord(); - dg.setRecordId( EscherDgRecord.RECORD_ID ); - dg.setOptions( (short) (16) ); - dg.setNumShapes( 1 ); - dg.setLastMSOSPID( 1024 ); - return dg; - } - } - /** - * Lets non UserModel tests at the low level Workbook - */ - public static InternalWorkbook getWorkbookForTest(HSSFWorkbook wb) { - return wb.getWorkbook(); - } - public static InternalSheet getSheetForTest(HSSFSheet sheet) { - return sheet.getSheet(); - } - - public static HSSFPatriarch createTestPatriarch(HSSFSheet sheet, EscherAggregate agg){ - return new HSSFPatriarch(sheet, agg); - } - - public static EscherAggregate getEscherAggregate(HSSFPatriarch patriarch){ - return patriarch.getBoundAggregate(); - } - - public static int allocateNewShapeId(HSSFPatriarch patriarch){ - return patriarch.newShapeId(); - } - - public static EscherOptRecord getOptRecord(HSSFShape shape){ - return shape.getOptRecord(); - } - - public static void setShapeId(HSSFShape shape, int id){ - shape.setShapeId(id); - } - - public static EscherContainerRecord getEscherContainer(HSSFShape shape){ - return shape.getEscherContainer(); - } - - public static TextObjectRecord getTextObjRecord(HSSFSimpleShape shape){ - return shape.getTextObjectRecord(); - } - - public static ObjRecord getObjRecord(HSSFShape shape){ - return shape.getObjRecord(); - } - - public static EscherRecord getEscherAnchor(HSSFAnchor anchor){ - return anchor.getEscherAnchor(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java b/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java deleted file mode 100644 index 22d0676d51..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java +++ /dev/null @@ -1,215 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.List; - -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.*; -import org.apache.poi.hssf.record.aggregates.PageSettingsBlock; - -/** - * Designed to check wither the records written actually make sense. - */ -public class SanityChecker { - static class CheckRecord { - Class record; - char occurance; // 1 = one time, M = 1..many times, * = 0..many, 0 = optional - private final boolean together; - - public CheckRecord(Class record, char occurance) { - this(record, occurance, true); - } - - /** - * @param record The record type to check - * @param occurance The occurance 1 = occurs once, M = occurs many times - * @param together - */ - public CheckRecord(Class record, char occurance, boolean together) { - this.record = record; - this.occurance = occurance; - this.together = together; - } - - public Class getRecord() { - return record; - } - - public boolean isRequired() { - return occurance == '1' || occurance == 'M'; - } - - public boolean isOptional() { - return occurance == '0' || occurance == '*'; - } - - public boolean isMany() { - return occurance == '*' || occurance == 'M'; - } - - public int match(List records, int recordIdx) { - int firstRecord = findFirstRecord(records, getRecord(), recordIdx); - if (isRequired()) { - return matchRequired(firstRecord, records, recordIdx); - } - return matchOptional(firstRecord, records, recordIdx); - } - - private int matchOptional(int firstRecord, List records, int recordIdx) { - if (firstRecord == -1) { - return recordIdx; - } - - return matchOneOrMany(records, firstRecord); - } - - private int matchRequired(int firstRecord, List records, int recordIdx) { - assertNotEquals(-1, firstRecord, "Manditory record missing or out of order: " + record); - - return matchOneOrMany(records, firstRecord); - } - - private int matchOneOrMany(List records, int recordIdx) { - if (isZeroOrOne()) { - // check no other records - assertEquals(-1, findFirstRecord(records, getRecord(), recordIdx + 1), - "More than one record matched for " + getRecord().getName()); - } else if (isZeroToMany()) { - if (together) { - int nextIdx = findFirstRecord(records, record, recordIdx + 1); - while (nextIdx != -1) { - assertEquals(recordIdx+1, nextIdx, "Records are not together " + record.getName()); - recordIdx = nextIdx; - nextIdx = findFirstRecord(records, record, recordIdx + 1); - } - } - } - return recordIdx + 1; - } - - private boolean isZeroToMany() { - return occurance == '*' || occurance == 'M'; - } - - private boolean isZeroOrOne() { - return occurance == '0' || occurance == '1'; - } - } - - CheckRecord[] workbookRecords = { - new CheckRecord(BOFRecord.class, '1'), - new CheckRecord(InterfaceHdrRecord.class, '1'), - new CheckRecord(MMSRecord.class, '1'), - new CheckRecord(InterfaceEndRecord.class, '1'), - new CheckRecord(WriteAccessRecord.class, '1'), - new CheckRecord(CodepageRecord.class, '1'), - new CheckRecord(DSFRecord.class, '1'), - new CheckRecord(TabIdRecord.class, '1'), - new CheckRecord(FnGroupCountRecord.class, '1'), - new CheckRecord(WindowProtectRecord.class, '1'), - new CheckRecord(ProtectRecord.class, '1'), - new CheckRecord(PasswordRev4Record.class, '1'), - new CheckRecord(WindowOneRecord.class, '1'), - new CheckRecord(BackupRecord.class, '1'), - new CheckRecord(HideObjRecord.class, '1'), - new CheckRecord(DateWindow1904Record.class, '1'), - new CheckRecord(PrecisionRecord.class, '1'), - new CheckRecord(RefreshAllRecord.class, '1'), - new CheckRecord(BookBoolRecord.class, '1'), - new CheckRecord(FontRecord.class, 'M'), - new CheckRecord(FormatRecord.class, 'M'), - new CheckRecord(ExtendedFormatRecord.class, 'M'), - new CheckRecord(StyleRecord.class, 'M'), - new CheckRecord(UseSelFSRecord.class, '1'), - new CheckRecord(BoundSheetRecord.class, 'M'), - new CheckRecord(CountryRecord.class, '1'), - new CheckRecord(SupBookRecord.class, '0'), - new CheckRecord(ExternSheetRecord.class, '0'), - new CheckRecord(NameRecord.class, '*'), - new CheckRecord(SSTRecord.class, '1'), - new CheckRecord(ExtSSTRecord.class, '1'), - new CheckRecord(EOFRecord.class, '1'), - }; - - CheckRecord[] sheetRecords = { - new CheckRecord(BOFRecord.class, '1'), - new CheckRecord(CalcModeRecord.class, '1'), - new CheckRecord(RefModeRecord.class, '1'), - new CheckRecord(IterationRecord.class, '1'), - new CheckRecord(DeltaRecord.class, '1'), - new CheckRecord(SaveRecalcRecord.class, '1'), - new CheckRecord(PrintHeadersRecord.class, '1'), - new CheckRecord(PrintGridlinesRecord.class, '1'), - new CheckRecord(GridsetRecord.class, '1'), - new CheckRecord(GutsRecord.class, '1'), - new CheckRecord(DefaultRowHeightRecord.class, '1'), - new CheckRecord(WSBoolRecord.class, '1'), - new CheckRecord(PageSettingsBlock.class, '1'), - new CheckRecord(DefaultColWidthRecord.class, '1'), - new CheckRecord(DimensionsRecord.class, '1'), - new CheckRecord(WindowTwoRecord.class, '1'), - new CheckRecord(SelectionRecord.class, '1'), - new CheckRecord(EOFRecord.class, '1') - }; - - private void checkWorkbookRecords(InternalWorkbook workbook) { - List records = workbook.getRecords(); - assertTrue(records.get(0) instanceof BOFRecord); - assertTrue(records.get(records.size() - 1) instanceof EOFRecord); - - checkRecordOrder(records, workbookRecords); - } - - private void checkSheetRecords(InternalSheet sheet) { - List records = sheet.getRecords(); - assertTrue(records.get(0) instanceof BOFRecord); - assertTrue(records.get(records.size() - 1) instanceof EOFRecord); - - checkRecordOrder(records, sheetRecords); - } - - void checkHSSFWorkbook(HSSFWorkbook wb) { - checkWorkbookRecords(wb.getWorkbook()); - for (int i = 0; i < wb.getNumberOfSheets(); i++) - checkSheetRecords(wb.getSheetAt(i).getSheet()); - - } - - static int findFirstRecord(List records, Class record, int startIndex) { - for (int i = startIndex; i < records.size(); i++) { - if (record.getName().equals(records.get(i).getClass().getName())) - return i; - } - return -1; - } - - void checkRecordOrder(List records, CheckRecord[] check) { - int recordIdx = 0; - for (CheckRecord element : check) { - recordIdx = element.match(records, recordIdx); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/StreamUtility.java b/src/testcases/org/apache/poi/hssf/usermodel/StreamUtility.java deleted file mode 100644 index d467333ffc..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/StreamUtility.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -/** - * Utility class to help test code verify that generated files do not differ from proof copies in - * any significant detail. Normally this task would be simple except for the presence of artifacts - * in the file that change every time it is generated. Usually these volatile artifacts are - * time-stamps, user names, or other machine dependent parameters. - * - * @author Josh Micich - */ -public final class StreamUtility { - - /** - * Compares two streams with expected differences in specified regions. The streams are - * expected to be of equal length and comparison is always byte for byte. That is - - * differences can only involve exchanging each individual byte for another single byte.
- * Both input streams are closed. - * - * @param allowableDifferenceRegions array of integer pairs: (offset, length). - * Any differences encountered in these regions of the streams will be ignored - * @return null if streams are identical, else the - * byte indexes of differing data. If streams were different lengths, - * the returned indexes will be -1 and the length of the shorter stream - */ - public static int[] diffStreams(InputStream isA, InputStream isB, int[] allowableDifferenceRegions) { - - if((allowableDifferenceRegions.length % 2) != 0) { - throw new RuntimeException("allowableDifferenceRegions length is odd"); - } - boolean success = false; - int[] result; - try { - result = diffInternal(isA, isB, allowableDifferenceRegions); - success = true; - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - close(isA, success); - close(isB, success); - } - return result; - } - - /** - * @param success false if the outer method is throwing an exception. - */ - private static void close(InputStream is, boolean success) { - try { - is.close(); - } catch (IOException e) { - if(success) { - // this is a new error. ok to throw - throw new RuntimeException(e); - } - // else don't subvert original exception. just print stack trace for this one - e.printStackTrace(); - } - } - - private static int[] diffInternal(InputStream isA, InputStream isB, int[] allowableDifferenceRegions) - throws IOException { - int offset = 0; - List temp = new ArrayList<>(); - while (true) { - int b = isA.read(); - int b2 = isB.read(); - if (b == -1) { - // EOF - if (b2 == -1) { - return toPrimitiveIntArray(temp); - } - return new int[] { -1, offset, }; - } - if (b2 == -1) { - return new int[] { -1, offset, }; - } - if (b != b2 && !isIgnoredRegion(allowableDifferenceRegions, offset)) { - temp.add(Integer.valueOf(offset)); - } - offset++; - } - } - - private static boolean isIgnoredRegion(int[] allowableDifferenceRegions, int offset) { - for (int i = 0; i < allowableDifferenceRegions.length; i+=2) { - int start = allowableDifferenceRegions[i]; - int end = start + allowableDifferenceRegions[i+1]; - if(start <= offset && offset < end) { - return true; - } - } - return false; - } - - private static int[] toPrimitiveIntArray(List temp) { - int nItems = temp.size(); - if(nItems < 1) { - return null; - } - Integer[] boxInts = new Integer[nItems]; - temp.toArray(boxInts); - - int[] result = new int[nItems]; - for (int i = 0; i < result.length; i++) { - result[i] = boxInts[i].intValue(); - } - return result; - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java b/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java deleted file mode 100644 index 8a3008cb45..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.util.Iterator; - -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.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; - -/** - * - */ -final class TestBug42464 { - - @Test - void testOKFile() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-ok.xls"); - process(wb); - wb.close(); - } - - @Test - void testExpSharedBadFile() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-bad.xls"); - process(wb); - wb.close(); - } - - private static void process(HSSFWorkbook wb) { - HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb); - for(int i=0; i it = s.rowIterator(); - while(it.hasNext()) { - HSSFRow r = (HSSFRow)it.next(); - process(r, eval); - } - } - } - - private static void process(HSSFRow row, HSSFFormulaEvaluator eval) { - Iterator it = row.cellIterator(); - while(it.hasNext()) { - HSSFCell cell = (HSSFCell)it.next(); - if(cell.getCellType() != CellType.FORMULA) { - continue; - } - FormulaRecordAggregate record = (FormulaRecordAggregate) cell.getCellValueRecord(); - FormulaRecord r = record.getFormulaRecord(); - /*Ptg[] ptgs =*/ r.getParsedExpression(); - - /*String cellRef =*/ new CellReference(row.getRowNum(), cell.getColumnIndex(), false, false).formatAsString(); -// if(false && cellRef.equals("BP24")) { // TODO - replace System.out.println()s with asserts -// System.out.print(cellRef); -// System.out.println(" - has " + ptgs.length + " ptgs:"); -// for(int i=0; i " + cell.getCellFormula()); -// } - - CellValue evalResult = eval.evaluate(cell); - assertNotNull(evalResult); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java deleted file mode 100644 index b30f9f71ec..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java +++ /dev/null @@ -1,2607 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook; -import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.jupiter.api.Assertions.*; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.TimeZone; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import javax.imageio.ImageIO; - -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.CellValueRecordInterface; -import org.apache.poi.hssf.record.CommonObjectDataSubRecord; -import org.apache.poi.hssf.record.EmbeddedObjectRefSubRecord; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.TabIdRecord; -import org.apache.poi.hssf.record.UnknownRecord; -import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; -import org.apache.poi.hssf.record.aggregates.PageSettingsBlock; -import org.apache.poi.hssf.record.common.UnicodeString; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.DeletedArea3DPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.apache.poi.ss.usermodel.ComparisonOperator; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.SheetVisibility; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; - -/** - * Testcases for bugs entered in bugzilla - * the Test name contains the bugzilla bug id - *

- * YK: If a bug can be tested in terms of common ss interfaces, - * define the test in the base class {@link BaseTestBugzillaIssues} - */ -final class TestBugs extends BaseTestBugzillaIssues { - - public TestBugs() { - super(HSSFITestDataProvider.instance); - } - - private static final Map SIMPLE_REFS = new LinkedHashMap<>(); - - // References used for the simpleTest convenience method - @BeforeAll - public static void initSimpleRefs() { - String[] refs = { - "Calculations", - "/Documents and Settings/crawformk.EUU/Local Settings/Temporary Internet Files/OLK64/Daily Status Report Generation Files/DST - Daily Data Transfer Sheet - 2002.xls", - "Sheet1", - "/Documents and Settings/donnag/Local Settings/Temporary Internet Files/OLK7/0231324V1-1.xls", - "Sheet1", - "refs/airport.xls", - "Sheet1", - "9http://www.principlesofeconometrics.com/excel/airline.xls", - "Sheet1", - "C:Documents and Settings/Yegor/My Documents/csco.xls", - }; - - for (int i=0; i assertNotNull(wb.getSheetAt(0).getRow(45))); - } - - @Test - void bug24215() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("24215.xls")) { - - for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) { - HSSFSheet sheet = wb.getSheetAt(sheetIndex); - assertNotNull(sheet); - int rows = sheet.getLastRowNum(); - - for (int rowIndex = 0; rowIndex < rows; rowIndex++) { - HSSFRow row = sheet.getRow(rowIndex); - assertNotNull(row); - int cells = row.getLastCellNum(); - - for (int cellIndex = 0; cellIndex < cells; cellIndex++) { - row.getCell(cellIndex); - } - } - } - } - } - - /** - * Tests read and write of Unicode strings in formula results - * bug and testcase submitted by Sompop Kumnoonsate - * The file contains THAI unicode characters. - */ - @Test - void bugUnicodeStringFormulaRead() throws Exception { - - try (HSSFWorkbook w = openSampleWorkbook("25695.xls")) { - - HSSFCell a1 = w.getSheetAt(0).getRow(0).getCell(0); - HSSFCell a2 = w.getSheetAt(0).getRow(0).getCell(1); - HSSFCell b1 = w.getSheetAt(0).getRow(1).getCell(0); - HSSFCell b2 = w.getSheetAt(0).getRow(1).getCell(1); - HSSFCell c1 = w.getSheetAt(0).getRow(2).getCell(0); - HSSFCell c2 = w.getSheetAt(0).getRow(2).getCell(1); - HSSFCell d1 = w.getSheetAt(0).getRow(3).getCell(0); - HSSFCell d2 = w.getSheetAt(0).getRow(3).getCell(1); - - /* - // 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); - - try (HSSFWorkbook rw = writeOutAndReadBack(w)) { - - HSSFCell ra1 = rw.getSheetAt(0).getRow(0).getCell(0); - HSSFCell ra2 = rw.getSheetAt(0).getRow(0).getCell(1); - HSSFCell rb1 = rw.getSheetAt(0).getRow(1).getCell(0); - HSSFCell rb2 = rw.getSheetAt(0).getRow(1).getCell(1); - HSSFCell rc1 = rw.getSheetAt(0).getRow(2).getCell(0); - HSSFCell rc2 = rw.getSheetAt(0).getRow(2).getCell(1); - HSSFCell rd1 = rw.getSheetAt(0).getRow(3).getCell(0); - HSSFCell rd2 = rw.getSheetAt(0).getRow(3).getCell(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()); - } - - /** - * names and macros - */ - @Test - void bug27852() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("27852.xls")) { - for (HSSFName name : wb.getAllNames()) { - assertNotNull(name.getNameName()); - if (!name.isFunctionName()) { - assertNotNull(name.getRefersToFormula()); - } - } - } - } - - /** - * Bug 29206: NPE on HSSFSheet.getRow for blank rows - */ - @Test - void bug29206() throws Exception { - //the first check with blank workbook - try (HSSFWorkbook wb = openSampleWorkbook("Simple.xls")) { - HSSFSheet sheet = wb.createSheet(); - for (int i = 1; i < 400; i++) { - HSSFRow row = sheet.getRow(i); - assertNull(row); - } - } - } - - /** - * Bug 29942: Importing Excel files that have been created by Open Office on Linux - */ - @Test - void bug29942() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("29942.xls")) { - - HSSFSheet sheet = wb.getSheetAt(0); - int count = 0; - for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { - HSSFRow row = sheet.getRow(i); - if (row != null) { - HSSFCell cell = row.getCell(0); - assertEquals(CellType.STRING, cell.getCellType()); - count++; - } - } - assertEquals(85, count); //should read 85 rows - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) { - assertNotNull(wb2.getSheetAt(0)); - } - } - } - - /** - * Bug 30540: HSSFSheet.setRowBreak throws NullPointerException - */ - @Test - void bug30540() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("30540.xls")) { - - HSSFSheet s1 = wb.getSheetAt(0); - s1.setRowBreak(1); - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) { - HSSFSheet s2 = wb2.getSheetAt(0); - int[] act = s2.getRowBreaks(); - int[] exp = { 1 }; - assertArrayEquals(exp, act); - } - } - } - - /** - * Bug 35564: HSSFCell.java: NullPtrExc in isGridsPrinted() and getProtect() - * when HSSFWorkbook is created from file - */ - @Test - void bug35564() throws Exception { - simpleTest("35564.xls", wb -> { - HSSFSheet sheet = wb.getSheetAt(0); - assertFalse(sheet.isGridsPrinted()); - assertFalse(sheet.getProtect()); - }); - } - - /** - * Bug 35565: HSSFCell.java: NullPtrExc in getColumnBreaks() when HSSFWorkbook is created from file - */ - @Test - void bug35565() throws Exception { - simpleTest("35565.xls", wb -> assertNotNull(wb.getSheetAt(0))); - } - - /** - * Bug 40285: CellIterator Skips First Column - */ - @Test - void bug40285() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("40285.xls")) { - - HSSFSheet sheet = wb.getSheetAt(0); - int rownum = 0; - for (Iterator it = sheet.rowIterator(); it.hasNext(); rownum++) { - Row row = it.next(); - assertEquals(rownum, row.getRowNum()); - int cellNum = 0; - for (Iterator it2 = row.cellIterator(); it2.hasNext(); cellNum++) { - Cell cell = it2.next(); - assertEquals(cellNum, cell.getColumnIndex()); - } - } - } - } - - /** - * Test bug 38266: NPE when adding a row break - *

- * User's diagnosis: - * 1. Manually (i.e., not using POI) create an Excel Workbook, making sure it - * contains a sheet that doesn't have any row breaks - * 2. Using POI, create a new HSSFWorkbook from the template in step #1 - * 3. Try adding a row break (via sheet.setRowBreak()) to the sheet mentioned in step #1 - * 4. Get a NullPointerException - */ - @Test - void bug38266() throws Exception { - String[] files = {"Simple.xls", "SimpleMultiCell.xls", "duprich1.xls"}; - for (String file : files) { - try (HSSFWorkbook wb = openSampleWorkbook(file)) { - - HSSFSheet sheet = wb.getSheetAt(0); - int[] breaks = sheet.getRowBreaks(); - assertEquals(0, breaks.length); - - //add 3 row breaks - for (int j = 1; j <= 3; j++) { - sheet.setRowBreak(j * 20); - } - } - } - } - - /** - * Bug 44200: Sheet not cloneable when Note added to excel cell - */ - @Test - void bug44200() throws Exception { - simpleTest("44200.xls", wb -> assertDoesNotThrow(() -> wb.cloneSheet(0))); - } - - /** - * Bug 41546: Constructing HSSFWorkbook is failed, - * Unknown Ptg in Formula: 0x1a (26) - */ - @Test - void bug41546() throws Exception { - simpleTest("41546.xls", wb -> assertEquals(1, wb.getNumberOfSheets())); - } - - /** - * Bug 42618: RecordFormatException reading a file containing - * =CHOOSE(2,A2,A3,A4) - */ - @Test - void bug42618() throws Exception { - try (HSSFWorkbook wb1 = openSampleWorkbook("SimpleWithChoose.xls"); - HSSFWorkbook wb2 = writeOutAndReadBack(wb1)){ - // Check we detect the string properly too - HSSFSheet s = wb2.getSheetAt(0); - - // Textual value - HSSFRow r1 = s.getRow(0); - HSSFCell c1 = r1.getCell(1); - assertEquals("=CHOOSE(2,A2,A3,A4)", c1.getRichStringCellValue().toString()); - - // Formula Value - HSSFRow r2 = s.getRow(1); - HSSFCell c2 = r2.getCell(1); - assertEquals(25, (int) c2.getNumericCellValue()); - - try { - assertEquals("CHOOSE(2,A2,A3,A4)", c2.getCellFormula()); - } catch (IllegalStateException e) { - if (e.getMessage().startsWith("Too few arguments") - && e.getMessage().indexOf("ConcatPtg") > 0) { - fail("identified bug 44306"); - } - } - } - } - - /** - * Something up with the FileSharingRecord - */ - @Test - void bug43251() throws Exception { - // Used to blow up with an IllegalArgumentException when creating a FileSharingRecord - simpleTest("43251.xls", wb -> assertEquals(1, wb.getNumberOfSheets())); - } - - /** - * Crystal reports generates files with short - * StyleRecords, which is against the spec - */ - @Test - void bug44471() throws Exception { - // Used to blow up with an ArrayIndexOutOfBounds when creating a StyleRecord - simpleTest("OddStyleRecord.xls", wb -> assertEquals(1, wb.getNumberOfSheets())); - } - - /** - * Files with "read only recommended" were giving - * grief on the FileSharingRecord - */ - @Test - void bug44536() throws Exception { - // Used to blow up with an IllegalArgumentException when creating a FileSharingRecord - simpleTest("ReadOnlyRecommended.xls", wb -> { - // Check read only advised - assertEquals(3, wb.getNumberOfSheets()); - assertTrue(wb.isWriteProtected()); - }); - - - // But also check that another wb isn't - simpleTest("SimpleWithChoose.xls", wb -> assertFalse(wb.isWriteProtected())); - } - - /** - * Some files were having problems with the DVRecord, - * probably due to dropdowns - */ - @Test - void bug44593() throws Exception { - // 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... - simpleTest("44593.xls", wb -> assertEquals(2, wb.getNumberOfSheets())); - } - - /** - * Used to give problems due to trying to read a zero - * length string, but that's now properly handled - */ - @Test - void bug44643() throws Exception { - // Used to blow up with an IllegalArgumentException - simpleTest("44643.xls", wb -> assertEquals(1, wb.getNumberOfSheets())); - } - - /** - * User reported the wrong number of rows from the - * iterator, but we can't replicate that - */ - @Test - void bug44693() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("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(); ) { - Row r = i.next(); - assertNotNull(r); - rowsSeen++; - } - assertEquals(713, rowsSeen); - } - } - - /** - * Problems with extracting check boxes from - * HSSFObjectData - */ - @Test - void bug44840() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("WithCheckBoxes.xls")) { - - // Take a look at the embedded objects - List objects = wb.getAllEmbeddedObjects(); - assertEquals(1, objects.size()); - - HSSFObjectData obj = objects.get(0); - assertNotNull(obj); - - // Peek inside the underlying record - EmbeddedObjectRefSubRecord rec = obj.findObjectRecord(); - assertNotNull(rec); - - // assertEquals(32, rec.field_1_stream_id_offset); - assertEquals(0, rec.getStreamId().intValue()); // WRONG! - assertEquals("Forms.CheckBox.1", rec.getOLEClassName()); - assertEquals(12, rec.getObjectData().length); - - // Doesn't have a directory - assertFalse(obj.hasDirectoryEntry()); - assertNotNull(obj.getObjectData()); - assertEquals(12, obj.getObjectData().length); - assertEquals("Forms.CheckBox.1", obj.getOLE2ClassName()); - - assertThrows(IllegalArgumentException.class, obj::getDirectory); - } - } - - /** - * Test that we can delete sheets without - * breaking the build in named ranges - * used for printing stuff. - */ - @Test - void bug30978() throws Exception { - try (HSSFWorkbook wb1 = openSampleWorkbook("30978-alt.xls")) { - assertEquals(1, wb1.getNumberOfNames()); - assertEquals(3, wb1.getNumberOfSheets()); - - // Check all names fit within range, and use - // DeletedArea3DPtg - InternalWorkbook w = wb1.getWorkbook(); - assertNames(wb1, w); - - // Delete the 2nd sheet - wb1.removeSheetAt(1); - - // Re-check - assertEquals(1, wb1.getNumberOfNames()); - assertEquals(2, wb1.getNumberOfSheets()); - assertNames(wb1, w); - - // Save and re-load - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - w = wb2.getWorkbook(); - - assertEquals(1, wb2.getNumberOfNames()); - assertEquals(2, wb2.getNumberOfSheets()); - - assertNames(wb2, w); - } - } - } - - private void assertNames(HSSFWorkbook wb1, InternalWorkbook w) { - for (int i = 0; i < w.getNumNames(); i++) { - NameRecord r = w.getNameRecord(i); - assertTrue(r.getSheetNumber() <= wb1.getNumberOfSheets()); - - Ptg[] nd = r.getNameDefinition(); - assertEquals(1, nd.length); - assertTrue(nd[0] instanceof DeletedArea3DPtg); - } - } - - /** - * Test that fonts get added properly - */ - @Test - void bug45338() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - assertEquals(4, wb.getNumberOfFonts()); - - HSSFSheet s = wb.createSheet(); - s.createRow(0); - s.createRow(1); - s.getRow(0).createCell(0); - s.getRow(1).createCell(0); - - assertEquals(4, wb.getNumberOfFonts()); - - HSSFFont f1 = wb.getFontAt(0); - assertFalse(f1.getBold()); - - // Check that asking for the same font multiple times gives you the same thing. - // Otherwise, our tests wouldn't work! - assertSame(wb.getFontAt(0), wb.getFontAt(0)); - assertEquals(wb.getFontAt(0), wb.getFontAt(0)); - assertEquals(wb.getFontAt(2), wb.getFontAt(2)); - assertNotSame(wb.getFontAt(0), wb.getFontAt(2)); - - // Look for a new font we have yet to add - assertNull(wb.findFont(false, (short) 123, (short) 22, "Thingy", false, true, (short) 2, (byte) 2)); - - HSSFFont nf = wb.createFont(); - assertEquals(5, wb.getNumberOfFonts()); - - assertEquals(5, nf.getIndex()); - assertEquals(nf, wb.getFontAt(5)); - - nf.setBold(false); - nf.setColor((short) 123); - nf.setFontHeight((short) 22); - nf.setFontName("Thingy"); - nf.setItalic(false); - nf.setStrikeout(true); - nf.setTypeOffset((short) 2); - nf.setUnderline((byte) 2); - - assertEquals(5, wb.getNumberOfFonts()); - assertEquals(nf, wb.getFontAt(5)); - - // Find it now - assertNotNull(wb.findFont(false, (short) 123, (short) 22, "Thingy", false, true, (short) 2, (byte) 2)); - HSSFFont font = wb.findFont(false, (short) 123, (short) 22, "Thingy", false, true, (short) 2, (byte) 2); - assertNotNull(font); - assertEquals(5, font.getIndex()); - assertEquals(nf, wb.findFont(false, (short) 123, (short) 22, "Thingy", false, true, (short) 2, (byte) 2)); - } - } - - /** - * From the mailing list - ensure we can handle a formula - * containing a zip code, eg ="70164" - */ - @Test - void bugZipCodeFormulas() throws Exception { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet(); - s.createRow(0); - HSSFCell c1 = s.getRow(0).createCell(0); - HSSFCell c2 = s.getRow(0).createCell(1); - HSSFCell c3 = s.getRow(0).createCell(2); - - // As number and string - c1.setCellFormula("70164"); - c2.setCellFormula("\"70164\""); - c3.setCellFormula("\"90210\""); - - // Check the formulas - assertEquals("70164", c1.getCellFormula()); - assertEquals("\"70164\"", c2.getCellFormula()); - - // And check the values - blank - confirmCachedValue(0.0, c1); - confirmCachedValue(0.0, c2); - confirmCachedValue(0.0, c3); - - // Try changing the cached value on one of the string - // formula cells, so we can see it updates properly - c3.setCellValue(new HSSFRichTextString("test")); - confirmCachedValue("test", c3); - IllegalStateException e = assertThrows(IllegalStateException.class, c3::getNumericCellValue); - assertEquals("Cannot get a NUMERIC value from a STRING formula cell", e.getMessage()); - - // Now evaluate, they should all be changed - HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb1); - eval.evaluateFormulaCell(c1); - eval.evaluateFormulaCell(c2); - eval.evaluateFormulaCell(c3); - - // Check that the cells now contain - // the correct values - confirmCachedValue(70164.0, c1); - confirmCachedValue("70164", c2); - confirmCachedValue("90210", c3); - - - // Write and read - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - HSSFSheet ns = wb2.getSheetAt(0); - HSSFCell nc1 = ns.getRow(0).getCell(0); - HSSFCell nc2 = ns.getRow(0).getCell(1); - HSSFCell nc3 = ns.getRow(0).getCell(2); - - // Re-check - confirmCachedValue(70164.0, nc1); - confirmCachedValue("70164", nc2); - confirmCachedValue("90210", nc3); - - int i = 0; - for (Iterator it = ns.getSheet().getCellValueIterator(); it.hasNext(); i++) { - CellValueRecordInterface cvr = it.next(); - if (cvr instanceof FormulaRecordAggregate) { - FormulaRecordAggregate fr = (FormulaRecordAggregate) cvr; - - if (i == 0) { - assertEquals(70164.0, fr.getFormulaRecord().getValue(), 0.0001); - assertNull(fr.getStringRecord()); - } else if (i == 1) { - assertEquals(0.0, fr.getFormulaRecord().getValue(), 0.0001); - assertNotNull(fr.getStringRecord()); - assertEquals("70164", fr.getStringRecord().getString()); - } else { - assertEquals(0.0, fr.getFormulaRecord().getValue(), 0.0001); - assertNotNull(fr.getStringRecord()); - assertEquals("90210", fr.getStringRecord().getString()); - } - } - } - assertEquals(3, i); - } - } - } - - private static void confirmCachedValue(double expectedValue, HSSFCell cell) { - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType()); - assertEquals(expectedValue, cell.getNumericCellValue(), 0.0); - } - - private static void confirmCachedValue(String expectedValue, HSSFCell cell) { - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.STRING, cell.getCachedFormulaResultType()); - assertEquals(expectedValue, cell.getRichStringCellValue().getString()); - } - - /** - * Problem with "Vector Rows", eg a whole - * column which is set to the result of - * {=sin(B1:B9)}(9,1), so that each cell is - * shown to have the contents - * {=sin(B1:B9){9,1)[rownum][0] - * In this sample file, the vector column - * is C, and the data column is B. - *

- * Expected ExpPtg to be converted from Shared to Non-Shared... - */ - @Disabled("For now, blows up with an exception from ExtPtg") - @Test - void test43623() throws Exception { - try (HSSFWorkbook wb1 = openSampleWorkbook("43623.xls")) { - assertEquals(1, wb1.getNumberOfSheets()); - - HSSFSheet s1 = wb1.getSheetAt(0); - - HSSFCell c1 = s1.getRow(0).getCell(2); - HSSFCell c2 = s1.getRow(1).getCell(2); - HSSFCell c3 = s1.getRow(2).getCell(2); - - // These formula contents are a guess... - assertEquals("{=sin(B1:B9){9,1)[0][0]", c1.getCellFormula()); - assertEquals("{=sin(B1:B9){9,1)[1][0]", c2.getCellFormula()); - assertEquals("{=sin(B1:B9){9,1)[2][0]", c3.getCellFormula()); - - // Save and re-open, ensure it still works - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - HSSFSheet ns1 = wb2.getSheetAt(0); - HSSFCell nc1 = ns1.getRow(0).getCell(2); - HSSFCell nc2 = ns1.getRow(1).getCell(2); - HSSFCell nc3 = ns1.getRow(2).getCell(2); - - assertEquals("{=sin(B1:B9){9,1)[0][0]", nc1.getCellFormula()); - assertEquals("{=sin(B1:B9){9,1)[1][0]", nc2.getCellFormula()); - assertEquals("{=sin(B1:B9){9,1)[2][0]", nc3.getCellFormula()); - } - } - } - - /** - * People are all getting confused about the last - * row and cell number - */ - @Test - void bug30635() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - - // No rows, first/last return -1 - assertEquals(-1, s.getFirstRowNum()); - assertEquals(-1, s.getLastRowNum()); - assertEquals(0, s.getPhysicalNumberOfRows()); - - // One row, most things are 0, physical is 1 - s.createRow(0); - assertEquals(0, s.getFirstRowNum()); - assertEquals(0, s.getLastRowNum()); - assertEquals(1, s.getPhysicalNumberOfRows()); - - // And another, things change - s.createRow(4); - assertEquals(0, s.getFirstRowNum()); - assertEquals(4, s.getLastRowNum()); - assertEquals(2, s.getPhysicalNumberOfRows()); - - - // Now start on cells - HSSFRow r = s.getRow(0); - assertEquals(-1, r.getFirstCellNum()); - assertEquals(-1, r.getLastCellNum()); - assertEquals(0, r.getPhysicalNumberOfCells()); - - // Add a cell, things move off -1 - r.createCell(0); - assertEquals(0, r.getFirstCellNum()); - assertEquals(1, r.getLastCellNum()); // last cell # + 1 - assertEquals(1, r.getPhysicalNumberOfCells()); - - r.createCell(1); - assertEquals(0, r.getFirstCellNum()); - assertEquals(2, r.getLastCellNum()); // last cell # + 1 - assertEquals(2, r.getPhysicalNumberOfCells()); - - r.createCell(4); - assertEquals(0, r.getFirstCellNum()); - assertEquals(5, r.getLastCellNum()); // last cell # + 1 - assertEquals(3, r.getPhysicalNumberOfCells()); - - } - } - - /** - * Data Tables - ptg 0x2 - */ - @Test - void bug44958() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("44958.xls")) { - HSSFSheet s; - HSSFRow r; - HSSFCell c; - - // Check the contents of the formulas - - // E4 to G9 of sheet 4 make up the table - s = wb.getSheet("OneVariable Table Completed"); - r = s.getRow(3); - c = r.getCell(4); - assertEquals(CellType.FORMULA, c.getCellType()); - - // TODO - check the formula once tables and - // arrays are properly supported - - - // E4 to H9 of sheet 5 make up the table - s = wb.getSheet("TwoVariable Table Example"); - r = s.getRow(3); - c = r.getCell(4); - assertEquals(CellType.FORMULA, c.getCellType()); - - // TODO - check the formula once tables and - // arrays are properly supported - } - } - - /** - * 45322: HSSFSheet.autoSizeColumn fails when style.getDataFormat() returns -1 - */ - @Test - void bug45322() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("44958.xls")) { - HSSFSheet sh = wb.getSheetAt(0); - for (short i = 0; i < 30; i++) { - sh.autoSizeColumn(i); - assertNotEquals(0, sh.getColumnWidth(i)); - } - } - } - - /** - * We used to add too many UncalcRecords to sheets - * with diagrams on. Don't any more - */ - @Test - void bug45414() throws Exception { - try (HSSFWorkbook wb1 = openSampleWorkbook("WithThreeCharts.xls")) { - wb1.getSheetAt(0).setForceFormulaRecalculation(true); - wb1.getSheetAt(1).setForceFormulaRecalculation(false); - wb1.getSheetAt(2).setForceFormulaRecalculation(true); - - // Write out and back in again - // This used to break - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - - // Check now set as it should be - assertTrue(wb2.getSheetAt(0).getForceFormulaRecalculation()); - assertFalse(wb2.getSheetAt(1).getForceFormulaRecalculation()); - assertTrue(wb2.getSheetAt(2).getForceFormulaRecalculation()); - } - } - } - - /** - * Very hidden sheets not displaying as such - */ - @Test - void bug45761() throws Exception { - try (HSSFWorkbook wb1 = openSampleWorkbook("45761.xls")) { - assertEquals(3, wb1.getNumberOfSheets()); - - assertFalse(wb1.isSheetHidden(0)); - assertFalse(wb1.isSheetVeryHidden(0)); - assertTrue(wb1.isSheetHidden(1)); - assertFalse(wb1.isSheetVeryHidden(1)); - assertFalse(wb1.isSheetHidden(2)); - assertTrue(wb1.isSheetVeryHidden(2)); - - // Change sheet 0 to be very hidden, and re-load - wb1.setSheetVisibility(0, SheetVisibility.VERY_HIDDEN); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - assertFalse(wb2.isSheetHidden(0)); - assertTrue(wb2.isSheetVeryHidden(0)); - assertTrue(wb2.isSheetHidden(1)); - assertFalse(wb2.isSheetVeryHidden(1)); - assertFalse(wb2.isSheetHidden(2)); - assertTrue(wb2.isSheetVeryHidden(2)); - } - } - } - - /** - * The resolution for bug 45777 assumed that the maximum text length in a header / footer - * record was 256 bytes. This assumption appears to be wrong. Since the fix for bug 47244, - * POI now supports header / footer text lengths beyond 256 bytes. - */ - @Test - void bug45777() throws Exception { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - - char[] cc248 = new char[248]; - Arrays.fill(cc248, 'x'); - String s248 = new String(cc248); - - String s249 = s248 + "1"; - String s250 = s248 + "12"; - String s251 = s248 + "123"; - assertEquals(248, s248.length()); - assertEquals(249, s249.length()); - assertEquals(250, s250.length()); - assertEquals(251, s251.length()); - - - // Try on headers - s.getHeader().setCenter(s248); - assertEquals(254, s.getHeader().getRawText().length()); - writeOutAndReadBack(wb).close(); - - s.getHeader().setCenter(s251); - assertEquals(257, s.getHeader().getRawText().length()); - writeOutAndReadBack(wb).close(); - - // header can be more than 256 bytes - s.getHeader().setCenter(s250); // 256 bytes required - s.getHeader().setCenter(s251); // 257 bytes required - - // Now try on footers - s.getFooter().setCenter(s248); - assertEquals(254, s.getFooter().getRawText().length()); - writeOutAndReadBack(wb).close(); - - s.getFooter().setCenter(s251); - assertEquals(257, s.getFooter().getRawText().length()); - writeOutAndReadBack(wb).close(); - - // footer can be more than 256 bytes - s.getFooter().setCenter(s250); // 256 bytes required - s.getFooter().setCenter(s251); // 257 bytes required - - } - } - - /** - * Charts with long titles - */ - @Test - void bug45784() throws Exception { - simpleTest("45784.xls", wb -> assertEquals(1, wb.getNumberOfSheets())); - } - - /** - * Cell background colours - */ - @Test - void bug45492() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("45492.xls")) { - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r = s.getRow(0); - HSSFPalette p = wb.getCustomPalette(); - - HSSFCell auto = r.getCell(0); - HSSFCell grey = r.getCell(1); - HSSFCell red = r.getCell(2); - HSSFCell blue = r.getCell(3); - HSSFCell green = r.getCell(4); - - assertEquals(64, auto.getCellStyle().getFillForegroundColor()); - assertEquals(64, auto.getCellStyle().getFillBackgroundColor()); - assertEquals("0:0:0", p.getColor(64).getHexString()); - - assertEquals(22, grey.getCellStyle().getFillForegroundColor()); - assertEquals(64, grey.getCellStyle().getFillBackgroundColor()); - assertEquals("C0C0:C0C0:C0C0", p.getColor(22).getHexString()); - - assertEquals(10, red.getCellStyle().getFillForegroundColor()); - assertEquals(64, red.getCellStyle().getFillBackgroundColor()); - assertEquals("FFFF:0:0", p.getColor(10).getHexString()); - - assertEquals(12, blue.getCellStyle().getFillForegroundColor()); - assertEquals(64, blue.getCellStyle().getFillBackgroundColor()); - assertEquals("0:0:FFFF", p.getColor(12).getHexString()); - - assertEquals(11, green.getCellStyle().getFillForegroundColor()); - assertEquals(64, green.getCellStyle().getFillBackgroundColor()); - assertEquals("0:FFFF:0", p.getColor(11).getHexString()); - } - } - - /** - * ContinueRecord after EOF - */ - @Test - void bug46137() throws Exception { - simpleTest("46137.xls", wb -> assertEquals(7, wb.getNumberOfSheets())); - } - - /** - * Odd POIFS blocks issue: - * block[ 44 ] already removed from org.apache.poi.poifs.storage.BlockListImpl.remove - */ - @Test - void bug45290() throws Exception { - simpleTest("45290.xls", wb -> assertEquals(1, wb.getNumberOfSheets())); - } - - /** - * In POI-2.5 user reported exception when parsing a name with a custom VBA function: - * =MY_VBA_FUNCTION("lskdjflsk") - */ - @Test - void bug30070() throws Exception { - //contains custom VBA function 'Commission' - try (HSSFWorkbook wb = openSampleWorkbook("30070.xls")) { - HSSFSheet sh = wb.getSheetAt(0); - HSSFCell cell = sh.getRow(0).getCell(1); - - //B1 uses VBA in the formula - assertEquals("Commission(A1)", cell.getCellFormula()); - - //name sales_1 refers to Commission(Sheet0!$A$1) - int idx = wb.getNameIndex("sales_1"); - assertTrue(idx != -1); - - HSSFName name = wb.getNameAt(idx); - assertEquals("Commission(Sheet0!$A$1)", name.getRefersToFormula()); - } - } - - /** - * The link formulas which is referring to other books cannot be taken (the bug existed prior to POI-3.2) - * Expected: - *

- * [link_sub.xls]Sheet1!$A$1 - * [link_sub.xls]Sheet1!$A$2 - * [link_sub.xls]Sheet1!$A$3 - *

- * POI-3.1 output: - *

- * Sheet1!$A$1 - * Sheet1!$A$2 - * Sheet1!$A$3 - */ - @Test - void bug27364() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("27364.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - - assertEquals("[link_sub.xls]Sheet1!$A$1", sheet.getRow(0).getCell(0).getCellFormula()); - assertEquals("[link_sub.xls]Sheet1!$A$2", sheet.getRow(1).getCell(0).getCellFormula()); - assertEquals("[link_sub.xls]Sheet1!$A$3", sheet.getRow(2).getCell(0).getCellFormula()); - } - } - - /** - * Similar to bug#27364: - * HSSFCell.getCellFormula() fails with references to external workbooks - */ - @Test - void bug31661() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("31661.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - HSSFCell cell = sheet.getRow(11).getCell(10); //K11 - assertEquals("+'[GM Budget.xls]8085.4450'!$B$2", cell.getCellFormula()); - } - } - - /** - * Incorrect handling of non-ISO 8859-1 characters in Windows ANSII Code Page 1252 - */ - @Test - void bug27394() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("27394.xls")) { - assertEquals("\u0161\u017E", wb.getSheetName(0)); - assertEquals("\u0161\u017E\u010D\u0148\u0159", wb.getSheetName(1)); - HSSFSheet sheet = wb.getSheetAt(0); - - assertEquals("\u0161\u017E", sheet.getRow(0).getCell(0).getStringCellValue()); - assertEquals("\u0161\u017E\u010D\u0148\u0159", sheet.getRow(1).getCell(0).getStringCellValue()); - } - } - - /** - * Multiple calls of HSSFWorkbook.write result in corrupted xls - */ - @Test - void bug32191() throws IOException { - try (HSSFWorkbook wb = openSampleWorkbook("27394.xls"); - ByteArrayOutputStream out1 = new ByteArrayOutputStream(); - ByteArrayOutputStream out2 = new ByteArrayOutputStream(); - ByteArrayOutputStream out3 = new ByteArrayOutputStream()) { - wb.write(out1); - wb.write(out2); - wb.write(out3); - assertArrayEquals(out1.toByteArray(), out2.toByteArray()); - assertArrayEquals(out2.toByteArray(), out3.toByteArray()); - } - } - - /** - * java.lang.NegativeArraySizeException reading long - * non-unicode data for a name record - */ - @Test - void bug47034() throws Exception { - simpleTest("47034.xls", wb -> { - assertEquals(893, wb.getNumberOfNames()); - assertEquals("Matthew\\Matthew11_1\\Matthew2331_1\\Matthew2351_1\\Matthew2361_1___lab", wb.getNameName(300)); - }); - } - - /** - * HSSFRichTextString.length() returns negative for really long strings. - * The test file was created in OpenOffice 3.0 as Excel does not allow cell text longer than 32,767 characters - */ - @Test - void bug46368() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("46368.xls")) { - HSSFSheet s = wb.getSheetAt(0); - HSSFCell cell1 = s.getRow(0).getCell(0); - assertEquals(32770, cell1.getStringCellValue().length()); - - HSSFCell cell2 = s.getRow(2).getCell(0); - assertEquals(32766, cell2.getStringCellValue().length()); - } - } - - /** - * Short records on certain sheets with charts in them - */ - @Test - void bug48180() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("48180.xls")) { - - HSSFSheet s = wb.getSheetAt(0); - HSSFCell cell1 = s.getRow(0).getCell(0); - assertEquals("test ", cell1.getStringCellValue()); - - HSSFCell cell2 = s.getRow(0).getCell(1); - assertEquals(1.0, cell2.getNumericCellValue(), 0.0); - } - } - - /** - * Round trip a file with an unusual UnicodeString/ExtRst record parts - */ - @Test - void bug47847() throws Exception { - try (HSSFWorkbook wb1 = openSampleWorkbook("47847.xls")) { - assertEquals(3, wb1.getNumberOfSheets()); - - // Find the SST record - UnicodeString withExt = wb1.getWorkbook().getSSTString(0); - UnicodeString withoutExt = wb1.getWorkbook().getSSTString(31); - - assertEquals("O:Alloc:Qty", withExt.getString()); - assertEquals(0x0004, (withExt.getOptionFlags() & 0x0004)); - - assertEquals("RT", withoutExt.getString()); - assertEquals(0x0000, (withoutExt.getOptionFlags() & 0x0004)); - - // Something about continues... - - - // Write out and re-read - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - assertEquals(3, wb2.getNumberOfSheets()); - - // Check it's the same now - withExt = wb2.getWorkbook().getSSTString(0); - withoutExt = wb2.getWorkbook().getSSTString(31); - - assertEquals("O:Alloc:Qty", withExt.getString()); - assertEquals(0x0004, (withExt.getOptionFlags() & 0x0004)); - - assertEquals("RT", withoutExt.getString()); - assertEquals(0x0000, (withoutExt.getOptionFlags() & 0x0004)); - } - } - } - - /** - * Problem with cloning a sheet with a chart - * contained in it. - */ - @Test - void bug49096() throws Exception { - try (HSSFWorkbook wb1 = openSampleWorkbook("49096.xls")) { - assertEquals(1, wb1.getNumberOfSheets()); - - assertNotNull(wb1.getSheetAt(0)); - wb1.cloneSheet(0); - assertEquals(2, wb1.getNumberOfSheets()); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - assertEquals(2, wb2.getNumberOfSheets()); - } - } - } - - /** - * Newly created sheets need to get a - * proper TabID, otherwise print setup - * gets confused on them. - * Also ensure that print setup refs are - * by reference not value - */ - @Test - void bug46664() throws Exception { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet sheet = wb1.createSheet("new_sheet"); - HSSFRow row = sheet.createRow((short) 0); - row.createCell(0).setCellValue(new HSSFRichTextString("Column A")); - row.createCell(1).setCellValue(new HSSFRichTextString("Column B")); - row.createCell(2).setCellValue(new HSSFRichTextString("Column C")); - row.createCell(3).setCellValue(new HSSFRichTextString("Column D")); - row.createCell(4).setCellValue(new HSSFRichTextString("Column E")); - row.createCell(5).setCellValue(new HSSFRichTextString("Column F")); - - //set print area from column a to column c (on first row) - wb1.setPrintArea( - 0, //sheet index - 0, //start column - 2, //end column - 0, //start row - 0 //end row - ); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - // Ensure the tab index - TabIdRecord tr = null; - for (org.apache.poi.hssf.record.Record r : wb2.getWorkbook().getRecords()) { - if (r instanceof TabIdRecord) { - tr = (TabIdRecord) r; - } - } - assertNotNull(tr); - assertEquals(1, tr.getTabIdSize()); - assertEquals(0, tr.getTabIdAt(0)); - - // Ensure the print setup - assertEquals("new_sheet!$A$1:$C$1", wb2.getPrintArea(0)); - HSSFName printArea = wb2.getName("Print_Area"); - assertNotNull(printArea); - assertEquals("new_sheet!$A$1:$C$1", printArea.getRefersToFormula()); - - // Needs reference not value - NameRecord nr = wb2.getWorkbook().getNameRecord( - wb2.getNameIndex("Print_Area") - ); - assertEquals("Print_Area", nr.getNameText()); - assertEquals(1, nr.getNameDefinition().length); - assertEquals( - "new_sheet!$A$1:$C$1", - ((Area3DPtg) nr.getNameDefinition()[0]).toFormulaString(HSSFEvaluationWorkbook.create(wb2)) - ); - assertEquals('R', nr.getNameDefinition()[0].getRVAType()); - } - } - } - - /** - * Problems with formula references to - * sheets via URLs - */ - @Test - void bug45970() throws Exception { - try (HSSFWorkbook wb1 = openSampleWorkbook("FormulaRefs.xls")) { - assertEquals(3, wb1.getNumberOfSheets()); - - HSSFSheet s = wb1.getSheetAt(0); - HSSFRow row; - - row = s.getRow(0); - assertEquals(CellType.NUMERIC, row.getCell(1).getCellType()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(1); - assertEquals(CellType.FORMULA, row.getCell(1).getCellType()); - assertEquals("B1", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(2); - assertEquals(CellType.FORMULA, row.getCell(1).getCellType()); - assertEquals("Sheet1!B1", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(3); - assertEquals(CellType.FORMULA, row.getCell(1).getCellType()); - assertEquals("[Formulas2.xls]Sheet1!B2", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(4); - assertEquals(CellType.FORMULA, row.getCell(1).getCellType()); - assertEquals("'[$http://gagravarr.org/FormulaRefs.xls]Sheet1'!B1", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - // Link our new workbook - Workbook externalWb1 = new HSSFWorkbook(); - externalWb1.createSheet("Sheet1"); - assertEquals(4, wb1.linkExternalWorkbook("$http://gagravarr.org/FormulaRefs2.xls", externalWb1)); - - // Change 4 - row.getCell(1).setCellFormula("'[$http://gagravarr.org/FormulaRefs2.xls]Sheet1'!B2"); - row.getCell(1).setCellValue(123.0); - - // Link our new workbook - Workbook externalWb2 = new HSSFWorkbook(); - externalWb2.createSheet("Sheet1"); - assertEquals(5, wb1.linkExternalWorkbook("$http://example.com/FormulaRefs.xls", externalWb2)); - - // Add 5 - row = s.createRow(5); - row.createCell(1, CellType.FORMULA); - row.getCell(1).setCellFormula("'[$http://example.com/FormulaRefs.xls]Sheet1'!B1"); - row.getCell(1).setCellValue(234.0); - - // Re-test - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - s = wb2.getSheetAt(0); - - row = s.getRow(0); - assertEquals(CellType.NUMERIC, row.getCell(1).getCellType()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(1); - assertEquals(CellType.FORMULA, row.getCell(1).getCellType()); - assertEquals("B1", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(2); - assertEquals(CellType.FORMULA, row.getCell(1).getCellType()); - assertEquals("Sheet1!B1", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(3); - assertEquals(CellType.FORMULA, row.getCell(1).getCellType()); - assertEquals("[Formulas2.xls]Sheet1!B2", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(4); - assertEquals(CellType.FORMULA, row.getCell(1).getCellType()); - assertEquals("'[$http://gagravarr.org/FormulaRefs2.xls]Sheet1'!B2", row.getCell(1).getCellFormula()); - assertEquals(123.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(5); - assertEquals(CellType.FORMULA, row.getCell(1).getCellType()); - assertEquals("'[$http://example.com/FormulaRefs.xls]Sheet1'!B1", row.getCell(1).getCellFormula()); - assertEquals(234.0, row.getCell(1).getNumericCellValue(), 0); - - } - } - } - - /** - * Test for a file with NameRecord with NameCommentRecord comments - */ - @Test - void bug49185() throws Exception { - try (HSSFWorkbook wb1 = openSampleWorkbook("49185.xls")) { - Name name = wb1.getName("foobarName"); - assertNotNull(name); - assertEquals("This is a comment", name.getComment()); - - // Rename the name, comment comes with it - name.setNameName("ChangedName"); - assertEquals("This is a comment", name.getComment()); - - // Save and re-check - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - name = wb2.getName("ChangedName"); - assertNotNull(name); - assertEquals("This is a comment", name.getComment()); - - // Now try to change it - name.setComment("Changed Comment"); - assertEquals("Changed Comment", name.getComment()); - - // Save and re-check - try (HSSFWorkbook wb3 = writeOutAndReadBack(wb2)) { - name = wb3.getName("ChangedName"); - assertNotNull(name); - assertEquals("Changed Comment", name.getComment()); - } - } - } - } - - /** Vertically aligned text */ - @Test - void bug49524() throws Exception { - try (HSSFWorkbook wb1 = openSampleWorkbook("49524.xls")) { - Sheet s = wb1.getSheetAt(0); - Row r = s.getRow(0); - Cell rotated = r.getCell(0); - Cell normal = r.getCell(1); - - // Check the current ones - assertEquals(0, normal.getCellStyle().getRotation()); - assertEquals(0xff, rotated.getCellStyle().getRotation()); - - // Add a new style, also rotated - CellStyle cs = wb1.createCellStyle(); - cs.setRotation((short) 0xff); - Cell nc = r.createCell(2); - nc.setCellValue("New Rotated Text"); - nc.setCellStyle(cs); - assertEquals(0xff, nc.getCellStyle().getRotation()); - - // Write out and read back - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - // Re-check - s = wb2.getSheetAt(0); - r = s.getRow(0); - rotated = r.getCell(0); - normal = r.getCell(1); - nc = r.getCell(2); - - assertEquals(0, normal.getCellStyle().getRotation()); - assertEquals(0xff, rotated.getCellStyle().getRotation()); - assertEquals(0xff, nc.getCellStyle().getRotation()); - } - } - } - - /** - * Setting the user style name on custom styles - */ - @Test - void bug49689() throws Exception { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet("Test"); - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(0); - - HSSFCellStyle cs1 = wb1.createCellStyle(); - HSSFCellStyle cs2 = wb1.createCellStyle(); - HSSFCellStyle cs3 = wb1.createCellStyle(); - - assertEquals(21, cs1.getIndex()); - cs1.setUserStyleName("Testing"); - - assertEquals(22, cs2.getIndex()); - cs2.setUserStyleName("Testing 2"); - - assertEquals(23, cs3.getIndex()); - cs3.setUserStyleName("Testing 3"); - - // Set one - c.setCellStyle(cs1); - - // Write out and read back - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - // Re-check - assertEquals("Testing", wb2.getCellStyleAt((short) 21).getUserStyleName()); - assertEquals("Testing 2", wb2.getCellStyleAt((short) 22).getUserStyleName()); - assertEquals("Testing 3", wb2.getCellStyleAt((short) 23).getUserStyleName()); - } - } - } - - @Test - void bug49751() throws Exception { - Set exp = new HashSet<>(Arrays.asList( - "20% - Accent1", "20% - Accent2", "20% - Accent3", "20% - Accent4", "20% - Accent5", - "20% - Accent6", "40% - Accent1", "40% - Accent2", "40% - Accent3", "40% - Accent4", - "40% - Accent5", "40% - Accent6", "60% - Accent1", "60% - Accent2", "60% - Accent3", - "60% - Accent4", "60% - Accent5", "60% - Accent6", "Accent1", "Accent2", "Accent3", - "Accent4", "Accent5", "Accent6", "Bad", "Calculation", "Check Cell", "Explanatory Text", - "Good", "Heading 1", "Heading 2", "Heading 3", "Heading 4", "Input", "Linked Cell", - "Neutral", "Note", "Output", "Title", "Total", "Warning Text")); - - try (HSSFWorkbook wb = openSampleWorkbook("49751.xls")) { - Set act = IntStream - .range(0, wb.getNumCellStyles()) - .mapToObj(wb::getCellStyleAt) - .map(HSSFCellStyle::getUserStyleName) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - assertEquals(exp, act); - } - } - - /** - * Regression with the PageSettingsBlock - */ - @Test - void bug49931() throws Exception { - simpleTest("49931.xls", wb -> { - assertEquals(1, wb.getNumberOfSheets()); - assertEquals("Foo", wb.getSheetAt(0).getRow(0).getCell(0).getRichStringCellValue().toString()); - }); - } - - /** - * Missing left/right/centre options on a footer - */ - @Test - void bug48325() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("48325.xls")) { - HSSFSheet sh = wb.getSheetAt(0); - HSSFFooter f = sh.getFooter(); - - // Will show as the center, as that is what excel does - // with an invalid footer lacking left/right/center details - assertEquals("", f.getLeft(), "Left text should be empty"); - assertEquals("", f.getRight(), "Right text should be empty"); - assertEquals("BlahBlah blah blah ", f.getCenter(), - "Center text should contain the illegal value"); - } - } - - /** - * Last row number when shifting rows - */ - @Test - void bug50416LastRowNumber() throws IOException { - // Create the workbook with 1 sheet which contains 3 rows - try (HSSFWorkbook wb = new HSSFWorkbook()) { - Sheet sheet = wb.createSheet("Bug50416"); - Row row1 = sheet.createRow(0); - Cell cellA_1 = row1.createCell(0, CellType.STRING); - cellA_1.setCellValue("Cell A,1"); - Row row2 = sheet.createRow(1); - Cell cellA_2 = row2.createCell(0, CellType.STRING); - cellA_2.setCellValue("Cell A,2"); - Row row3 = sheet.createRow(2); - Cell cellA_3 = row3.createCell(0, CellType.STRING); - cellA_3.setCellValue("Cell A,3"); - - // Test the last Row number it currently correct - assertEquals(2, sheet.getLastRowNum()); - - // Shift the first row to the end - sheet.shiftRows(0, 0, 3); - assertEquals(3, sheet.getLastRowNum()); - assertEquals(-1, sheet.getRow(0).getLastCellNum()); - assertEquals("Cell A,2", sheet.getRow(1).getCell(0).getStringCellValue()); - assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue()); - assertEquals("Cell A,1", sheet.getRow(3).getCell(0).getStringCellValue()); - - // Shift the 2nd row up to the first one - sheet.shiftRows(1, 1, -1); - assertEquals(3, sheet.getLastRowNum()); - assertEquals("Cell A,2", sheet.getRow(0).getCell(0).getStringCellValue()); - assertEquals(-1, sheet.getRow(1).getLastCellNum()); - assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue()); - assertEquals("Cell A,1", sheet.getRow(3).getCell(0).getStringCellValue()); - - // Shift the 4th row up into the gap in the 3rd row - sheet.shiftRows(3, 3, -2); - assertEquals(2, sheet.getLastRowNum()); - assertEquals("Cell A,2", sheet.getRow(0).getCell(0).getStringCellValue()); - assertEquals("Cell A,1", sheet.getRow(1).getCell(0).getStringCellValue()); - assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue()); - assertEquals(-1, sheet.getRow(3).getLastCellNum()); - - // Now zap the empty 4th row - won't do anything - sheet.removeRow(sheet.getRow(3)); - - // Test again the last row number which should be 2 - assertEquals(2, sheet.getLastRowNum()); - assertEquals("Cell A,2", sheet.getRow(0).getCell(0).getStringCellValue()); - assertEquals("Cell A,1", sheet.getRow(1).getCell(0).getStringCellValue()); - assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue()); - - } - } - - /** - * If you send a file between Excel and OpenOffice enough, something - * will turn the "General" format into "GENERAL" - */ - @Test - void bug50756() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("50756.xls")) { - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r17 = s.getRow(16); - HSSFRow r18 = s.getRow(17); - HSSFDataFormatter df = new HSSFDataFormatter(); - - assertEquals(10.0, r17.getCell(1).getNumericCellValue(), 0); - assertEquals(20.0, r17.getCell(2).getNumericCellValue(), 0); - assertEquals(20.0, r17.getCell(3).getNumericCellValue(), 0); - assertEquals("GENERAL", r17.getCell(1).getCellStyle().getDataFormatString()); - assertEquals("GENERAL", r17.getCell(2).getCellStyle().getDataFormatString()); - assertEquals("GENERAL", r17.getCell(3).getCellStyle().getDataFormatString()); - assertEquals("10", df.formatCellValue(r17.getCell(1))); - assertEquals("20", df.formatCellValue(r17.getCell(2))); - assertEquals("20", df.formatCellValue(r17.getCell(3))); - - assertEquals(16.0, r18.getCell(1).getNumericCellValue(), 0); - assertEquals(35.0, r18.getCell(2).getNumericCellValue(), 0); - assertEquals(123.0, r18.getCell(3).getNumericCellValue(), 0); - assertEquals("GENERAL", r18.getCell(1).getCellStyle().getDataFormatString()); - assertEquals("GENERAL", r18.getCell(2).getCellStyle().getDataFormatString()); - assertEquals("GENERAL", r18.getCell(3).getCellStyle().getDataFormatString()); - assertEquals("16", df.formatCellValue(r18.getCell(1))); - assertEquals("35", df.formatCellValue(r18.getCell(2))); - assertEquals("123", df.formatCellValue(r18.getCell(3))); - } - } - - /** - * A protected sheet with comments, when written out by - * POI, ends up upsetting excel. - * TODO Identify the cause and add extra asserts for - * the bit excel cares about - */ - @Test - void bug50833() throws Exception { - HSSFWorkbook wb1 = openSampleWorkbook("50833.xls"); - HSSFSheet s = wb1.getSheetAt(0); - assertEquals("Sheet1", s.getSheetName()); - assertFalse(s.getProtect()); - - HSSFCell c = s.getRow(0).getCell(0); - assertEquals("test cell value", c.getRichStringCellValue().getString()); - - HSSFComment cmt = c.getCellComment(); - assertNotNull(cmt); - assertEquals("Robert Lawrence", cmt.getAuthor()); - assertEquals("Robert Lawrence:\ntest comment", cmt.getString().getString()); - - // Reload - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - c = s.getRow(0).getCell(0); - - // Re-check the comment - cmt = c.getCellComment(); - assertNotNull(cmt); - assertEquals("Robert Lawrence", cmt.getAuthor()); - assertEquals("Robert Lawrence:\ntest comment", cmt.getString().getString()); - - // TODO Identify what excel doesn't like, and check for that - wb2.close(); - } - - /** - * The spec says that ChartEndObjectRecord has 6 reserved - * bytes on the end, but we sometimes find files without... - */ - @Test - void bug50939() throws Exception { - simpleTest("50939.xls", wb -> assertEquals(2, wb.getNumberOfSheets())); - } - - @Test - void bug49219() throws Exception { - simpleTest("49219.xls", wb -> { - assertEquals(1, wb.getNumberOfSheets()); - assertEquals("DGATE", wb.getSheetAt(0).getRow(1).getCell(0).getStringCellValue()); - }); - } - - @Test - void bug48968() throws Exception { - TimeZone userTimeZone = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - try { - HSSFWorkbook wb = openSampleWorkbook("48968.xls"); - assertEquals(1, wb.getNumberOfSheets()); - - DataFormatter fmt = new DataFormatter(); - - // Check the dates - HSSFSheet s = wb.getSheetAt(0); - Cell cell_d20110325 = s.getRow(0).getCell(0); - Cell cell_d19000102 = s.getRow(11).getCell(0); - Cell cell_d19000100 = s.getRow(21).getCell(0); - assertEquals(s.getRow(0).getCell(3).getStringCellValue(), fmt.formatCellValue(cell_d20110325)); - assertEquals(s.getRow(11).getCell(3).getStringCellValue(), fmt.formatCellValue(cell_d19000102)); - // There is no such thing as 00/01/1900... - assertEquals("00/01/1900 06:14:24", s.getRow(21).getCell(3).getStringCellValue()); - assertEquals("31/12/1899 06:14:24", fmt.formatCellValue(cell_d19000100)); - - // Check the cached values - assertEquals("HOUR(A1)", s.getRow(5).getCell(0).getCellFormula()); - assertEquals(11.0, s.getRow(5).getCell(0).getNumericCellValue(), 0); - assertEquals("MINUTE(A1)", s.getRow(6).getCell(0).getCellFormula()); - assertEquals(39.0, s.getRow(6).getCell(0).getNumericCellValue(), 0); - assertEquals("SECOND(A1)", s.getRow(7).getCell(0).getCellFormula()); - assertEquals(54.0, s.getRow(7).getCell(0).getNumericCellValue(), 0); - - // Re-evaluate and check - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - assertEquals("HOUR(A1)", s.getRow(5).getCell(0).getCellFormula()); - assertEquals(11.0, s.getRow(5).getCell(0).getNumericCellValue(), 0); - assertEquals("MINUTE(A1)", s.getRow(6).getCell(0).getCellFormula()); - assertEquals(39.0, s.getRow(6).getCell(0).getNumericCellValue(), 0); - assertEquals("SECOND(A1)", s.getRow(7).getCell(0).getCellFormula()); - assertEquals(54.0, s.getRow(7).getCell(0).getNumericCellValue(), 0); - - // Push the time forward a bit and check - double date = s.getRow(0).getCell(0).getNumericCellValue(); - s.getRow(0).getCell(0).setCellValue(date + 1.26); - - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - assertEquals("HOUR(A1)", s.getRow(5).getCell(0).getCellFormula()); - assertEquals(11.0 + 6.0, s.getRow(5).getCell(0).getNumericCellValue(), 0); - assertEquals("MINUTE(A1)", s.getRow(6).getCell(0).getCellFormula()); - assertEquals(39.0 + 14.0 + 1, s.getRow(6).getCell(0).getNumericCellValue(), 0); - assertEquals("SECOND(A1)", s.getRow(7).getCell(0).getCellFormula()); - assertEquals(54.0 + 24.0 - 60, s.getRow(7).getCell(0).getNumericCellValue(), 0); - - wb.close(); - } finally { - LocaleUtil.setUserTimeZone(userTimeZone); - } - } - - - /** - * Mixture of Ascii and Unicode strings in a - * NameComment record - */ - @Test - void bug51143() throws Exception { - simpleTest("51143.xls", wb -> assertEquals(1, wb.getNumberOfSheets())); - } - - /** - * File with exactly 256 data blocks (+header block) - * shouldn't break on POIFS loading - */ - @Test - void bug51461() throws Exception { - byte[] data = HSSFITestDataProvider.instance.getTestDataFileContent("51461.xls"); - - HSSFWorkbook wbPOIFS = new HSSFWorkbook(new POIFSFileSystem( - new ByteArrayInputStream(data)).getRoot(), false); - HSSFWorkbook wbPOIFS2 = new HSSFWorkbook(new POIFSFileSystem( - new ByteArrayInputStream(data)).getRoot(), false); - - assertEquals(2, wbPOIFS.getNumberOfSheets()); - assertEquals(2, wbPOIFS2.getNumberOfSheets()); - } - - @Test - void bug51535() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("51535.xls")) { - assertEquals(3, wb.getNumberOfSheets()); - - // Check directly - HSSFSheet s = wb.getSheetAt(0); - assertEquals("Top Left Cell", s.getRow(0).getCell(0).getStringCellValue()); - assertEquals("Top Right Cell", s.getRow(0).getCell(255).getStringCellValue()); - assertEquals("Bottom Left Cell", s.getRow(65535).getCell(0).getStringCellValue()); - assertEquals("Bottom Right Cell", s.getRow(65535).getCell(255).getStringCellValue()); - - // Extract and check - try (ExcelExtractor ex = new ExcelExtractor(wb)) { - String text = ex.getText(); - assertContains(text, "Top Left Cell"); - assertContains(text, "Top Right Cell"); - assertContains(text, "Bottom Left Cell"); - assertContains(text, "Bottom Right Cell"); - } - } - } - - /** - * Sum across multiple workbooks - * eg =SUM($Sheet2.A1:$Sheet3.A1) - */ - @Test - void test48703() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("48703.xls")) { - assertEquals(3, wb.getNumberOfSheets()); - - // Check reading the formula - Sheet sheet = wb.getSheetAt(0); - Row r = sheet.getRow(0); - Cell c = r.getCell(0); - - assertEquals("SUM(Sheet2:Sheet3!A1)", c.getCellFormula()); - assertEquals(4.0, c.getNumericCellValue(), 0); - - // Check the evaluated result - HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb); - eval.evaluateFormulaCell(c); - assertEquals(4.0, c.getNumericCellValue(), 0); - } - } - - @Test - void bug49896() throws Exception { - String exp = "VLOOKUP(A2,'[C:Documents and Settings/Yegor/My Documents/csco.xls]Sheet1'!$A$2:$B$3,2,FALSE)" - .replace("/", File.separator); - simpleTest("49896.xls", wb -> assertEquals(exp, wb.getSheetAt(0).getRow(1).getCell(1).getCellFormula())); - } - - @Test - void bug49529() throws Exception { - // user code reported in Bugzilla #49529 - simpleTest("49529.xls", wb -> { - wb.getSheetAt(0).createDrawingPatriarch(); - // prior to the fix the line below failed with - // java.lang.IllegalStateException: EOF - next record not available - wb.cloneSheet(0); - }); - } - - @Test - void bug49612_part() throws IOException { - try (HSSFWorkbook wb = openSampleWorkbook("49612.xls")) { - HSSFSheet sh = wb.getSheetAt(0); - HSSFRow row = sh.getRow(0); - HSSFCell c1 = row.getCell(2); - HSSFCell d1 = row.getCell(3); - HSSFCell e1 = row.getCell(2); - - assertEquals("SUM(BOB+JIM)", c1.getCellFormula()); - - // Problem 1: See TestUnfixedBugs#test49612() - // Problem 2: TestUnfixedBugs#test49612() - - // Problem 3: These used to fail, now pass - HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb); - assertEquals(30.0, eval.evaluate(c1).getNumberValue(), 0.001, "evaluating c1"); - assertEquals(30.0, eval.evaluate(d1).getNumberValue(), 0.001, "evaluating d1"); - assertEquals(30.0, eval.evaluate(e1).getNumberValue(), 0.001, "evaluating e1"); - } - } - - @Test - void bug51675() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("51675.xls")) { - HSSFSheet sh = wb.getSheetAt(0); - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - PageSettingsBlock psb = (PageSettingsBlock) ish.getRecords().get(13); - List list = new ArrayList<>(); - psb.visitContainedRecords(r -> list.add(r.getSid())); - assertEquals(UnknownRecord.BITMAP_00E9, list.get(list.size() - 1).intValue()); - assertEquals(UnknownRecord.HEADER_FOOTER_089C, list.get(list.size() - 2).intValue()); - } - } - - @Test - void bug52272() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch p = sh.createDrawingPatriarch(); - - HSSFSimpleShape s = p.createSimpleShape(new HSSFClientAnchor()); - s.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - - HSSFSheet sh2 = wb.cloneSheet(0); - assertNotNull(sh2.getDrawingPatriarch()); - } - } - - @Test - void bug53432() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - wb1.addPicture(new byte[]{123, 22}, Workbook.PICTURE_TYPE_JPEG); - assertEquals(wb1.getAllPictures().size(), 1); - } - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - assertEquals(wb2.getAllPictures().size(), 0); - wb2.addPicture(new byte[]{123, 22}, Workbook.PICTURE_TYPE_JPEG); - assertEquals(wb2.getAllPictures().size(), 1); - - try (HSSFWorkbook wb3 = writeOutAndReadBack(wb2)) { - assertEquals(wb3.getAllPictures().size(), 1); - } - } - } - } - - @Test - void bug46250() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("46250.xls")) { - Sheet sh = wb.getSheet("Template"); - Sheet cSh = wb.cloneSheet(wb.getSheetIndex(sh)); - int sIdx = wb.getSheetIndex(cSh); - - HSSFPatriarch patriarch = (HSSFPatriarch) cSh.createDrawingPatriarch(); - HSSFTextbox tb = (HSSFTextbox) patriarch.getChildren().get(2); - - tb.setString(new HSSFRichTextString("POI test")); - tb.setAnchor(new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 0, (short) 10, 10)); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) { - HSSFSheet sh2 = wb2.getSheetAt(sIdx); - assertNotNull(sh2); - assertNotNull(sh2.getDrawingPatriarch()); - } - } - } - - @Test - void bug53404() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("53404.xls")) { - Sheet sheet = wb.getSheet("test-sheet"); - int rowCount = sheet.getLastRowNum() + 1; - int newRows = 5; - Calendar cal = LocaleUtil.getLocaleCalendar(); - for (int r = rowCount; r < rowCount + newRows; r++) { - Row row = sheet.createRow((short) r); - row.createCell(0).setCellValue(1.03 * (r + 7)); - row.createCell(1).setCellValue(cal.getTime()); - row.createCell(2).setCellValue(cal); - row.createCell(3).setCellValue(String.format(Locale.ROOT, "row:%d/col:%d", r, 3)); - row.createCell(4).setCellValue(true); - row.createCell(5).setCellErrorValue(FormulaError.NUM.getCode()); - row.createCell(6).setCellValue("added cells."); - } - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) { - Sheet sheet2 = wb2.getSheet("test-sheet"); - Row row2 = sheet2.getRow(5); - assertNotNull(row2); - assertEquals(cal.getTime(),row2.getCell(2).getDateCellValue()); - } - } - } - - /** - * Row style information is 12 not 16 bits - */ - @Test - void bug49237() throws Exception { - try (Workbook wb = openSampleWorkbook("49237.xls")) { - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - CellStyle rstyle = row.getRowStyle(); - assertNotNull(rstyle); - assertEquals(BorderStyle.DOUBLE, rstyle.getBorderBottom()); - } - } - - /** - * POI does now support the RC4 CryptoAPI encryption header structure - */ - @ParameterizedTest - @CsvSource({ - "xor-encryption-abc.xls, abc", - "35897-type4.xls, freedom" - }) - void bug35897(String file, String pass) throws Exception { - Biff8EncryptionKey.setCurrentUserPassword(pass); - try { - simpleTest(file, null); - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } - - @Test - void bug56450() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("56450.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - int comments = 0; - for (Row r : sheet) { - for (Cell c : r) { - if (c.getCellComment() != null) { - assertNotNull(c.getCellComment().getString().getString()); - comments++; - } - } - } - assertEquals(0, comments); - } - } - - /** - * Files initially created with Excel 2010 can have >3 CF rules - */ - @Test - void bug56482() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("56482.xls")) { - assertEquals(1, wb.getNumberOfSheets()); - - HSSFSheet sheet = wb.getSheetAt(0); - HSSFSheetConditionalFormatting cf = sheet.getSheetConditionalFormatting(); - - assertEquals(5, cf.getNumConditionalFormattings()); - } - } - - @Test - void bug56325() throws IOException { - try (HSSFWorkbook wb1 = openSampleWorkbook("56325.xls")) { - assertEquals(3, wb1.getNumberOfSheets()); - wb1.removeSheetAt(0); - assertEquals(2, wb1.getNumberOfSheets()); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - assertEquals(2, wb2.getNumberOfSheets()); - wb2.removeSheetAt(0); - assertEquals(1, wb2.getNumberOfSheets()); - wb2.removeSheetAt(0); - assertEquals(0, wb2.getNumberOfSheets()); - - try (HSSFWorkbook wb3 = writeOutAndReadBack(wb2)) { - assertEquals(0, wb3.getNumberOfSheets()); - } - } - } - } - - @Test - void bug56325a() throws IOException { - try (HSSFWorkbook wb1 = openSampleWorkbook("56325a.xls")) { - - HSSFSheet sheet = wb1.cloneSheet(2); - wb1.setSheetName(3, "Clone 1"); - sheet.setRepeatingRows(CellRangeAddress.valueOf("2:3")); - wb1.setPrintArea(3, "$A$4:$C$10"); - - sheet = wb1.cloneSheet(2); - wb1.setSheetName(4, "Clone 2"); - sheet.setRepeatingRows(CellRangeAddress.valueOf("2:3")); - wb1.setPrintArea(4, "$A$4:$C$10"); - - wb1.removeSheetAt(2); - - try (Workbook wb2 = writeOutAndReadBack(wb1)) { - assertEquals(4, wb2.getNumberOfSheets()); - } - } - } - - /** - * Formulas which reference named ranges, either in other - * sheets, or workbook scoped but in other workbooks. - * Used to fail with - * java.lang.RuntimeException: Unexpected eval class (org.apache.poi.ss.formula.eval.NameXEval) - */ - @Test - void bug56737() throws IOException { - try (Workbook wb = openSampleWorkbook("56737.xls")) { - - // Check the named range definitions - Name nSheetScope = wb.getName("NR_To_A1"); - Name nWBScope = wb.getName("NR_Global_B2"); - - assertNotNull(nSheetScope); - assertNotNull(nWBScope); - - assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula()); - assertEquals("Defines!$B$2", nWBScope.getRefersToFormula()); - - // Check the different kinds of formulas - Sheet s = wb.getSheetAt(0); - Cell cRefSName = s.getRow(1).getCell(3); - Cell cRefWName = s.getRow(2).getCell(3); - - assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula()); - - // TODO Correct this, so that the filename is shown too, see bug #56742 - // This is what Excel itself shows - //assertEquals("'56737.xls'!NR_Global_B2", cRefWName.getCellFormula()); - // TODO This isn't right, but it's what we currently generate.... - assertEquals("NR_Global_B2", cRefWName.getCellFormula()); - - // Try to evaluate them - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue()); - assertEquals(142, (int) eval.evaluate(cRefWName).getNumberValue()); - - // Try to evaluate everything - eval.evaluateAll(); - } - } - - /** - * ClassCastException in HSSFOptimiser - StyleRecord cannot be cast to - * ExtendedFormatRecord when removing un-used styles - */ - @Test - void bug54443() throws Exception { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFCellStyle style = workbook.createCellStyle(); - HSSFCellStyle newStyle = workbook.createCellStyle(); - - HSSFSheet mySheet = workbook.createSheet(); - HSSFRow row = mySheet.createRow(0); - HSSFCell cell = row.createCell(0); - - // Use style - cell.setCellStyle(style); - // Switch to newStyle, style is now un-used - cell.setCellStyle(newStyle); - - // Optimize - int nbrOfCellStyles = workbook.getNumCellStyles(); - HSSFOptimiser.optimiseCellStyles(workbook); - assertEquals(nbrOfCellStyles-1, workbook.getNumCellStyles()); - } - } - - /** - * Intersection formula ranges, eg =(C2:D3 D3:E4) - */ - @Test - void bug52111() throws Exception { - try (Workbook wb = openSampleWorkbook("Intersection-52111.xls")) { - Sheet s = wb.getSheetAt(0); - assertFormula(wb, s.getRow(2).getCell(0), "(C2:D3 D3:E4)", "4.0"); - assertFormula(wb, s.getRow(6).getCell(0), "Tabelle2!E:E Tabelle2!$A11:$IV11", "5.0"); - assertFormula(wb, s.getRow(8).getCell(0), "Tabelle2!E:F Tabelle2!$A11:$IV12", null); - } - } - - @Test - void bug42016() throws Exception { - try (Workbook wb = openSampleWorkbook("42016.xls")) { - Sheet s = wb.getSheetAt(0); - for (int row = 0; row < 7; row++) { - assertEquals("A$1+B$1", s.getRow(row).getCell(2).getCellFormula()); - } - } - } - - /** - * Unexpected record type (org.apache.poi.hssf.record.ColumnInfoRecord) - */ - @Test - void bug53984() throws Exception { - try (Workbook wb = openSampleWorkbook("53984.xls")) { - Sheet s = wb.getSheetAt(0); - assertEquals("International Communication Services SA", s.getRow(2).getCell(0).getStringCellValue()); - assertEquals("Saudi Arabia-Riyadh", s.getRow(210).getCell(0).getStringCellValue()); - } - } - - /** - * Read, write, read for formulas point to cells in other files. - * See {@link #bug46670()} for the main test, this just - * covers reading an existing file and checking it. - * - * See base-test-class for some related tests that still fail - */ - @Test - void bug46670_existing() throws Exception { - // Expected values - String refLocal = "'[refs" + File.separator + "airport.xls]Sheet1'!$A$2"; - String refHttp = "'[9http://www.principlesofeconometrics.com/excel/airline.xls]Sheet1'!$A$2"; - - // Check we can read them correctly - simpleTest("46670_local.xls", - wb -> assertEquals(refLocal, wb.getSheetAt(0).getRow(0).getCell(0).getCellFormula())); - - simpleTest("46670_http.xls", - wb -> assertEquals(refHttp, wb.getSheetAt(0).getRow(0).getCell(0).getCellFormula())); - - // Now try to set them to the same values, and ensure that - // they end up as they did before, even with a save and re-load - try (HSSFWorkbook wb3 = openSampleWorkbook("46670_local.xls")) { - Sheet s = wb3.getSheetAt(0); - Cell c = s.getRow(0).getCell(0); - c.setCellFormula(refLocal); - assertEquals(refLocal, c.getCellFormula()); - - try (HSSFWorkbook wb4 = writeOutAndReadBack(wb3)) { - s = wb4.getSheetAt(0); - assertEquals(refLocal, s.getRow(0).getCell(0).getCellFormula()); - } - } - - try (HSSFWorkbook wb5 = openSampleWorkbook("46670_http.xls")) { - Sheet s = wb5.getSheetAt(0); - Cell c = s.getRow(0).getCell(0); - c.setCellFormula(refHttp); - assertEquals(refHttp, c.getCellFormula()); - - try (Workbook wb6 = writeOutAndReadBack(wb5)) { - s = wb6.getSheetAt(0); - assertEquals(refHttp, s.getRow(0).getCell(0).getCellFormula()); - } - } - } - - @Test - void test57163() throws IOException { - simpleTest("57163.xls", wb -> { - while (wb.getNumberOfSheets() > 1) { - wb.removeSheetAt(1); - } - }); - } - - @Test - void test48043() throws IOException { - try (HSSFWorkbook wb = openSampleWorkbook("56325a.xls")) { - - wb.removeSheetAt(2); - wb.removeSheetAt(1); - - //Sheet s = wb.createSheet("sheetname"); - Sheet s = wb.getSheetAt(0); - Row row = s.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellFormula( - "IF(AND(ISBLANK(A10)," + - "ISBLANK(B10)),\"\"," + - "CONCATENATE(A10,\"-\",B10))"); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - eval.evaluateAll(); - try (Workbook wbBack = writeOutAndReadBack(wb)) { - assertNotNull(wbBack); - } - } - } - - @Test - void test57925() throws IOException { - try (Workbook wb = openSampleWorkbook("57925.xls")) { - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - DataFormatter df = new DataFormatter(); - for (Sheet sheet : wb) { - for (Row row : sheet) { - for (Cell cell : row) { - assertNotNull(df.formatCellValue(cell)); - } - } - } - } - } - - @Test - void test46515() throws IOException { - try (Workbook wb = openSampleWorkbook("46515.xls")) { - - // Get structure from webservice - String urlString = "https://poi.apache.org/components/spreadsheet/images/calendar.jpg"; - URL structURL = new URL(urlString); - BufferedImage bimage; - try { - bimage = ImageIO.read(structURL); - } catch (IOException e) { - Assumptions.assumeFalse(true, "Downloading a jpg from poi.apache.org should work"); - return; - } - - // Convert BufferedImage to byte[] - ByteArrayOutputStream imageBAOS = new ByteArrayOutputStream(); - ImageIO.write(bimage, "jpeg", imageBAOS); - imageBAOS.flush(); - byte[] imageBytes = imageBAOS.toByteArray(); - imageBAOS.close(); - - // Pop structure into Structure HSSFSheet - int pict = wb.addPicture(imageBytes, HSSFWorkbook.PICTURE_TYPE_JPEG); - Sheet sheet = wb.getSheet("Structure"); - assertNotNull(sheet, "Did not find sheet"); - HSSFPatriarch patriarch = (HSSFPatriarch) sheet.createDrawingPatriarch(); - HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 10, 22); - anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE); - patriarch.createPicture(anchor, pict); - } - } - - @Test - void test55668() throws IOException { - try (Workbook wb = openSampleWorkbook("55668.xls")) { - - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("IF(TRUE,\"\",\"\")", cell.getCellFormula()); - assertEquals("", cell.getStringCellValue()); - //noinspection deprecation - cell.setCellType(CellType.STRING); - - assertEquals(CellType.BLANK, cell.getCellType()); - assertEquals("", cell.getStringCellValue()); - - assertThrows(IllegalStateException.class, cell::getCellFormula); - } - } - - @Test - void test55982() throws IOException { - simpleTest("55982.xls", wb -> assertNotNull(wb.cloneSheet(1))); - } - - /** - * Test generator of ids for the CommonObjectDataSubRecord record. - */ - @Test - void test51332() { - HSSFClientAnchor anchor = new HSSFClientAnchor(); - HSSFSimpleShape shape; - CommonObjectDataSubRecord cmo; - - shape = new HSSFTextbox(null, anchor); - shape.setShapeId(1025); - cmo = (CommonObjectDataSubRecord) shape.getObjRecord().getSubRecords().get(0); - assertEquals(1, cmo.getObjectId()); - - shape = new HSSFPicture(null, anchor); - shape.setShapeId(1026); - cmo = (CommonObjectDataSubRecord) shape.getObjRecord().getSubRecords().get(0); - assertEquals(2, cmo.getObjectId()); - - shape = new HSSFComment(null, anchor); - shape.setShapeId(1027); - cmo = (CommonObjectDataSubRecord) shape.getObjRecord().getSubRecords().get(0); - assertEquals(1027, cmo.getObjectId()); - } - - // As of POI 3.15 beta 2, LibreOffice does not display the diagonal border while it does display the bottom border - // I have not checked Excel to know if this is a LibreOffice or a POI problem. - @Test - void test53564() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet("Page 1"); - final short BLUE = 30; - - HSSFSheetConditionalFormatting scf = sheet.getSheetConditionalFormatting(); - HSSFConditionalFormattingRule rule = scf.createConditionalFormattingRule(ComparisonOperator.GT, "10"); - - HSSFBorderFormatting bord = rule.createBorderFormatting(); - bord.setBorderDiagonal(BorderStyle.THICK); - assertEquals(BorderStyle.THICK, bord.getBorderDiagonal()); - - bord.setBackwardDiagonalOn(true); - assertTrue(bord.isBackwardDiagonalOn()); - - bord.setForwardDiagonalOn(true); - assertTrue(bord.isForwardDiagonalOn()); - - bord.setDiagonalBorderColor(BLUE); - assertEquals(BLUE, bord.getDiagonalBorderColor()); - - // Create the bottom border style so we know what a border is supposed to look like - bord.setBorderBottom(BorderStyle.THICK); - assertEquals(BorderStyle.THICK, bord.getBorderBottom()); - bord.setBottomBorderColor(BLUE); - assertEquals(BLUE, bord.getBottomBorderColor()); - - CellRangeAddress[] A2_D4 = {new CellRangeAddress(1, 3, 0, 3)}; - scf.addConditionalFormatting(A2_D4, rule); - - // Set a cell value within the conditional formatting range whose rule would resolve to True. - Cell C3 = sheet.createRow(2).createCell(2); - C3.setCellValue(30.0); - } - } - - @Test - void test61287() throws IOException { - try (HSSFWorkbook wb = openSampleWorkbook("61287.xls"); - ExcelExtractor ex = new ExcelExtractor(wb)) { - String text = ex.getText(); - assertContains(text, "\u8D44\u4EA7\u8D1F\u503A\u8868"); - } - } - - @Test - void test61300() throws Exception { - try (POIFSFileSystem poifs = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("61300.xls"))) { - - DocumentEntry entry = - (DocumentEntry) poifs.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - - RuntimeException ex = assertThrows( - RuntimeException.class, - () -> new PropertySet(new DocumentInputStream(entry)) - ); - assertEquals("Can't read negative number of bytes", ex.getMessage()); - } - } - - @Test - void test51262() throws IOException { - try (HSSFWorkbook wb = openSampleWorkbook("51262.xls")) { - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(2); - - Cell cell = row.getCell(1); - CellStyle style = cell.getCellStyle(); - assertEquals(26, style.getFontIndex()); - - row = sheet.getRow(3); - cell = row.getCell(1); - style = cell.getCellStyle(); - assertEquals(28, style.getFontIndex()); - - // check the two fonts - HSSFFont font = wb.getFontAt(26); - assertTrue(font.getBold()); - assertEquals(10, font.getFontHeightInPoints()); - assertEquals("\uFF2D\uFF33 \uFF30\u30B4\u30B7\u30C3\u30AF", font.getFontName()); - - font = wb.getFontAt(28); - assertTrue(font.getBold()); - assertEquals(10, font.getFontHeightInPoints()); - assertEquals("\uFF2D\uFF33 \uFF30\u30B4\u30B7\u30C3\u30AF", font.getFontName()); - } - } - - @Test - void test60460() throws IOException { - try (final Workbook wb = openSampleWorkbook("60460.xls")) { - assertEquals(2, wb.getAllNames().size()); - - Name rangedName = wb.getAllNames().get(0); - assertFalse(rangedName.isFunctionName()); - assertEquals("'[\\\\HEPPC3\\gt$\\Teaching\\Syn\\physyn.xls]#REF'!$AK$70:$AL$70", - // replace '/' to make test work equally on Windows and Linux - rangedName.getRefersToFormula().replace("/", "\\")); - - rangedName = wb.getAllNames().get(1); - assertFalse(rangedName.isFunctionName()); - assertEquals("Questionnaire!$A$1:$L$65", rangedName.getRefersToFormula()); - } - } - - @Test - void test63819() throws IOException { - LocaleUtil.setUserLocale(Locale.UK); - try { - simpleTest("63819.xls", null); - } finally { - LocaleUtil.resetUserLocale(); - } - } - - /** - * Test that VALUE behaves properly as array function and its result is handled by aggregate function - */ - @Test - void testValueAsArrayFunction() throws IOException { - try (final Workbook wb = openSampleWorkbook("TestValueAsArrayFunction.xls")) { - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - assertEquals(6.0, cell.getNumericCellValue(), 0.0); - } - } - - // a simple test which rewrites the file once and evaluates its formulas - @ParameterizedTest - @CsvSource({ - "15228.xls", "13796.xls", "14460.xls", "14330-1.xls", "14330-2.xls", "22742.xls", "12561-1.xls", "12561-2.xls", - "12843-1.xls", "12843-2.xls", "13224.xls", "19599-1.xls", "19599-2.xls", "32822.xls", "15573.xls", - "33082.xls", "34775.xls", "37630.xls", "25183.xls", "26100.xls", "27933.xls", "29675.xls", "29982.xls", - "31749.xls", "37376.xls", "SimpleWithAutofilter.xls", "44201.xls", "37684-1.xls", "37684-2.xls", - "41139.xls", "ex42564-21435.xls", "ex42564-21503.xls", "28774.xls", "44891.xls", "44235.xls", "36947.xls", - "39634.xls", "47701.xls", "48026.xls", "47251.xls", "47251_1.xls", "50020.xls", "50426.xls", "50779_1.xls", - "50779_2.xls", "51670.xls", "54016.xls", "57456.xls", "53109.xls", "com.aida-tour.www_SPO_files_maldives%20august%20october.xls", - "named-cell-in-formula-test.xls", "named-cell-test.xls", "bug55505.xls", "SUBSTITUTE.xls", "64261.xls" - }) - void simpleTest(String fileName) throws IOException { - simpleTest(fileName, null); - } - - @SuppressWarnings("unchecked") - @ParameterizedTest - @CsvSource({ - "46904.xls, org.apache.poi.hssf.OldExcelFormatException, The supplied spreadsheet seems to be Excel", - "51832.xls, org.apache.poi.EncryptedDocumentException, Default password is invalid for salt/verifier/verifierHash" - }) - void simpleTest(String fileName, String exClazz, String exMessage) throws IOException, ClassNotFoundException { - Class ex = (Class)Class.forName(exClazz); - Exception e = assertThrows(ex, () -> simpleTest(fileName, null)); - assertTrue(e.getMessage().startsWith(exMessage)); - } - - private void simpleTest(String fileName, Consumer addTest) throws IOException { - try (HSSFWorkbook wb1 = openSampleWorkbook(fileName)) { - if (addTest != null) { - addTest.accept(wb1); - } - - HSSFSheet s = wb1.getSheetAt(0); - HSSFRow r = s.createRow(10_000); - HSSFCell c = r.createCell(0); - c.setCellValue(10); - - HSSFSheet tmpSheet = wb1.createSheet("POITESTSHEET"); - tmpSheet.createRow(10).createCell(10).setCellValue("Test"); - wb1.removeSheetAt(wb1.getSheetIndex(tmpSheet)); - - simpleTestHelper(wb1, fileName); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - if (addTest != null) { - addTest.accept(wb2); - } - - double act = wb2.getSheetAt(0).getRow(10_000).getCell(0).getNumericCellValue(); - assertEquals(10, act, 0); - simpleTestHelper(wb2, fileName); - } - } - } - - private void simpleTestHelper(HSSFWorkbook wb, String fileName) { - List files = new ArrayList<>(); - files.add(fileName); - files.addAll(SIMPLE_REFS.keySet()); - List evals = new ArrayList<>(); - evals.add(wb.getCreationHelper().createFormulaEvaluator()); - evals.addAll(SIMPLE_REFS.values()); - - try { - HSSFFormulaEvaluator.setupEnvironment(files.toArray(new String[0]), evals.toArray(new HSSFFormulaEvaluator[0])); - evals.get(0).evaluateAll(); - } catch (RuntimeException e) { - throw new RuntimeException("While handling files " + files + " and evals " + evals, e); - } - } - - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java deleted file mode 100644 index d80f000368..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java +++ /dev/null @@ -1,504 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.ss.usermodel.BorderStyle.*; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Calendar; -import java.util.Date; -import java.util.Random; -import java.util.stream.Stream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.Test; - -/** - * Class to test cell styling functionality - */ - -final class TestCellStyle { - - private static HSSFWorkbook openSample(String sampleFileName) { - return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - - /** - * TEST NAME: Test Write Sheet Font

- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with fonts.

- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (99,0).

- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

- * - */ - @Test - void testWriteSheetFont() throws IOException{ - File file = TempFile.createTempFile("testWriteSheetFont", ".xls"); - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - HSSFFont fnt = wb.createFont(); - HSSFCellStyle cs = wb.createCellStyle(); - - fnt.setColor(HSSFFont.COLOR_RED); - fnt.setBold(true); - cs.setFont(fnt); - for (int rownum = 0; rownum < 100; rownum++) { - HSSFRow r = s.createRow(rownum); - - for (int cellnum = 0; cellnum < 50; cellnum += 2) { - HSSFCell c = r.createCell(cellnum); - c.setCellValue(rownum * 10000 + cellnum - + (((double) rownum / 1000) - + ((double) cellnum / 10000))); - c = r.createCell(cellnum + 1); - c.setCellValue("TEST"); - c.setCellStyle(cs); - } - } - try (FileOutputStream out = new FileOutputStream(file)) { - wb.write(out); - } - - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb); - assertEquals(99, s.getLastRowNum(), "LAST ROW == 99"); - assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0"); - } - - // assert((s.getLastRowNum() == 99)); - } - - /** - * Tests that is creating a file with a date or an calendar works correctly. - */ - @Test - void testDataStyle() throws IOException { - File file = TempFile.createTempFile("testWriteSheetStyleDate", ".xls"); - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - HSSFCellStyle cs = wb.createCellStyle(); - HSSFRow row = s.createRow(0); - - // with Date: - HSSFCell cell = row.createCell(1); - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); - cell.setCellStyle(cs); - cell.setCellValue(new Date()); - - // with Calendar: - cell = row.createCell(2); - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); - cell.setCellStyle(cs); - Calendar cal = LocaleUtil.getLocaleCalendar(); - cell.setCellValue(cal); - - try (FileOutputStream out = new FileOutputStream(file)) { - wb.write(out); - } - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb); - - assertEquals(0, s.getLastRowNum(), "LAST ROW"); - assertEquals(0, s.getFirstRowNum(), "FIRST ROW"); - } - } - - @Test - void testHashEquals() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - HSSFCellStyle cs1 = wb.createCellStyle(); - HSSFCellStyle cs2 = wb.createCellStyle(); - HSSFRow row = s.createRow(0); - HSSFCell cell1 = row.createCell(1); - HSSFCell cell2 = row.createCell(2); - - cs1.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); - cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/dd/yy")); - - cell1.setCellStyle(cs1); - cell1.setCellValue(new Date()); - - cell2.setCellStyle(cs2); - cell2.setCellValue(new Date()); - - assertEquals(cs1.hashCode(), cs1.hashCode()); - assertEquals(cs2.hashCode(), cs2.hashCode()); - assertEquals(cs1, cs1); - assertEquals(cs2, cs2); - - // Change cs1, hash will alter - int hash1 = cs1.hashCode(); - cs1.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/dd/yy")); - assertNotEquals(hash1, cs1.hashCode()); - } - } - - /** - * TEST NAME: Test Write Sheet Style

- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with colors - * and borders.

- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (99,0).

- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

- * - */ - @Test - void testWriteSheetStyle() throws IOException { - File file = TempFile.createTempFile("testWriteSheetStyle", ".xls"); - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - HSSFFont fnt = wb.createFont(); - HSSFCellStyle cs = wb.createCellStyle(); - HSSFCellStyle cs2 = wb.createCellStyle(); - - cs.setBorderBottom(THIN); - cs.setBorderLeft(THIN); - cs.setBorderRight(THIN); - cs.setBorderTop(THIN); - cs.setFillForegroundColor((short) 0xA); - cs.setFillPattern(FillPatternType.DIAMONDS); - fnt.setColor((short) 0xf); - fnt.setItalic(true); - cs2.setFillForegroundColor((short) 0x0); - cs2.setFillPattern(FillPatternType.DIAMONDS); - cs2.setFont(fnt); - for (int rownum = 0; rownum < 100; rownum++) { - HSSFRow r = s.createRow(rownum); - - for (int cellnum = 0; cellnum < 50; cellnum += 2) { - HSSFCell c = r.createCell(cellnum); - c.setCellValue(rownum * 10000 + cellnum - + (((double) rownum / 1000) - + ((double) cellnum / 10000))); - c.setCellStyle(cs); - c = r.createCell(cellnum + 1); - c.setCellValue("TEST"); - c.setCellStyle(cs2); - } - } - try (FileOutputStream out = new FileOutputStream(file)) { - wb.write(out); - } - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb); - assertEquals(99, s.getLastRowNum(), "LAST ROW == 99"); - assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0"); - } - } - - /** - * Cloning one HSSFCellStyle onto Another, same - * HSSFWorkbook - */ - @Test - void testCloneStyleSameWB() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFFont fnt = wb.createFont(); - fnt.setFontName("TestingFont"); - assertEquals(5, wb.getNumberOfFonts()); - - HSSFCellStyle orig = wb.createCellStyle(); - orig.setAlignment(HorizontalAlignment.JUSTIFY); - orig.setFont(fnt); - orig.setDataFormat((short) 18); - - assertEquals(HorizontalAlignment.JUSTIFY, orig.getAlignment()); - assertEquals(fnt, orig.getFont(wb)); - assertEquals(18, orig.getDataFormat()); - - HSSFCellStyle clone = wb.createCellStyle(); - assertNotSame(HorizontalAlignment.RIGHT, clone.getAlignment()); - assertNotSame(fnt, clone.getFont(wb)); - assertNotEquals(18, clone.getDataFormat()); - - clone.cloneStyleFrom(orig); - assertEquals(HorizontalAlignment.JUSTIFY, clone.getAlignment()); - assertEquals(fnt, clone.getFont(wb)); - assertEquals(18, clone.getDataFormat()); - assertEquals(5, wb.getNumberOfFonts()); - } - } - - /** - * Cloning one HSSFCellStyle onto Another, across - * two different HSSFWorkbooks - */ - @Test - void testCloneStyleDiffWB() throws IOException { - try (HSSFWorkbook wbOrig = new HSSFWorkbook()) { - - HSSFFont fnt = wbOrig.createFont(); - fnt.setFontName("TestingFont"); - assertEquals(5, wbOrig.getNumberOfFonts()); - - HSSFDataFormat fmt = wbOrig.createDataFormat(); - fmt.getFormat("MadeUpOne"); - fmt.getFormat("MadeUpTwo"); - - HSSFCellStyle orig = wbOrig.createCellStyle(); - orig.setAlignment(HorizontalAlignment.RIGHT); - orig.setFont(fnt); - orig.setDataFormat(fmt.getFormat("Test##")); - - assertEquals(HorizontalAlignment.RIGHT, orig.getAlignment()); - assertEquals(fnt, orig.getFont(wbOrig)); - assertEquals(fmt.getFormat("Test##"), orig.getDataFormat()); - - // Now a style on another workbook - try (HSSFWorkbook wbClone = new HSSFWorkbook()) { - assertEquals(4, wbClone.getNumberOfFonts()); - HSSFDataFormat fmtClone = wbClone.createDataFormat(); - - HSSFCellStyle clone = wbClone.createCellStyle(); - assertEquals(4, wbClone.getNumberOfFonts()); - - assertNotSame(HorizontalAlignment.RIGHT, clone.getAlignment()); - assertNotSame("TestingFont", clone.getFont(wbClone).getFontName()); - - clone.cloneStyleFrom(orig); - assertEquals(HorizontalAlignment.RIGHT, clone.getAlignment()); - assertEquals("TestingFont", clone.getFont(wbClone).getFontName()); - assertEquals(fmtClone.getFormat("Test##"), clone.getDataFormat()); - assertNotEquals(fmtClone.getFormat("Test##"), fmt.getFormat("Test##")); - assertEquals(5, wbClone.getNumberOfFonts()); - } - } - } - - @Test - void testStyleNames() throws IOException { - try (HSSFWorkbook wb = openSample("WithExtendedStyles.xls")) { - HSSFSheet s = wb.getSheetAt(0); - HSSFCell c1 = s.getRow(0).getCell(0); - HSSFCell c2 = s.getRow(1).getCell(0); - HSSFCell c3 = s.getRow(2).getCell(0); - - HSSFCellStyle cs1 = c1.getCellStyle(); - HSSFCellStyle cs2 = c2.getCellStyle(); - HSSFCellStyle cs3 = c3.getCellStyle(); - - assertNotNull(cs1); - assertNotNull(cs2); - assertNotNull(cs3); - - // Check we got the styles we'd expect - assertEquals(10, cs1.getFont(wb).getFontHeightInPoints()); - assertEquals(9, cs2.getFont(wb).getFontHeightInPoints()); - assertEquals(12, cs3.getFont(wb).getFontHeightInPoints()); - - assertEquals(15, cs1.getIndex()); - assertEquals(23, cs2.getIndex()); - assertEquals(24, cs3.getIndex()); - - assertNull(cs1.getParentStyle()); - assertNotNull(cs2.getParentStyle()); - assertNotNull(cs3.getParentStyle()); - - assertEquals(21, cs2.getParentStyle().getIndex()); - assertEquals(22, cs3.getParentStyle().getIndex()); - - // Now check we can get style records for the parent ones - assertNull(wb.getWorkbook().getStyleRecord(15)); - assertNull(wb.getWorkbook().getStyleRecord(23)); - assertNull(wb.getWorkbook().getStyleRecord(24)); - - assertNotNull(wb.getWorkbook().getStyleRecord(21)); - assertNotNull(wb.getWorkbook().getStyleRecord(22)); - - // Now check the style names - assertNull(cs1.getUserStyleName()); - assertNull(cs2.getUserStyleName()); - assertNull(cs3.getUserStyleName()); - assertEquals("style1", cs2.getParentStyle().getUserStyleName()); - assertEquals("style2", cs3.getParentStyle().getUserStyleName()); - - // now apply a named style to a new cell - HSSFCell c4 = s.getRow(0).createCell(1); - c4.setCellStyle(cs2); - assertEquals("style1", c4.getCellStyle().getParentStyle().getUserStyleName()); - } - } - - @Test - void testGetSetBorderHair() throws IOException { - BorderStyle[] bs = { - HAIR, DOTTED, DASH_DOT_DOT, DASHED, THIN, MEDIUM_DASH_DOT_DOT, SLANTED_DASH_DOT, - MEDIUM_DASH_DOT, MEDIUM_DASHED, MEDIUM, THICK, DOUBLE - }; - - try (HSSFWorkbook wb = openSample("55341_CellStyleBorder.xls")) { - HSSFSheet s = wb.getSheetAt(0); - for (int i = 0; i assertDoesNotThrow(() -> { - Random rand = new Random(); - for(int i=0; i<10; i++) { - Thread.sleep(rand.nextInt(300)); - try (Workbook wb = openSample(fileName)) { - for (Row row : wb.getSheetAt(0)) { - for (Cell cell : row) { - cell.getCellStyle().getDataFormatString(); - if (cell.getCellType() == CellType.NUMERIC) { - boolean isDate = DateUtil.isCellDateFormatted(cell); - int cid = cell.getColumnIndex(); - assertFalse(cid > 0 && isDate, "cell " + cid + " is not a date."); - } - } - } - } - } - })); - } - - @Test - void test56959() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = wb.createSheet("somesheet"); - - Row row = sheet.createRow(0); - - // Create a new font and alter it. - Font font = wb.createFont(); - font.setFontHeightInPoints((short) 24); - font.setFontName("Courier New"); - font.setItalic(true); - font.setStrikeout(true); - font.setColor(Font.COLOR_RED); - - CellStyle style = wb.createCellStyle(); - style.setBorderBottom(DOTTED); - style.setFont(font); - - Cell cell = row.createCell(0); - cell.setCellStyle(style); - cell.setCellValue("testtext"); - - Cell newCell = row.createCell(1); - - newCell.setCellStyle(style); - newCell.setCellValue("2testtext2"); - - CellStyle newStyle = newCell.getCellStyle(); - assertEquals(DOTTED, newStyle.getBorderBottom()); - assertEquals(Font.COLOR_RED, ((HSSFCellStyle) newStyle).getFont(wb).getColor()); - } - } - - - @Test - void test58043() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFCellStyle cellStyle = wb.createCellStyle(); - - assertEquals(0, cellStyle.getRotation()); - - cellStyle.setRotation((short) 89); - assertEquals(89, cellStyle.getRotation()); - - cellStyle.setRotation((short) 90); - assertEquals(90, cellStyle.getRotation()); - - cellStyle.setRotation((short) -1); - assertEquals(-1, cellStyle.getRotation()); - - cellStyle.setRotation((short) -89); - assertEquals(-89, cellStyle.getRotation()); - - cellStyle.setRotation((short) -90); - assertEquals(-90, cellStyle.getRotation()); - - cellStyle.setRotation((short) -89); - assertEquals(-89, cellStyle.getRotation()); - - // values above 90 are mapped to the correct values for compatibility between HSSF and XSSF - cellStyle.setRotation((short) 179); - assertEquals(-89, cellStyle.getRotation()); - - cellStyle.setRotation((short) 180); - assertEquals(-90, cellStyle.getRotation()); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java deleted file mode 100644 index cb3d92d113..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java +++ /dev/null @@ -1,135 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.record.CommonObjectDataSubRecord; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.ss.usermodel.BaseTestCloneSheet; -import org.junit.jupiter.api.Test; - -/** - * Test the ability to clone a sheet. - * If adding new records that belong to a sheet (as opposed to a book) - * add that record to the sheet in the testCloneSheetBasic method. - * @author avik - */ -final class TestCloneSheet extends BaseTestCloneSheet { - public TestCloneSheet() { - super(HSSFITestDataProvider.instance); - } - - @Test - void testCloneSheetWithoutDrawings(){ - HSSFWorkbook b = new HSSFWorkbook(); - HSSFSheet s = b.createSheet("Test"); - HSSFSheet s2 = s.cloneSheet(b); - - assertNull(s.getDrawingPatriarch()); - assertNull(s2.getDrawingPatriarch()); - assertEquals(HSSFTestHelper.getSheetForTest(s).getRecords().size(), HSSFTestHelper.getSheetForTest(s2).getRecords().size()); - } - - @Test - void testCloneSheetWithEmptyDrawingAggregate(){ - HSSFWorkbook b = new HSSFWorkbook(); - HSSFSheet s = b.createSheet("Test"); - HSSFPatriarch patriarch = s.createDrawingPatriarch(); - - EscherAggregate agg1 = patriarch.getBoundAggregate(); - - HSSFSheet s2 = s.cloneSheet(b); - - patriarch = s2.getDrawingPatriarch(); - - EscherAggregate agg2 = patriarch.getBoundAggregate(); - - EscherSpRecord sp1 = (EscherSpRecord) agg1.getEscherContainer().getChild(1).getChild(0).getChild(1); - EscherSpRecord sp2 = (EscherSpRecord) agg2.getEscherContainer().getChild(1).getChild(0).getChild(1); - - assertEquals(sp1.getShapeId(), 1024); - assertEquals(sp2.getShapeId(), 2048); - - EscherDgRecord dg = (EscherDgRecord) agg2.getEscherContainer().getChild(0); - - assertEquals(dg.getLastMSOSPID(), 2048); - assertEquals(dg.getInstance(), 0x2); - - //everything except id and DgRecord.lastMSOSPID and DgRecord.Instance must be the same - - sp2.setShapeId(1024); - dg.setLastMSOSPID(1024); - dg.setInstance((short) 0x1); - - assertEquals(agg1.serialize().length, agg2.serialize().length); - assertEquals(agg1.toXml(""), agg2.toXml("")); - assertArrayEquals(agg1.serialize(), agg2.serialize()); - } - - @Test - void testCloneComment() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch p = sh.createDrawingPatriarch(); - HSSFComment c = p.createComment(new HSSFClientAnchor(0,0,100,100, (short) 0,0,(short)5,5)); - c.setColumn(1); - c.setRow(2); - c.setString(new HSSFRichTextString("qwertyuio")); - - HSSFSheet sh2 = wb.cloneSheet(0); - HSSFPatriarch p2 = sh2.getDrawingPatriarch(); - HSSFComment c2 = (HSSFComment) p2.getChildren().get(0); - - assertEquals(c.getString(), c2.getString()); - assertEquals(c.getRow(), c2.getRow()); - assertEquals(c.getColumn(), c2.getColumn()); - - // The ShapeId is not equal? - // assertEquals(c.getNoteRecord().getShapeId(), c2.getNoteRecord().getShapeId()); - - assertArrayEquals(c2.getTextObjectRecord().serialize(), c.getTextObjectRecord().serialize()); - - // ShapeId is different - CommonObjectDataSubRecord subRecord = (CommonObjectDataSubRecord) c2.getObjRecord().getSubRecords().get(0); - subRecord.setObjectId(1025); - - assertArrayEquals(c2.getObjRecord().serialize(), c.getObjRecord().serialize()); - - // ShapeId is different - c2.getNoteRecord().setShapeId(1025); - assertArrayEquals(c2.getNoteRecord().serialize(), c.getNoteRecord().serialize()); - - //everything except spRecord.shapeId must be the same - assertFalse(Arrays.equals(c2.getEscherContainer().serialize(), c.getEscherContainer().serialize())); - EscherSpRecord sp = (EscherSpRecord) c2.getEscherContainer().getChild(0); - sp.setShapeId(1025); - assertArrayEquals(c2.getEscherContainer().serialize(), c.getEscherContainer().serialize()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java deleted file mode 100644 index 0f7d5788fe..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.POITestCase.assertContains; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.junit.jupiter.api.Test; - -class TestCryptoAPI { - final HSSFITestDataProvider ssTests = HSSFITestDataProvider.instance; - - @Test - void bug59857() throws IOException { - // XOR-Obfuscation - // TODO: XOR-Obfuscation is currently flawed - although the de-/obfuscation initially works, - // it suddenly differs from the result of encrypted files via Office ... - // and only very small files can be opened without file validation errors - validateContent("xor-encryption-abc.xls", "abc", "Sheet1\n1\n2\n3\n"); - - // BinaryRC4 - validateContent("password.xls", "password", "A ZIP bomb is a variant of mail-bombing. After most commercial mail servers began checking mail with anti-virus software and filtering certain malicious file types, trojan horse viruses tried to send themselves compressed into archives, such as ZIP, RAR or 7-Zip. Mail server software was then configured to unpack archives and check their contents as well. That gave black hats the idea to compose a \"bomb\" consisting of an enormous text file, containing, for example, only the letter z repeated millions of times. Such a file compresses into a relatively small archive, but its unpacking (especially by early versions of mail servers) would use a high amount of processing power, RAM and swap space, which could result in denial of service. Modern mail server computers usually have sufficient intelligence to recognize such attacks as well as sufficient processing power and memory space to process malicious attachments without interruption of service, though some are still susceptible to this technique if the ZIP bomb is mass-mailed."); - - // CryptoAPI - validateContent("35897-type4.xls", "freedom", "Sheet1\nhello there!\n"); - } - - private void validateContent(String wbFile, String password, String textExpected) throws IOException { - Biff8EncryptionKey.setCurrentUserPassword(password); - try (HSSFWorkbook wb = ssTests.openSampleWorkbook(wbFile); - ExcelExtractor ee1 = new ExcelExtractor(wb) - ) { - Biff8EncryptionKey.setCurrentUserPassword("bla"); - try (HSSFWorkbook wbBla = ssTests.writeOutAndReadBack(wb); - ExcelExtractor ee2 = new ExcelExtractor(wbBla)) { - assertContains(ee1.getText(), textExpected); - assertContains(ee2.getText(), textExpected); - } - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java b/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java deleted file mode 100644 index 4a120b2ac6..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java +++ /dev/null @@ -1,434 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.util.List; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.DVRecord; -import org.apache.poi.ss.usermodel.BaseTestDataValidation; -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidation.ErrorStyle; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType; -import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.junit.jupiter.api.Test; - -/** - * Class for testing Excel's data validation mechanism - * - * @author Dragos Buleandra ( dragos.buleandra@trade2b.ro ) - */ -final class TestDataValidation extends BaseTestDataValidation { - - public TestDataValidation(){ - super(HSSFITestDataProvider.instance); - } - - - void assertDataValidation(Workbook wb) { - - byte[] generatedContent; - try (ByteArrayOutputStream baos = new ByteArrayOutputStream(22000)) { - wb.write(baos); - generatedContent = baos.toByteArray(); - } catch (IOException e) { - throw new RuntimeException(e); - } - - boolean isSame; -// if (false) { -// // TODO - add proof spreadsheet and compare -// InputStream proofStream = HSSFTestDataSamples.openSampleFileStream("TestDataValidation.xls"); -// isSame = compareStreams(proofStream, generatedContent); -// } - isSame = true; - - if (isSame) { - return; - } - File tempDir = new File(System.getProperty("java.io.tmpdir")); - File generatedFile = new File(tempDir, "GeneratedTestDataValidation.xls"); - try (FileOutputStream fileOut = new FileOutputStream(generatedFile)) { - fileOut.write(generatedContent); - } catch (IOException e) { - throw new RuntimeException(e); - } - - PrintStream ps = System.out; - - ps.println("This test case has failed because the generated file differs from proof copy '" - ); // TODO+ proofFile.getAbsolutePath() + "'."); - ps.println("The cause is usually a change to this test, or some common spreadsheet generation code. " - + "The developer has to decide whether the changes were wanted or unwanted."); - ps.println("If the changes to the generated version were unwanted, " - + "make the fix elsewhere (do not modify this test or the proof spreadsheet to get the test working)."); - ps.println("If the changes were wanted, make sure to open the newly generated file in Excel " - + "and verify it manually. The new proof file should be submitted after it is verified to be correct."); - ps.println(); - ps.println("One other possible (but less likely) cause of a failed test is a problem in the " - + "comparison logic used here. Perhaps some extra file regions need to be ignored."); - ps.println("The generated file has been saved to '" + generatedFile.getAbsolutePath() + "' for manual inspection."); - - fail("Generated file differs from proof copy. See sysout comments for details on how to fix."); - - } - - /* package */ static void setCellValue(HSSFCell cell, String text) { - cell.setCellValue(new HSSFRichTextString(text)); - - } - - @Test - void testAddToExistingSheet() throws Exception { - - // dvEmpty.xls is a simple one sheet workbook. With a DataValidations header record but no - // DataValidations. It's important that the example has one SHEETPROTECTION record. - // Such a workbook can be created in Excel (2007) by adding datavalidation for one cell - // and then deleting the row that contains the cell. - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("dvEmpty.xls")) { - int dvRow = 0; - Sheet sheet = wb.getSheetAt(0); - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint dc = dataValidationHelper.createIntegerConstraint(OperatorType.EQUAL, "42", null); - DataValidation dv = dataValidationHelper.createValidation(dc, new CellRangeAddressList(dvRow, dvRow, 0, 0)); - - dv.setEmptyCellAllowed(false); - dv.setErrorStyle(ErrorStyle.STOP); - dv.setShowPromptBox(true); - dv.createErrorBox("Xxx", "Yyy"); - dv.setSuppressDropDownArrow(true); - - sheet.addValidationData(dv); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - wb.write(baos); - - byte[] wbData = baos.toByteArray(); - -// if (false) { // TODO (Jul 2008) fix EventRecordFactory to process unknown records, (and DV records for that matter) -// -// ERFListener erfListener = null; // new MyERFListener(); -// EventRecordFactory erf = new EventRecordFactory(erfListener, null); -// try { -// POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(baos.toByteArray())); -// erf.processRecords(fs.createDocumentInputStream("Workbook")); -// } catch (RecordFormatException e) { -// throw new RuntimeException(e); -// } catch (IOException e) { -// throw new RuntimeException(e); -// } -// } - // else verify record ordering by navigating the raw bytes - - byte[] dvHeaderRecStart = {(byte) 0xB2, 0x01, 0x12, 0x00,}; - int dvHeaderOffset = findIndex(wbData, dvHeaderRecStart); - assertTrue(dvHeaderOffset > 0); - int nextRecIndex = dvHeaderOffset + 22; - int nextSid - = ((wbData[nextRecIndex + 0] << 0) & 0x00FF) - + ((wbData[nextRecIndex + 1] << 8) & 0xFF00); - // nextSid should be for a DVRecord. If anything comes between the DV header record - // and the DV records, Excel will not be able to open the workbook without error. - - assertNotEquals(0x0867, nextSid, "Identified bug 45519"); - assertEquals(DVRecord.sid, nextSid); - } - } - - private int findIndex(byte[] largeData, byte[] searchPattern) { - byte firstByte = searchPattern[0]; - for (int i = 0; i < largeData.length; i++) { - if(largeData[i] != firstByte) { - continue; - } - boolean match = true; - for (int j = 1; j < searchPattern.length; j++) { - if(searchPattern[j] != largeData[i+j]) { - match = false; - break; - } - } - if (match) { - return i; - } - } - return -1; - } - - @Test - void testGetDataValidationsAny() throws Exception { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dvh = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dvh.createNumericConstraint(ValidationType.ANY, OperatorType.IGNORED, null, null); - CellRangeAddressList addressList = new CellRangeAddressList(1, 2, 3, 4); - DataValidation validation = dvh.createValidation(constraint, addressList); - validation.setEmptyCellAllowed(true); - validation.createErrorBox("error-title", "error-text"); - validation.createPromptBox("prompt-title", "prompt-text"); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - { - CellRangeAddressList regions = dv.getRegions(); - assertEquals(1, regions.countRanges()); - - CellRangeAddress address = regions.getCellRangeAddress(0); - assertEquals(1, address.getFirstRow()); - assertEquals(2, address.getLastRow()); - assertEquals(3, address.getFirstColumn()); - assertEquals(4, address.getLastColumn()); - } - assertTrue(dv.getEmptyCellAllowed()); - assertFalse(dv.getSuppressDropDownArrow()); - assertTrue(dv.getShowErrorBox()); - assertEquals("error-title", dv.getErrorBoxTitle()); - assertEquals("error-text", dv.getErrorBoxText()); - assertTrue(dv.getShowPromptBox()); - assertEquals("prompt-title", dv.getPromptBoxTitle()); - assertEquals("prompt-text", dv.getPromptBoxText()); - - DataValidationConstraint c = dv.getValidationConstraint(); - assertEquals(ValidationType.ANY, c.getValidationType()); - assertEquals(OperatorType.IGNORED, c.getOperator()); - } - } - - @Test - void testGetDataValidationsIntegerFormula() throws Exception { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dvh = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dvh.createIntegerConstraint(OperatorType.BETWEEN, "=A2", "=A3"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dvh.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.INTEGER, c.getValidationType()); - assertEquals(OperatorType.BETWEEN, c.getOperator()); - assertEquals("A2", c.getFormula1()); - assertEquals("A3", c.getFormula2()); - assertNull(c.getValue1()); - assertNull(c.getValue2()); - } - } - - @Test - void testGetDataValidationsIntegerValue() throws Exception { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dvh = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dvh.createIntegerConstraint(OperatorType.BETWEEN, "100", "200"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dvh.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.INTEGER, c.getValidationType()); - assertEquals(OperatorType.BETWEEN, c.getOperator()); - assertNull(c.getFormula1()); - assertNull(c.getFormula2()); - assertEquals(100d, c.getValue1(), 0); - assertEquals(200d, c.getValue2(), 0); - } - } - - @Test - void testGetDataValidationsDecimal() throws Exception { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dvh = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dvh.createDecimalConstraint(OperatorType.BETWEEN, "=A2", "200"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dvh.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.DECIMAL, c.getValidationType()); - assertEquals(OperatorType.BETWEEN, c.getOperator()); - assertEquals("A2", c.getFormula1()); - assertNull(c.getFormula2()); - assertNull(c.getValue1()); - assertEquals(200, c.getValue2(), 0); - } - } - - @Test - void testGetDataValidationsDate() throws Exception { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dvh = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dvh.createDateConstraint(OperatorType.EQUAL, "2014/10/25", null, null); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dvh.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.DATE, c.getValidationType()); - assertEquals(OperatorType.EQUAL, c.getOperator()); - assertNull(c.getFormula1()); - assertNull(c.getFormula2()); - assertEquals(DateUtil.getExcelDate(DateUtil.parseYYYYMMDDDate("2014/10/25")), c.getValue1(), 0); - assertNull(c.getValue2()); - } - } - - @Test - void testGetDataValidationsListExplicit() throws Exception { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dvh = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dvh.createExplicitListConstraint(new String[]{"aaa", "bbb", "ccc"}); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dvh.createValidation(constraint, addressList); - validation.setSuppressDropDownArrow(true); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - assertTrue(dv.getSuppressDropDownArrow()); - - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.LIST, c.getValidationType()); - assertNull(c.getFormula1()); - assertNull(c.getFormula2()); - assertNull(c.getValue1()); - assertNull(c.getValue2()); - String[] values = c.getExplicitListValues(); - assertEquals(3, values.length); - assertEquals("aaa", values[0]); - assertEquals("bbb", values[1]); - assertEquals("ccc", values[2]); - } - } - - @Test - void testGetDataValidationsListFormula() throws Exception { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createFormulaListConstraint("A2"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - validation.setSuppressDropDownArrow(true); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - assertTrue(dv.getSuppressDropDownArrow()); - - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.LIST, c.getValidationType()); - assertEquals("A2", c.getFormula1()); - assertNull(c.getFormula2()); - assertNull(c.getValue1()); - assertNull(c.getValue2()); - } - } - - @Test - void testGetDataValidationsFormula() throws Exception { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("A2:A3"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.FORMULA, c.getValidationType()); - assertEquals("A2:A3", c.getFormula1()); - assertNull(c.getFormula2()); - assertNull(c.getValue1()); - assertNull(c.getValue2()); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java deleted file mode 100644 index 1617bd65ad..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * Tests for the embedded object fetching support in HSSF - */ -class TestEmbeddedObjects { - @Test - void testReadExistingObject() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls")) { - List list = wb.getAllEmbeddedObjects(); - assertEquals(list.size(), 1); - HSSFObjectData obj = list.get(0); - assertNotNull(obj.getObjectData()); - assertNotNull(obj.getDirectory()); - assertNotNull(obj.getOLE2ClassName()); - } - } - - /** - * Need to recurse into the shapes to find this one - * See https://github.com/apache/poi/pull/2 - */ - @Test - void testReadNestedObject() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithCheckBoxes.xls")) { - List list = wb.getAllEmbeddedObjects(); - assertEquals(list.size(), 1); - HSSFObjectData obj = list.get(0); - assertNotNull(obj.getObjectData()); - assertNotNull(obj.getOLE2ClassName()); - } - } - - /** - * One with large numbers of recursivly embedded resources - * See https://github.com/apache/poi/pull/2 - */ - @Test - void testReadManyNestedObjects() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("45538_form_Header.xls")) { - List list = wb.getAllEmbeddedObjects(); - assertEquals(list.size(), 40); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java deleted file mode 100644 index 3ddac1b794..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java +++ /dev/null @@ -1,307 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.awt.Color; -import java.awt.Font; -import java.awt.FontMetrics; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Tests the capabilities of the EscherGraphics class. - * - * All tests have two escher groups available to them, - * one anchored at 0,0,1022,255 and another anchored - * at 20,30,500,200 - */ -final class TestEscherGraphics { - private HSSFWorkbook workbook; - private HSSFPatriarch patriarch; - private HSSFShapeGroup escherGroupA; - private EscherGraphics graphics; - - @BeforeEach - void setUp() throws IOException { - workbook = new HSSFWorkbook(); - - HSSFSheet sheet = workbook.createSheet("test"); - patriarch = sheet.createDrawingPatriarch(); - escherGroupA = patriarch.createGroup(new HSSFClientAnchor(0,0,1022,255,(short)0,0,(short) 0,0)); - patriarch.createGroup(new HSSFClientAnchor(20,30,500,200,(short)0,0,(short) 0,0)); - graphics = new EscherGraphics(escherGroupA, workbook, Color.black, 1.0f); - } - - @AfterEach - void closeResources() throws IOException { - workbook.close(); - } - - @Test - void testGetFont() { - Font f = graphics.getFont(); - if (! f.toString().contains("dialog") && ! f.toString().contains("Dialog")) { - assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", f.toString()); - } - } - - @Test - void testGetFontMetrics() { - Font f = graphics.getFont(); - if (f.toString().contains("dialog") || f.toString().contains("Dialog")) { - return; - } - FontMetrics fontMetrics = graphics.getFontMetrics(graphics.getFont()); - assertEquals(7, fontMetrics.charWidth('X')); - assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", fontMetrics.getFont().toString()); - } - - @Test - void testSetFont() { - Font f = new Font("Helvetica", 0, 12); - graphics.setFont(f); - assertEquals(f, graphics.getFont()); - } - - @Test - void testSetColor() { - graphics.setColor(Color.red); - assertEquals(Color.red, graphics.getColor()); - } - - @Test - void testFillRect() { - graphics.fillRect( 10, 10, 20, 20 ); - HSSFSimpleShape s = (HSSFSimpleShape) escherGroupA.getChildren().get(0); - assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, s.getShapeType()); - assertEquals(10, s.getAnchor().getDx1()); - assertEquals(10, s.getAnchor().getDy1()); - assertEquals(30, s.getAnchor().getDy2()); - assertEquals(30, s.getAnchor().getDx2()); - } - - @Test - void testDrawString() { - graphics.drawString("This is a test", 10, 10); - HSSFTextbox t = (HSSFTextbox) escherGroupA.getChildren().get(0); - assertEquals("This is a test", t.getString().getString()); - } - - @Test - void testGetDataBackAgain() throws Exception { - HSSFSheet s; - HSSFShapeGroup s1; - HSSFShapeGroup s2; - - patriarch.setCoordinates(10, 20, 30, 40); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - - patriarch = s.getDrawingPatriarch(); - - assertNotNull(patriarch); - assertEquals(10, patriarch.getX1()); - assertEquals(20, patriarch.getY1()); - assertEquals(30, patriarch.getX2()); - assertEquals(40, patriarch.getY2()); - - // Check the two groups too - assertEquals(2, patriarch.countOfAllChildren()); - assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup); - assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup); - - s1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - s2 = (HSSFShapeGroup)patriarch.getChildren().get(1); - - assertEquals(0, s1.getX1()); - assertEquals(0, s1.getY1()); - assertEquals(1023, s1.getX2()); - assertEquals(255, s1.getY2()); - assertEquals(0, s2.getX1()); - assertEquals(0, s2.getY1()); - assertEquals(1023, s2.getX2()); - assertEquals(255, s2.getY2()); - - assertEquals(0, s1.getAnchor().getDx1()); - assertEquals(0, s1.getAnchor().getDy1()); - assertEquals(1022, s1.getAnchor().getDx2()); - assertEquals(255, s1.getAnchor().getDy2()); - assertEquals(20, s2.getAnchor().getDx1()); - assertEquals(30, s2.getAnchor().getDy1()); - assertEquals(500, s2.getAnchor().getDx2()); - assertEquals(200, s2.getAnchor().getDy2()); - - - // Write and re-load once more, to check that's ok - baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - patriarch = s.getDrawingPatriarch(); - - assertNotNull(patriarch); - assertEquals(10, patriarch.getX1()); - assertEquals(20, patriarch.getY1()); - assertEquals(30, patriarch.getX2()); - assertEquals(40, patriarch.getY2()); - - // Check the two groups too - assertEquals(2, patriarch.countOfAllChildren()); - assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup); - assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup); - - s1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - s2 = (HSSFShapeGroup)patriarch.getChildren().get(1); - - assertEquals(0, s1.getX1()); - assertEquals(0, s1.getY1()); - assertEquals(1023, s1.getX2()); - assertEquals(255, s1.getY2()); - assertEquals(0, s2.getX1()); - assertEquals(0, s2.getY1()); - assertEquals(1023, s2.getX2()); - assertEquals(255, s2.getY2()); - - assertEquals(0, s1.getAnchor().getDx1()); - assertEquals(0, s1.getAnchor().getDy1()); - assertEquals(1022, s1.getAnchor().getDx2()); - assertEquals(255, s1.getAnchor().getDy2()); - assertEquals(20, s2.getAnchor().getDx1()); - assertEquals(30, s2.getAnchor().getDy1()); - assertEquals(500, s2.getAnchor().getDx2()); - assertEquals(200, s2.getAnchor().getDy2()); - - // Change the positions of the first groups, - // but not of their anchors - s1.setCoordinates(2, 3, 1021, 242); - - baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - patriarch = s.getDrawingPatriarch(); - - assertNotNull(patriarch); - assertEquals(10, patriarch.getX1()); - assertEquals(20, patriarch.getY1()); - assertEquals(30, patriarch.getX2()); - assertEquals(40, patriarch.getY2()); - - // Check the two groups too - assertEquals(2, patriarch.countOfAllChildren()); - assertEquals(2, patriarch.getChildren().size()); - assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup); - assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup); - - s1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - s2 = (HSSFShapeGroup)patriarch.getChildren().get(1); - - assertEquals(2, s1.getX1()); - assertEquals(3, s1.getY1()); - assertEquals(1021, s1.getX2()); - assertEquals(242, s1.getY2()); - assertEquals(0, s2.getX1()); - assertEquals(0, s2.getY1()); - assertEquals(1023, s2.getX2()); - assertEquals(255, s2.getY2()); - - assertEquals(0, s1.getAnchor().getDx1()); - assertEquals(0, s1.getAnchor().getDy1()); - assertEquals(1022, s1.getAnchor().getDx2()); - assertEquals(255, s1.getAnchor().getDy2()); - assertEquals(20, s2.getAnchor().getDx1()); - assertEquals(30, s2.getAnchor().getDy1()); - assertEquals(500, s2.getAnchor().getDx2()); - assertEquals(200, s2.getAnchor().getDy2()); - - - // Now add some text to one group, and some more - // to the base, and check we can get it back again - HSSFTextbox tbox1 = - patriarch.createTextbox(new HSSFClientAnchor(1,2,3,4, (short)0,0,(short)0,0)); - tbox1.setString(new HSSFRichTextString("I am text box 1")); - HSSFTextbox tbox2 = - s2.createTextbox(new HSSFChildAnchor(41,42,43,44)); - tbox2.setString(new HSSFRichTextString("This is text box 2")); - - assertEquals(3, patriarch.getChildren().size()); - - - baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - - patriarch = s.getDrawingPatriarch(); - - assertNotNull(patriarch); - assertEquals(10, patriarch.getX1()); - assertEquals(20, patriarch.getY1()); - assertEquals(30, patriarch.getX2()); - assertEquals(40, patriarch.getY2()); - - // Check the two groups and the text - // Result of patriarch.countOfAllChildren() makes no sense: - // Returns 4 for 2 empty groups + 1 TextBox. - //assertEquals(3, patriarch.countOfAllChildren()); - assertEquals(3, patriarch.getChildren().size()); - - // Should be two groups and a text - assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup); - assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup); - assertTrue(patriarch.getChildren().get(2) instanceof HSSFTextbox); - - s1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - tbox1 = (HSSFTextbox)patriarch.getChildren().get(2); - - s2 = (HSSFShapeGroup)patriarch.getChildren().get(1); - - assertEquals(2, s1.getX1()); - assertEquals(3, s1.getY1()); - assertEquals(1021, s1.getX2()); - assertEquals(242, s1.getY2()); - assertEquals(0, s2.getX1()); - assertEquals(0, s2.getY1()); - assertEquals(1023, s2.getX2()); - assertEquals(255, s2.getY2()); - - assertEquals(0, s1.getAnchor().getDx1()); - assertEquals(0, s1.getAnchor().getDy1()); - assertEquals(1022, s1.getAnchor().getDx2()); - assertEquals(255, s1.getAnchor().getDy2()); - assertEquals(20, s2.getAnchor().getDx1()); - assertEquals(30, s2.getAnchor().getDy1()); - assertEquals(500, s2.getAnchor().getDx2()); - assertEquals(200, s2.getAnchor().getDy2()); - - // Not working just yet - assertEquals("I am text box 1", tbox1.getString().getString()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java deleted file mode 100644 index e6aaf092b6..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java +++ /dev/null @@ -1,143 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.awt.Color; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.geom.Line2D; -import java.io.IOException; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Tests the Graphics2d drawing capability. - */ -final class TestEscherGraphics2d { - private HSSFWorkbook workbook; - private HSSFShapeGroup escherGroup; - private EscherGraphics2d graphics; - - @BeforeEach - void setUp() { - workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("test"); - escherGroup = sheet.createDrawingPatriarch().createGroup(new HSSFClientAnchor(0,0,1023,255,(short)0,0,(short) 0,0)); - escherGroup = new HSSFShapeGroup(null, new HSSFChildAnchor()); - EscherGraphics g = new EscherGraphics(escherGroup, workbook, Color.black, 1.0f); - graphics = new EscherGraphics2d(g); - } - - @AfterEach - void closeResources() throws IOException { - workbook.close(); - } - - @Test - void testDrawString() { - graphics.drawString("This is a test", 10, 10); - HSSFTextbox t = (HSSFTextbox) escherGroup.getChildren().get(0); - assertEquals("This is a test", t.getString().getString()); - - // Check that with a valid font, it's still ok - Font font = new Font("Forte", Font.PLAIN, 12); - graphics.setFont(font); - graphics.drawString("This is another test", 10, 10); - - // And test with ones that need the style appending - font = new Font("dialog", Font.PLAIN, 12); - graphics.setFont(font); - graphics.drawString("This is another test", 10, 10); - - font = new Font("dialog", Font.BOLD, 12); - graphics.setFont(font); - graphics.drawString("This is another test", 10, 10); - - // But with an invalid font, we get an exception - font = new Font("IamAmadeUPfont", Font.PLAIN, 22); - graphics.setFont(font); - assertThrows(IllegalArgumentException.class, () -> graphics.drawString("This is another test", 10, 10)); - } - - @Test - void testFillRect() { - graphics.fillRect( 10, 10, 20, 20 ); - HSSFSimpleShape s = (HSSFSimpleShape) escherGroup.getChildren().get(0); - assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, s.getShapeType()); - assertEquals(10, s.getAnchor().getDx1()); - assertEquals(10, s.getAnchor().getDy1()); - assertEquals(30, s.getAnchor().getDy2()); - assertEquals(30, s.getAnchor().getDx2()); - } - - @Test - void testGetFontMetrics() { - FontMetrics fontMetrics = graphics.getFontMetrics(graphics.getFont()); - if (isDialogPresent()) { - // if dialog is returned we can't run the test properly. - return; - } - assertEquals(7, fontMetrics.charWidth('X')); - assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", fontMetrics.getFont().toString()); - } - - @Test - void testSetFont() { - Font f = new Font("Helvetica", Font.PLAIN, 12); - graphics.setFont(f); - assertEquals(f, graphics.getFont()); - } - - @Test - void testSetColor() { - graphics.setColor(Color.red); - assertEquals(Color.red, graphics.getColor()); - } - - @Test - void testGetFont() { - Font f = graphics.getFont(); - if (isDialogPresent()) { - // if dialog is returned we can't run the test properly. - return; - } - - assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", f.toString()); - } - - private boolean isDialogPresent() { - String fontDebugStr = graphics.getFont().toString(); - return fontDebugStr.contains("dialog") || fontDebugStr.contains("Dialog"); - } - - @Test - void testDraw() { - graphics.draw(new Line2D.Double(10,10,20,20)); - HSSFSimpleShape s = (HSSFSimpleShape) escherGroup.getChildren().get(0); - assertEquals(s.getShapeType(), HSSFSimpleShape.OBJECT_TYPE_LINE); - assertEquals(10, s.getAnchor().getDx1()); - assertEquals(10, s.getAnchor().getDy1()); - assertEquals(20, s.getAnchor().getDx2()); - assertEquals(20, s.getAnchor().getDy2()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java b/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java deleted file mode 100644 index 2d8ff7e834..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.CellType; -import org.junit.jupiter.api.Test; - -class TestExternalReferenceChange { - - private static final String MAIN_WORKBOOK_FILENAME = "52575_main.xls"; - private static final String SOURCE_DUMMY_WORKBOOK_FILENAME = "source_dummy.xls"; - private static final String SOURCE_WORKBOOK_FILENAME = "52575_source.xls"; - - @Test - void testDummyToSource() throws IOException { - try (HSSFWorkbook mainWorkbook = HSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME); - HSSFWorkbook sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME)) { - - assertNotNull(mainWorkbook); - assertNotNull(sourceWorkbook); - - boolean changed = mainWorkbook.changeExternalReference("DOESNOTEXIST", SOURCE_WORKBOOK_FILENAME); - assertFalse(changed); - - changed = mainWorkbook.changeExternalReference(SOURCE_DUMMY_WORKBOOK_FILENAME, SOURCE_WORKBOOK_FILENAME); - assertTrue(changed); - - HSSFSheet lSheet = mainWorkbook.getSheetAt(0); - HSSFCell lA1Cell = lSheet.getRow(0).getCell(0); - - assertEquals(CellType.FORMULA, lA1Cell.getCellType()); - - HSSFFormulaEvaluator lMainWorkbookEvaluator = new HSSFFormulaEvaluator(mainWorkbook); - HSSFFormulaEvaluator lSourceEvaluator = new HSSFFormulaEvaluator(sourceWorkbook); - HSSFFormulaEvaluator.setupEnvironment( - new String[]{MAIN_WORKBOOK_FILENAME, SOURCE_WORKBOOK_FILENAME}, - new HSSFFormulaEvaluator[]{lMainWorkbookEvaluator, lSourceEvaluator}); - - assertEquals(CellType.NUMERIC, lMainWorkbookEvaluator.evaluateFormulaCell(lA1Cell)); - - assertEquals(20.0d, lA1Cell.getNumericCellValue(), 0.00001d); - } - } - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java deleted file mode 100644 index 7341a43b1f..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Properties; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Tests the implementation of the FontDetails class. - */ -final class TestFontDetails { - private FontDetails fontDetails; - - @BeforeEach - void setUp() { - Properties properties = new Properties(); - properties.setProperty("font.Arial.height", "13"); - properties.setProperty("font.Arial.characters", "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "); - properties.setProperty("font.Arial.widths", "6, 6, 6, 6, 6, 3, 6, 6, 3, 4, 6, 3, 9, 6, 6, 6, 6, 4, 6, 3, 6, 7, 9, 6, 5, 5, 7, 7, 7, 7, 7, 6, 8, 7, 3, 6, 7, 6, 9, 7, 8, 7, 8, 7, 7, 5, 7, 7, 9, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, "); - fontDetails = FontDetails.create("Arial", properties); - } - - @Test - void testCreate() { - assertEquals(13, fontDetails.getHeight()); - assertEquals(6, fontDetails.getCharWidth('a')); - assertEquals(3, fontDetails.getCharWidth('f')); - } - - @Test - void testGetStringWidth() { - assertEquals(9, fontDetails.getStringWidth("af")); - } - - @Test - void testGetCharWidth() { - assertEquals(6, fontDetails.getCharWidth('a')); - assertEquals(9, fontDetails.getCharWidth('=')); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java deleted file mode 100644 index 0ddc016d29..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java +++ /dev/null @@ -1,578 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.File; -import java.io.FileOutputStream; -import java.util.Calendar; - -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.formula.EvaluationCell; -import org.apache.poi.ss.formula.EvaluationListener; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.WorkbookEvaluatorTestHelper; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.ptg.FuncPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * - */ -final class TestFormulaEvaluatorBugs { - private static boolean OUTPUT_TEST_FILES; - private static String tmpDirName; - - @BeforeAll - public static void setUp() { - tmpDirName = System.getProperty("java.io.tmpdir"); - OUTPUT_TEST_FILES = Boolean.parseBoolean( - System.getProperty("org.apache.poi.test.output_test_files", "False")); - } - - /** - * An odd problem with evaluateFormulaCell giving the - * right values when file is opened, but changes - * to the source data in some versions of excel - * doesn't cause them to be updated. However, other - * versions of excel, and gnumeric, work just fine - * WARNING - tedious bug where you actually have to - * open up excel - */ - @Test - void test44636() throws Exception { - // Open the existing file, tweak one value and - // re-calculate - - HSSFWorkbook wb = openSampleWorkbook("44636.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFRow row = sheet.getRow(0); - - row.getCell(0).setCellValue(4.2); - row.getCell(2).setCellValue(25); - - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - assertEquals(4.2 * 25, row.getCell(3).getNumericCellValue(), 0.0001); - - if (OUTPUT_TEST_FILES) { - // 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); - } - wb.close(); - - // Now, do a new file from scratch - wb = new HSSFWorkbook(); - sheet = wb.createSheet(); - - row = sheet.createRow(0); - row.createCell(0).setCellValue(1.2); - row.createCell(1).setCellValue(4.2); - - row = sheet.createRow(1); - row.createCell(0).setCellFormula("SUM(A1:B1)"); - - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - assertEquals(5.4, row.getCell(0).getNumericCellValue(), 0.0001); - - if (OUTPUT_TEST_FILES) { - // Save - File scratch = new File(tmpDirName, "44636-scratch.xls"); - FileOutputStream out = new FileOutputStream(scratch); - wb.write(out); - out.close(); - System.err.println("New file for bug #44636 written to " + scratch); - } - wb.close(); - } - - /** - * Bug 44297: 32767+32768 is evaluated to -1 - * Fix: IntPtg must operate with unsigned short. Reading signed short results in incorrect formula calculation - * if a formula has values in the interval [Short.MAX_VALUE, (Short.MAX_VALUE+1)*2] - */ - @Test - void test44297() throws Exception { - - HSSFWorkbook wb = openSampleWorkbook("44297.xls"); - - HSSFRow row; - HSSFCell cell; - - HSSFSheet sheet = wb.getSheetAt(0); - - HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(wb); - - row = sheet.getRow(0); - cell = row.getCell(0); - assertEquals("31+46", cell.getCellFormula()); - assertEquals(77, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(1); - cell = row.getCell(0); - assertEquals("30+53", cell.getCellFormula()); - assertEquals(83, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(2); - cell = row.getCell(0); - assertEquals("SUM(A1:A2)", cell.getCellFormula()); - assertEquals(160, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(4); - cell = row.getCell(0); - assertEquals("32767+32768", cell.getCellFormula()); - assertEquals(65535, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(7); - cell = row.getCell(0); - assertEquals("32744+42333", cell.getCellFormula()); - assertEquals(75077, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(8); - cell = row.getCell(0); - assertEquals("327680/32768", cell.getCellFormula()); - assertEquals(10, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(9); - cell = row.getCell(0); - assertEquals("32767+32769", cell.getCellFormula()); - assertEquals(65536, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(10); - cell = row.getCell(0); - assertEquals("35000+36000", cell.getCellFormula()); - assertEquals(71000, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(11); - cell = row.getCell(0); - assertEquals("-1000000-3000000", cell.getCellFormula()); - assertEquals(-4000000, eva.evaluate(cell).getNumberValue(), 0); - - wb.close(); - } - - /** - * Bug 44410: SUM(C:C) is valid in excel, and means a sum - * of all the rows in Column C - */ - @Test - void test44410() throws Exception { - HSSFWorkbook wb = openSampleWorkbook("SingleLetterRanges.xls"); - - HSSFSheet sheet = wb.getSheetAt(0); - - HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(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(0); - - FormulaRecordAggregate frec = (FormulaRecordAggregate) cellSUM.getCellValueRecord(); - Ptg[] ops = frec.getFormulaRecord().getParsedExpression(); - assertEquals(2, ops.length); - assertEquals(AreaPtg.class, ops[0].getClass()); - assertEquals(FuncVarPtg.class, ops[1].getClass()); - - // Actually stored as C1 to C65536 - // (last row is -1 === 65535) - AreaPtg ptg = (AreaPtg) ops[0]; - assertEquals(2, ptg.getFirstColumn()); - assertEquals(2, ptg.getLastColumn()); - assertEquals(0, ptg.getFirstRow()); - assertEquals(65535, ptg.getLastRow()); - assertEquals("C:C", ptg.toFormulaString()); - - // 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()); - - // 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(0); - assertEquals("INDEX(C:C,2,1)", cellIDX.getCellFormula()); - assertEquals(2, eva.evaluate(cellIDX).getNumberValue(), 0); - - // Across two colums - HSSFCell cellSUM2D = rowSUM2D.getCell(0); - assertEquals("SUM(C:D)", cellSUM2D.getCellFormula()); - assertEquals(66, eva.evaluate(cellSUM2D).getNumberValue(), 0); - - wb.close(); - } - - /** - * Tests that we can evaluate boolean cells properly - */ - @Test - void testEvaluateBooleanInCell_bug44508() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - wb.setSheetName(0, "Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - - cell.setCellFormula("1=1"); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - try { - fe.evaluateInCell(cell); - } catch (NumberFormatException e) { - fail("Identified bug 44508"); - } - assertTrue(cell.getBooleanCellValue()); - - wb.close(); - } - - @Test - void testClassCast_bug44861() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("44861.xls")) { - // Check direct - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - - // And via calls - for (Sheet s : wb) { - HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb); - - for (Row r : s) { - for (Cell c : r) { - CellType ct = eval.evaluateFormulaCell(c); - assertNotNull(ct); - } - } - } - - } - } - - @Test - void testEvaluateInCellWithErrorCode_bug44950() throws Exception { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(1); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("na()"); // this formula evaluates to an Excel error code '#N/A' - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - fe.evaluateInCell(cell); - } catch (NumberFormatException e) { - if (e.getMessage().equals("You cannot get an error value from a non-error cell")) { - fail("Identified bug 44950 b"); - } - throw e; - } - } - - @Test - void testDateWithNegativeParts_bug48528() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(1); - HSSFCell cell = row.createCell(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - // 5th Feb 2012 = 40944 - // 1st Feb 2012 = 40940 - // 5th Jan 2012 = 40913 - // 5th Dec 2011 = 40882 - // 5th Feb 2011 = 40579 - - cell.setCellFormula("DATE(2012,2,1)"); - fe.notifyUpdateCell(cell); - assertEquals(40940.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2,1+4)"); - fe.notifyUpdateCell(cell); - assertEquals(40944.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2-1,1+4)"); - fe.notifyUpdateCell(cell); - assertEquals(40913.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2,1-27)"); - fe.notifyUpdateCell(cell); - assertEquals(40913.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2-2,1+4)"); - fe.notifyUpdateCell(cell); - assertEquals(40882.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2,1-58)"); - fe.notifyUpdateCell(cell); - assertEquals(40882.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2-12,1+4)"); - fe.notifyUpdateCell(cell); - assertEquals(40579.0, fe.evaluate(cell).getNumberValue(), 0); - - wb.close(); - } - - private static final class EvalListener extends EvaluationListener { - private int _countCacheHits; - private int _countCacheMisses; - - public EvalListener() { - _countCacheHits = 0; - _countCacheMisses = 0; - } - public int getCountCacheHits() { - return _countCacheHits; - } - public int getCountCacheMisses() { - return _countCacheMisses; - } - - @Override - public void onCacheHit(int sheetIndex, int srcRowNum, int srcColNum, ValueEval result) { - _countCacheHits++; - } - @Override - public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) { - _countCacheMisses++; - } - } - - /** - * The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values - */ - @Test - void testSlowEvaluate45376() throws Exception { - /* - * Note - to observe behaviour without caching, disable the call to - * updateValue() from FormulaCellCacheEntry.updateFormulaResult(). - */ - - // Firstly set up a sequence of formula cells where each depends on the previous multiple - // times. Without caching, each subsequent cell take about 4 times longer to evaluate. - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - for(int i=1; i<10; i++) { - HSSFCell cell = row.createCell(i); - char prevCol = (char) ('A' + i-1); - String prevCell = prevCol + "1"; - // this formula is inspired by the offending formula of the attachment for bug 45376 - // IF(DATE(YEAR(A1),MONTH(A1)+1,1)<=$D$3,DATE(YEAR(A1),MONTH(A1)+1,1),NA()) etc - String formula = "IF(DATE(YEAR(" + prevCell + "),MONTH(" + prevCell + ")+1,1)<=$D$3," + - "DATE(YEAR(" + prevCell + "),MONTH(" + prevCell + ")+1,1),NA())"; - cell.setCellFormula(formula); - } - Calendar cal = LocaleUtil.getLocaleCalendar(2000, 0, 1, 0, 0, 0); - row.createCell(0).setCellValue(cal); - - // Choose cell A9 instead of A10, so that the failing test case doesn't take too long to execute. - HSSFCell cell = row.getCell(8); - EvalListener evalListener = new EvalListener(); - WorkbookEvaluator evaluator = WorkbookEvaluatorTestHelper.createEvaluator(wb, evalListener); - ValueEval ve = evaluator.evaluate(HSSFEvaluationTestHelper.wrapCell(cell)); - int evalCount = evalListener.getCountCacheMisses(); - // Without caching, evaluating cell 'A9' takes 21845 evaluations which consumes - // much time (~3 sec on Core 2 Duo 2.2GHz) - // short-circuit-if optimisation cuts this down to 255 evaluations which is still too high - // System.err.println("Cell A9 took " + evalCount + " intermediate evaluations"); - assertTrue(evalCount <= 10, "Identifed bug 45376 - Formula evaluator should cache values"); - // With caching, the evaluationCount is 8 which is exactly the - // number of formula cells that needed to be evaluated. - assertEquals(8, evalCount); - - // The cache hits would be 24 if fully evaluating all arguments of the - // "IF()" functions (Each of the 8 formulas has 4 refs to formula cells - // which result in 1 cache miss and 3 cache hits). However with the - // short-circuit-if optimisation, 2 of the cell refs get skipped - // reducing this metric 8. - assertEquals(8, evalListener.getCountCacheHits()); - - // confirm the evaluation result too - assertEquals(ErrorEval.NA, ve); - - wb.close(); - } - - @SuppressWarnings("resource") - @Test - void test55747_55324() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFFormulaEvaluator ev = wb.getCreationHelper().createFormulaEvaluator(); - HSSFSheet ws = wb.createSheet(); - HSSFRow row = ws.createRow(0); - HSSFCell cell; - - // Our test value - cell = row.createCell(0); - cell.setCellValue("abc"); - - // Lots of IF cases - - cell = row.createCell(1); - cell.setCellFormula("IF(A1<>\"\",MID(A1,1,2),\"X\")");//if(expr,func,val) - - cell = row.createCell(2); - cell.setCellFormula("IF(A1<>\"\",\"A\",\"B\")");// if(expr,val,val) - - cell = row.createCell(3); - cell.setCellFormula("IF(A1=\"\",\"X\",MID(A1,1,2))");//if(expr,val,func), - - cell = row.createCell(4); - cell.setCellFormula("IF(A1<>\"\",\"X\",MID(A1,1,2))");//if(expr,val,func), - - cell = row.createCell(5); - cell.setCellFormula("IF(A1=\"\",MID(A1,1,2),MID(A1,2,2))");//if(exp,func,func) - cell = row.createCell(6); - cell.setCellFormula("IF(A1<>\"\",MID(A1,1,2),MID(A1,2,2))");//if(exp,func,func) - - cell = row.createCell(7); - cell.setCellFormula("IF(MID(A1,1,2)<>\"\",\"A\",\"B\")");//if(func_expr,val,val) - - // And some MID ones just to check - row = ws.createRow(1); - cell = row.createCell(1); - cell.setCellFormula("MID(A1,1,2)"); - cell = row.createCell(2); - cell.setCellFormula("MID(A1,2,2)"); - cell = row.createCell(3); - cell.setCellFormula("MID(A1,2,1)"); - cell = row.createCell(4); - cell.setCellFormula("MID(A1,3,1)"); - - // Evaluate - ev.evaluateAll(); - - // Save and re-load - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - ws = wb.getSheetAt(0); - - // Check the MID Ptgs in Row 2 have V RefPtgs for A1 - row = ws.getRow(1); - for (int i=1; i<=4; i++) { - cell = row.getCell(i); - Ptg[] ptgs = getPtgs(cell); - assertEquals(4, ptgs.length); - assertEquals(FuncPtg.class, ptgs[3].getClass()); - assertEquals("MID", ((FuncPtg)ptgs[3]).getName()); - assertRefPtgA1('V', ptgs, 0); - } - - // Now check the IF formulas - row = ws.getRow(0); - - // H1, MID is used in the expression IF checks, so A1 should be V - cell = row.getCell(CellReference.convertColStringToIndex("H")); - assertRefPtgA1('V', getPtgs(cell), 0); - - // E1, MID is used in the FALSE route, so: - // A1 should be V in the IF check - // A1 should be R in the FALSE route - cell = row.getCell(CellReference.convertColStringToIndex("E")); - assertRefPtgA1('V', getPtgs(cell), 0); - assertRefPtgA1('R', getPtgs(cell), 6); - - // Check that, for B1, D1, F1 and G1, the references to A1 - // from all of IF check, True and False are V - cell = row.getCell(CellReference.convertColStringToIndex("B")); - assertRefPtgA1('V', getPtgs(cell), 0); -// assertRefPtgA1('V', getPtgs(cell), 4); // FIXME! - - cell = row.getCell(CellReference.convertColStringToIndex("D")); - assertRefPtgA1('V', getPtgs(cell), 0); -// assertRefPtgA1('V', getPtgs(cell), 6); // FIXME! - - cell = row.getCell(CellReference.convertColStringToIndex("F")); - assertRefPtgA1('V', getPtgs(cell), 0); -// assertRefPtgA1('V', getPtgs(cell), 4); // FIXME! -// assertRefPtgA1('V', getPtgs(cell), 9); // FIXME! - - cell = row.getCell(CellReference.convertColStringToIndex("G")); - assertRefPtgA1('V', getPtgs(cell), 0); -// assertRefPtgA1('V', getPtgs(cell), 4); // FIXME! -// assertRefPtgA1('V', getPtgs(cell), 9); // FIXME! - - - // Check our cached values were correctly evaluated - cell = row.getCell(CellReference.convertColStringToIndex("A")); - assertEquals("abc", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("B")); - assertEquals("ab", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("C")); - assertEquals("A", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("D")); - assertEquals("ab", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("E")); - assertEquals("X", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("F")); - assertEquals("bc", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("G")); - assertEquals("ab", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("H")); - assertEquals("A", cell.getStringCellValue()); - - // Enable this to write out + check in Excel - if (OUTPUT_TEST_FILES) { - FileOutputStream out = new FileOutputStream("/tmp/test.xls"); - wb.write(out); - out.close(); - } - } - private Ptg[] getPtgs(HSSFCell cell) { - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(FormulaRecordAggregate.class, cell.getCellValueRecord().getClass()); - FormulaRecordAggregate agg = (FormulaRecordAggregate)cell.getCellValueRecord(); - FormulaRecord rec = agg.getFormulaRecord(); - return rec.getParsedExpression(); - } - private void assertRefPtgA1(char rv, Ptg[] ptgs, int at) { - Ptg ptg = ptgs[at]; - assertEquals(RefPtg.class, ptg.getClass()); - assertEquals(0, ((RefPtg)ptg).getRow()); - assertEquals(0, ((RefPtg)ptg).getColumn()); - assertEquals(rv, ptg.getRVAType()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java deleted file mode 100644 index ef8cd2538a..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java +++ /dev/null @@ -1,128 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.junit.jupiter.api.Test; - -/** - * Tests to show that our documentation at - * https://poi.apache.org/hssf/eval.html - * all actually works as we'd expect them to - */ -final class TestFormulaEvaluatorDocs { - - /** - * https://poi.apache.org/hssf/eval.html#EvaluateAll - */ - @Test - void testEvaluateAll() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s1 = wb.createSheet(); - HSSFSheet s2 = wb.createSheet(); - wb.setSheetName(0, "S1"); - wb.setSheetName(1, "S2"); - - HSSFRow s1r1 = s1.createRow(0); - HSSFRow s1r2 = s1.createRow(1); - HSSFRow s2r1 = s2.createRow(0); - - HSSFCell s1r1c1 = s1r1.createCell(0); - HSSFCell s1r1c2 = s1r1.createCell(1); - HSSFCell s1r1c3 = s1r1.createCell(2); - s1r1c1.setCellValue(22.3); - s1r1c2.setCellValue(33.4); - s1r1c3.setCellFormula("SUM(A1:B1)"); - - HSSFCell s1r2c1 = s1r2.createCell(0); - HSSFCell s1r2c2 = s1r2.createCell(1); - HSSFCell s1r2c3 = s1r2.createCell(2); - s1r2c1.setCellValue(-1.2); - s1r2c2.setCellValue(-3.4); - s1r2c3.setCellFormula("SUM(A2:B2)"); - - HSSFCell s2r1c1 = s2r1.createCell(0); - s2r1c1.setCellFormula("S1!A1"); - - // Not evaluated yet - assertEquals(0.0, s1r1c3.getNumericCellValue(), 0); - assertEquals(0.0, s1r2c3.getNumericCellValue(), 0); - assertEquals(0.0, s2r1c1.getNumericCellValue(), 0); - - // Do a full evaluate, as per our docs - // uses evaluateFormulaCell() - for (Sheet sheet : wb) { - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); - for (Row r : sheet) { - for (Cell c : r) { - if (c.getCellType() == CellType.FORMULA) { - evaluator.evaluateFormulaCell(c); - - // For testing - all should be numeric - assertEquals(CellType.NUMERIC, evaluator.evaluateFormulaCell(c)); - } - } - } - } - - // Check now as expected - assertEquals(55.7, wb.getSheetAt(0).getRow(0).getCell(2).getNumericCellValue(), 0); - assertEquals("SUM(A1:B1)", wb.getSheetAt(0).getRow(0).getCell(2).getCellFormula()); - assertEquals(CellType.FORMULA, wb.getSheetAt(0).getRow(0).getCell(2).getCellType()); - - assertEquals(-4.6, wb.getSheetAt(0).getRow(1).getCell(2).getNumericCellValue(), 0); - assertEquals("SUM(A2:B2)", wb.getSheetAt(0).getRow(1).getCell(2).getCellFormula()); - assertEquals(CellType.FORMULA, wb.getSheetAt(0).getRow(1).getCell(2).getCellType()); - - assertEquals(22.3, wb.getSheetAt(1).getRow(0).getCell(0).getNumericCellValue(), 0); - assertEquals("'S1'!A1", wb.getSheetAt(1).getRow(0).getCell(0).getCellFormula()); - assertEquals(CellType.FORMULA, wb.getSheetAt(1).getRow(0).getCell(0).getCellType()); - - - // Now do the alternate call, which zaps the formulas - // uses evaluateInCell() - for (Sheet sheet : wb) { - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); - - for (Row r : sheet) { - for (Cell c : r) { - if (c.getCellType() == CellType.FORMULA) { - evaluator.evaluateInCell(c); - } - } - } - } - - assertEquals(55.7, wb.getSheetAt(0).getRow(0).getCell(2).getNumericCellValue(), 0); - assertEquals(CellType.NUMERIC, wb.getSheetAt(0).getRow(0).getCell(2).getCellType()); - - assertEquals(-4.6, wb.getSheetAt(0).getRow(1).getCell(2).getNumericCellValue(), 0); - assertEquals(CellType.NUMERIC, wb.getSheetAt(0).getRow(1).getCell(2).getCellType()); - - assertEquals(22.3, wb.getSheetAt(1).getRow(0).getCell(0).getNumericCellValue(), 0); - assertEquals(CellType.NUMERIC, wb.getSheetAt(1).getRow(0).getCell(0).getCellType()); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java deleted file mode 100644 index 836ed32bae..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java +++ /dev/null @@ -1,950 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Calendar; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.NamePtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.Test; - -final class TestFormulas { - - private static HSSFWorkbook openSample(String sampleFileName) { - return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - /** - * Add 1+1 -- WHoohoo! - */ - @Test - void testBasicAddIntegers() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet(); - - //get our minimum values - HSSFRow r = s.createRow(1); - HSSFCell c = r.createCell(1); - c.setCellFormula(1 + "+" + 1); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - s = wb2.getSheetAt(0); - r = s.getRow(1); - c = r.getCell(1); - - assertEquals("1+1", c.getCellFormula(), "Formula is as expected"); - } - } - } - - /** - * Add various integers - */ - @Test - void testAddIntegers() throws IOException { - binomialOperator("+"); - } - - /** - * Multiply various integers - */ - @Test - void testMultplyIntegers() throws IOException { - binomialOperator("*"); - } - - /** - * Subtract various integers - */ - @Test - void testSubtractIntegers() throws IOException { - binomialOperator("-"); - } - - /** - * Subtract various integers - */ - @Test - void testDivideIntegers() throws IOException { - binomialOperator("/"); - } - - /** - * Exponentialize various integers; - */ - @Test - void testPowerIntegers() throws IOException { - binomialOperator("^"); - } - - /** - * Concatenate two numbers 1&2 = 12 - */ - @Test - void testConcatIntegers() throws IOException { - binomialOperator("&"); - } - - /** - * tests 1*2+3*4 - */ - @Test - void testOrderOfOperationsMultiply() throws IOException { - orderTest("1*2+3*4"); - } - - /** - * tests 1*2+3^4 - */ - @Test - void testOrderOfOperationsPower() throws IOException { - orderTest("1*2+3^4"); - } - - /** - * Tests that parenthesis are obeyed - */ - @Test - void testParenthesis() throws IOException { - orderTest("(1*3)+2+(1+2)*(3^4)^5"); - } - - @Test - void testReferencesOpr() throws IOException { - String[] operation = new String[] { - "+", "-", "*", "/", "^", "&" - }; - for (final String op : operation) { - operationRefTest(op); - } - } - - /** - * Tests creating a file with floating point in a formula. - * - */ - @Test - void testFloat() throws IOException { - floatTest("*"); - floatTest("/"); - } - - private static void floatTest(String operator) throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet(); - - //get our minimum values - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(1); - c.setCellFormula("" + Float.MIN_VALUE + operator + Float.MIN_VALUE); - - for (int x = 1; x < Short.MAX_VALUE && x > 0; x = (short) (x * 2)) { - r = s.createRow(x); - - for (int y = 1; y < 256 && y > 0; y = (short) (y + 2)) { - c = r.createCell(y); - c.setCellFormula("" + x + "." + y + operator + y + "." + x); - } - } - if (s.getLastRowNum() < Short.MAX_VALUE) { - r = s.createRow(0); - c = r.createCell(0); - c.setCellFormula("" + Float.MAX_VALUE + operator + Float.MAX_VALUE); - } - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - floatVerify(operator, wb2); - } - } - } - - private static void floatVerify(String operator, HSSFWorkbook wb) { - HSSFSheet s = wb.getSheetAt(0); - - // don't know how to check correct result .. for the moment, we just verify that the file can be read. - for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { - HSSFRow r = s.getRow(x); - - for (int y = 1; y < 256 && y > 0; y=(short)(y+2)) { - - HSSFCell c = r.getCell(y); - assertNotNull(c.getCellFormula(), "got a formula"); - - assertEquals(("" + x + "." + y + operator + y + "." + x), c.getCellFormula(), - "loop Formula is as expected " + x + "." + y + operator + y + "." + x + "!=" + c.getCellFormula()); - } - } - } - - @Test - void testAreaSum() throws IOException { - areaFunctionTest("SUM"); - } - - @Test - void testAreaAverage() throws IOException { - areaFunctionTest("AVERAGE"); - } - - @Test - void testRefArraySum() throws IOException { - refArrayFunctionTest("SUM"); - } - - @Test - void testAreaArraySum() throws IOException { - refAreaArrayFunctionTest("SUM"); - } - - private static void operationRefTest(String operator) throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet(); - - //get our minimum values - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(1); - c.setCellFormula("A2" + operator + "A3"); - - for (int x = 1; x < Short.MAX_VALUE && x > 0; x = (short) (x * 2)) { - r = s.createRow(x); - - for (int y = 1; y < 256 && y > 0; y++) { - short refx1 = (short)(x + (x + 50 < Short.MAX_VALUE ? 50 : -4)); - short refx2 = (short)(x + (x + 50 < Short.MAX_VALUE ? 46 : -3)); - short refy1 = (short)(y + (y + 50 < 255 ? 50 : -4)); - short refy2 = (short)(y + (y + 50 < 255 ? 49 : -3)); - - CellReference cr = new CellReference(refx1, refy1, false, false); - String ref = cr.formatAsString(); - cr = new CellReference(refx2, refy2, false, false); - String ref2 = cr.formatAsString(); - - c = r.createCell(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.getRow(0); - c = r.createCell(0); - c.setCellFormula("" + "B1" + operator + "IV255"); - } - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - operationalRefVerify(operator, wb2); - } - } - } - - /** - * Opens the sheet we wrote out by binomialOperator and makes sure the formulas - * all match what we expect (x operator y) - */ - private static void operationalRefVerify(String operator, HSSFWorkbook wb) { - - HSSFSheet s = wb.getSheetAt(0); - - //get our minimum values - HSSFRow r = s.getRow(0); - HSSFCell c = r.getCell(1); - //get our minimum values - assertEquals(("A2" + operator + "A3"), c.getCellFormula(), - "minval Formula is as expected A2" + operator + "A3 != " + c.getCellFormula()); - - - for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { - r = s.getRow(x); - - for (int y = 1; y < 256 && y > 0; y++) { - - int refx1 = x + (x+50 < Short.MAX_VALUE ? 50 : -4); - int refx2 = x + (x+50 < Short.MAX_VALUE ? 46 : -3); - int refy1 = y + (y+50 < 255 ? 50 : -4); - int refy2 = y + (y+50 < 255 ? 49 : -3); - - c = r.getCell(y); - CellReference cr= new CellReference(refx1, refy1, false, false); - String ref=cr.formatAsString(); - cr=new CellReference(refx2,refy2, false, false); - String ref2=cr.formatAsString(); - - - assertEquals(("" + ref + operator + ref2), c.getCellFormula(), - "loop Formula is as expected " + ref + operator + ref2 + "!=" + c.getCellFormula()); - } - } - - //test our maximum values - r = s.getRow(0); - c = r.getCell(0); - - assertEquals("B1"+operator+"IV255", c.getCellFormula()); - } - - - - /** - * tests order wrting out == order writing in for a given formula - */ - private static void orderTest(String formula) throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet(); - - //get our minimum values - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(1); - c.setCellFormula(formula); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - s = wb2.getSheetAt(0); - - //get our minimum values - r = s.getRow(0); - c = r.getCell(1); - assertEquals(formula, c.getCellFormula(), "minval Formula is as expected"); - } - } - } - - /** - * 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 - * that they are all how we expect. - */ - private static void binomialOperator(String operator) throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet(); - - //get our minimum values - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(1); - c.setCellFormula(1 + operator + 1); - - for (int x = 1; x < Short.MAX_VALUE && x > 0; x = (short) (x * 2)) { - r = s.createRow(x); - - for (int y = 1; y < 256 && y > 0; y++) { - c = r.createCell(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.getRow(0); - c = r.createCell(0); - c.setCellFormula("" + Short.MAX_VALUE + operator + Short.MAX_VALUE); - } - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - binomialVerify(operator, wb2); - } - } - } - - /** - * Opens the sheet we wrote out by binomialOperator and makes sure the formulas - * all match what we expect (x operator y) - */ - private static void binomialVerify(String operator, HSSFWorkbook wb) { - HSSFSheet s = wb.getSheetAt(0); - - //get our minimum values - HSSFRow r = s.getRow(0); - HSSFCell c = r.getCell(1); - assertEquals(("1" + operator + "1"), c.getCellFormula(), - "minval Formula is as expected 1" + operator + "1 != " + c.getCellFormula()); - - for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { - r = s.getRow(x); - - for (int y = 1; y < 256 && y > 0; y++) { - c = r.getCell(y); - assertEquals(("" + x + operator + y), c.getCellFormula(), - "loop Formula is as expected " + x + operator + y + "!=" + c.getCellFormula()); - } - } - - //test our maximum values - r = s.getRow(0); - c = r.getCell(0); - - assertEquals(("" + Short.MAX_VALUE + operator + Short.MAX_VALUE), c.getCellFormula(), - "maxval Formula is as expected"); - } - - /** - * Writes a function then tests to see if its correct - */ - public static void areaFunctionTest(String function) throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet(); - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(0); - c.setCellFormula(function + "(A2:A3)"); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - - assertEquals(function + "(A2:A3)", c.getCellFormula(), - "function =" + function + "(A2:A3)"); - } - } - } - - /** - * Writes a function then tests to see if its correct - */ - void refArrayFunctionTest(String function) throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet(); - HSSFRow r = s.createRow(0); - - HSSFCell c = r.createCell(0); - c.setCellFormula(function + "(A2,A3)"); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - - assertEquals((function + "(A2,A3)"), c.getCellFormula(), "function =" + function + "(A2,A3)"); - } - } - } - - - /** - * Writes a function then tests to see if its correct - * - */ - void refAreaArrayFunctionTest(String function) throws IOException { - - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet(); - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(0); - c.setCellFormula(function + "(A2:A4,B2:B4)"); - c = r.createCell(1); - c.setCellFormula(function + "($A$2:$A4,B$2:B4)"); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - - assertEquals((function + "(A2:A4,B2:B4)"), c.getCellFormula(), "function =" + function + "(A2:A4,B2:B4)"); - - c = r.getCell(1); - assertEquals((function + "($A$2:$A4,B$2:B4)"), c.getCellFormula(), "function =" + function + "($A$2:$A4,B$2:B4)"); - } - } - } - - - @Test - void testAbsRefs() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet(); - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(0); - c.setCellFormula("A3+A2"); - c = r.createCell(1); - c.setCellFormula("$A3+$A2"); - c = r.createCell(2); - c.setCellFormula("A$3+A$2"); - c = r.createCell(3); - c.setCellFormula("$A$3+$A$2"); - c = r.createCell(4); - c.setCellFormula("SUM($A$3,$A$2)"); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - assertEquals("A3+A2", c.getCellFormula()); - c = r.getCell(1); - assertEquals("$A3+$A2", c.getCellFormula()); - c = r.getCell(2); - assertEquals("A$3+A$2", c.getCellFormula()); - c = r.getCell(3); - assertEquals("$A$3+$A$2", c.getCellFormula()); - c = r.getCell(4); - assertEquals("SUM($A$3,$A$2)", c.getCellFormula()); - } - } - } - - @Test - void testSheetFunctions() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet("A"); - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(0); - c.setCellValue(1); - c = r.createCell(1); - c.setCellValue(2); - - s = wb1.createSheet("B"); - r = s.createRow(0); - c = r.createCell(0); - c.setCellFormula("AVERAGE(A!A1:B1)"); - c = r.createCell(1); - c.setCellFormula("A!A1+A!B1"); - c = r.createCell(2); - c.setCellFormula("A!$A$1+A!$B1"); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - s = wb2.getSheet("B"); - r = s.getRow(0); - c = r.getCell(0); - assertEquals("AVERAGE(A!A1:B1)", c.getCellFormula(), - "expected: AVERAGE(A!A1:B1) got: " + c.getCellFormula()); - c = r.getCell(1); - assertEquals("A!A1+A!B1", c.getCellFormula(), - "expected: A!A1+A!B1 got: " + c.getCellFormula()); - } - } - } - - @Test - void testRVAoperands() throws IOException { - File file = TempFile.createTempFile("testFormulaRVA",".xls"); - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(0); - c.setCellFormula("A3+A2"); - c = r.createCell(1); - c.setCellFormula("AVERAGE(A3,A2)"); - c = r.createCell(2); - c.setCellFormula("ROW(A3)"); - c = r.createCell(3); - c.setCellFormula("AVERAGE(A2:A3)"); - c = r.createCell(4); - c.setCellFormula("POWER(A2,A3)"); - c = r.createCell(5); - c.setCellFormula("SIN(A2)"); - - c = r.createCell(6); - c.setCellFormula("SUM(A2:A3)"); - - c = r.createCell(7); - c.setCellFormula("SUM(A2,A3)"); - - r = s.createRow(1); - c = r.createCell(0); - c.setCellValue(2.0); - r = s.createRow(2); - c = r.createCell(0); - c.setCellValue(3.0); - - try (FileOutputStream out = new FileOutputStream(file)) { - wb.write(out); - } - assertTrue(file.exists()); - } - } - - @Test - void testStringFormulas() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet("A"); - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(1); - c.setCellFormula("UPPER(\"abc\")"); - c = r.createCell(2); - c.setCellFormula("LOWER(\"ABC\")"); - c = r.createCell(3); - c.setCellFormula("CONCATENATE(\" my \",\" name \")"); - - writeOutAndReadBack(wb).close(); - } - - try (HSSFWorkbook wb = openSample("StringFormulas.xls")) { - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r = s.getRow(0); - HSSFCell c = r.getCell(0); - assertEquals("UPPER(\"xyz\")", c.getCellFormula()); - } - } - - @Test - void testLogicalFormulas() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet("A"); - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(1); - c.setCellFormula("IF(A14000\",B1:B5)"; - - try (HSSFWorkbook wb = openSample("sumifformula.xls")) { - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r = s.getRow(0); - HSSFCell c = r.getCell(2); - assertEquals(function, c.getCellFormula()); - } - - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(0); - c.setCellValue(1000); - c = r.createCell(1); - c.setCellValue(1); - - r = s.createRow(1); - c = r.createCell(0); - c.setCellValue(2000); - c = r.createCell(1); - c.setCellValue(2); - - r = s.createRow(2); - c = r.createCell(0); - c.setCellValue(3000); - c = r.createCell(1); - c.setCellValue(3); - - r = s.createRow(3); - c = r.createCell(0); - c.setCellValue(4000); - c = r.createCell(1); - c.setCellValue(4); - - r = s.createRow(4); - c = r.createCell(0); - c.setCellValue(5000); - c = r.createCell(1); - c.setCellValue(5); - - r = s.getRow(0); - c = r.createCell(2); - c.setCellFormula(function); - - writeOutAndReadBack(wb).close(); - } - } - - @Test - void testSquareMacro() throws IOException { - try (HSSFWorkbook w = openSample("SquareMacro.xls")) { - HSSFSheet s0 = w.getSheetAt(0); - HSSFRow[] r = {s0.getRow(0), s0.getRow(1)}; - - HSSFCell a1 = r[0].getCell(0); - assertEquals("square(1)", a1.getCellFormula()); - assertEquals(1d, a1.getNumericCellValue(), 1e-9); - - HSSFCell a2 = r[1].getCell(0); - assertEquals("square(2)", a2.getCellFormula()); - assertEquals(4d, a2.getNumericCellValue(), 1e-9); - - HSSFCell b1 = r[0].getCell(1); - assertEquals("IF(TRUE,square(1))", b1.getCellFormula()); - assertEquals(1d, b1.getNumericCellValue(), 1e-9); - - HSSFCell b2 = r[1].getCell(1); - assertEquals("IF(TRUE,square(2))", b2.getCellFormula()); - assertEquals(4d, b2.getNumericCellValue(), 1e-9); - - HSSFCell c1 = r[0].getCell(2); - assertEquals("square(square(1))", c1.getCellFormula()); - assertEquals(1d, c1.getNumericCellValue(), 1e-9); - - HSSFCell c2 = r[1].getCell(2); - assertEquals("square(square(2))", c2.getCellFormula()); - assertEquals(16d, c2.getNumericCellValue(), 1e-9); - - HSSFCell d1 = r[0].getCell(3); - assertEquals("square(one())", d1.getCellFormula()); - assertEquals(1d, d1.getNumericCellValue(), 1e-9); - - HSSFCell d2 = r[1].getCell(3); - assertEquals("square(two())", d2.getCellFormula()); - assertEquals(4d, d2.getNumericCellValue(), 1e-9); - } - } - - @Test - void testStringFormulaRead() throws IOException { - try (HSSFWorkbook w = openSample("StringFormulas.xls")) { - HSSFCell c = w.getSheetAt(0).getRow(0).getCell(0); - assertEquals("XYZ", c.getRichStringCellValue().getString(), "String Cell value"); - } - } - - /** test for bug 34021*/ - @Test - void testComplexSheetRefs() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s1 = wb1.createSheet("Sheet a.1"); - HSSFSheet s2 = wb1.createSheet("Sheet.A"); - s2.createRow(1).createCell(2).setCellFormula("'Sheet a.1'!A1"); - s1.createRow(1).createCell(2).setCellFormula("'Sheet.A'!A1"); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - s1 = wb2.getSheet("Sheet a.1"); - assertNotNull(s1); - assertEquals("Sheet.A!A1", s1.getRow(1).getCell(2).getCellFormula()); - s2 = wb2.getSheet("Sheet.A"); - assertNotNull(s2); - assertEquals("'Sheet a.1'!A1", s2.getRow(1).getCell(2).getCellFormula()); - } - } - } - - /** Unknown Ptg 3C*/ - @Test - void test27272_1() throws IOException { - try (HSSFWorkbook wb = openSample("27272_1.xls")) { - wb.getSheetAt(0); - assertEquals("Compliance!#REF!", wb.getNameAt(0).getRefersToFormula(), "Reference for named range"); - writeOutAndReadBack(wb).close(); - } - } - - /** Unknown Ptg 3D*/ - @Test - void test27272_2() throws IOException { - try (HSSFWorkbook wb = openSample("27272_2.xls")) { - assertEquals("LOAD.POD_HISTORIES!#REF!", wb.getNameAt(0).getRefersToFormula(), "Reference for named range"); - writeOutAndReadBack(wb).close(); - } - } - - /** MissingArgPtg */ - @Test - void testMissingArgPtg() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell(0); - assertDoesNotThrow(() -> cell.setCellFormula("IF(A1=\"A\",1,)")); - } - } - - @Test - void testSharedFormula() throws IOException { - try (HSSFWorkbook wb = openSample("SharedFormulaTest.xls")) { - assertEquals("A$1*2", wb.getSheetAt(0).getRow(1).getCell(1).toString()); - assertEquals("$A11*2", wb.getSheetAt(0).getRow(11).getCell(1).toString()); - assertEquals("DZ2*2", wb.getSheetAt(0).getRow(1).getCell(128).toString()); - assertEquals("B32770*2", wb.getSheetAt(0).getRow(32768).getCell(1).toString()); - } - } - - /** - * Test creation / evaluation of formulas with sheet-level names - */ - @Test - void testSheetLevelFormulas() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sh1 = wb.createSheet("Sheet1"); - HSSFName nm1 = wb.createName(); - nm1.setNameName("sales_1"); - nm1.setSheetIndex(0); - nm1.setRefersToFormula("Sheet1!$A$1"); - HSSFRow row = sh1.createRow(0); - row.createCell(0).setCellValue(3); - row.createCell(1).setCellFormula("sales_1"); - row.createCell(2).setCellFormula("sales_1*2"); - - - HSSFSheet sh2 = wb.createSheet("Sheet2"); - HSSFName nm2 = wb.createName(); - nm2.setNameName("sales_1"); - nm2.setSheetIndex(1); - nm2.setRefersToFormula("Sheet2!$A$1"); - - row = sh2.createRow(0); - row.createCell(0).setCellValue(5); - row.createCell(1).setCellFormula("sales_1"); - row.createCell(2).setCellFormula("sales_1*3"); - - //check that NamePtg refers to the correct NameRecord - Ptg[] ptgs1 = HSSFFormulaParser.parse("sales_1", wb, FormulaType.CELL, 0); - NamePtg nPtg1 = (NamePtg) ptgs1[0]; - assertSame(nm1, wb.getNameAt(nPtg1.getIndex())); - - Ptg[] ptgs2 = HSSFFormulaParser.parse("sales_1", wb, FormulaType.CELL, 1); - NamePtg nPtg2 = (NamePtg) ptgs2[0]; - assertSame(nm2, wb.getNameAt(nPtg2.getIndex())); - - //check that the formula evaluator returns the correct result - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); - assertEquals(3.0, evaluator.evaluate(sh1.getRow(0).getCell(1)).getNumberValue(), 0.0); - assertEquals(6.0, evaluator.evaluate(sh1.getRow(0).getCell(2)).getNumberValue(), 0.0); - - assertEquals(5.0, evaluator.evaluate(sh2.getRow(0).getCell(1)).getNumberValue(), 0.0); - assertEquals(15.0, evaluator.evaluate(sh2.getRow(0).getCell(2)).getNumberValue(), 0.0); - } - } - - /** - * Verify that FormulaParser handles defined names beginning with underscores, - * see Bug #49640 - */ - @Test - void testFormulasWithUnderscore() throws IOException{ - try (HSSFWorkbook wb = new HSSFWorkbook()) { - Name nm1 = wb.createName(); - nm1.setNameName("_score1"); - nm1.setRefersToFormula("A1"); - - Name nm2 = wb.createName(); - nm2.setNameName("_score2"); - nm2.setRefersToFormula("A2"); - - Sheet sheet = wb.createSheet(); - Cell cell = sheet.createRow(0).createCell(2); - cell.setCellFormula("_score1*SUM(_score1+_score2)"); - assertEquals("_score1*SUM(_score1+_score2)", cell.getCellFormula()); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java deleted file mode 100644 index 57f0fbc19d..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java +++ /dev/null @@ -1,418 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.ListIterator; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.record.DBCellRecord; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.StringRecord; -import org.apache.poi.ss.usermodel.BaseTestCell; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * Tests various functionality having to do with {@link HSSFCell}. For instance support for - * particular datatypes, etc. - */ -final class TestHSSFCell extends BaseTestCell { - - public TestHSSFCell() { - super(HSSFITestDataProvider.instance); - } - - /** - * Checks that the recognition of files using 1904 date windowing - * is working properly. Conversion of the date is also an issue, - * but there's a separate unit test for that. - */ - @Test - void testDateWindowingRead() throws IOException { - Calendar cal = LocaleUtil.getLocaleCalendar(2000, 0, 1, 0, 0, 0);// Jan. 1, 2000 - Date date = cal.getTime(); - - // first check a file with 1900 Date Windowing - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("1900DateWindowing.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - - assertEquals(date.getTime(), - sheet.getRow(0).getCell(0).getDateCellValue().getTime(), - "Date from file using 1900 Date Windowing"); - } - - // now check a file with 1904 Date Windowing - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("1904DateWindowing.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - - assertEquals(date.getTime(), - sheet.getRow(0).getCell(0).getDateCellValue().getTime(), - "Date from file using 1904 Date Windowing"); - } - } - - - - /** - * Checks that dates are properly written to both types of files: - * those with 1900 and 1904 date windowing. Note that if the - * previous test ({@link #testDateWindowingRead}) fails, the - * results of this test are meaningless. - */ - @Test - void testDateWindowingWrite() throws IOException { - Calendar cal = LocaleUtil.getLocaleCalendar(2000,0,1,0,0,0); // Jan. 1, 2000 - Date date = cal.getTime(); - - // first check a file with 1900 Date Windowing - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("1900DateWindowing.xls")) { - - setCell(wb1, 0, 1, date); - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - - assertEquals(date.getTime(), - readCell(wb2, 0, 1).getTime(), - "Date from file using 1900 Date Windowing"); - } - } - - // now check a file with 1904 Date Windowing - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("1904DateWindowing.xls")) { - setCell(wb1, 0, 1, date); - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - assertEquals(date.getTime(), - readCell(wb2, 0, 1).getTime(), - "Date from file using 1900 Date Windowing"); - } - } - } - - 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.setCellValue(date); - } - - 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); - return cell.getDateCellValue(); - } - - /** - * Tests that the active cell can be correctly read and set - */ - @Test - void testActiveCell() throws IOException { - //read in sample - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls")) { - - //check initial position - HSSFSheet umSheet = wb1.getSheetAt(0); - InternalSheet s = umSheet.getSheet(); - assertEquals((short) 0, s.getActiveCellCol(), "Initial active cell should be in col 0"); - assertEquals(1, s.getActiveCellRow(), "Initial active cell should be on row 1"); - - //modify position through HSSFCell - HSSFCell cell = umSheet.createRow(3).createCell(2); - cell.setAsActiveCell(); - assertEquals((short) 2, s.getActiveCellCol(), "After modify, active cell should be in col 2"); - assertEquals(3, s.getActiveCellRow(), "After modify, active cell should be on row 3"); - - //write book to temp file; read and verify that position is serialized - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - umSheet = wb2.getSheetAt(0); - s = umSheet.getSheet(); - - assertEquals((short) 2, s.getActiveCellCol(), "After serialize, active cell should be in col 2"); - assertEquals(3, s.getActiveCellRow(), "After serialize, active cell should be on row 3"); - } - } - } - - - @Test - void testActiveCellBug56114() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sh = wb.createSheet(); - - sh.createRow(0); - sh.createRow(1); - sh.createRow(2); - sh.createRow(3); - - Cell cell = sh.getRow(1).createCell(3); - sh.getRow(3).createCell(3); - - assertEquals(0, ((HSSFSheet) wb.getSheetAt(0)).getSheet().getActiveCellRow()); - assertEquals(0, ((HSSFSheet) wb.getSheetAt(0)).getSheet().getActiveCellCol()); - - cell.setAsActiveCell(); - cell.setCellValue("this should be active"); - - assertEquals(1, ((HSSFSheet) wb.getSheetAt(0)).getSheet().getActiveCellRow()); - assertEquals(3, ((HSSFSheet) wb.getSheetAt(0)).getSheet().getActiveCellCol()); - - try (Workbook wbBack = _testDataProvider.writeOutAndReadBack(wb)) { - assertEquals(1, ((HSSFSheet) wbBack.getSheetAt(0)).getSheet().getActiveCellRow()); - assertEquals(3, ((HSSFSheet) wbBack.getSheetAt(0)).getSheet().getActiveCellCol()); - - wbBack.getSheetAt(0).getRow(3).getCell(3).setAsActiveCell(); - - assertEquals(3, ((HSSFSheet) wbBack.getSheetAt(0)).getSheet().getActiveCellRow()); - assertEquals(3, ((HSSFSheet) wbBack.getSheetAt(0)).getSheet().getActiveCellCol()); - - try (Workbook wbBack2 = _testDataProvider.writeOutAndReadBack(wbBack)) { - assertEquals(3, ((HSSFSheet) wbBack2.getSheetAt(0)).getSheet().getActiveCellRow()); - assertEquals(3, ((HSSFSheet) wbBack2.getSheetAt(0)).getSheet().getActiveCellCol()); - } - } - } - } - - /** - * Test reading hyperlinks - */ - @Test - void testWithHyperlink() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithHyperlink.xls")) { - - HSSFSheet sheet = wb.getSheetAt(0); - HSSFCell cell = sheet.getRow(4).getCell(0); - HSSFHyperlink link = cell.getHyperlink(); - assertNotNull(link); - - assertEquals("Foo", link.getLabel()); - assertEquals("http://poi.apache.org/", link.getAddress()); - assertEquals(4, link.getFirstRow()); - assertEquals(0, link.getFirstColumn()); - } - } - - /** - * Test reading hyperlinks - */ - @Test - void testWithTwoHyperlinks() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithTwoHyperLinks.xls")) { - - HSSFSheet sheet = wb.getSheetAt(0); - - HSSFCell cell1 = sheet.getRow(4).getCell(0); - HSSFHyperlink link1 = cell1.getHyperlink(); - assertNotNull(link1); - assertEquals("Foo", link1.getLabel()); - assertEquals("http://poi.apache.org/", link1.getAddress()); - assertEquals(4, link1.getFirstRow()); - assertEquals(0, link1.getFirstColumn()); - - HSSFCell cell2 = sheet.getRow(8).getCell(1); - HSSFHyperlink link2 = cell2.getHyperlink(); - assertNotNull(link2); - assertEquals("Bar", link2.getLabel()); - assertEquals("http://poi.apache.org/hssf/", link2.getAddress()); - assertEquals(8, link2.getFirstRow()); - assertEquals(1, link2.getFirstColumn()); - } - } - - /** - * Test to ensure we can only assign cell styles that belong - * to our workbook, and not those from other workbooks. - */ - @Test - void testCellStyleWorkbookMatch() throws IOException { - try (HSSFWorkbook wbA = new HSSFWorkbook(); - HSSFWorkbook wbB = new HSSFWorkbook()) { - - HSSFCellStyle styA = wbA.createCellStyle(); - HSSFCellStyle styB = wbB.createCellStyle(); - - styA.verifyBelongsToWorkbook(wbA); - styB.verifyBelongsToWorkbook(wbB); - assertThrows(IllegalArgumentException.class, () -> styA.verifyBelongsToWorkbook(wbB)); - assertThrows(IllegalArgumentException.class, () -> styB.verifyBelongsToWorkbook(wbA)); - - Cell cellA = wbA.createSheet().createRow(0).createCell(0); - Cell cellB = wbB.createSheet().createRow(0).createCell(0); - - cellA.setCellStyle(styA); - cellB.setCellStyle(styB); - assertThrows(IllegalArgumentException.class, () -> cellA.setCellStyle(styB)); - assertThrows(IllegalArgumentException.class, () -> cellB.setCellStyle(styA)); - } - } - - /** - * Test for small bug observable around r736460 (prior to version 3.5). POI fails to remove - * the {@link StringRecord} following the {@link FormulaRecord} after the result type had been - * changed to number/boolean/error. Excel silently ignores the extra record, but some POI - * versions (prior to bug 46213 / r717883) crash instead. - */ - @Test - void testCachedTypeChange() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet("Sheet1"); - Cell cell = sheet.createRow(0).createCell(0); - cell.setCellFormula("A1"); - cell.setCellValue("abc"); - confirmStringRecord(sheet, true); - cell.setCellValue(123); - - final List recs = new ArrayList<>(); - sheet.getSheet().visitContainedRecords(recs::add, 0); - assertFalse(recs.size() == 28 && recs.get(23) instanceof StringRecord, "Identified bug - leftover StringRecord"); - confirmStringRecord(sheet, false); - - // string to error code - cell.setCellValue("abc"); - confirmStringRecord(sheet, true); - cell.setCellErrorValue(FormulaError.REF.getCode()); - confirmStringRecord(sheet, false); - - // string to boolean - cell.setCellValue("abc"); - confirmStringRecord(sheet, true); - cell.setCellValue(false); - confirmStringRecord(sheet, false); - } - } - - private static void confirmStringRecord(HSSFSheet sheet, boolean isPresent) { - List recs = new ArrayList<>(); - sheet.getSheet().visitContainedRecords(recs::add, 0); - assertEquals(isPresent ? 28 : 27, recs.size()); - - ListIterator iter = recs.listIterator(22); - assertEquals(FormulaRecord.class, iter.next().getClass()); - if (isPresent) { - assertEquals(StringRecord.class, iter.next().getClass()); - } - assertEquals(DBCellRecord.class, iter.next().getClass()); - } - - /** - * HSSF prior to version 3.7 had a bug: it could write a NaN but could not read such a file back. - */ - @Test - void testReadNaN() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49761.xls")) { - assertNotNull(wb); - } - } - - @Test - void testHSSFCell() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - HSSFRow row = sheet.createRow(0); - row.createCell(0); - HSSFCell cell = new HSSFCell(wb, sheet, 0, (short) 0); - assertNotNull(cell); - } - } - - @Test - void testDeprecatedMethods() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - - // cover some deprecated methods and other smaller stuff... - assertEquals(wb.getWorkbook(), cell.getBoundWorkbook()); - - assertThrows(IllegalStateException.class, cell::getCachedFormulaResultType); - - cell.removeCellComment(); - cell.removeCellComment(); - } - } - - @Test - void testCellType() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - cell.setBlank(); - assertNull(cell.getDateCellValue()); - assertFalse(cell.getBooleanCellValue()); - assertEquals("", cell.toString()); - - cell.setCellType(CellType.STRING); - assertEquals("", cell.toString()); - cell.setCellValue(1.2); - assertEquals("1.2", cell.toString()); - cell.setCellType(CellType.BOOLEAN); - assertEquals("TRUE", cell.toString()); - cell.setCellType(CellType.BOOLEAN); - cell.setCellValue("" + FormulaError.VALUE.name()); - assertEquals(CellType.STRING, cell.getCellType()); - cell.setCellType(CellType.BOOLEAN); - assertEquals("FALSE", cell.toString()); - cell.setCellValue(1.2); - assertEquals("1.2", cell.toString()); - cell.setCellType(CellType.BOOLEAN); - cell.setCellType(CellType.STRING); - cell.setCellType(CellType.ERROR); - cell.setCellType(CellType.STRING); - cell.setCellValue(1.2); - cell.setCellType(CellType.STRING); - assertEquals("1.2", cell.toString()); - - cell.setCellValue((String) null); - cell.setCellValue((RichTextString) null); - } - } - - @Test - void getErrorCellValue_throwsISE_onABlankCell() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - Cell cell = wb.createSheet().createRow(0).createCell(0); - assertThrows(IllegalStateException.class, cell::getErrorCellValue); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java deleted file mode 100644 index a6555e3f6c..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java +++ /dev/null @@ -1,267 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.record.chart.SeriesRecord; -import org.apache.poi.hssf.usermodel.HSSFChart.HSSFSeries; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressBase; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link HSSFChart} - */ -final class TestHSSFChart { - - @Test - void testSingleChart() { - HSSFWorkbook wb = openSampleWorkbook("WithChart.xls"); - - HSSFSheet s1 = wb.getSheetAt(0); - HSSFSheet s2 = wb.getSheetAt(1); - HSSFSheet s3 = wb.getSheetAt(2); - - assertEquals(0, HSSFChart.getSheetCharts(s1).length); - assertEquals(1, HSSFChart.getSheetCharts(s2).length); - assertEquals(0, HSSFChart.getSheetCharts(s3).length); - - HSSFChart[] charts; - - // Check the chart on the 2nd sheet - charts = HSSFChart.getSheetCharts(s2); - assertEquals(1, charts.length); - - assertEquals(2, charts[0].getSeries().length); - assertEquals("1st Column", charts[0].getSeries()[0].getSeriesTitle()); - assertEquals("2nd Column", charts[0].getSeries()[1].getSeriesTitle()); - assertNull(charts[0].getChartTitle()); - - // Check x, y, width, height - assertEquals(0, charts[0].getChartX()); - assertEquals(0, charts[0].getChartY()); - assertEquals(26492928, charts[0].getChartWidth()); - assertEquals(15040512, charts[0].getChartHeight()); - } - - @Test - void testTwoCharts() { - HSSFWorkbook wb = openSampleWorkbook("WithTwoCharts.xls"); - - HSSFSheet s1 = wb.getSheetAt(0); - HSSFSheet s2 = wb.getSheetAt(1); - HSSFSheet s3 = wb.getSheetAt(2); - - assertEquals(0, HSSFChart.getSheetCharts(s1).length); - assertEquals(1, HSSFChart.getSheetCharts(s2).length); - assertEquals(1, HSSFChart.getSheetCharts(s3).length); - - HSSFChart[] charts; - - // Check the chart on the 2nd sheet - charts = HSSFChart.getSheetCharts(s2); - assertEquals(1, charts.length); - - assertEquals(2, charts[0].getSeries().length); - assertEquals("1st Column", charts[0].getSeries()[0].getSeriesTitle()); - assertEquals("2nd Column", charts[0].getSeries()[1].getSeriesTitle()); - assertNull(charts[0].getChartTitle()); - - // And the third sheet - charts = HSSFChart.getSheetCharts(s3); - assertEquals(1, charts.length); - - assertEquals(2, charts[0].getSeries().length); - assertEquals("Squares", charts[0].getSeries()[0].getSeriesTitle()); - assertEquals("Base Numbers", charts[0].getSeries()[1].getSeriesTitle()); - assertNull(charts[0].getChartTitle()); - } - - @Test - void testThreeCharts() { - HSSFWorkbook wb = openSampleWorkbook("WithThreeCharts.xls"); - - HSSFSheet s1 = wb.getSheetAt(0); - HSSFSheet s2 = wb.getSheetAt(1); - HSSFSheet s3 = wb.getSheetAt(2); - - assertEquals(0, HSSFChart.getSheetCharts(s1).length); - assertEquals(2, HSSFChart.getSheetCharts(s2).length); - assertEquals(1, HSSFChart.getSheetCharts(s3).length); - - HSSFChart[] charts; - - // Check the charts on the 2nd sheet - charts = HSSFChart.getSheetCharts(s2); - assertEquals(2, charts.length); - - assertEquals(2, charts[0].getSeries().length); - assertEquals("1st Column", charts[0].getSeries()[0].getSeriesTitle()); - assertEquals("2nd Column", charts[0].getSeries()[1].getSeriesTitle()); - assertEquals(6, charts[0].getSeries()[0].getNumValues()); - assertEquals(6, charts[0].getSeries()[1].getNumValues()); - assertEquals(SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC, charts[0].getSeries()[0].getValueType()); - assertEquals(SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC, charts[0].getSeries()[1].getValueType()); - assertNull(charts[0].getChartTitle()); - - assertEquals(1, charts[1].getSeries().length); - assertNull(charts[1].getSeries()[0].getSeriesTitle()); - assertEquals("Pie Chart Title Thingy", charts[1].getChartTitle()); - - // And the third sheet - charts = HSSFChart.getSheetCharts(s3); - assertEquals(1, charts.length); - - assertEquals(2, charts[0].getSeries().length); - assertEquals("Squares", charts[0].getSeries()[0].getSeriesTitle()); - assertEquals("Base Numbers", charts[0].getSeries()[1].getSeriesTitle()); - assertEquals("Sheet 3 Chart with Title", charts[0].getChartTitle()); - } - - @Test - void testExistingSheet3() throws Exception { - HSSFWorkbook wb = openSampleWorkbook("49581.xls"); - - HSSFSheet sheet = wb.getSheetAt( 2 ) ; - HSSFChart[] charts = HSSFChart.getSheetCharts( sheet ) ; - assertEquals(1, charts.length); - - for ( HSSFChart chart : charts ) { - for ( HSSFSeries series : chart.getSeries() ) { - chart.removeSeries( series ) ; - } - } - - // Save and re-check - wb = HSSFITestDataProvider.instance.writeOutAndReadBack(wb); - sheet = wb.getSheetAt( 2 ) ; - assertEquals(1, HSSFChart.getSheetCharts(sheet).length); - - HSSFChart c = HSSFChart.getSheetCharts(sheet)[0]; - assertEquals(0, c.getSeries().length); - } - - @Test - void testExistingSheet2() throws Exception { - HSSFWorkbook wb = openSampleWorkbook("49581.xls"); - HSSFSheet sheet = wb.getSheetAt( 1 ) ; - HSSFChart[] charts = HSSFChart.getSheetCharts( sheet ) ; - - assertEquals(1, charts.length); - for ( HSSFChart chart : charts ) { - HSSFSeries series ; - - // Starts with one - assertEquals(1, chart.getSeries().length); - - // Add two more - series = chart.createSeries() ; - series.setCategoryLabelsCellRange( new CellRangeAddress( 3, 4, 0, 0 ) ) ; - series.setValuesCellRange( new CellRangeAddress( 3, 4, 1, 1 ) ) ; - - series = chart.createSeries() ; - series.setCategoryLabelsCellRange( new CellRangeAddress( 6, 7, 0, 0 ) ) ; - series.setValuesCellRange( new CellRangeAddress( 6, 7, 1, 1 ) ) ; - } - - // Save and re-check - wb = HSSFITestDataProvider.instance.writeOutAndReadBack(wb); - sheet = wb.getSheetAt( 1 ) ; - assertEquals(1, HSSFChart.getSheetCharts(sheet).length); - - HSSFChart c = HSSFChart.getSheetCharts(sheet)[0]; - assertEquals(3, c.getSeries().length); - } - - @Test - void testExistingSheet1() throws Exception { - try (HSSFWorkbook wb = openSampleWorkbook("49581.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - HSSFChart[] charts = HSSFChart.getSheetCharts(sheet); - - for (HSSFChart chart : charts) { - for (HSSFSeries series : chart.getSeries()) { - CellRangeAddressBase range; - - range = series.getValuesCellRange(); - range.setLastRow(range.getLastRow() + 1); - series.setValuesCellRange(range); - - range = series.getCategoryLabelsCellRange(); - range.setLastRow(range.getLastRow() + 1); - series.setCategoryLabelsCellRange(range); - } - - for (int id = 0; id < 2; id++) { - HSSFSeries newSeries = chart.createSeries(); - assertNotNull(newSeries); - newSeries.setValuesCellRange(new CellRangeAddress(1 + id, 4, 3, 3)); - String oldSeriesTitle = newSeries.getSeriesTitle(); - if (oldSeriesTitle != null) { - newSeries.setSeriesTitle("new series"); - } - } - } - - HSSFChart chart = charts[2]; - chart.removeSeries(chart.getSeries()[0]); - assertEquals(2, chart.getSeries().length); - } - } - - /** - * Bug 26862: HSSFWorkbook.cloneSheet copies charts - */ - @Test - void test26862() throws IOException, Exception { - HSSFWorkbook wb = openSampleWorkbook("SimpleChart.xls"); - HSSFSheet srcSheet = wb.getSheetAt(0); - HSSFChart[] srcCharts = HSSFChart.getSheetCharts(srcSheet); - assertEquals(1, srcCharts.length); - HSSFChart srcChart = srcCharts[0]; - - // Clone the sheet - HSSFSheet clonedSheet = wb.cloneSheet(0); - - // Verify the chart was copied - HSSFChart[] clonedCharts = HSSFChart.getSheetCharts(clonedSheet); - assertEquals(1, clonedCharts.length); - HSSFChart clonedChart = clonedCharts[0]; - assertNotSame(srcChart, clonedChart); //refer to different objects - assertEquals(srcChart.getType(), clonedChart.getType()); - assertEquals(srcChart.getChartTitle(), clonedChart.getChartTitle()); - assertEquals(srcChart.getChartWidth(), clonedChart.getChartWidth()); - assertEquals(srcChart.getChartHeight(), clonedChart.getChartHeight()); - assertEquals(srcChart.getChartX(), clonedChart.getChartX()); - assertEquals(srcChart.getChartY(), clonedChart.getChartY()); - - // Check if chart was shallow copied or deep copied - clonedChart.setChartWidth(clonedChart.getChartWidth()+10); - assertEquals(srcChart.getChartWidth()+10, clonedChart.getChartWidth()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java deleted file mode 100644 index 1cc79736c1..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java +++ /dev/null @@ -1,162 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.IOException; - -import org.apache.poi.ddf.EscherClientAnchorRecord; -import org.apache.poi.hssf.model.ConvertAnchor; -import org.junit.jupiter.api.Test; - -/** - * Various tests for HSSFClientAnchor. - */ -final class TestHSSFClientAnchor { - @Test - void testGetAnchorHeightInPoints() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet("test"); - HSSFClientAnchor a = new HSSFClientAnchor(0, 0, 1023, 255, (short) 0, 0, (short) 0, 0); - float p = a.getAnchorHeightInPoints(sheet); - assertEquals(12.7, p, 0.001); - - sheet.createRow(0).setHeightInPoints(14); - a = new HSSFClientAnchor(0, 0, 1023, 255, (short) 0, 0, (short) 0, 0); - p = a.getAnchorHeightInPoints(sheet); - assertEquals(13.945, p, 0.001); - - a = new HSSFClientAnchor(0, 0, 1023, 127, (short) 0, 0, (short) 0, 0); - p = a.getAnchorHeightInPoints(sheet); - assertEquals(6.945, p, 0.001); - - a = new HSSFClientAnchor(0, 126, 1023, 127, (short) 0, 0, (short) 0, 0); - p = a.getAnchorHeightInPoints(sheet); - assertEquals(0.054, p, 0.001); - - a = new HSSFClientAnchor(0, 0, 1023, 0, (short) 0, 0, (short) 0, 1); - p = a.getAnchorHeightInPoints(sheet); - assertEquals(14.0, p, 0.001); - - sheet.createRow(0).setHeightInPoints(12); - a = new HSSFClientAnchor(0, 127, 1023, 127, (short) 0, 0, (short) 0, 1); - p = a.getAnchorHeightInPoints(sheet); - assertEquals(12.372, p, 0.001); - } - } - - /** - * When HSSFClientAnchor is converted into EscherClientAnchorRecord - * check that dx1, dx2, dy1 and dy2 are written "as is". - * (Bug 42999 reported that dx1 and dx2 are swapped if dx1>dx2. It doesn't make sense for client anchors.) - */ - @Test - void testConvertAnchor() { - HSSFClientAnchor[] anchors = { - new HSSFClientAnchor( 0 , 0 , 0 , 0 ,(short)0, 1,(short)1,3), - new HSSFClientAnchor( 100 , 0 , 900 , 255 ,(short)0, 1,(short)1,3), - new HSSFClientAnchor( 900 , 0 , 100 , 255 ,(short)0, 1,(short)1,3) - }; - for (HSSFClientAnchor anchor : anchors) { - EscherClientAnchorRecord record = (EscherClientAnchorRecord)ConvertAnchor.createAnchor(anchor); - assertEquals(anchor.getDx1(), record.getDx1()); - assertEquals(anchor.getDx2(), record.getDx2()); - assertEquals(anchor.getDy1(), record.getDy1()); - assertEquals(anchor.getDy2(), record.getDy2()); - assertEquals(anchor.getCol1(), record.getCol1()); - assertEquals(anchor.getCol2(), record.getCol2()); - assertEquals(anchor.getRow1(), record.getRow1()); - assertEquals(anchor.getRow2(), record.getRow2()); - } - } - - @Test - void testAnchorHeightInPoints() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - - HSSFClientAnchor[] anchor = { - new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 1, (short) 1, 3), - new HSSFClientAnchor(0, 254, 0, 126, (short) 0, 1, (short) 1, 3), - new HSSFClientAnchor(0, 128, 0, 128, (short) 0, 1, (short) 1, 3), - new HSSFClientAnchor(0, 0, 0, 128, (short) 0, 1, (short) 1, 3), - }; - float[] ref = {25.5f, 19.125f, 25.5f, 31.875f}; - for (int i = 0; i < anchor.length; i++) { - float height = anchor[i].getAnchorHeightInPoints(sheet); - assertEquals(ref[i], height, 0); - } - } - } - - /** - * Check {@link HSSFClientAnchor} constructor does not treat 32768 as -32768. - */ - @Test - void testCanHaveRowGreaterThan32767() { - // Maximum permitted row number should be 65535. - HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 32768, (short) 0, 32768); - - assertEquals(32768, anchor.getRow1()); - assertEquals(32768, anchor.getRow2()); - } - - /** - * Check the maximum is not set at 255*256 instead of 256*256 - 1. - */ - @Test - void testCanHaveRowUpTo65535() { - HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 65535, (short) 0, 65535); - - assertEquals(65535, anchor.getRow1()); - assertEquals(65535, anchor.getRow2()); - } - - @Test - void testCannotHaveRowGreaterThan65535() { - assertThrows(IllegalArgumentException.class, () -> - new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 65536, (short) 0, 65536)); - } - - /** - * Check the same maximum value enforced when using {@link HSSFClientAnchor#setRow1}. - */ - @Test - void testCanSetRowUpTo65535() { - HSSFClientAnchor anchor = new HSSFClientAnchor(); - anchor.setRow1(65535); - anchor.setRow2(65535); - - assertEquals(65535, anchor.getRow1()); - assertEquals(65535, anchor.getRow2()); - } - - @Test - void testCannotSetRow1GreaterThan65535() { - assertThrows(IllegalArgumentException.class, () -> - new HSSFClientAnchor().setRow1(65536)); - } - - @Test - void testCannotSetRow2GreaterThan65535() { - assertThrows(IllegalArgumentException.class, () -> - new HSSFClientAnchor().setRow2(65536)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFColumnShifting.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFColumnShifting.java deleted file mode 100644 index 66a5c308df..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFColumnShifting.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.usermodel.helpers.HSSFColumnShifter; -import org.apache.poi.ss.usermodel.BaseTestColumnShifting; - -class TestHSSFColumnShifting extends BaseTestColumnShifting { - public TestHSSFColumnShifting() { - super(); - wb = new HSSFWorkbook(); - } - @Override - protected void initColumnShifter(){ - columnShifter = new HSSFColumnShifter((HSSFSheet)sheet1); - } - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java deleted file mode 100644 index 181cd5052b..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java +++ /dev/null @@ -1,452 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.CommonObjectDataSubRecord; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.hssf.record.NoteRecord; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.record.TextObjectRecord; -import org.apache.poi.ss.usermodel.BaseTestCellComment; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Tests TestHSSFCellComment. - * - * @author Yegor Kozlov - */ -final class TestHSSFComment extends BaseTestCellComment { - - public TestHSSFComment() { - super(HSSFITestDataProvider.instance); - } - - @Test - void defaultShapeType() { - HSSFComment comment = new HSSFComment(null, new HSSFClientAnchor()); - assertEquals(HSSFSimpleShape.OBJECT_TYPE_COMMENT, comment.getShapeType()); - } - - /** - * HSSFCell#findCellComment should NOT rely on the order of records - * when matching cells and their cell comments. The correct algorithm is to map - */ - @Test - void bug47924() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("47924.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFCell cell; - HSSFComment comment; - - cell = sheet.getRow(0).getCell(0); - comment = cell.getCellComment(); - assertEquals("a1", comment.getString().getString()); - - cell = sheet.getRow(1).getCell(0); - comment = cell.getCellComment(); - assertEquals("a2", comment.getString().getString()); - - cell = sheet.getRow(2).getCell(0); - comment = cell.getCellComment(); - assertEquals("a3", comment.getString().getString()); - - cell = sheet.getRow(2).getCell(2); - comment = cell.getCellComment(); - assertEquals("c3", comment.getString().getString()); - - cell = sheet.getRow(4).getCell(1); - comment = cell.getCellComment(); - assertEquals("b5", comment.getString().getString()); - - cell = sheet.getRow(5).getCell(2); - comment = cell.getCellComment(); - assertEquals("c6", comment.getString().getString()); - - wb.close(); - } - - @Test - void testBug56380InsertComments() throws Exception { - HSSFWorkbook workbook = new HSSFWorkbook(); - Sheet sheet = workbook.createSheet(); - Drawing drawing = sheet.createDrawingPatriarch(); - int noOfRows = 1025; - String comment = "c"; - - for(int i = 0; i < noOfRows; i++) { - Row row = sheet.createRow(i); - Cell cell = row.createCell(0); - insertComment(drawing, cell, comment + i); - } - - // assert that the comments are created properly before writing - checkComments(sheet, noOfRows, comment); - - /*// store in temp-file - OutputStream fs = new FileOutputStream("/tmp/56380.xls"); - try { - sheet.getWorkbook().write(fs); - } finally { - fs.close(); - }*/ - - // save and recreate the workbook from the saved file - HSSFWorkbook workbookBack = HSSFTestDataSamples.writeOutAndReadBack(workbook); - sheet = workbookBack.getSheetAt(0); - - // assert that the comments are created properly after reading back in - checkComments(sheet, noOfRows, comment); - - workbook.close(); - workbookBack.close(); - } - - @Test - void testBug56380InsertTooManyComments() throws Exception { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - Sheet sheet = workbook.createSheet(); - Drawing drawing = sheet.createDrawingPatriarch(); - String comment = "c"; - - for (int rowNum = 0; rowNum < 258; rowNum++) { - sheet.createRow(rowNum); - } - - // should still work, for some reason DrawingManager2.allocateShapeId() skips the first 1024... - for (int count = 1025; count < 65535; count++) { - int rowNum = count / 255; - int cellNum = count % 255; - Cell cell = sheet.getRow(rowNum).createCell(cellNum); - try { - Comment commentObj = insertComment(drawing, cell, comment + cellNum); - - assertEquals(count, ((HSSFComment) commentObj).getNoteRecord().getShapeId()); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("While adding shape number " + count, e); - } - } - - // this should now fail to insert - Row row = sheet.createRow(257); - Cell cell = row.createCell(0); - insertComment(drawing, cell, comment + 0); - } - } - - private void checkComments(Sheet sheet, int noOfRows, String comment) { - for(int i = 0; i < noOfRows; i++) { - assertNotNull(sheet.getRow(i)); - assertNotNull(sheet.getRow(i).getCell(0)); - assertNotNull(sheet.getRow(i).getCell(0).getCellComment(), "Did not get a Cell Comment for row " + i); - assertNotNull(sheet.getRow(i).getCell(0).getCellComment().getString()); - assertEquals(comment + i, sheet.getRow(i).getCell(0).getCellComment().getString().getString()); - } - } - - private Comment insertComment(Drawing drawing, Cell cell, String message) { - CreationHelper factory = cell.getSheet().getWorkbook().getCreationHelper(); - - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(cell.getColumnIndex()); - anchor.setCol2(cell.getColumnIndex() + 1); - anchor.setRow1(cell.getRowIndex()); - anchor.setRow2(cell.getRowIndex() + 1); - anchor.setDx1(100); - anchor.setDx2(100); - anchor.setDy1(100); - anchor.setDy2(100); - - Comment comment = drawing.createCellComment(anchor); - - RichTextString str = factory.createRichTextString(message); - comment.setString(str); - comment.setAuthor("fanfy"); - cell.setCellComment(comment); - - return comment; - } - - @Test - void resultEqualsToNonExistingAbstractShape() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - HSSFRow row = sh.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellComment(comment); - - assertEquals(comment.getEscherContainer().getChildCount(), 5); - - //sp record - byte[] expected = decompress("H4sIAAAAAAAAAFvEw/WBg4GBgZEFSHAxMAAA9gX7nhAAAAA="); - byte[] actual = comment.getEscherContainer().getChild(0).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPggxIANAABK4+laGgAAAA=="); - actual = comment.getEscherContainer().getChild(2).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPzAAAQACl6c5QgAAAA="); - actual = comment.getEscherContainer().getChild(3).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNg4P3AAAQA6pyIkQgAAAA="); - actual = comment.getEscherContainer().getChild(4).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - ObjRecord obj = comment.getObjRecord(); - - expected = decompress("H4sIAAAAAAAAAItlMGEQZRBikGRgZBF0YEACvAxiDLgBAJZsuoU4AAAA"); - actual = obj.serialize(); - - assertEquals(expected.length, actual.length); - //assertArrayEquals(expected, actual); - - TextObjectRecord tor = comment.getTextObjectRecord(); - - expected = decompress("H4sIAAAAAAAAANvGKMQgxMSABgBGi8T+FgAAAA=="); - actual = tor.serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - NoteRecord note = comment.getNoteRecord(); - - expected = decompress("H4sIAAAAAAAAAJNh4GGAAEYWEAkAS0KXuRAAAAA="); - actual = note.serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - wb.close(); - } - - @Test - void addToExistingFile() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - int idx = wb.addPicture(new byte[]{1,2,3}, Workbook.PICTURE_TYPE_PNG); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - comment.setColumn(5); - comment.setString(new HSSFRichTextString("comment1")); - comment = patriarch.createCellComment(new HSSFClientAnchor(0,0,100,100,(short)0,0,(short)10,10)); - comment.setRow(5); - comment.setString(new HSSFRichTextString("comment2")); - comment.setBackgroundImage(idx); - assertEquals(comment.getBackgroundImageId(), idx); - - assertEquals(patriarch.getChildren().size(), 2); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wbBack.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - comment = (HSSFComment) patriarch.getChildren().get(1); - assertEquals(comment.getBackgroundImageId(), idx); - comment.resetBackgroundImage(); - assertEquals(comment.getBackgroundImageId(), 0); - - assertEquals(patriarch.getChildren().size(), 2); - comment = patriarch.createCellComment(new HSSFClientAnchor()); - comment.setString(new HSSFRichTextString("comment3")); - - assertEquals(patriarch.getChildren().size(), 3); - HSSFWorkbook wbBack2 = HSSFTestDataSamples.writeOutAndReadBack(wbBack); - sh = wbBack2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - comment = (HSSFComment) patriarch.getChildren().get(1); - assertEquals(comment.getBackgroundImageId(), 0); - assertEquals(patriarch.getChildren().size(), 3); - assertEquals(((HSSFComment) patriarch.getChildren().get(0)).getString().getString(), "comment1"); - assertEquals(((HSSFComment) patriarch.getChildren().get(1)).getString().getString(), "comment2"); - assertEquals(((HSSFComment) patriarch.getChildren().get(2)).getString().getString(), "comment3"); - - wb.close(); - wbBack.close(); - wbBack2.close(); - } - - @Test - void setGetProperties() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - comment.setString(new HSSFRichTextString("comment1")); - assertEquals(comment.getString().getString(), "comment1"); - - comment.setAuthor("poi"); - assertEquals(comment.getAuthor(), "poi"); - - comment.setColumn(3); - assertEquals(comment.getColumn(), 3); - - comment.setRow(4); - assertEquals(comment.getRow(), 4); - - comment.setVisible(false); - assertFalse(comment.isVisible()); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wbBack.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - comment = (HSSFComment) patriarch.getChildren().get(0); - - assertEquals(comment.getString().getString(), "comment1"); - assertEquals("poi", comment.getAuthor()); - assertEquals(comment.getColumn(), 3); - assertEquals(comment.getRow(), 4); - assertFalse(comment.isVisible()); - - comment.setString(new HSSFRichTextString("comment12")); - comment.setAuthor("poi2"); - comment.setColumn(32); - comment.setRow(42); - comment.setVisible(true); - - HSSFWorkbook wbBack2 = HSSFTestDataSamples.writeOutAndReadBack(wbBack); - sh = wbBack2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - comment = (HSSFComment) patriarch.getChildren().get(0); - - assertEquals(comment.getString().getString(), "comment12"); - assertEquals("poi2", comment.getAuthor()); - assertEquals(comment.getColumn(), 32); - assertEquals(comment.getRow(), 42); - assertTrue(comment.isVisible()); - - wb.close(); - wbBack.close(); - wbBack2.close(); - } - - @Test - void existingFileWithComment() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("comments"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - HSSFComment comment = (HSSFComment) drawing.getChildren().get(0); - assertEquals(comment.getAuthor(), "evgeniy"); - assertEquals(comment.getString().getString(), "evgeniy:\npoi test"); - assertEquals(comment.getColumn(), 1); - assertEquals(comment.getRow(), 2); - wb.close(); - } - - @Test - void findComments() throws IOException{ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - HSSFRow row = sh.createRow(5); - HSSFCell cell = row.createCell(4); - cell.setCellComment(comment); - - assertNotNull(sh.findCellComment(5, 4)); - assertNull(sh.findCellComment(5, 5)); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wbBack.getSheetAt(0); - - assertNotNull(sh.findCellComment(5, 4)); - assertNull(sh.findCellComment(5, 5)); - - wb.close(); - wbBack.close(); - } - - @Test - void initState() throws IOException{ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch); - assertEquals(agg.getTailRecords().size(), 0); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - assertEquals(agg.getTailRecords().size(), 1); - - HSSFSimpleShape shape = patriarch.createSimpleShape(new HSSFClientAnchor()); - assertNotNull(shape); - - assertEquals(comment.getOptRecord().getEscherProperties().size(), 10); - - wb.close(); - } - - @Test - void shapeId() throws IOException{ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - - comment.setShapeId(2024); - - assertEquals(comment.getShapeId(), 2024); - - CommonObjectDataSubRecord cod = (CommonObjectDataSubRecord) comment.getObjRecord().getSubRecords().get(0); - assertEquals(2024, cod.getObjectId()); - EscherSpRecord spRecord = (EscherSpRecord) comment.getEscherContainer().getChild(0); - assertEquals(2024, spRecord.getShapeId(), 2024); - assertEquals(2024, comment.getShapeId(), 2024); - assertEquals(2024, comment.getNoteRecord().getShapeId()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java deleted file mode 100644 index b6a472ad38..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.BaseTestConditionalFormatting; -import org.apache.poi.ss.usermodel.Color; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.SheetConditionalFormatting; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * HSSF-specific Conditional Formatting tests - */ -final class TestHSSFConditionalFormatting extends BaseTestConditionalFormatting { - public TestHSSFConditionalFormatting(){ - super(HSSFITestDataProvider.instance); - } - @Override - protected void assertColor(String hexExpected, Color actual) { - assertNotNull(actual, "Colour must be given"); - if (actual instanceof HSSFColor) { - HSSFColor colour = (HSSFColor)actual; - assertEquals(hexExpected, colour.getHexString()); - } else { - HSSFExtendedColor colour = (HSSFExtendedColor)actual; - if (hexExpected.length() == 8) { - assertEquals(hexExpected, colour.getARGBHex()); - } else { - assertEquals(hexExpected, colour.getARGBHex().substring(2)); - } - } - } - - @Test - void testRead() throws IOException { - testRead("WithConditionalFormatting.xls"); - } - - @Test - void testReadOffice2007() throws IOException { - testReadOffice2007("NewStyleConditionalFormattings.xls"); - } - - @Test - void test53691() throws IOException { - SheetConditionalFormatting cf; - final Workbook wb = HSSFITestDataProvider.instance.openSampleWorkbook("53691.xls"); - /* - FileInputStream s = new FileInputStream("C:\\temp\\53691bbadfixed.xls"); - try { - wb = new HSSFWorkbook(s); - } finally { - s.close(); - } - - wb.removeSheetAt(1);*/ - - // initially it is good - writeTemp53691(wb, "agood"); - - // clone sheet corrupts it - Sheet sheet = wb.cloneSheet(0); - writeTemp53691(wb, "bbad"); - - // removing the sheet makes it good again - wb.removeSheetAt(wb.getSheetIndex(sheet)); - writeTemp53691(wb, "cgood"); - - // cloning again and removing the conditional formatting makes it good again - sheet = wb.cloneSheet(0); - removeConditionalFormatting(sheet); - writeTemp53691(wb, "dgood"); - - // cloning the conditional formatting manually makes it bad again - cf = sheet.getSheetConditionalFormatting(); - SheetConditionalFormatting scf = wb.getSheetAt(0).getSheetConditionalFormatting(); - for (int j = 0; j < scf.getNumConditionalFormattings(); j++) { - cf.addConditionalFormatting(scf.getConditionalFormattingAt(j)); - } - writeTemp53691(wb, "ebad"); - - // remove all conditional formatting for comparing BIFF output - removeConditionalFormatting(sheet); - removeConditionalFormatting(wb.getSheetAt(0)); - writeTemp53691(wb, "fgood"); - - wb.close(); - } - - private void removeConditionalFormatting(Sheet sheet) { - SheetConditionalFormatting cf = sheet.getSheetConditionalFormatting(); - for (int j = 0; j < cf.getNumConditionalFormattings(); j++) { - cf.removeConditionalFormatting(j); - } - } - - private void writeTemp53691(Workbook wb, @SuppressWarnings("UnusedParameters") String suffix) throws IOException { - // assert that we can write/read it in memory - Workbook wbBack = HSSFITestDataProvider.instance.writeOutAndReadBack(wb); - assertNotNull(wbBack); - wbBack.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java deleted file mode 100644 index 98195b11d5..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestDataFormat; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link HSSFDataFormat} - */ -final class TestHSSFDataFormat extends BaseTestDataFormat { - - public TestHSSFDataFormat() { - super(HSSFITestDataProvider.instance); - } - - /** - * Bug 51378: getDataFormatString method call crashes when reading the test file - */ - @Test - void test51378() throws IOException { - List expNull = Arrays.asList( "0-3-0","0-43-11" ); - try (HSSFWorkbook wb = openSampleWorkbook("12561-1.xls")) { - for (Sheet sheet : wb) { - for (Row row : sheet) { - for (Cell cell : row) { - CellStyle style = cell.getCellStyle(); - assertNotNull(style); - String coord = wb.getSheetIndex(sheet)+"-"+cell.getRowIndex()+"-"+cell.getColumnIndex(); - String fmt = style.getDataFormatString(); - assertEquals(expNull.contains(coord), fmt == null, coord+" unexpected"); - } - } - } - } - } - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java deleted file mode 100644 index 4e2843ad22..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java +++ /dev/null @@ -1,459 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.Format; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Iterator; -import java.util.Locale; -import java.util.TimeZone; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Unit tests for HSSFDataFormatter.java - */ -public final class TestHSSFDataFormatter { - private static TimeZone userTimeZone; - - @BeforeAll - public static void setTimeZone() { - userTimeZone = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - LocaleUtil.setUserLocale(Locale.US); - } - - @AfterAll - public static void resetTimeZone() { - LocaleUtil.setUserTimeZone(userTimeZone); - LocaleUtil.setUserLocale(Locale.ROOT); - } - - - private final HSSFDataFormatter formatter; - private final HSSFWorkbook wb; - - public TestHSSFDataFormatter() { - // create the formatter to test - formatter = new HSSFDataFormatter(); - - // create a workbook to test with - wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - HSSFDataFormat format = wb.createDataFormat(); - - // create a row and put some cells in it - HSSFRow row = sheet.createRow(0); - - // date value for July 8 1901 1:19 PM - double dateNum = 555.555; - // date value for July 8 1901 11:23 AM - double timeNum = 555.47431; - - //valid date formats -- all should have "Jul" in output - String[] goodDatePatterns = { - "[$-F800]dddd\\,\\ mmmm\\ dd\\,\\ yyyy", - "mmm/d/yy\\ h:mm PM;@", - "mmmm/d/yy\\ h:mm;@", - "mmmm/d;@", - "mmmm/d/yy;@", - "mmm/dd/yy;@", - "[$-409]d\\-mmm;@", - "[$-409]d\\-mmm\\-yy;@", - "[$-409]dd\\-mmm\\-yy;@", - "[$-409]mmm\\-yy;@", - "[$-409]mmmm\\-yy;@", - "[$-409]mmmm\\ d\\,\\ yyyy;@", - "[$-409]mmm/d/yy\\ h:mm:ss;@", - "[$-409]mmmm/d/yy\\ h:mm:ss am;@", - "[$-409]mmmmm;@", - "[$-409]mmmmm\\-yy;@", - "mmmm/d/yyyy;@", - "[$-409]d\\-mmm\\-yyyy;@", - "[$-409]d\\-mmm;[$-3]d\\-mmm;@", // international three-part - "[$-41f]d\\-mmm;[$-41f]d\\-mmm;@", // turkish international three-part - "[$-F40f]d\\-mmm;[$-F40f]d\\-mmm;@", // custom international three-part - "[$-F40f]d\\-mmm;[$-F40f]d\\-mmm;0;@" // custom international four-part - }; - - //valid time formats - all should have 11:23 in output - String[] goodTimePatterns = { - "HH:MM", - "HH:MM:SS", - "HH:MM;HH:MM;HH:MM", - // This is fun - blue if positive time, - // red if negative time or green for zero! - "[BLUE]HH:MM;[RED]HH:MM;[GREEN]HH:MM", - "yyyy-mm-dd hh:mm", - "yyyy-mm-dd hh:mm:ss", - }; - - // valid number formats - String[] goodNumPatterns = { - "#,##0.0000", - "#,##0;[Red]#,##0", - "(#,##0.00_);(#,##0.00)", - "($#,##0.00_);[Red]($#,##0.00)", - "$#,##0.00", - "[$-809]#,##0.00", // international format - "[$-2]#,##0.00", // international format - "[$-041f]#,##0.00", // international format - "0000.00000%", - "0.000E+00", - "0.00E+00", - "[BLACK]0.00;[COLOR 5]##.##", - "[>999999]#,,\"M\";[>999]#,\"K\";#", // num/K/M - "[>999999]#.000,,\"M\";[>999]#.000,\"K\";#.000", // with decimals - "[$-809]#,##0.00;[$-809]#,##0.00", // two-part international format - "[$-809]#,##0.00;[$-809]#,##0.00;0", // three-part international format - "[$-809]#,##0.00;[$-809]#,##0.00;0;@", // four-part international format - }; - - // invalid date formats -- will throw exception in DecimalFormat ctor - String[] badNumPatterns = { - "#,#$'#0.0000", - "'#','#ABC#0;##,##0", - "000 '123 4'5'6 000", - "#''0#0'1#10L16EE" - }; - - // create cells with good date patterns - for (int i = 0; i < goodDatePatterns.length; i++) { - HSSFCell cell = row.createCell(i); - cell.setCellValue(dateNum); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat(goodDatePatterns[i])); - cell.setCellStyle(cellStyle); - } - row = sheet.createRow(1); - - // create cells with time patterns - for (int i = 0; i < goodTimePatterns.length; i++) { - HSSFCell cell = row.createCell(i); - cell.setCellValue(timeNum); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat(goodTimePatterns[i])); - cell.setCellStyle(cellStyle); - } - row = sheet.createRow(2); - - // create cells with num patterns - for (int i = 0; i < goodNumPatterns.length; i++) { - HSSFCell cell = row.createCell(i); - cell.setCellValue(-1234567890.12345); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat(goodNumPatterns[i])); - cell.setCellStyle(cellStyle); - } - row = sheet.createRow(3); - - // create cells with bad num patterns - for (int i = 0; i < badNumPatterns.length; i++) { - HSSFCell cell = row.createCell(i); - // If the '.' is any later, ExcelGeneralNumberFormat will render an integer, as Excel does. - cell.setCellValue(12345678.9012345); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat(badNumPatterns[i])); - cell.setCellStyle(cellStyle); - } - - // Built in formats - - { // Zip + 4 format - row = sheet.createRow(4); - HSSFCell cell = row.createCell(0); - cell.setCellValue(123456789); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat("00000-0000")); - cell.setCellStyle(cellStyle); - } - - { // Phone number format - row = sheet.createRow(5); - HSSFCell cell = row.createCell(0); - cell.setCellValue(5551234567D); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat("[<=9999999]###-####;(###) ###-####")); - cell.setCellStyle(cellStyle); - } - - { // SSN format - row = sheet.createRow(6); - HSSFCell cell = row.createCell(0); - cell.setCellValue(444551234); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat("000-00-0000")); - cell.setCellStyle(cellStyle); - } - - { // formula cell - row = sheet.createRow(7); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("SUM(12.25,12.25)/100"); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat("##.00%;")); - cell.setCellStyle(cellStyle); - } - } - - /** - * Test getting formatted values from numeric and date cells. - */ - @Test - void testGetFormattedCellValueHSSFCell() { - // Valid date formats -- cell values should be date formatted & not "555.555" - HSSFRow row = wb.getSheetAt(0).getRow(0); - Iterator it = row.cellIterator(); - log("==== VALID DATE FORMATS ===="); - while (it.hasNext()) { - Cell cell = it.next(); - String fmtval = formatter.formatCellValue(cell); - log(fmtval); - - // should not be equal to "555.555" - assertTrue( DateUtil.isCellDateFormatted(cell) ); - assertNotEquals(fmtval, "555.555"); - - String fmt = cell.getCellStyle().getDataFormatString(); - - //assert the correct month form, as in the original Excel format - String monthPtrn = fmt.contains("mmmm") ? "MMMM" : "MMM"; - // this line is intended to compute how "July" would look like in the current locale - SimpleDateFormat sdf = new SimpleDateFormat(monthPtrn, LocaleUtil.getUserLocale()); - sdf.setTimeZone(LocaleUtil.getUserTimeZone()); - Calendar calDef = LocaleUtil.getLocaleCalendar(2010, 6, 15, 0, 0, 0); - String jul = sdf.format(calDef.getTime()); - // special case for MMMMM = 1st letter of month name - if(fmt.contains("mmmmm")) { - jul = jul.substring(0,1); - } - // check we found july properly - assertTrue(fmtval.contains(jul), "Format came out incorrect - " + fmt); - } - - row = wb.getSheetAt(0).getRow(1); - it = row.cellIterator(); - log("==== VALID TIME FORMATS ===="); - while (it.hasNext()) { - Cell cell = it.next(); - String fmt = cell.getCellStyle().getDataFormatString(); - String fmtval = formatter.formatCellValue(cell); - log(fmtval); - - // should not be equal to "555.47431" - assertTrue( DateUtil.isCellDateFormatted(cell) ); - assertNotEquals(fmtval, "555.47431"); - - // check we found the time properly - assertTrue(fmtval.contains("11:23"), - "Format came out incorrect - " + fmt + " - found " + fmtval + ", but expected to find '11:23'"); - } - - // test number formats - row = wb.getSheetAt(0).getRow(1); - it = row.cellIterator(); - log("\n==== VALID NUMBER FORMATS ===="); - while (it.hasNext()) { - HSSFCell cell = (HSSFCell) it.next(); - final String formatted = formatter.formatCellValue(cell); - log(formatted); - - // should not include "12345678" - note that the input value was negative - assertTrue(formatted != null && ! formatted.contains("12345678")); - } - - // test bad number formats - row = wb.getSheetAt(0).getRow(3); - it = row.cellIterator(); - log("\n==== INVALID NUMBER FORMATS ===="); - while (it.hasNext()) { - HSSFCell cell = (HSSFCell) it.next(); - log(formatter.formatCellValue(cell)); - // in some locales the the decimal delimiter is a comma, not a dot - char decimalSeparator = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale()).getDecimalSeparator(); - assertEquals("12345678" + decimalSeparator + "9", formatter.formatCellValue(cell)); - } - - // test Zip+4 format - row = wb.getSheetAt(0).getRow(4); - HSSFCell cell = row.getCell(0); - log("\n==== ZIP FORMAT ===="); - log(formatter.formatCellValue(cell)); - assertEquals("12345-6789", formatter.formatCellValue(cell)); - - // test phone number format - row = wb.getSheetAt(0).getRow(5); - cell = row.getCell(0); - log("\n==== PHONE FORMAT ===="); - log(formatter.formatCellValue(cell)); - assertEquals("(555) 123-4567", formatter.formatCellValue(cell)); - - // test SSN format - row = wb.getSheetAt(0).getRow(6); - cell = row.getCell(0); - log("\n==== SSN FORMAT ===="); - log(formatter.formatCellValue(cell)); - assertEquals("444-55-1234", formatter.formatCellValue(cell)); - - // null test-- null cell should result in empty String - assertEquals(formatter.formatCellValue(null), ""); - - // null test-- null cell should result in empty String - assertEquals(formatter.formatCellValue(null), ""); - } - - @Test - void testGetFormattedCellValueHSSFCellHSSFFormulaEvaluator() { - // test formula format - HSSFRow row = wb.getSheetAt(0).getRow(7); - HSSFCell cell = row.getCell(0); - log("\n==== FORMULA CELL ===="); - - // first without a formula evaluator - log(formatter.formatCellValue(cell) + "\t (without evaluator)"); - assertEquals("SUM(12.25,12.25)/100", formatter.formatCellValue(cell)); - - // now with a formula evaluator - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); - log(formatter.formatCellValue(cell, evaluator) + "\t\t\t (with evaluator)"); - char decimalSeparator = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale()).getDecimalSeparator(); - assertEquals("24" + decimalSeparator + "50%", formatter.formatCellValue(cell,evaluator)); - - } - - /** - * Test using a default number format. The format should be used when a - * format pattern cannot be parsed by DecimalFormat. - */ - @Test - void testSetDefaultNumberFormat() { - HSSFRow row = wb.getSheetAt(0).getRow(3); - Iterator it = row.cellIterator(); - DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale()); - Format defaultFormat = new DecimalFormat("Balance $#,#00.00 USD;Balance -$#,#00.00 USD", dfs); - formatter.setDefaultNumberFormat(defaultFormat); - - log("\n==== DEFAULT NUMBER FORMAT ===="); - while (it.hasNext()) { - Cell cell = it.next(); - cell.setCellValue(cell.getNumericCellValue() * Math.random() / 1000000 - 1000); - log(formatter.formatCellValue(cell)); - - String formatted = formatter.formatCellValue(cell); - assertTrue(formatted.startsWith("Balance "), "Doesn't start with Balance: " + formatted); - assertTrue(formatted.endsWith(" USD"), "Doesn't end with USD: " + formatted); - } - } - - /** - * A format of "@" means use the general format - */ - @Test - void testGeneralAtFormat() { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("47154.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFRow row = sheet.getRow(0); - HSSFCell cellA1 = row.getCell(0); - - assertEquals(CellType.NUMERIC, cellA1.getCellType()); - assertEquals(2345.0, cellA1.getNumericCellValue(), 0.0001); - assertEquals("@", cellA1.getCellStyle().getDataFormatString()); - - HSSFDataFormatter f = new HSSFDataFormatter(); - - assertEquals("2345", f.formatCellValue(cellA1)); - } - - /** - * Tests various formattings of dates and numbers - */ - @Test - void testFromFile() { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("Formatting.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - - HSSFDataFormatter f = new HSSFDataFormatter(); - - // This one is one of the nasty auto-locale changing ones... - assertEquals("dd/mm/yyyy", sheet.getRow(1).getCell(0).getStringCellValue()); - assertEquals("m/d/yy", sheet.getRow(1).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("11/24/06", f.formatCellValue(sheet.getRow(1).getCell(1))); - - assertEquals("yyyy/mm/dd", sheet.getRow(2).getCell(0).getStringCellValue()); - assertEquals("yyyy/mm/dd", sheet.getRow(2).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("2006/11/24", f.formatCellValue(sheet.getRow(2).getCell(1))); - - assertEquals("yyyy-mm-dd", sheet.getRow(3).getCell(0).getStringCellValue()); - assertEquals("yyyy\\-mm\\-dd", sheet.getRow(3).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("2006-11-24", f.formatCellValue(sheet.getRow(3).getCell(1))); - - assertEquals("yy/mm/dd", sheet.getRow(4).getCell(0).getStringCellValue()); - assertEquals("yy/mm/dd", sheet.getRow(4).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("06/11/24", f.formatCellValue(sheet.getRow(4).getCell(1))); - - // Another builtin fun one - assertEquals("dd/mm/yy", sheet.getRow(5).getCell(0).getStringCellValue()); - assertEquals("d/m/yy;@", sheet.getRow(5).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("24/11/06", f.formatCellValue(sheet.getRow(5).getCell(1))); - - assertEquals("dd-mm-yy", sheet.getRow(6).getCell(0).getStringCellValue()); - assertEquals("dd\\-mm\\-yy", sheet.getRow(6).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("24-11-06", f.formatCellValue(sheet.getRow(6).getCell(1))); - - - // Another builtin fun one - assertEquals("nn.nn", sheet.getRow(9).getCell(0).getStringCellValue()); - assertEquals("General", sheet.getRow(9).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("10.52", f.formatCellValue(sheet.getRow(9).getCell(1))); - - // text isn't quite the format rule... - assertEquals("nn.nnn", sheet.getRow(10).getCell(0).getStringCellValue()); - assertEquals("0.000", sheet.getRow(10).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("10.520", f.formatCellValue(sheet.getRow(10).getCell(1))); - - // text isn't quite the format rule... - assertEquals("nn.n", sheet.getRow(11).getCell(0).getStringCellValue()); - assertEquals("0.0", sheet.getRow(11).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("10.5", f.formatCellValue(sheet.getRow(11).getCell(1))); - - // text isn't quite the format rule... - assertEquals("\u00a3nn.nn", sheet.getRow(12).getCell(0).getStringCellValue()); - assertEquals("\"\u00a3\"#,##0.00", sheet.getRow(12).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("\u00a310.52", f.formatCellValue(sheet.getRow(12).getCell(1))); - } - - private static void log(@SuppressWarnings("UnusedParameters") String msg) { -// if (false) { // successful tests should be silent -// System.out.println(msg); -// } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java deleted file mode 100644 index 2949dbeeee..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.TimeZone; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Class TestHSSFDateUtil - */ -class TestHSSFDateUtil { - - static TimeZone userTimeZone; - - @BeforeAll - public static void setCEST() { - userTimeZone = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CEST")); - } - - @AfterAll - public static void resetTimeZone() { - LocaleUtil.setUserTimeZone(userTimeZone); - } - - /** - * Test that against a real, test file, we still do everything - * correctly - */ - @Test - void onARealFile() throws IOException { - - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - InternalWorkbook wb = workbook.getWorkbook(); - assertNotNull(wb); - - HSSFRow row; - HSSFCell cell; - HSSFCellStyle style; - - double aug_10_2007 = 39304.0; - - // Should have dates in 2nd column - // All of them are the 10th of August - // 2 US dates, 3 UK dates - row = sheet.getRow(0); - cell = row.getCell(1); - style = cell.getCellStyle(); - assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001); - assertEquals("d-mmm-yy", style.getDataFormatString()); - assertTrue(DateUtil.isInternalDateFormat(style.getDataFormat())); - assertTrue(DateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString())); - assertTrue(DateUtil.isCellDateFormatted(cell)); - - row = sheet.getRow(1); - cell = row.getCell(1); - style = cell.getCellStyle(); - assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001); - assertFalse(DateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat())); - assertTrue(DateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString())); - assertTrue(DateUtil.isCellDateFormatted(cell)); - - row = sheet.getRow(2); - cell = row.getCell(1); - style = cell.getCellStyle(); - assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001); - assertTrue(DateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat())); - assertTrue(DateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString())); - assertTrue(DateUtil.isCellDateFormatted(cell)); - - row = sheet.getRow(3); - cell = row.getCell(1); - style = cell.getCellStyle(); - assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001); - assertFalse(DateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat())); - assertTrue(DateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString())); - assertTrue(DateUtil.isCellDateFormatted(cell)); - - row = sheet.getRow(4); - cell = row.getCell(1); - style = cell.getCellStyle(); - assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001); - assertFalse(DateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat())); - assertTrue(DateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString())); - assertTrue(DateUtil.isCellDateFormatted(cell)); - - workbook.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFEvaluationSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFEvaluationSheet.java deleted file mode 100644 index dfc64df1bb..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFEvaluationSheet.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -import java.io.IOException; -import java.util.AbstractMap; -import java.util.Map; - -import org.apache.poi.ss.formula.EvaluationSheet; -import org.apache.poi.ss.usermodel.BaseTestXEvaluationSheet; -import org.apache.poi.ss.usermodel.Sheet; -import org.junit.jupiter.api.Test; - -class TestHSSFEvaluationSheet extends BaseTestXEvaluationSheet { - @Override - protected Map.Entry getInstance() { - HSSFSheet sheet = new HSSFWorkbook().createSheet(); - return new AbstractMap.SimpleEntry<>(sheet, new HSSFEvaluationSheet(sheet)); - } - - @Test - void testMissingExternalName() throws IOException { - try (HSSFWorkbook wb = openSampleWorkbook("external_name.xls")) { - // this sometimes causes exceptions - wb.getAllNames().stream().filter(n -> !n.isFunctionName()).forEach( - n -> assertDoesNotThrow(n::getRefersToFormula) - ); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFExternalFunctions.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFExternalFunctions.java deleted file mode 100644 index 552e028aff..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFExternalFunctions.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.formula.BaseTestExternalFunctions; - -/** - * Tests setting and evaluating user-defined functions in HSSF - */ -final class TestHSSFExternalFunctions extends BaseTestExternalFunctions { - public TestHSSFExternalFunctions() { - super(HSSFITestDataProvider.instance, "atp.xls"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java deleted file mode 100644 index e4859923ff..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import java.util.stream.Stream; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestFont; -import org.apache.poi.ss.usermodel.Font; -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests various functionality having to do with {@link org.apache.poi.ss.usermodel.Name}. - */ -final class TestHSSFFont extends BaseTestFont { - - public TestHSSFFont() { - super(HSSFITestDataProvider.instance); - } - - @SuppressWarnings("unused") - public static Stream defaultFont() { - return Stream.of(Arguments.of(HSSFFont.FONT_ARIAL, (short)200, Font.COLOR_NORMAL)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java deleted file mode 100644 index afe96936fd..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java +++ /dev/null @@ -1,289 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.EvaluationListener; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.WorkbookEvaluatorTestHelper; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator { - - public TestHSSFFormulaEvaluator() { - super(HSSFITestDataProvider.instance); - } - - /** - * Test that the HSSFFormulaEvaluator can evaluate simple named ranges - * (single cells and rectangular areas) - */ - @Test - void testEvaluateSimple() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testNames.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFCell cell = sheet.getRow(8).getCell(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue cv = fe.evaluate(cell); - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(3.72, cv.getNumberValue(), 0.0); - wb.close(); - } - - /** - * When evaluating defined names, POI has to decide whether it is capable. Currently - * (May2009) POI only supports simple cell and area refs.
- * The sample spreadsheet (bugzilla attachment 23508) had a name flagged as 'complex' - * which contained a simple area ref. It is not clear what the 'complex' flag is used - * for but POI should look elsewhere to decide whether it can evaluate the name. - */ - @Test - void testDefinedNameWithComplexFlag_bug47048() throws IOException { - // Mock up a spreadsheet to match the critical details of the sample - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Input"); - HSSFName definedName = wb.createName(); - definedName.setNameName("Is_Multicar_Vehicle"); - definedName.setRefersToFormula("Input!$B$17:$G$17"); - - // Set up some data and the formula - HSSFRow row17 = sheet.createRow(16); - row17.createCell(0).setCellValue(25.0); - row17.createCell(1).setCellValue(1.33); - row17.createCell(2).setCellValue(4.0); - - HSSFRow row = sheet.createRow(0); - HSSFCell cellA1 = row.createCell(0); - cellA1.setCellFormula("SUM(Is_Multicar_Vehicle)"); - - // Set the complex flag - POI doesn't usually manipulate this flag - NameRecord nameRec = TestHSSFName.getNameRecord(definedName); - nameRec.setOptionFlag((short) 0x10); // 0x10 -> complex - - HSSFFormulaEvaluator hsf = new HSSFFormulaEvaluator(wb); - CellValue value; - try { - value = hsf.evaluate(cellA1); - - assertEquals(CellType.NUMERIC, value.getCellType()); - assertEquals(5.33, value.getNumberValue(), 0.0); - - } catch (RuntimeException e) { - if (e.getMessage().equals("Don't know how to evaluate name 'Is_Multicar_Vehicle'")) { - fail("Identified bug 47048a"); - } - throw e; - } finally { - wb.close(); - } - } - - private static final class EvalCountListener extends EvaluationListener { - private int _evalCount; - - public EvalCountListener() { - _evalCount = 0; - } - - @Override - public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) { - _evalCount++; - } - - public int getEvalCount() { - return _evalCount; - } - } - - /** - * The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values - */ - @Test - void testShortCircuitIfEvaluation() throws IOException { - // Set up a simple IF() formula that has measurable evaluation cost for its operands. - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cellA1 = row.createCell(0); - cellA1.setCellFormula("if(B1,C1,D1+E1+F1)"); - // populate cells B1..F1 with simple formulas instead of plain values so we can use - // EvaluationListener to check which parts of the first formula get evaluated - for (int i = 1; i < 6; i++) { - // formulas are just literal constants "1".."5" - row.createCell(i).setCellFormula(String.valueOf(i)); - } - - EvalCountListener evalListener = new EvalCountListener(); - WorkbookEvaluator evaluator = WorkbookEvaluatorTestHelper.createEvaluator(wb, evalListener); - ValueEval ve = evaluator.evaluate(HSSFEvaluationTestHelper.wrapCell(cellA1)); - int evalCount = evalListener.getEvalCount(); - // Without short-circuit-if evaluation, evaluating cell 'A1' takes 3 extra evaluations (for D1,E1,F1) - assertNotEquals(6, evalCount, "Identifed bug 48195 - Formula evaluator should short-circuit IF() calculations."); - assertEquals(3, evalCount); - assertEquals(2.0, ((NumberEval) ve).getNumberValue(), 0D); - } - } - - /** - * Ensures that we can handle NameXPtgs in the formulas - * we parse. - */ - @Test - void testXRefs() throws IOException { - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("XRefCalc.xls"); - HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook("XRefCalcData.xls")) { - Cell cell; - - // VLookup on a name in another file - cell = wb1.getSheetAt(0).getRow(1).getCell(2); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType()); - assertEquals(12.30, cell.getNumericCellValue(), 0.0001); - // WARNING - this is wrong! - // The file name should be showing, but bug #45970 is fixed - // we seem to loose it - assertEquals("VLOOKUP(PART,COSTS,2,FALSE)", cell.getCellFormula()); - - - // Simple reference to a name in another file - cell = wb1.getSheetAt(0).getRow(1).getCell(4); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType()); - assertEquals(36.90, cell.getNumericCellValue(), 0.0001); - // TODO Correct this! - // The file name should be shown too, see bug #56742 - assertEquals("Cost*Markup_Cost", cell.getCellFormula()); - - - // Evaluate the cells - HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb1); - HSSFFormulaEvaluator.setupEnvironment( - new String[]{"XRefCalc.xls", "XRefCalcData.xls"}, - new HSSFFormulaEvaluator[]{ - eval, - new HSSFFormulaEvaluator(wb2) - } - ); - eval.evaluateFormulaCell( - wb1.getSheetAt(0).getRow(1).getCell(2) - ); - eval.evaluateFormulaCell( - wb1.getSheetAt(0).getRow(1).getCell(4) - ); - - - // Re-check VLOOKUP one - cell = wb1.getSheetAt(0).getRow(1).getCell(2); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType()); - assertEquals(12.30, cell.getNumericCellValue(), 0.0001); - - // Re-check ref one - cell = wb1.getSheetAt(0).getRow(1).getCell(4); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType()); - assertEquals(36.90, cell.getNumericCellValue(), 0.0001); - - - // Add a formula that refers to one of the existing external workbooks - cell = wb1.getSheetAt(0).getRow(1).createCell(40); - cell.setCellFormula("Cost*[XRefCalcData.xls]MarkupSheet!$B$1"); - - // Check is was stored correctly - assertEquals("Cost*[XRefCalcData.xls]MarkupSheet!$B$1", cell.getCellFormula()); - - // Check it evaluates correctly - eval.evaluateFormulaCell(cell); - assertEquals(24.60 * 1.8, cell.getNumericCellValue(), 0); - - // Try to add a formula for a new external workbook, won't be allowed to start - cell = wb1.getSheetAt(0).getRow(1).createCell(42); - final Cell cell2 = cell; - assertThrows(Exception.class, () -> cell2.setCellFormula("[alt.xls]Sheet0!$A$1"), - "New workbook not linked, shouldn't be able to add"); - - // Link our new workbook - try (HSSFWorkbook wb3 = new HSSFWorkbook()) { - wb3.createSheet().createRow(0).createCell(0).setCellValue("In another workbook"); - assertEquals(2, wb1.linkExternalWorkbook("alt.xls", wb3)); - - // Now add a formula that refers to our new workbook - cell.setCellFormula("[alt.xls]Sheet0!$A$1"); - assertEquals("[alt.xls]Sheet0!$A$1", cell.getCellFormula()); - - HSSFFormulaEvaluator eval2 = eval; - assertThrows(Exception.class, () -> eval2.evaluate(cell2), - "No cached value and no link to workbook, shouldn't evaluate"); - - // Add a link, check it does - HSSFFormulaEvaluator.setupEnvironment( - new String[]{"XRefCalc.xls", "XRefCalcData.xls", "alt.xls"}, - new HSSFFormulaEvaluator[]{ - eval, - new HSSFFormulaEvaluator(wb2), - new HSSFFormulaEvaluator(wb3) - } - ); - eval.evaluateFormulaCell(cell); - assertEquals("In another workbook", cell.getStringCellValue()); - - - // Save and re-load - try (HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - eval = new HSSFFormulaEvaluator(wb4); - HSSFFormulaEvaluator.setupEnvironment( - new String[]{"XRefCalc.xls", "XRefCalcData.xls", "alt.xls"}, - new HSSFFormulaEvaluator[]{ - eval, - new HSSFFormulaEvaluator(wb2), - new HSSFFormulaEvaluator(wb3) - } - ); - - // Check the one referring to the previously existing workbook behaves - cell = wb4.getSheetAt(0).getRow(1).getCell(40); - assertEquals("Cost*[XRefCalcData.xls]MarkupSheet!$B$1", cell.getCellFormula()); - eval.evaluateFormulaCell(cell); - assertEquals(24.60 * 1.8, cell.getNumericCellValue(), 0); - - // Now check the newly added reference - cell = wb4.getSheetAt(0).getRow(1).getCell(42); - assertEquals("[alt.xls]Sheet0!$A$1", cell.getCellFormula()); - eval.evaluateFormulaCell(cell); - assertEquals("In another workbook", cell.getStringCellValue()); - } - } - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java deleted file mode 100644 index a104bba25f..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java +++ /dev/null @@ -1,195 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link HSSFHeader} / {@link HSSFFooter} - */ -final class TestHSSFHeaderFooter { - - /** - * Tests that get header retrieves the proper values. - */ - @Test - void testRetrieveCorrectHeader() throws IOException { - - try (HSSFWorkbook wb = openSampleWorkbook("EmbeddedChartHeaderTest.xls")) { - HSSFSheet s = wb.getSheetAt(0); - HSSFHeader head = s.getHeader(); - - assertEquals("Top Left", head.getLeft()); - assertEquals("Top Center", head.getCenter()); - assertEquals("Top Right", head.getRight()); - } - } - - @Test - void testSpecialChars() { - assertEquals("&U", HSSFHeader.startUnderline()); - assertEquals("&U", HSSFHeader.endUnderline()); - assertEquals("&P", HSSFHeader.page()); - - assertEquals("&22", HSSFFooter.fontSize((short)22)); - assertEquals("&\"Arial,bold\"", HSSFFooter.font("Arial", "bold")); - } - - @Test - void testStripFields() throws IOException { - String simple = "I am a test header"; - String withPage = "I am a&P test header"; - String withLots = "I&A am&N a&P test&T header&U"; - String withFont = "I&22 am a&\"Arial,bold\" test header"; - String withOtherAnds = "I am a&P test header&&"; - String withOtherAnds2 = "I am a&P test header&a&b"; - - assertEquals(simple, HSSFHeader.stripFields(simple)); - assertEquals(simple, HSSFHeader.stripFields(withPage)); - assertEquals(simple, HSSFHeader.stripFields(withLots)); - assertEquals(simple, HSSFHeader.stripFields(withFont)); - assertEquals(simple + "&&", HSSFHeader.stripFields(withOtherAnds)); - assertEquals(simple + "&a&b", HSSFHeader.stripFields(withOtherAnds2)); - - // Now test the default strip flag - try (HSSFWorkbook wb = openSampleWorkbook("EmbeddedChartHeaderTest.xls")) { - HSSFSheet s = wb.getSheetAt(0); - HSSFHeader head = s.getHeader(); - - assertEquals("Top Left", head.getLeft()); - assertEquals("Top Center", head.getCenter()); - assertEquals("Top Right", head.getRight()); - - head.setLeft("Top &P&F&D Left"); - assertEquals("Top &P&F&D Left", head.getLeft()); - - assertEquals("Top Left", HeaderFooter.stripFields(head.getLeft())); - - // Now even more complex - head.setCenter("HEADER TEXT &P&N&D&T&Z&F&F&A&G&X END"); - assertEquals("HEADER TEXT END", HeaderFooter.stripFields(head.getCenter())); - } - } - - /** - * Tests that get header retrieves the proper values. - */ - @Test - void testRetrieveCorrectFooter() throws IOException { - try (HSSFWorkbook wb = openSampleWorkbook("EmbeddedChartHeaderTest.xls")) { - HSSFSheet s = wb.getSheetAt(0); - HSSFFooter foot = s.getFooter(); - - assertEquals("Bottom Left", foot.getLeft()); - assertEquals("Bottom Center", foot.getCenter()); - assertEquals("Bottom Right", foot.getRight()); - } - } - - /** - * Testcase for Bug 17039 HSSFHeader does not support DBCS - */ - @Test - void testHeaderHas16bitCharacter() throws IOException { - try (HSSFWorkbook b = new HSSFWorkbook()) { - HSSFSheet s = b.createSheet("Test"); - HSSFHeader h = s.getHeader(); - h.setLeft("\u0391"); - h.setCenter("\u0392"); - h.setRight("\u0393"); - - try (HSSFWorkbook b2 = HSSFTestDataSamples.writeOutAndReadBack(b)) { - HSSFHeader h2 = b2.getSheet("Test").getHeader(); - - assertEquals(h2.getLeft(), "\u0391"); - assertEquals(h2.getCenter(), "\u0392"); - assertEquals(h2.getRight(), "\u0393"); - } - } - } - - /** - * Testcase for Bug 17039 HSSFFooter does not support DBCS - */ - @Test - void testFooterHas16bitCharacter() throws IOException { - try (HSSFWorkbook b = new HSSFWorkbook()) { - HSSFSheet s = b.createSheet("Test"); - HSSFFooter f = s.getFooter(); - f.setLeft("\u0391"); - f.setCenter("\u0392"); - f.setRight("\u0393"); - - try (HSSFWorkbook b2 = HSSFTestDataSamples.writeOutAndReadBack(b)) { - HSSFFooter f2 = b2.getSheet("Test").getFooter(); - - assertEquals(f2.getLeft(), "\u0391"); - assertEquals(f2.getCenter(), "\u0392"); - assertEquals(f2.getRight(), "\u0393"); - } - } - } - - @Test - void testReadDBCSHeaderFooter() throws IOException { - try (HSSFWorkbook wb = openSampleWorkbook("DBCSHeader.xls")) { - HSSFSheet s = wb.getSheetAt(0); - HSSFHeader h = s.getHeader(); - assertEquals(h.getLeft(), "\u090f\u0915", "Header Left"); - assertEquals(h.getCenter(), "\u0939\u094b\u0917\u093e", "Header Center"); - assertEquals(h.getRight(), "\u091c\u093e", "Header Right"); - - HSSFFooter f = s.getFooter(); - assertEquals(f.getLeft(), "\u091c\u093e", "Footer Left"); - assertEquals(f.getCenter(), "\u091c\u093e", "Footer Center"); - assertEquals(f.getRight(), "\u091c\u093e", "Footer Right"); - } - } - - /** - * Excel tolerates files with missing HEADER/FOOTER records. POI should do the same. - */ - @Test - void testMissingHeaderFooterRecord_bug47244() throws IOException { - // noHeaderFooter47244.xls was created by a slightly modified POI - // which omitted the HEADER/FOOTER records - try (HSSFWorkbook wb = openSampleWorkbook("noHeaderFooter47244.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - // bug 47244a - NullPointerException - HSSFFooter footer = sheet.getFooter(); - assertEquals("", footer.getRawText()); - HSSFHeader header = sheet.getHeader(); - assertEquals("", header.getRawText()); - - // make sure header / footer is properly linked to underlying data - HSSFHeader header2 = sheet.getHeader(); - header.setCenter("foo"); - assertEquals("foo", header2.getCenter()); - - HSSFFooter footer2 = sheet.getFooter(); - footer.setCenter("bar"); - assertEquals("bar", footer2.getCenter()); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java deleted file mode 100644 index 67cb04010d..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java +++ /dev/null @@ -1,287 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.io.IOException; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.BaseTestHyperlink; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.junit.jupiter.api.Test; - -/** - * Tests HSSFHyperlink. - * - * @author Yegor Kozlov - */ -final class TestHSSFHyperlink extends BaseTestHyperlink { - - public TestHSSFHyperlink() { - super(HSSFITestDataProvider.instance); - } - /** - * Test that we can read hyperlinks. - */ - @Test - void testRead() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls"); - - HSSFSheet sheet; - HSSFCell cell; - HSSFHyperlink link; - - sheet = wb.getSheet("WebLinks"); - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("POI", link.getLabel()); - assertEquals("POI", cell.getRichStringCellValue().getString()); - assertEquals("http://poi.apache.org/", link.getAddress()); - assertEquals(HyperlinkType.URL, link.getType()); - - cell = sheet.getRow(8).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("HSSF", link.getLabel()); - assertEquals("HSSF", cell.getRichStringCellValue().getString()); - assertEquals("http://poi.apache.org/hssf/", link.getAddress()); - assertEquals(HyperlinkType.URL, link.getType()); - - sheet = wb.getSheet("Emails"); - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("dev", link.getLabel()); - assertEquals("dev", cell.getRichStringCellValue().getString()); - assertEquals("mailto:dev@poi.apache.org", link.getAddress()); - assertEquals(HyperlinkType.EMAIL, link.getType()); - - sheet = wb.getSheet("Internal"); - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("Link To First Sheet", link.getLabel()); - assertEquals("Link To First Sheet", cell.getRichStringCellValue().getString()); - assertEquals("WebLinks!A1", link.getTextMark()); - assertEquals("WebLinks!A1", link.getAddress()); - assertEquals(HyperlinkType.DOCUMENT, link.getType()); - } - - @Test - void testModify() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls"); - - HSSFSheet sheet; - HSSFCell cell; - HSSFHyperlink link; - - sheet = wb.getSheet("WebLinks"); - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - //modify the link - link.setAddress("www.apache.org"); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheet("WebLinks"); - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("www.apache.org", link.getAddress()); - - } - - /** - * HSSF-specific ways of creating links to a place in workbook. - * You can set the target in two ways: - * link.setTextMark("'Target Sheet-1'!A1"); //HSSF-specific - * or - * link.setAddress("'Target Sheet-1'!A1"); //common between XSSF and HSSF - * @throws IOException - */ - @Test - void testCreateDocumentLink() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - //link to a place in this workbook - HSSFHyperlink link; - HSSFCell cell; - HSSFSheet sheet = wb.createSheet("Hyperlinks"); - - //create a target sheet and cell - HSSFSheet sheet2 = wb.createSheet("Target Sheet"); - sheet2.createRow(0).createCell(0).setCellValue("Target Cell"); - - //cell A1 has a link to 'Target Sheet-1'!A1 - cell = sheet.createRow(0).createCell(0); - cell.setCellValue("Worksheet Link"); - link = new HSSFHyperlink(HyperlinkType.DOCUMENT); - link.setTextMark("'Target Sheet'!A1"); - cell.setHyperlink(link); - - //cell B1 has a link to cell A1 on the same sheet - cell = sheet.createRow(1).createCell(0); - cell.setCellValue("Worksheet Link"); - link = new HSSFHyperlink(HyperlinkType.DOCUMENT); - link.setAddress("'Hyperlinks'!A1"); - cell.setHyperlink(link); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - - sheet = wbBack.getSheet("Hyperlinks"); - - cell = sheet.getRow(0).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("'Target Sheet'!A1", link.getTextMark()); - assertEquals("'Target Sheet'!A1", link.getAddress()); - - cell = sheet.getRow(1).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("'Hyperlinks'!A1", link.getTextMark()); - assertEquals("'Hyperlinks'!A1", link.getAddress()); - - wbBack.close(); - } - - @Test - void testCloneSheet() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls"); - - HSSFCell cell; - HSSFHyperlink link; - - HSSFSheet sheet = wb.cloneSheet(0); - - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("http://poi.apache.org/", link.getAddress()); - - cell = sheet.getRow(8).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("http://poi.apache.org/hssf/", link.getAddress()); - } - - @Test - void testCreate() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFHyperlink link; - HSSFCell cell; - HSSFSheet sheet = wb.createSheet("Hyperlinks"); - - cell = sheet.createRow(1).createCell(0); - cell.setCellValue("File Link"); - link = new HSSFHyperlink(HyperlinkType.FILE); - link.setAddress("testfolder\\test.PDF"); - cell.setHyperlink(link); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - - wb.close(); - - sheet = wbBack.getSheet("Hyperlinks"); - - cell = sheet.getRow(1).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("testfolder\\test.PDF", link.getAddress()); - - wbBack.close(); - } - - /** - * Test that HSSFSheet#shiftRows moves hyperlinks, - * see bugs #46445 and #29957 - */ - @Test - void testShiftRows(){ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("46445.xls"); - - - HSSFSheet sheet = wb.getSheetAt(0); - - //verify existing hyperlink in A3 - HSSFCell cell1 = sheet.getRow(2).getCell(0); - HSSFHyperlink link1 = cell1.getHyperlink(); - assertNotNull(link1); - assertEquals(2, link1.getFirstRow()); - assertEquals(2, link1.getLastRow()); - - //assign a hyperlink to A4 - HSSFHyperlink link2 = new HSSFHyperlink(HyperlinkType.DOCUMENT); - link2.setAddress("Sheet2!A2"); - HSSFCell cell2 = sheet.getRow(3).getCell(0); - cell2.setHyperlink(link2); - assertEquals(3, link2.getFirstRow()); - assertEquals(3, link2.getLastRow()); - - //move the 3rd row two rows down - sheet.shiftRows(sheet.getFirstRowNum(), sheet.getLastRowNum(), 2); - - //cells A3 and A4 don't contain hyperlinks anymore - assertNull(sheet.getRow(2).getCell(0).getHyperlink()); - assertNull(sheet.getRow(3).getCell(0).getHyperlink()); - - //the first hyperlink now belongs to A5 - HSSFHyperlink link1_shifted = sheet.getRow(2+2).getCell(0).getHyperlink(); - assertNotNull(link1_shifted); - assertEquals(4, link1_shifted.getFirstRow()); - assertEquals(4, link1_shifted.getLastRow()); - - //the second hyperlink now belongs to A6 - HSSFHyperlink link2_shifted = sheet.getRow(3+2).getCell(0).getHyperlink(); - assertNotNull(link2_shifted); - assertEquals(5, link2_shifted.getFirstRow()); - assertEquals(5, link2_shifted.getLastRow()); - } - - @Override - public HSSFHyperlink copyHyperlink(Hyperlink link) { - return new HSSFHyperlink(link); - } - - /* - @Test - void testCopyXSSFHyperlink() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFCreationHelper helper = wb.getCreationHelper(); - XSSFHyperlink xlink = helper.createHyperlink(Hyperlink.LINK_URL); - xlink.setAddress("http://poi.apache.org/"); - xlink.setCellReference("D3"); - xlink.setTooltip("tooltip"); - HSSFHyperlink hlink = new HSSFHyperlink(xlink); - - assertEquals("http://poi.apache.org/", hlink.getAddress()); - assertEquals("D3", new CellReference(hlink.getFirstRow(), hlink.getFirstColumn()).formatAsString()); - // Are HSSFHyperlink.label and XSSFHyperlink.tooltip the same? If so, perhaps one of these needs renamed for a consistent Hyperlink interface - // assertEquals("tooltip", hlink.getLabel()); - - wb.close(); - }*/ -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java deleted file mode 100644 index e3e6cea444..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java +++ /dev/null @@ -1,270 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.POITestCase; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.BaseTestNamedRange; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Test; - -/** - * Tests various functionality having to do with {@link org.apache.poi.ss.usermodel.Name}. - */ -public final class TestHSSFName extends BaseTestNamedRange { - - /** - * For manipulating the internals of {@link HSSFName} during testing.
- * Some tests need a {@link NameRecord} with unusual state, not normally producible by POI. - * This method achieves the aims at low cost without augmenting the POI usermodel api. - * @return a reference to the wrapped {@link NameRecord} - */ - public static NameRecord getNameRecord(HSSFName definedName) { - return POITestCase.getFieldValue(HSSFName.class, definedName, NameRecord.class, "_definedNameRec"); - } - - public TestHSSFName() { - super(HSSFITestDataProvider.instance); - } - - @Test - void testRepeatingRowsAndColumnsNames() throws Exception { - // First test that setting RR&C for same sheet more than once only creates a - // single Print_Titles built-in record - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("FirstSheet"); - - // set repeating rows and columns twice for the first sheet - CellRangeAddress cra = CellRangeAddress.valueOf("A1:A3"); - for (int i = 0; i < 2; i++) { - sheet.setRepeatingColumns(cra); - sheet.setRepeatingRows(cra); - sheet.createFreezePane(0, 3); - } - assertEquals(1, wb.getNumberOfNames()); - HSSFName nr1 = wb.getNameAt(0); - - assertEquals("Print_Titles", nr1.getNameName()); - // TODO - full column references not rendering properly, absolute markers not present either - // assertEquals("FirstSheet!$A:$A,FirstSheet!$1:$3", nr1.getRefersToFormula()); - assertEquals("FirstSheet!A:A,FirstSheet!$A$1:$IV$3", nr1.getRefersToFormula()); - - // Save and re-open - HSSFWorkbook nwb = HSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - - assertEquals(1, nwb.getNumberOfNames()); - nr1 = nwb.getNameAt(0); - - assertEquals("Print_Titles", nr1.getNameName()); - assertEquals("FirstSheet!A:A,FirstSheet!$A$1:$IV$3", nr1.getRefersToFormula()); - - // check that setting RR&C on a second sheet causes a new Print_Titles built-in - // name to be created - sheet = nwb.createSheet("SecondSheet"); - cra = CellRangeAddress.valueOf("B1:C1"); - sheet.setRepeatingColumns(cra); - sheet.setRepeatingRows(cra); - - assertEquals(2, nwb.getNumberOfNames()); - HSSFName nr2 = nwb.getNameAt(1); - - assertEquals("Print_Titles", nr2.getNameName()); - assertEquals("SecondSheet!B:C,SecondSheet!$A$1:$IV$1", nr2.getRefersToFormula()); - - nwb.close(); - } - - @Test - void testNamedRange() throws Exception { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls"); - - //Creating new Named Range - HSSFName newNamedRange = wb1.createName(); - - //Getting Sheet Name for the reference - String sheetName = wb1.getSheetName(0); - - //Setting its name - newNamedRange.setNameName("RangeTest"); - //Setting its reference - newNamedRange.setRefersToFormula(sheetName + "!$D$4:$E$8"); - - //Getting NAmed Range - HSSFName namedRange1 = wb1.getNameAt(0); - //Getting it sheet name - sheetName = namedRange1.getSheetName(); - assertNotNull(sheetName); - - // sanity check - SanityChecker c = new SanityChecker(); - c.checkHSSFWorkbook(wb1); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - HSSFName nm = wb2.getNameAt(wb2.getNameIndex("RangeTest")); - assertEquals("RangeTest", nm.getNameName(), "Name is " + nm.getNameName()); - assertEquals(wb2.getSheetName(0)+"!$D$4:$E$8", nm.getRefersToFormula()); - wb2.close(); - wb1.close(); - } - - /** - * Reads an excel file already containing a named range. - *

- * Addresses Bug #9632 - */ - @Test - void testNamedRead() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("namedinput.xls"); - - //Get index of the named range with the name = "NamedRangeName" , which was defined in input.xls as A1:D10 - int NamedRangeIndex = wb.getNameIndex("NamedRangeName"); - - //Getting NAmed Range - HSSFName namedRange1 = wb.getNameAt(NamedRangeIndex); - String sheetName = wb.getSheetName(0); - - //Getting its reference - String reference = namedRange1.getRefersToFormula(); - - assertEquals(sheetName+"!$A$1:$D$10", reference); - assertFalse(namedRange1.isDeleted()); - assertFalse(namedRange1.isHidden()); - - HSSFName namedRange2 = wb.getNameAt(1); - - assertEquals(sheetName+"!$D$17:$G$27", namedRange2.getRefersToFormula()); - assertEquals("SecondNamedRange", namedRange2.getNameName()); - assertFalse(namedRange2.isDeleted()); - assertFalse(namedRange2.isHidden()); - - wb.close(); - } - - /** - * Reads an excel file already containing a named range and updates it - *

- * Addresses Bug #16411 - */ - @Test - void testNamedReadModify() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("namedinput.xls"); - - HSSFName name = wb.getNameAt(0); - String sheetName = wb.getSheetName(0); - - assertEquals(sheetName+"!$A$1:$D$10", name.getRefersToFormula()); - - name = wb.getNameAt(1); - String newReference = sheetName +"!$A$1:$C$36"; - - name.setRefersToFormula(newReference); - assertEquals(newReference, name.getRefersToFormula()); - - wb.close(); - } - - /** - * Test to see if the print area can be retrieved from an excel created file - */ - @Test - void testPrintAreaFileRead() throws Exception { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPrintArea.xls"); - - String sheetName = workbook.getSheetName(0); - String reference = sheetName+"!$A$1:$C$5"; - - assertEquals(reference, workbook.getPrintArea(0)); - workbook.close(); - } - - @Test - void testDeletedReference() throws Exception { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("24207.xls")) { - assertEquals(2, wb.getNumberOfNames()); - - HSSFName name1 = wb.getNameAt(0); - assertEquals("a", name1.getNameName()); - assertEquals("Sheet1!$A$1", name1.getRefersToFormula()); - wb.getCreationHelper().createAreaReference(name1.getRefersToFormula()); - - HSSFName name2 = wb.getNameAt(1); - assertEquals("b", name2.getNameName()); - assertEquals("Sheet1!#REF!", name2.getRefersToFormula()); - assertTrue(name2.isDeleted()); - // TODO - use a stronger typed exception for this condition - assertThrows(IllegalArgumentException.class, () -> - wb.getCreationHelper().createAreaReference(name2.getRefersToFormula()), - "attempt to supply an invalid reference to AreaReference constructor results in exception"); - } - } - - /** - * When setting A1 type of references with HSSFName.setRefersToFormula - * must set the type of operands to Ptg.CLASS_REF, - * otherwise created named don't appear in the drop-down to the left of formula bar in Excel - */ - @Test - void testTypeOfRootPtg() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("CSCO"); - - Ptg[] ptgs = HSSFFormulaParser.parse("CSCO!$E$71", wb, FormulaType.NAMEDRANGE, 0); - for (Ptg ptg : ptgs) { - assertEquals('R', ptg.getRVAType()); - } - wb.close(); - } - - @Test - public final void testHSSFAddRemove() throws Exception { - HSSFWorkbook wb = HSSFITestDataProvider.instance.createWorkbook(); - assertEquals(0, wb.getNumberOfNames()); - Name name1 = wb.createName(); - name1.setNameName("name1"); - assertEquals(1, wb.getNumberOfNames()); - - Name name2 = wb.createName(); - name2.setNameName("name2"); - assertEquals(2, wb.getNumberOfNames()); - - Name name3 = wb.createName(); - name3.setNameName("name3"); - assertEquals(3, wb.getNumberOfNames()); - - wb.removeName(wb.getName("name2")); - assertEquals(2, wb.getNumberOfNames()); - - wb.removeName(0); - assertEquals(1, wb.getNumberOfNames()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java deleted file mode 100644 index 95364a33c2..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java +++ /dev/null @@ -1,706 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -final class TestHSSFOptimiser { - @Test - void testDoesNoHarmIfNothingToDo() { - HSSFWorkbook wb = new HSSFWorkbook(); - - // New files start with 4 built in fonts, and 21 built in styles - assertEquals(4, wb.getNumberOfFonts()); - assertEquals(21, wb.getNumCellStyles()); - - // Create a test font and style, and use them - HSSFFont f = wb.createFont(); - f.setFontName("Testing"); - HSSFCellStyle s = wb.createCellStyle(); - s.setFont(f); - - HSSFSheet sheet = wb.createSheet(); - HSSFRow row = sheet.createRow(0); - row.createCell(0).setCellStyle(s); - - // Should have one more than the default of each - assertEquals(5, wb.getNumberOfFonts()); - assertEquals(22, wb.getNumCellStyles()); - - // Optimise fonts - HSSFOptimiser.optimiseFonts(wb); - - assertEquals(5, wb.getNumberOfFonts()); - assertEquals(22, wb.getNumCellStyles()); - - assertEquals(f, s.getFont(wb)); - - // Optimise styles - HSSFOptimiser.optimiseCellStyles(wb); - - assertEquals(5, wb.getNumberOfFonts()); - assertEquals(22, wb.getNumCellStyles()); - - assertEquals(f, s.getFont(wb)); - } - - @Test - void testOptimiseFonts() { - HSSFWorkbook wb = new HSSFWorkbook(); - - // Add 6 fonts, some duplicates - HSSFFont f1 = wb.createFont(); - f1.setFontHeight((short) 11); - f1.setFontName("Testing"); - - HSSFFont f2 = wb.createFont(); - f2.setFontHeight((short) 22); - f2.setFontName("Also Testing"); - - HSSFFont f3 = wb.createFont(); - f3.setFontHeight((short) 33); - f3.setFontName("Unique"); - - HSSFFont f4 = wb.createFont(); - f4.setFontHeight((short) 11); - f4.setFontName("Testing"); - - HSSFFont f5 = wb.createFont(); - f5.setFontHeight((short) 22); - f5.setFontName("Also Testing"); - - HSSFFont f6 = wb.createFont(); - f6.setFontHeight((short) 66); - f6.setFontName("Also Unique"); - - // Use all three of the four in cell styles - assertEquals(21, wb.getNumCellStyles()); - - HSSFCellStyle cs1 = wb.createCellStyle(); - cs1.setFont(f1); - assertEquals(5, cs1.getFontIndex()); - - HSSFCellStyle cs2 = wb.createCellStyle(); - cs2.setFont(f4); - assertEquals(8, cs2.getFontIndex()); - - HSSFCellStyle cs3 = wb.createCellStyle(); - cs3.setFont(f5); - assertEquals(9, cs3.getFontIndex()); - - HSSFCellStyle cs4 = wb.createCellStyle(); - cs4.setFont(f6); - assertEquals(10, cs4.getFontIndex()); - - assertEquals(25, wb.getNumCellStyles()); - - // And three in rich text - HSSFSheet s = wb.createSheet(); - HSSFRow r = s.createRow(0); - - HSSFRichTextString rtr1 = new HSSFRichTextString("Test"); - rtr1.applyFont(0, 2, f1); - rtr1.applyFont(3, 4, f2); - r.createCell(0).setCellValue(rtr1); - - HSSFRichTextString rtr2 = new HSSFRichTextString("AlsoTest"); - rtr2.applyFont(0, 2, f3); - rtr2.applyFont(3, 5, f5); - rtr2.applyFont(6, 8, f6); - r.createCell(1).setCellValue(rtr2); - - // Check what we have now - assertEquals(10, wb.getNumberOfFonts()); - assertEquals(25, wb.getNumCellStyles()); - - // Optimise - HSSFOptimiser.optimiseFonts(wb); - - // Check font count - assertEquals(8, wb.getNumberOfFonts()); - assertEquals(25, wb.getNumCellStyles()); - - // Check font use in cell styles - assertEquals(5, cs1.getFontIndex()); - assertEquals(5, cs2.getFontIndex()); // duplicate of 1 - assertEquals(6, cs3.getFontIndex()); // duplicate of 2 - assertEquals(8, cs4.getFontIndex()); // two have gone - - // And in rich text - - // RTR 1 had f1 and f2, unchanged - assertEquals(5, r.getCell(0).getRichStringCellValue().getFontAtIndex(0)); - assertEquals(5, r.getCell(0).getRichStringCellValue().getFontAtIndex(1)); - assertEquals(6, r.getCell(0).getRichStringCellValue().getFontAtIndex(3)); - assertEquals(6, r.getCell(0).getRichStringCellValue().getFontAtIndex(4)); - - // RTR 2 had f3 (unchanged), f5 (=f2) and f6 (moved down) - assertEquals(7, r.getCell(1).getRichStringCellValue().getFontAtIndex(0)); - assertEquals(7, r.getCell(1).getRichStringCellValue().getFontAtIndex(1)); - assertEquals(6, r.getCell(1).getRichStringCellValue().getFontAtIndex(3)); - assertEquals(6, r.getCell(1).getRichStringCellValue().getFontAtIndex(4)); - assertEquals(8, r.getCell(1).getRichStringCellValue().getFontAtIndex(6)); - assertEquals(8, r.getCell(1).getRichStringCellValue().getFontAtIndex(7)); - } - - @Test - void testOptimiseStyles() { - HSSFWorkbook wb = new HSSFWorkbook(); - - // Two fonts - assertEquals(4, wb.getNumberOfFonts()); - - HSSFFont f1 = wb.createFont(); - f1.setFontHeight((short) 11); - f1.setFontName("Testing"); - - HSSFFont f2 = wb.createFont(); - f2.setFontHeight((short) 22); - f2.setFontName("Also Testing"); - - assertEquals(6, wb.getNumberOfFonts()); - - // Several styles - assertEquals(21, wb.getNumCellStyles()); - - HSSFCellStyle cs1 = wb.createCellStyle(); - cs1.setFont(f1); - - HSSFCellStyle cs2 = wb.createCellStyle(); - cs2.setFont(f2); - - HSSFCellStyle cs3 = wb.createCellStyle(); - cs3.setFont(f1); - - HSSFCellStyle cs4 = wb.createCellStyle(); - cs4.setFont(f1); - cs4.setAlignment(HorizontalAlignment.CENTER); - - HSSFCellStyle cs5 = wb.createCellStyle(); - cs5.setFont(f2); - cs5.setAlignment(HorizontalAlignment.FILL); - - HSSFCellStyle cs6 = wb.createCellStyle(); - cs6.setFont(f2); - - assertEquals(27, wb.getNumCellStyles()); - - // Use them - HSSFSheet s = wb.createSheet(); - HSSFRow r = s.createRow(0); - - r.createCell(0).setCellStyle(cs1); - r.createCell(1).setCellStyle(cs2); - r.createCell(2).setCellStyle(cs3); - r.createCell(3).setCellStyle(cs4); - r.createCell(4).setCellStyle(cs5); - r.createCell(5).setCellStyle(cs6); - r.createCell(6).setCellStyle(cs1); - r.createCell(7).setCellStyle(cs2); - - assertEquals(21, r.getCell(0).getCellValueRecord().getXFIndex()); - assertEquals(26, r.getCell(5).getCellValueRecord().getXFIndex()); - assertEquals(21, r.getCell(6).getCellValueRecord().getXFIndex()); - - // Optimise - HSSFOptimiser.optimiseCellStyles(wb); - - // Check - assertEquals(6, wb.getNumberOfFonts()); - assertEquals(25, wb.getNumCellStyles()); - - // cs1 -> 21 - assertEquals(21, r.getCell(0).getCellValueRecord().getXFIndex()); - // cs2 -> 22 - assertEquals(22, r.getCell(1).getCellValueRecord().getXFIndex()); - assertEquals(22, r.getCell(1).getCellStyle().getFont(wb).getFontHeight()); - // cs3 = cs1 -> 21 - assertEquals(21, r.getCell(2).getCellValueRecord().getXFIndex()); - // cs4 --> 24 -> 23 - assertEquals(23, r.getCell(3).getCellValueRecord().getXFIndex()); - // cs5 --> 25 -> 24 - assertEquals(24, r.getCell(4).getCellValueRecord().getXFIndex()); - // cs6 = cs2 -> 22 - assertEquals(22, r.getCell(5).getCellValueRecord().getXFIndex()); - // cs1 -> 21 - assertEquals(21, r.getCell(6).getCellValueRecord().getXFIndex()); - // cs2 -> 22 - assertEquals(22, r.getCell(7).getCellValueRecord().getXFIndex()); - - - // Add a new duplicate, and two that aren't used - HSSFCellStyle csD = wb.createCellStyle(); - csD.setFont(f1); - r.createCell(8).setCellStyle(csD); - - HSSFFont f3 = wb.createFont(); - f3.setFontHeight((short) 23); - f3.setFontName("Testing 3"); - HSSFFont f4 = wb.createFont(); - f4.setFontHeight((short) 24); - f4.setFontName("Testing 4"); - - HSSFCellStyle csU1 = wb.createCellStyle(); - csU1.setFont(f3); - HSSFCellStyle csU2 = wb.createCellStyle(); - csU2.setFont(f4); - - // Check before the optimise - assertEquals(8, wb.getNumberOfFonts()); - assertEquals(28, wb.getNumCellStyles()); - - // Optimise, should remove the two un-used ones and the one duplicate - HSSFOptimiser.optimiseCellStyles(wb); - - // Check - assertEquals(8, wb.getNumberOfFonts()); - assertEquals(25, wb.getNumCellStyles()); - - // csD -> cs1 -> 21 - assertEquals(21, r.getCell(8).getCellValueRecord().getXFIndex()); - } - - @Test - void testOptimiseStylesCheckActualStyles() { - HSSFWorkbook wb = new HSSFWorkbook(); - - // Several styles - assertEquals(21, wb.getNumCellStyles()); - - HSSFCellStyle cs1 = wb.createCellStyle(); - cs1.setBorderBottom(BorderStyle.THICK); - - HSSFCellStyle cs2 = wb.createCellStyle(); - cs2.setBorderBottom(BorderStyle.DASH_DOT); - - HSSFCellStyle cs3 = wb.createCellStyle(); // = cs1 - cs3.setBorderBottom(BorderStyle.THICK); - - assertEquals(24, wb.getNumCellStyles()); - - // Use them - HSSFSheet s = wb.createSheet(); - HSSFRow r = s.createRow(0); - - r.createCell(0).setCellStyle(cs1); - r.createCell(1).setCellStyle(cs2); - r.createCell(2).setCellStyle(cs3); - - assertEquals(21, r.getCell(0).getCellValueRecord().getXFIndex()); - assertEquals(22, r.getCell(1).getCellValueRecord().getXFIndex()); - assertEquals(23, r.getCell(2).getCellValueRecord().getXFIndex()); - - // Optimise - HSSFOptimiser.optimiseCellStyles(wb); - - // Check - assertEquals(23, wb.getNumCellStyles()); - - assertEquals(BorderStyle.THICK, r.getCell(0).getCellStyle().getBorderBottom()); - assertEquals(BorderStyle.DASH_DOT, r.getCell(1).getCellStyle().getBorderBottom()); - assertEquals(BorderStyle.THICK, r.getCell(2).getCellStyle().getBorderBottom()); - } - - @Test - void testColumnAndRowStyles() { - HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals(21, wb.getNumCellStyles(), - "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); - - HSSFSheet sheet = wb.createSheet(); - - Row row = sheet.createRow(0); - row.createCell(0); - row.createCell(1); - row.setRowStyle(createColorStyle(wb, IndexedColors.RED)); - - row = sheet.createRow(1); - row.createCell(0); - row.createCell(1); - row.setRowStyle(createColorStyle(wb, IndexedColors.RED)); - - sheet.setDefaultColumnStyle(0, createColorStyle(wb, IndexedColors.RED)); - sheet.setDefaultColumnStyle(1, createColorStyle(wb, IndexedColors.RED)); - - // now the color should be equal for those two columns and rows - checkColumnStyles(sheet, 0, 1, false); - checkRowStyles(sheet, 0, 1, false); - - // Optimise styles - HSSFOptimiser.optimiseCellStyles(wb); - - // We should have the same style-objects for these two columns and rows - checkColumnStyles(sheet, 0, 1, true); - checkRowStyles(sheet, 0, 1, true); - } - - @Test - void testUnusedStyle() { - HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals(21, wb.getNumCellStyles(), - "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); - - HSSFSheet sheet = wb.createSheet(); - - Row row = sheet.createRow(0); - row.createCell(0); - row.createCell(1).setCellStyle( - createColorStyle(wb, IndexedColors.GREEN)); - - - row = sheet.createRow(1); - row.createCell(0); - row.createCell(1).setCellStyle( - createColorStyle(wb, IndexedColors.RED)); - - - // Create style. But don't use it. - for (int i = 0; i < 3; i++) { - // Set Cell Color : AQUA - createColorStyle(wb, IndexedColors.AQUA); - } - - assertEquals(21 + 2 + 3, wb.getNumCellStyles()); - assertEquals(IndexedColors.GREEN.getIndex(), sheet.getRow(0).getCell(1).getCellStyle().getFillForegroundColor()); - assertEquals(IndexedColors.RED.getIndex(), sheet.getRow(1).getCell(1).getCellStyle().getFillForegroundColor()); - - // Optimise styles - HSSFOptimiser.optimiseCellStyles(wb); - - assertEquals(21 + 2, wb.getNumCellStyles()); - assertEquals(IndexedColors.GREEN.getIndex(), sheet.getRow(0).getCell(1).getCellStyle().getFillForegroundColor()); - assertEquals(IndexedColors.RED.getIndex(), sheet.getRow(1).getCell(1).getCellStyle().getFillForegroundColor()); - } - - @Test - void testUnusedStyleOneUsed() { - HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals(21, wb.getNumCellStyles(), - "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); - - HSSFSheet sheet = wb.createSheet(); - - Row row = sheet.createRow(0); - row.createCell(0); - row.createCell(1).setCellStyle( - createColorStyle(wb, IndexedColors.GREEN)); - - // Create style. But don't use it. - for (int i = 0; i < 3; i++) { - // Set Cell Color : AQUA - createColorStyle(wb, IndexedColors.AQUA); - } - - row = sheet.createRow(1); - row.createCell(0).setCellStyle(createColorStyle(wb, IndexedColors.AQUA)); - row.createCell(1).setCellStyle( - createColorStyle(wb, IndexedColors.RED)); - - assertEquals(21 + 3 + 3, wb.getNumCellStyles()); - assertEquals(IndexedColors.GREEN.getIndex(), sheet.getRow(0).getCell(1).getCellStyle().getFillForegroundColor()); - assertEquals(IndexedColors.AQUA.getIndex(), sheet.getRow(1).getCell(0).getCellStyle().getFillForegroundColor()); - assertEquals(IndexedColors.RED.getIndex(), sheet.getRow(1).getCell(1).getCellStyle().getFillForegroundColor()); - - // Optimise styles - HSSFOptimiser.optimiseCellStyles(wb); - - assertEquals(21 + 3, wb.getNumCellStyles()); - assertEquals(IndexedColors.GREEN.getIndex(), sheet.getRow(0).getCell(1).getCellStyle().getFillForegroundColor()); - assertEquals(IndexedColors.AQUA.getIndex(), sheet.getRow(1).getCell(0).getCellStyle().getFillForegroundColor()); - assertEquals(IndexedColors.RED.getIndex(), sheet.getRow(1).getCell(1).getCellStyle().getFillForegroundColor()); - } - - @Test - void testDefaultColumnStyleWitoutCell() { - HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals(21, wb.getNumCellStyles(), - "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); - - HSSFSheet sheet = wb.createSheet(); - - //Set CellStyle and RowStyle and ColumnStyle - for (int i = 0; i < 2; i++) { - sheet.createRow(i); - } - - // Create a test font and style, and use them - int obj_cnt = wb.getNumCellStyles(); - int cnt = wb.getNumCellStyles(); - - // Set Column Color : Red - sheet.setDefaultColumnStyle(3, - createColorStyle(wb, IndexedColors.RED)); - obj_cnt++; - - // Set Column Color : Red - sheet.setDefaultColumnStyle(4, - createColorStyle(wb, IndexedColors.RED)); - obj_cnt++; - - assertEquals(obj_cnt, wb.getNumCellStyles()); - - // now the color should be equal for those two columns and rows - checkColumnStyles(sheet, 3, 4, false); - - // Optimise styles - HSSFOptimiser.optimiseCellStyles(wb); - - // We should have the same style-objects for these two columns and rows - checkColumnStyles(sheet, 3, 4, true); - - // (GREEN + RED + BLUE + CORAL) + YELLOW(2*2) - assertEquals(cnt + 1, wb.getNumCellStyles()); - } - - @Test - void testUserDefinedStylesAreNeverOptimizedAway() { - HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals(21, wb.getNumCellStyles(), - "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); - - HSSFSheet sheet = wb.createSheet(); - - //Set CellStyle and RowStyle and ColumnStyle - for (int i = 0; i < 2; i++) { - sheet.createRow(i); - } - - // Create a test font and style, and use them - int obj_cnt = wb.getNumCellStyles(); - int cnt = wb.getNumCellStyles(); - for (int i = 0; i < 3; i++) { - HSSFCellStyle s = null; - if (i == 0) { - // Set cell color : +2(user style + proxy of it) - s = (HSSFCellStyle) createColorStyle(wb, - IndexedColors.YELLOW); - s.setUserStyleName("user define"); - obj_cnt += 2; - } - - HSSFRow row = sheet.getRow(1); - row.createCell(i).setCellStyle(s); - } - - // Create style. But don't use it. - for (int i = 3; i < 6; i++) { - // Set Cell Color : AQUA - createColorStyle(wb, IndexedColors.AQUA); - obj_cnt++; - } - - // Set cell color : +2(user style + proxy of it) - HSSFCellStyle s = (HSSFCellStyle) createColorStyle(wb, IndexedColors.YELLOW); - s.setUserStyleName("user define2"); - obj_cnt += 2; - - sheet.createRow(10).createCell(0).setCellStyle(s); - - assertEquals(obj_cnt, wb.getNumCellStyles()); - - // Confirm user style name - checkUserStyles(sheet); - - // Optimise styles - HSSFOptimiser.optimiseCellStyles(wb); - - // Confirm user style name - checkUserStyles(sheet); - - // (GREEN + RED + BLUE + CORAL) + YELLOW(2*2) - assertEquals(cnt + 2 * 2, wb.getNumCellStyles()); - } - - @Test - void testBug57517() { - HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals(21, wb.getNumCellStyles(), - "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); - - HSSFSheet sheet = wb.createSheet(); - - //Set CellStyle and RowStyle and ColumnStyle - for (int i = 0; i < 2; i++) { - sheet.createRow(i); - } - - // Create a test font and style, and use them - int obj_cnt = wb.getNumCellStyles(); - int cnt = wb.getNumCellStyles(); - for (int i = 0; i < 3; i++) { - // Set Cell Color : GREEN - HSSFRow row = sheet.getRow(0); - row.createCell(i).setCellStyle( - createColorStyle(wb, IndexedColors.GREEN)); - obj_cnt++; - - // Set Column Color : Red - sheet.setDefaultColumnStyle(i + 3, - createColorStyle(wb, IndexedColors.RED)); - obj_cnt++; - - // Set Row Color : Blue - row = sheet.createRow(i + 3); - row.setRowStyle(createColorStyle(wb, IndexedColors.BLUE)); - obj_cnt++; - - HSSFCellStyle s = null; - if (i == 0) { - // Set cell color : +2(user style + proxy of it) - s = (HSSFCellStyle) createColorStyle(wb, - IndexedColors.YELLOW); - s.setUserStyleName("user define"); - obj_cnt += 2; - } - - row = sheet.getRow(1); - row.createCell(i).setCellStyle(s); - - } - - // Create style. But don't use it. - for (int i = 3; i < 6; i++) { - // Set Cell Color : AQUA - createColorStyle(wb, IndexedColors.AQUA); - obj_cnt++; - } - - // Set CellStyle and RowStyle and ColumnStyle - for (int i = 9; i < 11; i++) { - sheet.createRow(i); - } - - //Set 0 or 255 index of ColumnStyle. - HSSFCellStyle s = (HSSFCellStyle) createColorStyle(wb, IndexedColors.CORAL); - obj_cnt++; - sheet.setDefaultColumnStyle(0, s); - sheet.setDefaultColumnStyle(255, s); - - // Create a test font and style, and use them - for (int i = 3; i < 6; i++) { - // Set Cell Color : GREEN - HSSFRow row = sheet.getRow(9); - row.createCell(i - 3).setCellStyle( - createColorStyle(wb, IndexedColors.GREEN)); - obj_cnt++; - - // Set Column Color : Red - sheet.setDefaultColumnStyle(i + 3, - createColorStyle(wb, IndexedColors.RED)); - obj_cnt++; - - // Set Row Color : Blue - row = sheet.createRow(i + 3); - row.setRowStyle(createColorStyle(wb, IndexedColors.BLUE)); - obj_cnt++; - - if (i == 3) { - // Set cell color : +2(user style + proxy of it) - s = (HSSFCellStyle) createColorStyle(wb, - IndexedColors.YELLOW); - s.setUserStyleName("user define2"); - obj_cnt += 2; - } - - row = sheet.getRow(1 + 9); - row.createCell(i - 3).setCellStyle(s); - } - - assertEquals(obj_cnt, wb.getNumCellStyles()); - - // now the color should be equal for those two columns and rows - checkColumnStyles(sheet, 3, 4, false); - checkRowStyles(sheet, 3, 4, false); - - // Confirm user style name - checkUserStyles(sheet); - -// out = new FileOutputStream(new File(tmpDirName, "out.xls")); -// wb.write(out); -// out.close(); - - // Optimise styles - HSSFOptimiser.optimiseCellStyles(wb); - -// out = new FileOutputStream(new File(tmpDirName, "out_optimised.xls")); -// wb.write(out); -// out.close(); - - // We should have the same style-objects for these two columns and rows - checkColumnStyles(sheet, 3, 4, true); - checkRowStyles(sheet, 3, 4, true); - - // Confirm user style name - checkUserStyles(sheet); - - // (GREEN + RED + BLUE + CORAL) + YELLOW(2*2) - assertEquals(cnt + 4 + 2 * 2, wb.getNumCellStyles()); - } - - private void checkUserStyles(HSSFSheet sheet) { - HSSFCellStyle parentStyle1 = sheet.getRow(1).getCell(0).getCellStyle().getParentStyle(); - assertNotNull(parentStyle1); - assertEquals(parentStyle1.getUserStyleName(), "user define"); - - HSSFCellStyle parentStyle10 = sheet.getRow(10).getCell(0).getCellStyle().getParentStyle(); - assertNotNull(parentStyle10); - assertEquals(parentStyle10.getUserStyleName(), "user define2"); - } - - private void checkColumnStyles(HSSFSheet sheet, int col1, int col2, boolean checkEquals) { - // we should have the same color for the column styles - HSSFCellStyle columnStyle1 = sheet.getColumnStyle(col1); - assertNotNull(columnStyle1); - HSSFCellStyle columnStyle2 = sheet.getColumnStyle(col2); - assertNotNull(columnStyle2); - assertEquals(columnStyle1.getFillForegroundColor(), columnStyle2.getFillForegroundColor()); - if (checkEquals) { - assertEquals(columnStyle1.getIndex(), columnStyle2.getIndex()); - assertEquals(columnStyle1, columnStyle2); - } - } - - private void checkRowStyles(HSSFSheet sheet, int row1, int row2, boolean checkEquals) { - // we should have the same color for the row styles - HSSFCellStyle rowStyle1 = sheet.getRow(row1).getRowStyle(); - assertNotNull(rowStyle1); - HSSFCellStyle rowStyle2 = sheet.getRow(row2).getRowStyle(); - assertNotNull(rowStyle2); - assertEquals(rowStyle1.getFillForegroundColor(), rowStyle2.getFillForegroundColor()); - if (checkEquals) { - assertEquals(rowStyle1.getIndex(), rowStyle2.getIndex()); - assertEquals(rowStyle1, rowStyle2); - } - } - - private CellStyle createColorStyle(Workbook wb, IndexedColors c) { - CellStyle cs = wb.createCellStyle(); - cs.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cs.setFillForegroundColor(c.getIndex()); - return cs; - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java deleted file mode 100644 index 1f6460e920..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java +++ /dev/null @@ -1,305 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.awt.Color; -import java.io.IOException; -import java.util.Map; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.PaletteRecord; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.Font; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -final class TestHSSFPalette { - private HSSFPalette _hssfPalette; - - - @BeforeEach - void setUp() { - PaletteRecord _palette = new PaletteRecord(); - _hssfPalette = new HSSFPalette(_palette); - } - - /** - * Verifies that a custom palette can be created, saved, and reloaded - */ - @Test - void testCustomPalette() { - //reading sample xls - HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("Simple.xls"); - - //creating custom palette - HSSFPalette palette = book.getCustomPalette(); - palette.setColorAtIndex((short) 0x12, (byte) 101, (byte) 230, (byte) 100); - palette.setColorAtIndex((short) 0x3b, (byte) 0, (byte) 255, (byte) 52); - - //writing to disk; reading in and verifying palette - book = HSSFTestDataSamples.writeOutAndReadBack(book); - - palette = book.getCustomPalette(); - HSSFColor color = palette.getColor(HSSFColorPredefined.CORAL.getIndex()); //unmodified - assertNotNull(color, "Unexpected null in custom palette (unmodified index)"); - short[] expectedRGB = HSSFColorPredefined.CORAL.getTriplet(); - short[] actualRGB = color.getTriplet(); - String msg = "Expected palette position to remain unmodified"; - assertEquals(expectedRGB[0], actualRGB[0], msg); - assertEquals(expectedRGB[1], actualRGB[1], msg); - assertEquals(expectedRGB[2], actualRGB[2], msg); - - color = palette.getColor((short) 0x12); - assertNotNull(color, "Unexpected null in custom palette (modified)"); - actualRGB = color.getTriplet(); - msg = "Expected palette modification to be preserved across save"; - assertEquals((short) 101, actualRGB[0], msg); - assertEquals((short) 230, actualRGB[1], msg); - assertEquals((short) 100, actualRGB[2], msg); - } - - /** - * Uses the palette from cell stylings - */ - @SuppressWarnings("ConstantConditions") - @Test - void testPaletteFromCellColours() { - HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("SimpleWithColours.xls"); - - HSSFPalette p = book.getCustomPalette(); - - HSSFCell cellA = book.getSheetAt(0).getRow(0).getCell(0); - HSSFCell cellB = book.getSheetAt(0).getRow(1).getCell(0); - HSSFCell cellC = book.getSheetAt(0).getRow(2).getCell(0); - HSSFCell cellD = book.getSheetAt(0).getRow(3).getCell(0); - HSSFCell cellE = book.getSheetAt(0).getRow(4).getCell(0); - - // Plain - assertEquals("I'm plain", cellA.getStringCellValue()); - assertEquals(64, cellA.getCellStyle().getFillForegroundColor()); - assertEquals(64, cellA.getCellStyle().getFillBackgroundColor()); - assertEquals(Font.COLOR_NORMAL, cellA.getCellStyle().getFont(book).getColor()); - assertEquals(FillPatternType.NO_FILL, cellA.getCellStyle().getFillPattern()); - assertNotNull(p.getColor((short)64)); - assertEquals("0:0:0", p.getColor((short)64).getHexString()); - assertNull(p.getColor((short) 32767)); - - // Red - assertEquals("I'm red", cellB.getStringCellValue()); - assertEquals(64, cellB.getCellStyle().getFillForegroundColor()); - assertEquals(64, cellB.getCellStyle().getFillBackgroundColor()); - assertEquals(10, cellB.getCellStyle().getFont(book).getColor()); - assertEquals(FillPatternType.NO_FILL, cellB.getCellStyle().getFillPattern()); - assertEquals("0:0:0", p.getColor((short)64).getHexString()); - assertEquals("FFFF:0:0", p.getColor((short)10).getHexString()); - - // Red + green bg - assertEquals("I'm red with a green bg", cellC.getStringCellValue()); - assertEquals(11, cellC.getCellStyle().getFillForegroundColor()); - assertEquals(64, cellC.getCellStyle().getFillBackgroundColor()); - assertEquals(10, cellC.getCellStyle().getFont(book).getColor()); - assertEquals(FillPatternType.SOLID_FOREGROUND, cellC.getCellStyle().getFillPattern()); - assertEquals("0:FFFF:0", p.getColor((short)11).getHexString()); - assertEquals("FFFF:0:0", p.getColor((short)10).getHexString()); - - // Pink with yellow - assertEquals("I'm pink with a yellow pattern (none)", cellD.getStringCellValue()); - assertEquals(13, cellD.getCellStyle().getFillForegroundColor()); - assertEquals(64, cellD.getCellStyle().getFillBackgroundColor()); - assertEquals(14, cellD.getCellStyle().getFont(book).getColor()); - assertEquals(FillPatternType.NO_FILL, cellD.getCellStyle().getFillPattern()); - assertEquals("FFFF:FFFF:0", p.getColor((short)13).getHexString()); - assertEquals("FFFF:0:FFFF", p.getColor((short)14).getHexString()); - - // Pink with yellow - full - assertEquals("I'm pink with a yellow pattern (full)", cellE.getStringCellValue()); - assertEquals(13, cellE.getCellStyle().getFillForegroundColor()); - assertEquals(64, cellE.getCellStyle().getFillBackgroundColor()); - assertEquals(14, cellE.getCellStyle().getFont(book).getColor()); - assertEquals(FillPatternType.NO_FILL, cellE.getCellStyle().getFillPattern()); - assertEquals("FFFF:FFFF:0", p.getColor((short)13).getHexString()); - assertEquals("FFFF:0:FFFF", p.getColor((short)14).getHexString()); - } - - @SuppressWarnings("ConstantConditions") - @Test - void testFindSimilar() throws IOException { - HSSFWorkbook book = new HSSFWorkbook(); - HSSFPalette p = book.getCustomPalette(); - - /* first test the defaults */ - assertArrayEquals( - new short[] {(short) 255, (short) 255, (short) 0}, // not [204, 255, 255] - p.findSimilarColor((byte) 204, (byte) 255, (byte) 0).getTriplet() - ); - - assertArrayEquals( - new short[] {(short) 153, (short) 204, (short) 0}, // not [128, 0, 0] - p.findSimilarColor((byte) 128, (byte) 255, (byte) 0).getTriplet() - ); - - assertArrayEquals( - new short[] {(short) 0, (short) 255, (short) 0}, // not [0, 51, 102] - p.findSimilarColor((byte) 0, (byte) 255, (byte) 102).getTriplet() - ); - - assertArrayEquals( - new short[] {(short) 0, (short) 102, (short) 204}, // not [255, 102, 0] - p.findSimilarColor((byte) 0, (byte) 102, (byte) 255).getTriplet() - ); - - assertArrayEquals( - new short[] {(short) 255, (short) 0, (short) 255}, // not [128, 0, 0] - p.findSimilarColor((byte) 128, (byte) 0, (byte) 255).getTriplet() - ); - - assertArrayEquals( - new short[] {(short) 255, (short) 0, (short) 255}, // not [255, 255, 153] - p.findSimilarColor((byte) 255, (byte) 0, (byte) 153).getTriplet() - ); - - - // Add a few edge colours in - p.setColorAtIndex((short)8, (byte)-1, (byte)0, (byte)0); - p.setColorAtIndex((short)9, (byte)0, (byte)-1, (byte)0); - p.setColorAtIndex((short)10, (byte)0, (byte)0, (byte)-1); - - // And some near a few of them - p.setColorAtIndex((short)11, (byte)-1, (byte)2, (byte)2); - p.setColorAtIndex((short)12, (byte)-2, (byte)2, (byte)10); - p.setColorAtIndex((short)13, (byte)-4, (byte)0, (byte)0); - p.setColorAtIndex((short)14, (byte)-8, (byte)0, (byte)0); - - assertEquals( - "FFFF:0:0", p.getColor((short)8).getHexString() - ); - - // Now check we get the right stuff back - assertEquals( - p.getColor((short)8).getHexString(), - p.findSimilarColor((byte)-1, (byte)0, (byte)0).getHexString() - ); - assertEquals( - p.getColor((short)8).getHexString(), - p.findSimilarColor((byte)-2, (byte)0, (byte)0).getHexString() - ); - assertEquals( - p.getColor((short)8).getHexString(), - p.findSimilarColor((byte)-1, (byte)1, (byte)0).getHexString() - ); - assertEquals( - p.getColor((short)11).getHexString(), - p.findSimilarColor((byte)-1, (byte)2, (byte)1).getHexString() - ); - assertEquals( - p.getColor((short)12).getHexString(), - p.findSimilarColor((byte)-1, (byte)2, (byte)10).getHexString() - ); - - // And with ints not bytes - assertEquals( - p.getColor((short)11).getHexString(), - p.findSimilarColor(255, 2, 1).getHexString() - ); - assertEquals( - p.getColor((short)12).getHexString(), - p.findSimilarColor(255, 2, 10).getHexString() - ); - - book.close(); - } - - /** - * Verifies that the generated gnumeric-format string values match the - * hardcoded values in the HSSFColor default color palette - */ - @Test - void testGnumericStrings() { - compareToDefaults((expected, palette) -> assertEquals(expected.getHexString(), palette.getHexString())); - } - - /** - * Verifies that the palette handles invalid palette indexes - */ - @Test - void testBadIndexes() { - //too small - _hssfPalette.setColorAtIndex((short) 2, (byte) 255, (byte) 255, (byte) 255); - //too large - _hssfPalette.setColorAtIndex((short) 0x45, (byte) 255, (byte) 255, (byte) 255); - - //should still match defaults; - compareToDefaults((expected, palette) -> { - short[] s1 = expected.getTriplet(); - short[] s2 = palette.getTriplet(); - assertEquals(s1[0], s2[0]); - assertEquals(s1[1], s2[1]); - assertEquals(s1[2], s2[2]); - }); - } - - private void compareToDefaults(ColorComparator c) { - Map colors = HSSFColor.getIndexHash(); - for (Integer index : colors.keySet()) { - HSSFColor expectedColor = colors.get(index); - HSSFColor paletteColor = _hssfPalette.getColor(index.shortValue()); - c.compare(expectedColor, paletteColor); - } - } - - @Test - void testAddColor() { - assertThrows(RuntimeException.class, () -> _hssfPalette.addColor((byte)10,(byte)10,(byte)10), - "Failing because by default there are no colours left in the palette."); - } - - private interface ColorComparator { - void compare(HSSFColor expected, HSSFColor palette); - } - - @Test - void test48403() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - - Color color = Color.decode("#006B6B"); - HSSFPalette palette = wb.getCustomPalette(); - - HSSFColor hssfColor = palette.findColor((byte) color.getRed(), - (byte) color.getGreen(), (byte) color.getBlue()); - assertNull(hssfColor); - - palette.setColorAtIndex( - (short) (PaletteRecord.STANDARD_PALETTE_SIZE - 1), - (byte) color.getRed(), (byte) color.getGreen(), - (byte) color.getBlue()); - hssfColor = palette.getColor((short) (PaletteRecord.STANDARD_PALETTE_SIZE - 1)); - assertNotNull(hssfColor); - assertEquals(55, hssfColor.getIndex()); - assertArrayEquals(new short[] {0, 107, 107}, hssfColor.getTriplet()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.java deleted file mode 100644 index 64b91fc516..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.junit.jupiter.api.Test; - -final class TestHSSFPatriarch { - - @Test - void testBasic() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - - HSSFPatriarch patr = sheet.createDrawingPatriarch(); - assertNotNull(patr); - } - } - - @Test - void test44916() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - - // 1. Create drawing patriarch - HSSFPatriarch patr = sheet.createDrawingPatriarch(); - - // 2. Try to re-get the patriarch - // bug 44916 - NullPointerException - HSSFPatriarch existingPatr = sheet.getDrawingPatriarch(); - - // 3. Use patriarch - HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 600, 245, (short) 1, 1, (short) 1, 2); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png"); - int idx1 = wb.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG); - patr.createPicture(anchor, idx1); - - // 4. Try to re-use patriarch later - existingPatr = sheet.getDrawingPatriarch(); - assertNotNull(existingPatr); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java deleted file mode 100644 index b2a793f972..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java +++ /dev/null @@ -1,287 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ddf.EscherBSERecord; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.ss.usermodel.BaseTestPicture; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Picture; -import org.apache.poi.ss.usermodel.PictureData; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; - -final class TestHSSFPicture extends BaseTestPicture { - - public TestHSSFPicture() { - super(HSSFITestDataProvider.instance); - } - - protected Picture getPictureShape(Drawing pat, int picIdx) { - return (Picture)((HSSFPatriarch)pat).getChildren().get(picIdx); - } - - /** - * Bug # 45829 reported ArithmeticException (/ by zero) when resizing png with zero DPI. - */ - @Test - void bug45829() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sh1 = wb.createSheet(); - HSSFPatriarch p1 = sh1.createDrawingPatriarch(); - - byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("45829.png"); - int idx1 = wb.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG); - HSSFPicture pic = p1.createPicture(new HSSFClientAnchor(), idx1); - assertDoesNotThrow((Executable) pic::resize); - } - } - - - @Test - void addPictures() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - - HSSFSheet sh = wb1.createSheet("Pictures"); - HSSFPatriarch dr = sh.createDrawingPatriarch(); - assertEquals(0, dr.getChildren().size()); - HSSFClientAnchor anchor = wb1.getCreationHelper().createClientAnchor(); - - //register a picture - byte[] data1 = {1, 2, 3}; - int idx1 = wb1.addPicture(data1, Workbook.PICTURE_TYPE_JPEG); - assertEquals(1, idx1); - HSSFPicture p1 = dr.createPicture(anchor, idx1); - assertArrayEquals(data1, p1.getPictureData().getData()); - - // register another one - byte[] data2 = {4, 5, 6}; - int idx2 = wb1.addPicture(data2, Workbook.PICTURE_TYPE_JPEG); - assertEquals(2, idx2); - HSSFPicture p2 = dr.createPicture(anchor, idx2); - assertEquals(2, dr.getChildren().size()); - assertArrayEquals(data2, p2.getPictureData().getData()); - - // confirm that HSSFPatriarch.getChildren() returns two picture shapes - assertArrayEquals(data1, ((HSSFPicture) dr.getChildren().get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((HSSFPicture) dr.getChildren().get(1)).getPictureData().getData()); - - // write, read back and verify that our pictures are there - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - List lst2 = wb2.getAllPictures(); - assertEquals(2, lst2.size()); - assertArrayEquals(data1, lst2.get(0).getData()); - assertArrayEquals(data2, lst2.get(1).getData()); - - // confirm that the pictures are in the Sheet's drawing - sh = wb2.getSheet("Pictures"); - dr = sh.createDrawingPatriarch(); - assertEquals(2, dr.getChildren().size()); - assertArrayEquals(data1, ((HSSFPicture) dr.getChildren().get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((HSSFPicture) dr.getChildren().get(1)).getPictureData().getData()); - - // add a third picture - byte[] data3 = {7, 8, 9}; - // picture index must increment across write-read - int idx3 = wb2.addPicture(data3, Workbook.PICTURE_TYPE_JPEG); - assertEquals(3, idx3); - HSSFPicture p3 = dr.createPicture(anchor, idx3); - assertArrayEquals(data3, p3.getPictureData().getData()); - assertEquals(3, dr.getChildren().size()); - assertArrayEquals(data1, ((HSSFPicture) dr.getChildren().get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((HSSFPicture) dr.getChildren().get(1)).getPictureData().getData()); - assertArrayEquals(data3, ((HSSFPicture) dr.getChildren().get(2)).getPictureData().getData()); - - // write and read again - try (HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2)) { - List lst3 = wb3.getAllPictures(); - // all three should be there - assertEquals(3, lst3.size()); - assertArrayEquals(data1, lst3.get(0).getData()); - assertArrayEquals(data2, lst3.get(1).getData()); - assertArrayEquals(data3, lst3.get(2).getData()); - - sh = wb3.getSheet("Pictures"); - dr = sh.createDrawingPatriarch(); - assertEquals(3, dr.getChildren().size()); - - // forth picture - byte[] data4 = {10, 11, 12}; - int idx4 = wb3.addPicture(data4, Workbook.PICTURE_TYPE_JPEG); - assertEquals(4, idx4); - dr.createPicture(anchor, idx4); - assertEquals(4, dr.getChildren().size()); - assertArrayEquals(data1, ((HSSFPicture) dr.getChildren().get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((HSSFPicture) dr.getChildren().get(1)).getPictureData().getData()); - assertArrayEquals(data3, ((HSSFPicture) dr.getChildren().get(2)).getPictureData().getData()); - assertArrayEquals(data4, ((HSSFPicture) dr.getChildren().get(3)).getPictureData().getData()); - - try (HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3)) { - List lst4 = wb4.getAllPictures(); - assertEquals(4, lst4.size()); - assertArrayEquals(data1, lst4.get(0).getData()); - assertArrayEquals(data2, lst4.get(1).getData()); - assertArrayEquals(data3, lst4.get(2).getData()); - assertArrayEquals(data4, lst4.get(3).getData()); - sh = wb4.getSheet("Pictures"); - dr = sh.createDrawingPatriarch(); - assertEquals(4, dr.getChildren().size()); - assertArrayEquals(data1, ((HSSFPicture) dr.getChildren().get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((HSSFPicture) dr.getChildren().get(1)).getPictureData().getData()); - assertArrayEquals(data3, ((HSSFPicture) dr.getChildren().get(2)).getPictureData().getData()); - assertArrayEquals(data4, ((HSSFPicture) dr.getChildren().get(3)).getPictureData().getData()); - } - } - } - } - } - - @SuppressWarnings("unused") - @Test - void bsePictureRef() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sh = wb.createSheet("Pictures"); - HSSFPatriarch dr = sh.createDrawingPatriarch(); - HSSFClientAnchor anchor = new HSSFClientAnchor(); - - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - - //register a picture - byte[] data1 = {1, 2, 3}; - int idx1 = wb.addPicture(data1, Workbook.PICTURE_TYPE_JPEG); - assertEquals(1, idx1); - HSSFPicture p1 = dr.createPicture(anchor, idx1); - - EscherBSERecord bse = wb.getWorkbook().getBSERecord(idx1); - - assertEquals(bse.getRef(), 1); - dr.createPicture(new HSSFClientAnchor(), idx1); - assertEquals(bse.getRef(), 2); - - HSSFShapeGroup gr = dr.createGroup(new HSSFClientAnchor()); - gr.createPicture(new HSSFChildAnchor(), idx1); - assertEquals(bse.getRef(), 3); - } - } - - @Test - void readExistingImage() throws IOException { - try (HSSFWorkbook wb = openSampleWorkbook("drawings.xls")) { - HSSFSheet sheet = wb.getSheet("picture"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - - HSSFPicture picture = (HSSFPicture) drawing.getChildren().get(0); - assertEquals(picture.getFileName(), "test"); - } - } - - @SuppressWarnings("resource") - @Test - void setGetProperties() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - - HSSFSheet sh = wb1.createSheet("Pictures"); - HSSFPatriarch dr = sh.createDrawingPatriarch(); - HSSFClientAnchor anchor = new HSSFClientAnchor(); - - //register a picture - byte[] data1 = {1, 2, 3}; - int idx1 = wb1.addPicture(data1, Workbook.PICTURE_TYPE_JPEG); - HSSFPicture p1 = dr.createPicture(anchor, idx1); - - assertEquals(p1.getFileName(), ""); - p1.setFileName("aaa"); - assertEquals(p1.getFileName(), "aaa"); - - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - sh = wb2.getSheet("Pictures"); - dr = sh.getDrawingPatriarch(); - - p1 = (HSSFPicture) dr.getChildren().get(0); - assertEquals(p1.getFileName(), "aaa"); - } - } - } - - @SuppressWarnings("resource") - @Test - void bug49658() throws IOException { - // test if inserted EscherMetafileBlip will be read again - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - - byte[] pictureDataEmf = POIDataSamples.getDocumentInstance().readFile("vector_image.emf"); - int indexEmf = wb1.addPicture(pictureDataEmf, HSSFWorkbook.PICTURE_TYPE_EMF); - byte[] pictureDataPng = POIDataSamples.getSpreadSheetInstance().readFile("logoKarmokar4.png"); - int indexPng = wb1.addPicture(pictureDataPng, HSSFWorkbook.PICTURE_TYPE_PNG); - byte[] pictureDataWmf = POIDataSamples.getSlideShowInstance().readFile("santa.wmf"); - int indexWmf = wb1.addPicture(pictureDataWmf, HSSFWorkbook.PICTURE_TYPE_WMF); - - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - CreationHelper ch = wb1.getCreationHelper(); - - ClientAnchor anchor = ch.createClientAnchor(); - anchor.setCol1(2); - anchor.setCol2(5); - anchor.setRow1(1); - anchor.setRow2(6); - patriarch.createPicture(anchor, indexEmf); - - anchor = ch.createClientAnchor(); - anchor.setCol1(2); - anchor.setCol2(5); - anchor.setRow1(10); - anchor.setRow2(16); - patriarch.createPicture(anchor, indexPng); - - anchor = ch.createClientAnchor(); - anchor.setCol1(6); - anchor.setCol2(9); - anchor.setRow1(1); - anchor.setRow2(6); - patriarch.createPicture(anchor, indexWmf); - - - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - byte[] pictureDataOut = wb2.getAllPictures().get(0).getData(); - assertArrayEquals(pictureDataEmf, pictureDataOut); - - byte[] wmfNoHeader = Arrays.copyOfRange(pictureDataWmf, 22, pictureDataWmf.length); - pictureDataOut = wb2.getAllPictures().get(2).getData(); - assertArrayEquals(wmfNoHeader, pictureDataOut); - } - } - } - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java deleted file mode 100644 index dd1de44da9..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.util.List; - -import javax.imageio.IIOException; -import javax.imageio.ImageIO; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Test HSSFPictureData. - * The code to retrieve images from a workbook provided by Trejkaz (trejkaz at trypticon dot org) in Bug 41223. - */ -final class TestHSSFPictureData { - @BeforeAll - public static void setUpClass() { - final String tmpDirProperty = System.getProperty("java.io.tmpdir"); - if(tmpDirProperty == null || "".equals(tmpDirProperty)) { - return; - } - // ensure that temp-dir exists because ImageIO requires it - final File tmpDir = new File(tmpDirProperty); - if(!tmpDir.exists() && !tmpDir.mkdirs()) { - throw new IllegalStateException("Could not create temporary directory " + tmpDirProperty + ", full path " + tmpDir.getAbsolutePath()); - } - ImageIO.setCacheDirectory(tmpDir); - } - - @Test - void testPictures() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithImages.xls"); - - // TODO - add getFormat() to interface PictureData and genericise wb.getAllPictures() - List lst = wb.getAllPictures(); - //assertEquals(2, lst.size()); - - try { - for (final HSSFPictureData pict : lst) { - String ext = pict.suggestFileExtension(); - byte[] data = pict.getData(); - if (ext.equals("jpeg")) { - //try to read image data using javax.imageio.* (JDK 1.4+) - BufferedImage jpg = ImageIO.read(new ByteArrayInputStream(data)); - assertNotNull(jpg); - assertEquals(192, jpg.getWidth()); - assertEquals(176, jpg.getHeight()); - assertEquals(HSSFWorkbook.PICTURE_TYPE_JPEG, pict.getFormat()); - assertEquals("image/jpeg", pict.getMimeType()); - } else if (ext.equals("png")) { - //try to read image data using javax.imageio.* (JDK 1.4+) - BufferedImage png = ImageIO.read(new ByteArrayInputStream(data)); - assertNotNull(png); - assertEquals(300, png.getWidth()); - assertEquals(300, png.getHeight()); - assertEquals(HSSFWorkbook.PICTURE_TYPE_PNG, pict.getFormat()); - assertEquals("image/png", pict.getMimeType()); - /*} else { - //TODO: test code for PICT, WMF and EMF*/ - } - } - } catch (IIOException e) { - assertFalse(e.getMessage().contains("Can't create cache file"), e.getMessage()); - } - } - - @Test - void testMacPicture() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("53446.xls"); - - try{ - List lst = wb.getAllPictures(); - assertEquals(1, lst.size()); - - HSSFPictureData pict = lst.get(0); - String ext = pict.suggestFileExtension(); - assertEquals("png", ext, "Expected a PNG."); - - //try to read image data using javax.imageio.* (JDK 1.4+) - byte[] data = pict.getData(); - BufferedImage png = ImageIO.read(new ByteArrayInputStream(data)); - assertNotNull(png); - assertEquals(78, png.getWidth()); - assertEquals(76, png.getHeight()); - assertEquals(HSSFWorkbook.PICTURE_TYPE_PNG, pict.getFormat()); - assertEquals("image/png", pict.getMimeType()); - } catch (IIOException e) { - assertFalse(e.getMessage().contains("Can't create cache file"), e.getMessage()); - } - } - - @Test - void testNotNullPictures() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SheetWithDrawing.xls"); - - // TODO - add getFormat() to interface PictureData and genericise wb.getAllPictures() - List lst = wb.getAllPictures(); - for(HSSFPictureData pict : lst){ - assertNotNull(pict); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRangeCopier.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRangeCopier.java deleted file mode 100644 index 4b17b77a8e..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRangeCopier.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.BaseTestRangeCopier; -import org.junit.jupiter.api.BeforeEach; - -class TestHSSFRangeCopier extends BaseTestRangeCopier { - - public TestHSSFRangeCopier() { - super(); - workbook = new HSSFWorkbook(); - testDataProvider = HSSFITestDataProvider.instance; - } - - @BeforeEach - void init() { - workbook = HSSFTestDataSamples.openSampleWorkbook("tile-range-test.xls"); - initSheets(); - rangeCopier = new HSSFRangeCopier(sheet1, sheet1); - transSheetRangeCopier = new HSSFRangeCopier(sheet1, sheet2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java deleted file mode 100644 index 44ae5b4fcf..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java +++ /dev/null @@ -1,130 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -final class TestHSSFRichTextString { - @Test - void testApplyFont() { - HSSFRichTextString r = new HSSFRichTextString("testing"); - assertEquals(0,r.numFormattingRuns()); - r.applyFont(2,4, new HSSFFont((short)1, null)); - assertEquals(2,r.numFormattingRuns()); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(0)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(1)); - assertEquals(1, r.getFontAtIndex(2)); - assertEquals(1, r.getFontAtIndex(3)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(4)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(5)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(6)); - - r.applyFont(6,7, new HSSFFont((short)2, null)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(0)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(1)); - assertEquals(1, r.getFontAtIndex(2)); - assertEquals(1, r.getFontAtIndex(3)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(4)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(5)); - assertEquals(2, r.getFontAtIndex(6)); - - r.applyFont(HSSFRichTextString.NO_FONT); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(0)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(1)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(2)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(3)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(4)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(5)); - - r.applyFont(new HSSFFont((short)1, null)); - assertEquals(1, r.getFontAtIndex(0)); - assertEquals(1, r.getFontAtIndex(1)); - assertEquals(1, r.getFontAtIndex(2)); - assertEquals(1, r.getFontAtIndex(3)); - assertEquals(1, r.getFontAtIndex(4)); - assertEquals(1, r.getFontAtIndex(5)); - assertEquals(1, r.getFontAtIndex(6)); - } - - @Test - void testClearFormatting() { - HSSFRichTextString r = new HSSFRichTextString("testing"); - assertEquals(0, r.numFormattingRuns()); - r.applyFont(2, 4, new HSSFFont( (short) 1, null)); - assertEquals(2, r.numFormattingRuns()); - r.clearFormatting(); - assertEquals(0, r.numFormattingRuns()); - } - - - /** - * Test case proposed in Bug 40520: formated twice => will format whole String - */ - @Test - void test40520_1() { - short font = 3; - - HSSFRichTextString r = new HSSFRichTextString("f0_123456789012345678901234567890123456789012345678901234567890"); - - r.applyFont(0,7,font); - r.applyFont(5,9,font); - - for(int i=0; i < 7; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=5; i < 9; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=9; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i)); - } - - /** - * Test case proposed in Bug 40520: overlapped range => will format whole String - */ - @Test - void test40520_2() { - short font = 3; - HSSFRichTextString r = new HSSFRichTextString("f0_123456789012345678901234567890123456789012345678901234567890"); - - r.applyFont(0,2,font); - for(int i=0; i < 2; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=2; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i)); - - r.applyFont(0,2,font); - for(int i=0; i < 2; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=2; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i)); - } - - /** - * Test case proposed in Bug 40520: formated twice => will format whole String - */ - @Test - void test40520_3() { - short font = 3; - HSSFRichTextString r = new HSSFRichTextString("f0_123456789012345678901234567890123456789012345678901234567890"); - - // wrong order => will format 0-6 - r.applyFont(0,2,font); - r.applyFont(5,7,font); - r.applyFont(0,2,font); - - r.applyFont(0,2,font); - for(int i=0; i < 2; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=2; i < 5; i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i)); - for(int i=5; i < 7; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=7; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java deleted file mode 100644 index b588f1375c..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java +++ /dev/null @@ -1,146 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.record.BlankRecord; -import org.apache.poi.hssf.record.RowRecord; -import org.apache.poi.ss.usermodel.BaseTestRow; -import org.junit.jupiter.api.Test; - -/** - * Test HSSFRow is okay. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -final class TestHSSFRow extends BaseTestRow { - - public TestHSSFRow() { - super(HSSFITestDataProvider.instance); - } - - @Test - void testLastAndFirstColumns_bug46654() throws IOException { - int ROW_IX = 10; - int COL_IX = 3; - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Sheet1"); - RowRecord rowRec = new RowRecord(ROW_IX); - rowRec.setFirstCol((short)2); - rowRec.setLastCol((short)5); - - BlankRecord br = new BlankRecord(); - br.setRow(ROW_IX); - br.setColumn((short)COL_IX); - - sheet.getSheet().addValueRecord(ROW_IX, br); - HSSFRow row = new HSSFRow(workbook, sheet, rowRec); - HSSFCell cell = row.createCellFromRecord(br); - - assertFalse(row.getFirstCellNum() == 2 && row.getLastCellNum() == 5, "Identified bug 46654a"); - - assertEquals(COL_IX, row.getFirstCellNum()); - assertEquals(COL_IX + 1, row.getLastCellNum()); - row.removeCell(cell); - assertEquals(-1, row.getFirstCellNum()); - assertEquals(-1, row.getLastCellNum()); - - workbook.close(); - } - - @Test - void testMoveCell() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - HSSFRow row = sheet.createRow(0); - HSSFRow rowB = sheet.createRow(1); - - HSSFCell cellA2 = rowB.createCell(0); - assertEquals(0, rowB.getFirstCellNum()); - assertEquals(0, rowB.getFirstCellNum()); - - assertEquals(-1, row.getLastCellNum()); - assertEquals(-1, row.getFirstCellNum()); - HSSFCell cellB2 = row.createCell(1); - row.createCell(2); // C2 - row.createCell(3); // D2 - - assertEquals(1, row.getFirstCellNum()); - assertEquals(4, row.getLastCellNum()); - - // Try to move to somewhere else that's used - assertThrows(IllegalArgumentException.class, () -> row.moveCell(cellB2, (short)3)); - - // Try to move one off a different row - assertThrows(IllegalArgumentException.class, () -> row.moveCell(cellA2, (short)3)); - - // Move somewhere spare - assertNotNull(row.getCell(1)); - row.moveCell(cellB2, (short)5); - assertNull(row.getCell(1)); - assertNotNull(row.getCell(5)); - - assertEquals(5, cellB2.getColumnIndex()); - assertEquals(2, row.getFirstCellNum()); - assertEquals(6, row.getLastCellNum()); - - workbook.close(); - } - - @Override - @Test - protected void testRowHeight() throws IOException{ - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - HSSFRow row = sheet.createRow(0); - - assertEquals(row.getHeight(), sheet.getDefaultRowHeight()); - assertFalse(row.getRowRecord().getBadFontHeight()); - - row.setHeight((short) 123); - assertEquals(123, row.getHeight()); - assertTrue(row.getRowRecord().getBadFontHeight()); - - row.setHeight((short) -1); - assertEquals(row.getHeight(), sheet.getDefaultRowHeight()); - assertFalse(row.getRowRecord().getBadFontHeight()); - - row.setHeight((short) 123); - assertEquals(123, row.getHeight()); - assertTrue(row.getRowRecord().getBadFontHeight()); - - row.setHeightInPoints(-1); - assertEquals(row.getHeight(), sheet.getDefaultRowHeight()); - assertFalse(row.getRowRecord().getBadFontHeight()); - - row.setHeightInPoints(432); - assertEquals(432*20, row.getHeight()); - assertTrue(row.getRowRecord().getBadFontHeight()); - - workbook.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java deleted file mode 100644 index b6c9c918d2..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java +++ /dev/null @@ -1,1115 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.DrawingManager2; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.*; -import org.apache.poi.hssf.record.aggregates.WorksheetProtectionBlock; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.AutoFilter; -import org.apache.poi.ss.usermodel.BaseTestSheet; -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.junit.jupiter.api.Test; - -/** - * Tests HSSFSheet. This test case is very incomplete at the moment. - */ -final class TestHSSFSheet extends BaseTestSheet { - - public TestHSSFSheet() { - super(HSSFITestDataProvider.instance); - } - - /** - * Test for Bugzilla #29747. - * Moved from TestHSSFWorkbook#testSetRepeatingRowsAndColumns(). - */ - @Test - void setRepeatingRowsAndColumnsBug29747() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - wb.createSheet(); - wb.createSheet(); - HSSFSheet sheet2 = wb.createSheet(); - sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:2")); - NameRecord nameRecord = wb.getWorkbook().getNameRecord(0); - assertEquals(3, nameRecord.getSheetNumber()); - } - } - - /** - * Test the gridset field gets set as expected. - */ - @Test - void backupRecord() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - GridsetRecord gridsetRec = s.getSheet().getGridsetRecord(); - assertTrue(gridsetRec.getGridset()); - s.setGridsPrinted(true); - assertFalse(gridsetRec.getGridset()); - } - } - - /** - * Test vertically centered output. - */ - @Test - void verticallyCenter() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - VCenterRecord record = s.getSheet().getPageSettings().getVCenter(); - - assertFalse(record.getVCenter()); - assertFalse(s.getVerticallyCenter()); - s.setVerticallyCenter(true); - assertTrue(record.getVCenter()); - assertTrue(s.getVerticallyCenter()); - } - } - - /** - * Test horizontally centered output. - */ - @Test - void horizontallyCenter() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - HCenterRecord record = s.getSheet().getPageSettings().getHCenter(); - - assertFalse(record.getHCenter()); - assertFalse(s.getHorizontallyCenter()); - s.setHorizontallyCenter(true); - assertTrue(record.getHCenter()); - assertTrue(s.getHorizontallyCenter()); - } - } - - - /** - * Test WSBoolRecord fields get set in the user model. - */ - @Test - void wsBool() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - WSBoolRecord record = (WSBoolRecord) s.getSheet().findFirstRecordBySid(WSBoolRecord.sid); - - // Check defaults - assertNotNull(record); - assertTrue(record.getAlternateExpression()); - assertTrue(record.getAlternateFormula()); - assertFalse(record.getAutobreaks()); - assertFalse(record.getDialog()); - assertFalse(record.getDisplayGuts()); - assertTrue(record.getFitToPage()); - assertFalse(record.getRowSumsBelow()); - assertFalse(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 - assertTrue(record.getAlternateExpression()); //sheet.setRowSumsBelow alters this field too - assertFalse(record.getAlternateFormula()); - assertTrue(record.getAutobreaks()); - assertTrue(record.getDialog()); - assertTrue(record.getDisplayGuts()); - assertFalse(record.getFitToPage()); - assertTrue(record.getRowSumsBelow()); - assertTrue(record.getRowSumsRight()); - assertTrue(s.getAlternateExpression()); - assertFalse(s.getAlternateFormula()); - assertTrue(s.getAutobreaks()); - assertTrue(s.getDialog()); - assertTrue(s.getDisplayGuts()); - assertFalse(s.getFitToPage()); - assertTrue(s.getRowSumsBelow()); - assertTrue(s.getRowSumsRight()); - } - } - - /** - * Setting landscape and portrait stuff on existing sheets - */ - @Test - void printSetupLandscapeExisting() throws IOException { - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls")) { - - assertEquals(3, wb1.getNumberOfSheets()); - - HSSFSheet sheetL = wb1.getSheetAt(0); - HSSFSheet sheetPM = wb1.getSheetAt(1); - HSSFSheet sheetLS = wb1.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 - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - sheetL = wb2.getSheetAt(0); - sheetPM = wb2.getSheetAt(1); - sheetLS = wb2.getSheetAt(2); - - 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()); - } - } - } - - @Test - void groupRows() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.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 - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - s = wb2.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()); - } - } - } - - @Test - void groupRowsExisting() throws IOException { - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("NoGutsRecords.xls")) { - - HSSFSheet s = wb1.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 - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - // OutOfMemoryError -> Identified bug 39903 - s = wb2.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()); - } - } - } - - @Test - void createDrawings() throws IOException { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFSheet sheet = workbook.createSheet(); - HSSFPatriarch p1 = sheet.createDrawingPatriarch(); - HSSFPatriarch p2 = sheet.createDrawingPatriarch(); - assertSame(p1, p2); - } - } - - @Test - void getDrawings() throws IOException { - try (HSSFWorkbook wb1c = HSSFTestDataSamples.openSampleWorkbook("WithChart.xls"); - HSSFWorkbook wb2c = HSSFTestDataSamples.openSampleWorkbook("WithTwoCharts.xls")) { - - // 1 chart sheet -> data on 1st, chart on 2nd - assertNotNull(wb1c.getSheetAt(0).getDrawingPatriarch()); - assertSame(wb1c.getSheetAt(0).getDrawingPatriarch(), wb1c.getSheetAt(0).getDrawingPatriarch()); - assertNotNull(wb1c.getSheetAt(1).getDrawingPatriarch()); - assertSame(wb1c.getSheetAt(1).getDrawingPatriarch(), 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 - */ - @Test - void cloneWithProtect() throws IOException { - String passwordA = "secrect"; - int expectedHashA = -6810; - String passwordB = "admin"; - int expectedHashB = -14556; - - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFSheet hssfSheet = workbook.createSheet(); - assertFalse(hssfSheet.getObjectProtect()); - hssfSheet.protectSheet(passwordA); - assertTrue(hssfSheet.getObjectProtect()); - assertEquals(expectedHashA, hssfSheet.getPassword()); - - assertEquals(expectedHashA, hssfSheet.getSheet().getProtectionBlock().getPasswordHash()); - - // Clone the sheet, and make sure the password hash is preserved - HSSFSheet sheet2 = workbook.cloneSheet(0); - assertTrue(hssfSheet.getObjectProtect()); - assertEquals(expectedHashA, sheet2.getSheet().getProtectionBlock().getPasswordHash()); - - // change the password on the first sheet - hssfSheet.protectSheet(passwordB); - assertTrue(hssfSheet.getObjectProtect()); - assertEquals(expectedHashB, hssfSheet.getSheet().getProtectionBlock().getPasswordHash()); - assertEquals(expectedHashB, hssfSheet.getPassword()); - // but the cloned sheet's password should remain unchanged - assertEquals(expectedHashA, sheet2.getSheet().getProtectionBlock().getPasswordHash()); - } - } - - @Test - void protectSheetA() throws IOException { - int expectedHash = (short)0xfef1; - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - s.protectSheet("abcdefghij"); - WorksheetProtectionBlock pb = s.getSheet().getProtectionBlock(); - assertTrue(pb.isSheetProtected(), "protection should be on"); - assertTrue(pb.isObjectProtected(), "object protection should be on"); - assertTrue(pb.isScenarioProtected(), "scenario protection should be on"); - assertEquals(expectedHash, pb.getPasswordHash(), "well known value for top secret hash should be " + Integer.toHexString(expectedHash).substring(4)); - } - } - - /** - * {@link PasswordRecord} belongs with the rest of the Worksheet Protection Block - * (which should be before {@link DimensionsRecord}). - */ - @Test - void protectSheetRecordOrder_bug47363a() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - s.protectSheet("secret"); - List recs = new ArrayList<>(); - s.getSheet().visitContainedRecords(recs::add, 0); - int nRecs = recs.size(); - - // Check that protection block is together, and before DIMENSION - // PASSWORD must be before DIMENSION - Class[] exp = {ProtectRecord.class, ObjectProtectRecord.class, ScenarioProtectRecord.class, - PasswordRecord.class, DefaultColWidthRecord.class, DimensionsRecord.class, WindowTwoRecord.class, - SelectionRecord.class, EOFRecord.class }; - Class[] act = recs.subList(nRecs - 9, nRecs).stream().map(Object::getClass).toArray(Class[]::new); - assertArrayEquals(exp, act); - } - } - - /** - * There should be no problem with adding data validations after sheet protection - */ - @Test - void dvProtectionOrder_bug47363b() throws IOException { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFSheet sheet = workbook.createSheet("Sheet1"); - sheet.protectSheet("secret"); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint dvc = dataValidationHelper.createIntegerConstraint(DataValidationConstraint.OperatorType.BETWEEN, "10", "100"); - CellRangeAddressList numericCellAddressList = new CellRangeAddressList(0, 0, 1, 1); - DataValidation dv = dataValidationHelper.createValidation(dvc, numericCellAddressList); - - // bug 47363b: Unexpected (org.apache.poi.hssf.record.PasswordRecord) while looking for DV Table insert pos - sheet.addValidationData(dv); - - int[] nRecsWithProtection = { 0 }; - sheet.getSheet().visitContainedRecords(r -> nRecsWithProtection[0]++, 0); - - sheet.protectSheet(null); - int[] nRecsWithoutProtection = { 0 }; - sheet.getSheet().visitContainedRecords(r -> nRecsWithoutProtection[0]++, 0); - - assertEquals(4, nRecsWithProtection[0] - nRecsWithoutProtection[0]); - } - } - - @Test - void zoom() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - assertEquals(-1, sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid)); - sheet.setZoom(75); - assertTrue(sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid) > 0); - SCLRecord sclRecord = (SCLRecord) sheet.getSheet().findFirstRecordBySid(SCLRecord.sid); - assertNotNull(sclRecord); - short numerator = sclRecord.getNumerator(); - assertEquals(75, 100 * numerator / sclRecord.getDenominator()); - - int sclLoc = sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid); - int window2Loc = sheet.getSheet().findFirstRecordLocBySid(WindowTwoRecord.sid); - assertEquals(sclLoc, window2Loc + 1); - - // verify limits - IllegalArgumentException e; - e = assertThrows(IllegalArgumentException.class, () -> sheet.setZoom(0)); - assertEquals("Numerator must be greater than 0 and less than 65536", e.getMessage()); - - e = assertThrows(IllegalArgumentException.class, () -> sheet.setZoom(65536)); - assertEquals("Numerator must be greater than 0 and less than 65536", e.getMessage()); - - e = assertThrows(IllegalArgumentException.class, () -> sheet.setZoom(2, 0)); - assertEquals("Denominator must be greater than 0 and less than 65536", e.getMessage()); - - e = assertThrows(IllegalArgumentException.class, () -> sheet.setZoom(2, 65536)); - assertEquals("Denominator must be greater than 0 and less than 65536", e.getMessage()); - } - } - - - /** - * When removing one merged region, it would break - * Make sure the excel file loads work - */ - @Test - void pageBreakFiles() throws IOException { - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls")) { - - HSSFSheet sheet = wb1.getSheetAt(0); - assertNotNull(sheet); - - assertEquals(1, sheet.getRowBreaks().length, "1 row page break"); - assertEquals(1, sheet.getColumnBreaks().length, "1 column page break"); - - assertTrue(sheet.isRowBroken(22), "No row page break"); - assertTrue(sheet.isColumnBroken((short) 4), "No column page break"); - - sheet.setRowBreak(10); - sheet.setColumnBreak((short) 13); - - assertEquals(2, sheet.getRowBreaks().length, "row breaks number"); - assertEquals(2, sheet.getColumnBreaks().length, "column breaks number"); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - sheet = wb2.getSheetAt(0); - - assertTrue(sheet.isRowBroken(22), "No row page break"); - assertTrue(sheet.isColumnBroken((short) 4), "No column page break"); - - assertEquals(2, sheet.getRowBreaks().length, "row breaks number"); - assertEquals(2, sheet.getColumnBreaks().length, "column breaks number"); - } - } - } - - @Test - void dbcsName () throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DBCSSheetName.xls")) { - wb.getSheetAt(1); - assertEquals(wb.getSheetName(1), "\u090f\u0915", "DBCS Sheet Name 2"); - assertEquals(wb.getSheetName(0), "\u091c\u093e", "DBCS Sheet Name 1"); - } - } - - /** - * 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. - */ - @Test - void topRow() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - assertNotNull(sheet); - - short toprow = (short) 100; - short leftcol = (short) 50; - sheet.showInPane(toprow, leftcol); - assertEquals(toprow, sheet.getTopRow(), "HSSFSheet.getTopRow()"); - assertEquals(leftcol, sheet.getLeftCol(), "HSSFSheet.getLeftCol()"); - } - } - - @Test - void addEmptyRow() throws IOException { - //try to add 5 empty rows to a new sheet - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet sheet = wb1.createSheet(); - for (int i = 0; i < 5; i++) { - sheet.createRow(i); - } - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - HSSFSheet sheet2 = wb2.getSheetAt(0); - assertNotNull(sheet2.getRow(4)); - } - } - - //try adding empty rows in an existing worksheet - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls")) { - HSSFSheet sheet = wb1.getSheetAt(0); - for (int i = 3; i < 10; i++) { - sheet.createRow(i); - } - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - HSSFSheet sheet2 = wb2.getSheetAt(0); - assertNotNull(sheet2.getRow(4)); - } - } - } - - @Test - void autoSizeColumn() throws IOException { - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("43902.xls")) { - String sheetName = "my sheet"; - HSSFSheet sheet = wb1.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. - // So, we use ranges, which are pretty large, but - // thankfully don't overlap! - int minWithRow1And2 = 6400; - int maxWithRow1And2 = 7800; - int minWithRow1Only = 2750; - int maxWithRow1Only = 3400; - - // 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(sheet.getColumnWidth(0) >= minWithRow1And2, "Column autosized with only one row: wrong width"); - assertTrue(sheet.getColumnWidth(0) <= maxWithRow1And2, "Column autosized with only one row: wrong width"); - - //create a region over the 2nd row and auto size the first column - assertEquals(1, sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 1))); - assertNotNull(sheet.getMergedRegion(0)); - sheet.autoSizeColumn((short) 0); - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - - // check that the autoSized column width has ignored the 2nd row - // because it is included in a merged region (Excel like behavior) - HSSFSheet sheet2 = wb2.getSheet(sheetName); - assertTrue(sheet2.getColumnWidth(0) >= minWithRow1Only); - assertTrue(sheet2.getColumnWidth(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); - try (HSSFWorkbook wb3 = writeOutAndReadBack(wb2)) { - HSSFSheet sheet3 = wb3.getSheet(sheetName); - assertTrue(sheet3.getColumnWidth(0) >= minWithRow1And2); - assertTrue(sheet3.getColumnWidth(0) <= maxWithRow1And2); - } - } - } - } - - /** - * Setting ForceFormulaRecalculation on sheets - */ - @Test - void forceRecalculation() throws IOException { - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("UncalcedRecord.xls")) { - - HSSFSheet sheet = wb1.getSheetAt(0); - HSSFSheet sheet2 = wb1.getSheetAt(0); - HSSFRow row = sheet.getRow(0); - row.createCell(0).setCellValue(5); - row.createCell(1).setCellValue(8); - assertFalse(sheet.getForceFormulaRecalculation()); - assertFalse(sheet2.getForceFormulaRecalculation()); - - // Save and manually verify that on column C we have 0, value in template - writeOutAndReadBack(wb1).close(); - sheet.setForceFormulaRecalculation(true); - assertTrue(sheet.getForceFormulaRecalculation()); - - // Save and manually verify that on column C we have now 13, calculated value - // Try it can be opened - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - // 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); - - try (HSSFWorkbook wb3 = writeOutAndReadBack(wb2)) { - assertFalse(wb3.getSheetAt(0).getForceFormulaRecalculation()); - assertFalse(wb3.getSheetAt(1).getForceFormulaRecalculation()); - assertFalse(wb3.getSheetAt(2).getForceFormulaRecalculation()); - - // Now add a new sheet, and check things work - // with old ones unset, new one set - HSSFSheet s4 = wb3.createSheet(); - s4.setForceFormulaRecalculation(true); - - assertFalse(sheet.getForceFormulaRecalculation()); - assertFalse(sheet2.getForceFormulaRecalculation()); - assertTrue(s4.getForceFormulaRecalculation()); - - try (HSSFWorkbook wb4 = writeOutAndReadBack(wb3)) { - assertFalse(wb4.getSheetAt(0).getForceFormulaRecalculation()); - assertFalse(wb4.getSheetAt(1).getForceFormulaRecalculation()); - assertFalse(wb4.getSheetAt(2).getForceFormulaRecalculation()); - assertTrue(wb4.getSheetAt(3).getForceFormulaRecalculation()); - } - } - } - } - } - - @Test - void columnWidthA() throws IOException { - // check we can correctly read column widths from a reference workbook - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("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(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(idx); - //getDefaultColumnWidth returns width measured in characters - //getColumnWidth returns width measured in 1/256th units - assertEquals(def_width * 256, w); - } - } - - // test new workbook - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet sh = wb1.createSheet(); - sh.setDefaultColumnWidth(10); - assertEquals(10, sh.getDefaultColumnWidth()); - assertEquals(256 * 10, sh.getColumnWidth(0)); - assertEquals(256 * 10, sh.getColumnWidth(1)); - assertEquals(256 * 10, sh.getColumnWidth(2)); - for (char i = 'D'; i <= 'F'; i++) { - short w = (256 * 12); - sh.setColumnWidth(i, w); - assertEquals(w, sh.getColumnWidth(i)); - } - - //serialize and read again - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - sh = wb2.getSheetAt(0); - assertEquals(10, sh.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256 * 10, sh.getColumnWidth(0)); - assertEquals(256 * 10, sh.getColumnWidth(1)); - assertEquals(256 * 10, sh.getColumnWidth(2)); - //columns D-F have custom width - for (char i = 'D'; i <= 'F'; i++) { - short w = (256 * 12); - assertEquals(w, sh.getColumnWidth(i)); - } - - // check for 16-bit signed/unsigned error: - sh.setColumnWidth(0, 40000); - assertEquals(40000, sh.getColumnWidth(0)); - } - } - } - - - @Test - void defaultColumnWidth() throws IOException { - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook( "12843-1.xls" )) { - HSSFSheet sheet = wb1.getSheetAt(7); - // shall not be NPE - assertEquals(8, sheet.getDefaultColumnWidth()); - assertEquals(8 * 256, sheet.getColumnWidth(0)); - - assertEquals(0xFF, sheet.getDefaultRowHeight()); - } - - try (HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook( "34775.xls" )) { - // second and third sheets miss DefaultColWidthRecord - for (int i = 1; i <= 2; i++) { - HSSFSheet sheet = wb2.getSheetAt(i); - int dw = sheet.getDefaultColumnWidth(); - assertEquals(8, dw); - int cw = sheet.getColumnWidth(0); - assertEquals(8 * 256, cw); - - assertEquals(0xFF, sheet.getDefaultRowHeight()); - } - } - } - - /** - * Some utilities write Excel files without the ROW records. - * Excel, ooo, and google docs are OK with this. - * Now POI is too. - */ - @Test - void missingRowRecords_bug41187() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex41187-19267.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - HSSFRow row = sheet.getRow(0); - assertNotNull(row, "Identified bug 41187 a"); - - assertNotEquals((short) 0, row.getHeight(), "Identified bug 41187 b"); - - assertEquals(row.getCell(0).getRichStringCellValue().getString(), "Hi Excel!"); - // check row height for 'default' flag - assertEquals((short) 0xFF, row.getHeight()); - - writeOutAndReadBack(wb).close(); - } - } - - /** - * If we clone a sheet containing drawings, - * we must allocate a new ID of the drawing group and re-create shape IDs - * - * See bug #45720. - */ - @Test - void cloneSheetWithDrawings() throws IOException { - try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("45720.xls")) { - HSSFSheet sheet1 = wb1.getSheetAt(0); - - DrawingManager2 dm1 = wb1.getWorkbook().findDrawingGroup(); - int maxDrawingGroupId1 = dm1.getDgg().getMaxDrawingGroupId(); - wb1.cloneSheet(0); - - //check EscherDggRecord - a workbook-level registry of drawing objects - assertEquals(maxDrawingGroupId1 + 1, dm1.getDgg().getMaxDrawingGroupId()); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - DrawingManager2 dm2 = wb2.getWorkbook().findDrawingGroup(); - assertEquals(maxDrawingGroupId1 + 1, dm2.getDgg().getMaxDrawingGroupId()); - - HSSFSheet sheet2 = wb2.getSheetAt(1); - - //check that id of the drawing group was updated - EscherDgRecord dg1 = (EscherDgRecord) sheet1.getDrawingPatriarch().getBoundAggregate().findFirstWithId(EscherDgRecord.RECORD_ID); - EscherDgRecord dg2 = (EscherDgRecord) sheet2.getDrawingPatriarch().getBoundAggregate().findFirstWithId(EscherDgRecord.RECORD_ID); - int dg_id_1 = dg1.getOptions() >> 4; - int dg_id_2 = dg2.getOptions() >> 4; - assertEquals(dg_id_1 + 1, dg_id_2); - - //TODO: check shapeId in the cloned sheet - } - } - } - - /** - * POI now (Sep 2008) allows sheet names longer than 31 chars (for other apps besides Excel). - * Since Excel silently truncates to 31, make sure that POI enforces uniqueness on the first - * 31 chars. - */ - @Test - void longSheetNames() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - final String SAME_PREFIX = "A123456789B123456789C123456789"; // 30 chars - - wb.createSheet(SAME_PREFIX + "Dxxxx"); - // identical up to the 32nd char - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> wb.createSheet(SAME_PREFIX + "Dyyyy")); - assertEquals("The workbook already contains a sheet named 'A123456789B123456789C123456789Dyyyy'", e.getMessage()); - - wb.createSheet(SAME_PREFIX + "Exxxx"); // OK - differs in the 31st char - } - } - - /** - * Tests that we can read existing column styles - */ - @Test - void readColumnStyles() throws IOException { - try (HSSFWorkbook wbNone = HSSFTestDataSamples.openSampleWorkbook("ColumnStyleNone.xls"); - HSSFWorkbook wbSimple = HSSFTestDataSamples.openSampleWorkbook("ColumnStyle1dp.xls"); - HSSFWorkbook wbComplex = HSSFTestDataSamples.openSampleWorkbook("ColumnStyle1dpColoured.xls")) { - - // Presence / absence checks - assertNull(wbNone.getSheetAt(0).getColumnStyle(0)); - assertNull(wbNone.getSheetAt(0).getColumnStyle(1)); - - assertNull(wbSimple.getSheetAt(0).getColumnStyle(0)); - assertNotNull(wbSimple.getSheetAt(0).getColumnStyle(1)); - - assertNull(wbComplex.getSheetAt(0).getColumnStyle(0)); - assertNotNull(wbComplex.getSheetAt(0).getColumnStyle(1)); - - // Details checks - HSSFCellStyle bs = wbSimple.getSheetAt(0).getColumnStyle(1); - assertNotNull(bs); - assertEquals(62, bs.getIndex()); - assertEquals("#,##0.0_ ;\\-#,##0.0\\ ", bs.getDataFormatString()); - assertEquals("Calibri", bs.getFont(wbSimple).getFontName()); - assertEquals(11 * 20, bs.getFont(wbSimple).getFontHeight()); - assertEquals(8, bs.getFont(wbSimple).getColor()); - assertFalse(bs.getFont(wbSimple).getItalic()); - assertFalse(bs.getFont(wbSimple).getBold()); - - - HSSFCellStyle cs = wbComplex.getSheetAt(0).getColumnStyle(1); - assertNotNull(cs); - assertEquals(62, cs.getIndex()); - assertEquals("#,##0.0_ ;\\-#,##0.0\\ ", cs.getDataFormatString()); - assertEquals("Arial", cs.getFont(wbComplex).getFontName()); - assertEquals(8 * 20, cs.getFont(wbComplex).getFontHeight()); - assertEquals(10, cs.getFont(wbComplex).getColor()); - assertFalse(cs.getFont(wbComplex).getItalic()); - assertTrue(cs.getFont(wbComplex).getBold()); - } - } - - /** - * Tests the arabic setting - */ - @Test - void arabic() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - - assertFalse(s.isRightToLeft()); - s.setRightToLeft(true); - assertTrue(s.isRightToLeft()); - } - } - - @Test - void autoFilter() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet sh = wb1.createSheet(); - InternalWorkbook iwb = wb1.getWorkbook(); - InternalSheet ish = sh.getSheet(); - - assertNull(iwb.getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1)); - assertNull(ish.findFirstRecordBySid(AutoFilterInfoRecord.sid)); - - CellRangeAddress range = CellRangeAddress.valueOf("A1:B10"); - sh.setAutoFilter(range); - - NameRecord name = iwb.getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1); - assertNotNull(name); - - // The built-in name for auto-filter must consist of a single Area3d Ptg. - Ptg[] ptg = name.getNameDefinition(); - assertEquals(1, ptg.length, "The built-in name for auto-filter must consist of a single Area3d Ptg"); - assertTrue(ptg[0] instanceof Area3DPtg, "The built-in name for auto-filter must consist of a single Area3d Ptg"); - - Area3DPtg aref = (Area3DPtg) ptg[0]; - assertEquals(range.getFirstColumn(), aref.getFirstColumn()); - assertEquals(range.getFirstRow(), aref.getFirstRow()); - assertEquals(range.getLastColumn(), aref.getLastColumn()); - assertEquals(range.getLastRow(), aref.getLastRow()); - - // verify AutoFilterInfoRecord - AutoFilterInfoRecord afilter = (AutoFilterInfoRecord) ish.findFirstRecordBySid(AutoFilterInfoRecord.sid); - assertNotNull(afilter); - assertEquals(2, afilter.getNumEntries()); //filter covers two columns - - HSSFPatriarch dr = sh.getDrawingPatriarch(); - assertNotNull(dr); - HSSFSimpleShape comboBoxShape = (HSSFSimpleShape) dr.getChildren().get(0); - assertEquals(comboBoxShape.getShapeType(), HSSFSimpleShape.OBJECT_TYPE_COMBO_BOX); - - assertNull(ish.findFirstRecordBySid(ObjRecord.sid)); // ObjRecord will appear after serializetion - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - sh = wb2.getSheetAt(0); - ish = sh.getSheet(); - ObjRecord objRecord = (ObjRecord) ish.findFirstRecordBySid(ObjRecord.sid); - assertNotNull(objRecord); - List subRecords = objRecord.getSubRecords(); - assertEquals(3, subRecords.size()); - assertTrue(subRecords.get(0) instanceof CommonObjectDataSubRecord); - assertTrue(subRecords.get(1) instanceof FtCblsSubRecord); // must be present, see Bug 51481 - assertTrue(subRecords.get(2) instanceof LbsDataSubRecord); - } - } - } - - @Test - void getSetColumnHiddenShort() throws IOException { - try (Workbook workbook = new HSSFWorkbook()) { - Sheet sheet = workbook.createSheet("Sheet 1"); - sheet.setColumnHidden((short) 2, true); - assertTrue(sheet.isColumnHidden((short) 2)); - } - } - - @Test - void columnWidthShort() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - Sheet sheet = wb1.createSheet(); - - //default column width measured in characters - sheet.setDefaultColumnWidth((short) 10); - assertEquals(10, sheet.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256 * 10, sheet.getColumnWidth((short) 0)); - assertEquals(256 * 10, sheet.getColumnWidth((short) 1)); - assertEquals(256 * 10, sheet.getColumnWidth((short) 2)); - - //set custom width for D-F - for (char i = 'D'; i <= 'F'; i++) { - //Sheet#setColumnWidth accepts the width in units of 1/256th of a character width - int w = 256 * 12; - sheet.setColumnWidth((short) i, w); - assertEquals(w, sheet.getColumnWidth((short) i)); - } - //reset the default column width, columns A-C change, D-F still have custom width - sheet.setDefaultColumnWidth((short) 20); - assertEquals(20, sheet.getDefaultColumnWidth()); - assertEquals(256 * 20, sheet.getColumnWidth((short) 0)); - assertEquals(256 * 20, sheet.getColumnWidth((short) 1)); - assertEquals(256 * 20, sheet.getColumnWidth((short) 2)); - for (char i = 'D'; i <= 'F'; i++) { - int w = 256 * 12; - assertEquals(w, sheet.getColumnWidth((short) i)); - } - - // check for 16-bit signed/unsigned error: - sheet.setColumnWidth((short) 10, 40000); - assertEquals(40000, sheet.getColumnWidth((short) 10)); - - //The maximum column width for an individual cell is 255 characters - Sheet sheet2 = sheet; - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> - sheet2.setColumnWidth((short) 9, 256 * 256)); - assertEquals("The maximum column width for an individual cell is 255 characters.", e.getMessage()); - - //serialize and read again - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - sheet = wb2.getSheetAt(0); - assertEquals(20, sheet.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256 * 20, sheet.getColumnWidth((short) 0)); - assertEquals(256 * 20, sheet.getColumnWidth((short) 1)); - assertEquals(256 * 20, sheet.getColumnWidth((short) 2)); - //columns D-F have custom width - for (char i = 'D'; i <= 'F'; i++) { - short w = (256 * 12); - assertEquals(w, sheet.getColumnWidth((short) i)); - } - assertEquals(40000, sheet.getColumnWidth((short) 10)); - } - } - } - - @Test - void showInPane() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - sheet.showInPane(2, 3); - - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> sheet.showInPane(Integer.MAX_VALUE, 3) - ); - assertEquals("Maximum row number is 65535", ex.getMessage()); - } - } - - @Test - void drawingRecords() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - - /* TODO: NPE? - sheet.dumpDrawingRecords(false); - sheet.dumpDrawingRecords(true);*/ - assertNull(sheet.getDrawingEscherAggregate()); - } - } - - @Test - void bug55723b() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - - // stored with a special name - assertNull(wb.getWorkbook().getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1)); - - CellRangeAddress range = CellRangeAddress.valueOf("A:B"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - - // stored with a special name - NameRecord record = wb.getWorkbook().getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1); - assertNotNull(record); - } - } - - @Test - void test58746() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - - HSSFSheet first = wb.createSheet("first"); - first.createRow(0).createCell(0).setCellValue(1); - - HSSFSheet second = wb.createSheet("second"); - second.createRow(0).createCell(0).setCellValue(2); - - HSSFSheet third = wb.createSheet("third"); - HSSFRow row = third.createRow(0); - row.createCell(0).setCellFormula("first!A1"); - row.createCell(1).setCellFormula("second!A1"); - - // re-order for sheet "third" - wb.setSheetOrder("third", 0); - - // verify results - assertEquals("third", wb.getSheetAt(0).getSheetName()); - assertEquals("first", wb.getSheetAt(1).getSheetName()); - assertEquals("second", wb.getSheetAt(2).getSheetName()); - - assertEquals("first!A1", wb.getSheetAt(0).getRow(0).getCell(0).getCellFormula()); - assertEquals("second!A1", wb.getSheetAt(0).getRow(0).getCell(1).getCellFormula()); - } - } - - @Test - void bug59135() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - wb1.createSheet().protectSheet("1111.2222.3333.1234"); - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - - assertEquals((short) 0xb86b, wb2.getSheetAt(0).getPassword()); - } - } - - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - wb1.createSheet().protectSheet("1111.2222.3333.12345"); - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { - - assertEquals((short) 0xbecc, wb2.getSheetAt(0).getPassword()); - } - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetAutosizeColumn.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetAutosizeColumn.java deleted file mode 100644 index 340211560d..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetAutosizeColumn.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestSheetAutosizeColumn; - -/** - * Test auto-sizing columns in HSSF - */ -final class TestHSSFSheetAutosizeColumn extends BaseTestSheetAutosizeColumn { - - public TestHSSFSheetAutosizeColumn() { - super(HSSFITestDataProvider.instance); - } - -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftColumns.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftColumns.java deleted file mode 100644 index 9333ac516a..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftColumns.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.hssf.usermodel; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.BaseTestSheetShiftColumns; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -class TestHSSFSheetShiftColumns extends BaseTestSheetShiftColumns { - public TestHSSFSheetShiftColumns() { - super(); - workbook = new HSSFWorkbook(); - _testDataProvider = HSSFITestDataProvider.instance; - } - - protected Workbook openWorkbook(String spreadsheetFileName) { - return HSSFTestDataSamples.openSampleWorkbook(spreadsheetFileName); - } - - protected Workbook getReadBackWorkbook(Workbook wb) { - return HSSFTestDataSamples.writeOutAndReadBack((HSSFWorkbook)wb); - } - - @Override - @Disabled("see ") - protected void shiftMergedColumnsToMergedColumnsLeft() { - // This override is used only in order to test failing for HSSF. Please remove method after code is fixed on hssf, - // so that original method from BaseTestSheetShiftColumns can be executed. - } - - @Override - @Disabled("see ") - protected void shiftMergedColumnsToMergedColumnsRight() { - // This override is used only in order to test failing for HSSF. Please remove method after code is fixed on hssf, - // so that original method from BaseTestSheetShiftColumns can be executed. - } - - @Override - @Disabled("see ") - protected void testBug54524() { - // This override is used only in order to test failing for HSSF. Please remove method after code is fixed on hssf, - // so that original method from BaseTestSheetShiftColumns can be executed. - } - - @Override - @Disabled("see ") - protected void testCommentsShifting() { - // This override is used only in order to test failing for HSSF. Please remove method after code is fixed on hssf, - // so that original method from BaseTestSheetShiftColumns can be executed. - } - - @Override - @Disabled("see ") - protected void testShiftWithMergedRegions() { - // This override is used only in order to test failing for HSSF. Please remove method after code is fixed on hssf, - // so that original method from BaseTestSheetShiftColumns can be executed. - // After removing, you can re-add 'final' keyword to specification of original method. - } - - @Override - @Disabled("see ") - protected void testShiftHyperlinks() {} -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftRows.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftRows.java deleted file mode 100644 index d78c3bf660..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftRows.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestSheetShiftRows; - -/** - * @author Yegor Kozlov - */ -final class TestHSSFSheetShiftRows extends BaseTestSheetShiftRows { - - public TestHSSFSheetShiftRows() { - super(HSSFITestDataProvider.instance); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java deleted file mode 100644 index 33f6607988..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.POITestCase; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.record.ArrayRecord; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; -import org.apache.poi.hssf.record.aggregates.RowRecordsAggregate; -import org.apache.poi.hssf.record.aggregates.SharedValueManager; -import org.apache.poi.ss.usermodel.BaseTestSheetUpdateArrayFormulas; -import org.apache.poi.ss.usermodel.CellRange; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Test; - -/** - * Test array formulas in HSSF - */ -final class TestHSSFSheetUpdateArrayFormulas extends BaseTestSheetUpdateArrayFormulas { - - public TestHSSFSheetUpdateArrayFormulas() { - super(HSSFITestDataProvider.instance); - } - - // Test methods common with XSSF are in superclass - // Local methods here test HSSF-specific details of updating array formulas - @Test - void testHSSFSetArrayFormula_singleCell() throws IOException { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFSheet sheet = workbook.createSheet("Sheet1"); - - CellRangeAddress range = new CellRangeAddress(2, 2, 2, 2); - HSSFCell[] cells = sheet.setArrayFormula("SUM(C11:C12*D11:D12)", range).getFlattenedCells(); - assertEquals(1, cells.length); - - // sheet.setArrayFormula creates rows and cells for the designated range - assertNotNull(sheet.getRow(2)); - HSSFCell cell = sheet.getRow(2).getCell(2); - assertNotNull(cell); - - assertTrue(cell.isPartOfArrayFormulaGroup()); - //retrieve the range and check it is the same - assertEquals(range.formatAsString(), cell.getArrayFormulaRange().formatAsString()); - - FormulaRecordAggregate agg = (FormulaRecordAggregate) cell.getCellValueRecord(); - assertEquals(range.formatAsString(), agg.getArrayFormulaRange().formatAsString()); - assertTrue(agg.isPartOfArrayFormula()); - } - } - - /** - * Makes sure the internal state of HSSFSheet is consistent after removing array formulas - */ - @Test - void testAddRemoveArrayFormulas_recordUpdates() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet("Sheet1"); - - CellRange cr = s.setArrayFormula("123", CellRangeAddress.valueOf("B5:C6")); - List recs = new ArrayList<>(); - s.getSheet().visitContainedRecords(recs::add, 0); - - int ix = 0; - for (org.apache.poi.hssf.record.Record r : recs) { - if (r instanceof ArrayRecord) break; - ix++; - } - - assertNotEquals(ix, recs.size()); - Class[] act = recs.subList(ix-1, ix+4).stream().map(Object::getClass).toArray(Class[]::new); - Class[] exp = { FormulaRecord.class, ArrayRecord.class, FormulaRecord.class, FormulaRecord.class, FormulaRecord.class }; - assertArrayEquals(exp, act); - - // just one array record - assertFalse(recs.subList(ix + 1, recs.size()).stream().anyMatch(r -> r instanceof ArrayRecord)); - - s.removeArrayFormula(cr.getTopLeftCell()); - - // Make sure the array formula has been removed properly - recs.clear(); - s.getSheet().visitContainedRecords(recs::add, 0); - - assertFalse(recs.stream().anyMatch(r -> r instanceof ArrayRecord || r instanceof FormulaRecord)); - RowRecordsAggregate rra = s.getSheet().getRowsAggregate(); - - SharedValueManager svm = POITestCase.getFieldValue(RowRecordsAggregate.class, rra, SharedValueManager.class, "_sharedValueManager"); - assertNull(svm.getArrayRecord(4, 1), "Array record was not cleaned up properly."); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFTextbox.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFTextbox.java deleted file mode 100644 index 5d08d77e4c..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFTextbox.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Test HSSFTextbox. - */ -final class TestHSSFTextbox { - - /** - * Test that accessors to horizontal and vertical alignment work properly - */ - @Test - void testAlignment() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sh1 = wb.createSheet(); - HSSFPatriarch patriarch = sh1.createDrawingPatriarch(); - - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 6, 4)); - HSSFRichTextString str = new HSSFRichTextString("Hello, World"); - textbox.setString(str); - textbox.setHorizontalAlignment(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED); - textbox.setVerticalAlignment(HSSFTextbox.VERTICAL_ALIGNMENT_CENTER); - - assertEquals(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED, textbox.getHorizontalAlignment()); - assertEquals(HSSFTextbox.VERTICAL_ALIGNMENT_CENTER, textbox.getVerticalAlignment()); - } - } - - /** - * Excel requires at least one format run in HSSFTextbox. - * When inserting text make sure that if font is not set we must set the default one. - */ - @Test - void testSetDeafultTextFormat() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFTextbox textbox1 = patriarch.createTextbox(new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 3, 3)); - HSSFRichTextString rt1 = new HSSFRichTextString("Hello, World!"); - assertEquals(0, rt1.numFormattingRuns()); - textbox1.setString(rt1); - - HSSFRichTextString rt2 = textbox1.getString(); - assertEquals(1, rt2.numFormattingRuns()); - assertEquals(HSSFRichTextString.NO_FONT, rt2.getFontOfFormattingRun(0)); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java deleted file mode 100644 index ac4f32cb0e..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java +++ /dev/null @@ -1,1189 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -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.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ddf.EscherBSERecord; -import org.apache.poi.hpsf.ClassID; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.CFRuleRecord; -import org.apache.poi.hssf.record.HSSFRecordTypes; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.hssf.record.WindowOneRecord; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.usermodel.BaseTestWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.ConditionalFormatting; -import org.apache.poi.ss.usermodel.ConditionalFormattingRule; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.SheetConditionalFormatting; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; - -/** - * Tests for {@link HSSFWorkbook} - */ -public final class TestHSSFWorkbook extends BaseTestWorkbook { - private static final HSSFITestDataProvider _testDataProvider = HSSFITestDataProvider.instance; - private static final POIDataSamples samples = POIDataSamples.getSpreadSheetInstance(); - - public TestHSSFWorkbook() { - super(_testDataProvider); - } - - /** - * gives test code access to the {@link InternalWorkbook} within {@link HSSFWorkbook} - */ - public static InternalWorkbook getInternalWorkbook(HSSFWorkbook wb) { - return wb.getWorkbook(); - } - - /** - * Tests for {@link HSSFWorkbook#isHidden()} etc - */ - @Test - void hidden() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - WindowOneRecord w1 = wb.getWorkbook().getWindowOne(); - - assertFalse(wb.isHidden()); - assertFalse(w1.getHidden()); - - wb.setHidden(true); - assertTrue(wb.isHidden()); - assertTrue(w1.getHidden()); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - w1 = wbBack.getWorkbook().getWindowOne(); - - wbBack.setHidden(true); - assertTrue(wbBack.isHidden()); - assertTrue(w1.getHidden()); - - wbBack.setHidden(false); - assertFalse(wbBack.isHidden()); - assertFalse(w1.getHidden()); - - wbBack.close(); - wb.close(); - } - - @Test - void readWriteWithCharts() throws IOException { - Sheet s; - - // Single chart, two sheets - HSSFWorkbook b1 = openSampleWorkbook("44010-SingleChart.xls"); - assertEquals(2, b1.getNumberOfSheets()); - assertEquals("Graph2", b1.getSheetName(1)); - s = b1.getSheetAt(1); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - - // Has chart on 1st sheet?? - // FIXME - assertNotNull(b1.getSheetAt(0).getDrawingPatriarch()); - assertNull(b1.getSheetAt(1).getDrawingPatriarch()); - assertFalse(b1.getSheetAt(0).getDrawingPatriarch().containsChart()); - b1.close(); - - // We've now called getDrawingPatriarch() so - // everything will be all screwy - // So, start again - HSSFWorkbook b2 = openSampleWorkbook("44010-SingleChart.xls"); - - HSSFWorkbook b3 = HSSFTestDataSamples.writeOutAndReadBack(b2); - b2.close(); - - assertEquals(2, b3.getNumberOfSheets()); - s = b3.getSheetAt(1); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - b3.close(); - - // Two charts, three sheets - HSSFWorkbook b4 = openSampleWorkbook("44010-TwoCharts.xls"); - assertEquals(3, b4.getNumberOfSheets()); - - s = b4.getSheetAt(1); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - s = b4.getSheetAt(2); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - - // Has chart on 1st sheet?? - // FIXME - assertNotNull(b4.getSheetAt(0).getDrawingPatriarch()); - assertNull(b4.getSheetAt(1).getDrawingPatriarch()); - assertNull(b4.getSheetAt(2).getDrawingPatriarch()); - assertFalse(b4.getSheetAt(0).getDrawingPatriarch().containsChart()); - b4.close(); - - // We've now called getDrawingPatriarch() so - // everything will be all screwy - // So, start again - HSSFWorkbook b5 = openSampleWorkbook("44010-TwoCharts.xls"); - - Workbook b6 = HSSFTestDataSamples.writeOutAndReadBack(b5); - b5.close(); - assertEquals(3, b6.getNumberOfSheets()); - - s = b6.getSheetAt(1); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - s = b6.getSheetAt(2); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - b6.close(); - } - - @Test - void selectedSheet_bug44523() throws IOException { - HSSFWorkbook wb=new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("Sheet3"); - HSSFSheet sheet4 = wb.createSheet("Sheet4"); - - confirmActiveSelected(sheet1, true); - confirmActiveSelected(sheet2, false); - confirmActiveSelected(sheet3, false); - confirmActiveSelected(sheet4, false); - - wb.setSelectedTab(1); - - // Demonstrate bug 44525: - // Well... not quite, since isActive + isSelected were also added in the same bug fix - assertFalse(sheet1.isSelected(), "Identified bug 44523 a"); - wb.setActiveSheet(1); - assertFalse(sheet1.isActive(), "Identified bug 44523 b"); - - confirmActiveSelected(sheet1, false); - confirmActiveSelected(sheet2, true); - confirmActiveSelected(sheet3, false); - confirmActiveSelected(sheet4, false); - - wb.close(); - } - - private static List arrayToList(int[] array) { - List list = new ArrayList<>(array.length); - for ( Integer element : array ) { - list.add(element); - } - return list; - } - - private static void assertCollectionsEquals(Collection expected, Collection actual) { - assertEquals(expected.size(), actual.size()); - for (int e : expected) { - assertTrue(actual.contains(e)); - } - for (int a : actual) { - assertTrue(expected.contains(a)); - } - } - - @Test - void selectMultiple() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet0 = wb.createSheet("Sheet0"); - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("Sheet3"); - HSSFSheet sheet4 = wb.createSheet("Sheet4"); - HSSFSheet sheet5 = wb.createSheet("Sheet5"); - - - List selected = arrayToList(new int[] { 0, 2, 3 }); - wb.setSelectedTabs(selected); - - assertCollectionsEquals(selected, wb.getSelectedTabs()); - assertTrue(sheet0.isSelected()); - assertFalse(sheet1.isSelected()); - assertTrue(sheet2.isSelected()); - assertTrue(sheet3.isSelected()); - assertFalse(sheet4.isSelected()); - assertFalse(sheet5.isSelected()); - - selected = arrayToList(new int[] { 1, 3, 5 }); - wb.setSelectedTabs(selected); - - // previous selection should be cleared - assertCollectionsEquals(selected, wb.getSelectedTabs()); - assertFalse(sheet0.isSelected()); - assertTrue(sheet1.isSelected()); - assertFalse(sheet2.isSelected()); - assertTrue(sheet3.isSelected()); - assertFalse(sheet4.isSelected()); - assertTrue(sheet5.isSelected()); - - assertTrue(sheet0.isActive()); - assertFalse(sheet2.isActive()); - wb.setActiveSheet(2); - assertFalse(sheet0.isActive()); - assertTrue(sheet2.isActive()); - - wb.close(); - } - - - @Test - void activeSheetAfterDelete_bug40414() throws IOException { - HSSFWorkbook wb=new HSSFWorkbook(); - HSSFSheet sheet0 = wb.createSheet("Sheet0"); - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("Sheet3"); - HSSFSheet sheet4 = wb.createSheet("Sheet4"); - - // confirm default activation/selection - confirmActiveSelected(sheet0, true); - confirmActiveSelected(sheet1, false); - confirmActiveSelected(sheet2, false); - confirmActiveSelected(sheet3, false); - confirmActiveSelected(sheet4, false); - - wb.setActiveSheet(3); - wb.setSelectedTab(3); - - confirmActiveSelected(sheet0, false); - confirmActiveSelected(sheet1, false); - confirmActiveSelected(sheet2, false); - confirmActiveSelected(sheet3, true); - confirmActiveSelected(sheet4, false); - - wb.removeSheetAt(3); - // after removing the only active/selected sheet, another should be active/selected in its place - assertTrue(sheet4.isSelected(), "identified bug 40414 a"); - assertTrue(sheet4.isActive(), "identified bug 40414 b"); - - confirmActiveSelected(sheet0, false); - confirmActiveSelected(sheet1, false); - confirmActiveSelected(sheet2, false); - confirmActiveSelected(sheet4, true); - - sheet3 = sheet4; // re-align local vars in this test case - - // Some more cases of removing sheets - - // Starting with a multiple selection, and different active sheet - wb.setSelectedTabs(new int[] { 1, 3, }); - wb.setActiveSheet(2); - confirmActiveSelected(sheet0, false, false); - confirmActiveSelected(sheet1, false, true); - confirmActiveSelected(sheet2, true, false); - confirmActiveSelected(sheet3, false, true); - - // removing a sheet that is not active, and not the only selected sheet - wb.removeSheetAt(3); - confirmActiveSelected(sheet0, false, false); - confirmActiveSelected(sheet1, false, true); - confirmActiveSelected(sheet2, true, false); - - // removing the only selected sheet - wb.removeSheetAt(1); - confirmActiveSelected(sheet0, false, false); - confirmActiveSelected(sheet2, true, true); - - // The last remaining sheet should always be active+selected - wb.removeSheetAt(1); - confirmActiveSelected(sheet0, true, true); - - wb.close(); - } - - private static void confirmActiveSelected(HSSFSheet sheet, boolean expected) { - confirmActiveSelected(sheet, expected, expected); - } - - - private static void confirmActiveSelected(HSSFSheet sheet, - boolean expectedActive, boolean expectedSelected) { - assertEquals(expectedActive, sheet.isActive(), "active"); - assertEquals(expectedSelected, sheet.isSelected(), "selected"); - } - - /** - * If Sheet.getSize() returns a different result to Sheet.serialize(), this will cause the BOF - * records to be written with invalid offset indexes. Excel does not like this, and such - * errors are particularly hard to track down. This test ensures that HSSFWorkbook throws - * a specific exception as soon as the situation is detected. See bugzilla 45066 - */ - @Test - void sheetSerializeSizeMismatch_bug45066() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - InternalSheet sheet = wb.createSheet("Sheet1").getSheet(); - List sheetRecords = sheet.getRecords(); - // one way (of many) to cause the discrepancy is with a badly behaved record: - sheetRecords.add(new BadlyBehavedRecord()); - // There is also much logic inside Sheet that (if buggy) might also cause the discrepancy - IllegalStateException e = assertThrows(IllegalStateException.class, wb::getBytes, "Identified bug 45066 a"); - assertTrue(e.getMessage().startsWith("Actual serialized sheet size")); - } - } - - /** - * Checks that us and HSSFName play nicely with named ranges - * that point to deleted sheets - */ - @Test - void namesToDeleteSheets() throws IOException { - HSSFWorkbook b = openSampleWorkbook("30978-deleted.xls"); - assertEquals(3, b.getNumberOfNames()); - - // Sheet 2 is deleted - assertEquals("Sheet1", b.getSheetName(0)); - assertEquals("Sheet3", b.getSheetName(1)); - - Area3DPtg ptg; - NameRecord nr; - HSSFName n; - - /* ======= Name pointing to deleted sheet ====== */ - - // First at low level - nr = b.getWorkbook().getNameRecord(0); - assertEquals("On2", nr.getNameText()); - assertEquals(0, nr.getSheetNumber()); - assertEquals(1, nr.getExternSheetNumber()); - assertEquals(1, nr.getNameDefinition().length); - - ptg = (Area3DPtg)nr.getNameDefinition()[0]; - assertEquals(1, ptg.getExternSheetIndex()); - assertEquals(0, ptg.getFirstColumn()); - assertEquals(0, ptg.getFirstRow()); - assertEquals(0, ptg.getLastColumn()); - assertEquals(2, ptg.getLastRow()); - - // Now at high level - n = b.getNameAt(0); - assertEquals("On2", n.getNameName()); - assertEquals("", n.getSheetName()); - assertEquals("#REF!$A$1:$A$3", n.getRefersToFormula()); - - - /* ======= Name pointing to 1st sheet ====== */ - - // First at low level - nr = b.getWorkbook().getNameRecord(1); - assertEquals("OnOne", nr.getNameText()); - assertEquals(0, nr.getSheetNumber()); - assertEquals(0, nr.getExternSheetNumber()); - assertEquals(1, nr.getNameDefinition().length); - - ptg = (Area3DPtg)nr.getNameDefinition()[0]; - assertEquals(0, ptg.getExternSheetIndex()); - assertEquals(0, ptg.getFirstColumn()); - assertEquals(2, ptg.getFirstRow()); - assertEquals(0, ptg.getLastColumn()); - assertEquals(3, ptg.getLastRow()); - - // Now at high level - n = b.getNameAt(1); - assertEquals("OnOne", n.getNameName()); - assertEquals("Sheet1", n.getSheetName()); - assertEquals("Sheet1!$A$3:$A$4", n.getRefersToFormula()); - - - /* ======= Name pointing to 3rd sheet ====== */ - - // First at low level - nr = b.getWorkbook().getNameRecord(2); - assertEquals("OnSheet3", nr.getNameText()); - assertEquals(0, nr.getSheetNumber()); - assertEquals(2, nr.getExternSheetNumber()); - assertEquals(1, nr.getNameDefinition().length); - - ptg = (Area3DPtg)nr.getNameDefinition()[0]; - assertEquals(2, ptg.getExternSheetIndex()); - assertEquals(0, ptg.getFirstColumn()); - assertEquals(0, ptg.getFirstRow()); - assertEquals(0, ptg.getLastColumn()); - assertEquals(1, ptg.getLastRow()); - - // Now at high level - n = b.getNameAt(2); - assertEquals("OnSheet3", n.getNameName()); - assertEquals("Sheet3", n.getSheetName()); - assertEquals("Sheet3!$A$1:$A$2", n.getRefersToFormula()); - - b.close(); - } - - /** - * result returned by getRecordSize() differs from result returned by serialize() - */ - private static final class BadlyBehavedRecord extends Record { - BadlyBehavedRecord() { - // - } - @Override - public short getSid() { - return 0x777; - } - @Override - public int serialize(int offset, byte[] data) { - return 4; - } - @Override - public int getRecordSize() { - return 8; - } - @Override - public BadlyBehavedRecord copy() { - return null; - } - - @Override - public HSSFRecordTypes getGenericRecordType() { - return null; - } - - @Override - public Map> getGenericProperties() { - return null; - } - } - - /** - * The sample file provided with bug 45582 seems to have one extra byte after the EOFRecord - */ - @Test - void extraDataAfterEOFRecord() throws IOException { - // bug 45582 - RecordFormatException - getCause() instanceof LittleEndian.BufferUnderrunException - try (HSSFWorkbook wb = openSampleWorkbook("ex45582-22397.xls")) { - assertNotNull(wb); - } - } - - /** - * Test to make sure that NameRecord.getSheetNumber() is interpreted as a - * 1-based sheet tab index (not a 1-based extern sheet index) - */ - @Test - void findBuiltInNameRecord() throws IOException { - // testRRaC has multiple (3) built-in name records - // The second print titles name record has getSheetNumber()==4 - HSSFWorkbook wb1 = openSampleWorkbook("testRRaC.xls"); - NameRecord nr; - assertEquals(3, wb1.getWorkbook().getNumNames()); - nr = wb1.getWorkbook().getNameRecord(2); - // TODO - render full row and full column refs properly - assertEquals("Sheet2!$A$1:$IV$1", HSSFFormulaParser.toFormulaString(wb1, nr.getNameDefinition())); // 1:1 - - try { - wb1.getSheetAt(3).setRepeatingRows(CellRangeAddress.valueOf("9:12")); - wb1.getSheetAt(3).setRepeatingColumns(CellRangeAddress.valueOf("E:F")); - } catch (RuntimeException e) { - if (e.getMessage().equals("Builtin (7) already exists for sheet (4)")) { - // there was a problem in the code which locates the existing print titles name record - fail("Identified bug 45720b"); - } - wb1.close(); - throw e; - } - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - assertEquals(3, wb2.getWorkbook().getNumNames()); - nr = wb2.getWorkbook().getNameRecord(2); - assertEquals("Sheet2!E:F,Sheet2!$A$9:$IV$12", HSSFFormulaParser.toFormulaString(wb2, nr.getNameDefinition())); // E:F,9:12 - wb2.close(); - } - - /** - * Test that the storage clsid property is preserved - */ - @Test - void bug47920() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(samples.openResourceAsStream("47920.xls")); - HSSFWorkbook wb = new HSSFWorkbook(fs1); - ClassID clsid1 = fs1.getRoot().getStorageClsid(); - - ByteArrayOutputStream out = new ByteArrayOutputStream(4096); - wb.write(out); - byte[] bytes = out.toByteArray(); - POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes)); - ClassID clsid2 = fs2.getRoot().getStorageClsid(); - - assertEquals(clsid1, clsid2); - - fs2.close(); - wb.close(); - fs1.close(); - } - - /** - * If we try to open an old (pre-97) workbook, we get a helpful - * Exception give to explain what we've done wrong - */ - @ParameterizedTest - @CsvSource({ - "testEXCEL_4.xls,BIFF4", - "testEXCEL_5.xls,BIFF5", - "testEXCEL_95.xls,BIFF5" - }) - void helpfulExceptionOnOldFiles(String file, String format) throws Exception { - POIDataSamples xlsData = samples; - try (InputStream is = xlsData.openResourceAsStream(file)) { - OldExcelFormatException e = assertThrows(OldExcelFormatException.class, () -> new HSSFWorkbook(is), - "Shouldn't be able to load an Excel " + format + " file"); - assertContains(e.getMessage(), format); - } - } - - /** - * Tests that we can work with both {@link POIFSFileSystem} - * and {@link POIFSFileSystem} - */ - @Test - void differentPOIFS() throws Exception { - // Open the two filesystems - DirectoryNode[] files = new DirectoryNode[2]; - try (POIFSFileSystem poifsFileSystem = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("Simple.xls"))) { - files[0] = poifsFileSystem.getRoot(); - try (POIFSFileSystem poifsFileSystem2 = new POIFSFileSystem(HSSFTestDataSamples.getSampleFile("Simple.xls"))) { - files[1] = poifsFileSystem2.getRoot(); - - // Open without preserving nodes - for (DirectoryNode dir : files) { - HSSFWorkbook workbook = new HSSFWorkbook(dir, false); - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFCell cell = sheet.getRow(0).getCell(0); - assertEquals("replaceMe", cell.getRichStringCellValue().getString()); - - workbook.close(); - } - - // Now re-check with preserving - for (DirectoryNode dir : files) { - HSSFWorkbook workbook = new HSSFWorkbook(dir, true); - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFCell cell = sheet.getRow(0).getCell(0); - assertEquals("replaceMe", cell.getRichStringCellValue().getString()); - - workbook.close(); - } - } - } - } - - @Test - void wordDocEmbeddedInXls() throws IOException { - // Open the two filesystems - DirectoryNode[] files = new DirectoryNode[2]; - try (POIFSFileSystem poifsFileSystem = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("WithEmbeddedObjects.xls"))) { - files[0] = poifsFileSystem.getRoot(); - try (POIFSFileSystem poifsFileSystem2 = new POIFSFileSystem(HSSFTestDataSamples.getSampleFile("WithEmbeddedObjects.xls"))) { - files[1] = poifsFileSystem2.getRoot(); - - // Check the embedded parts - for (DirectoryNode root : files) { - HSSFWorkbook hw = new HSSFWorkbook(root, true); - List objects = hw.getAllEmbeddedObjects(); - boolean found = false; - for (HSSFObjectData embeddedObject : objects) { - if (embeddedObject.hasDirectoryEntry()) { - DirectoryEntry dir = embeddedObject.getDirectory(); - if (dir instanceof DirectoryNode) { - DirectoryNode dNode = (DirectoryNode) dir; - if (dNode.hasEntry("WordDocument")) { - found = true; - break; - } - } - } - } - assertTrue(found); - - hw.close(); - } - } - } - } - - /** - * Checks that we can open a workbook with POIFS, and write it out - * again (via POIFS) and have it be valid - */ - @Test - void writeWorkbookFromPOIFS() throws IOException { - try (InputStream is = HSSFTestDataSamples.openSampleFileStream("WithEmbeddedObjects.xls"); - POIFSFileSystem fs = new POIFSFileSystem(is)) { - - HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot(), true); - assertEquals(3, wb.getNumberOfSheets()); - assertEquals("Root xls", wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(3, wbBack.getNumberOfSheets()); - assertEquals("Root xls", wbBack.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); - wbBack.close(); - - wb.close(); - } - } - - @Test - void cellStylesLimit() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - int numBuiltInStyles = wb.getNumCellStyles(); - int MAX_STYLES = 4030; - int limit = MAX_STYLES - numBuiltInStyles; - for (int i = 0; i < limit; i++) { - wb.createCellStyle(); - } - - assertEquals(MAX_STYLES, wb.getNumCellStyles()); - IllegalStateException e = assertThrows(IllegalStateException.class, wb::createCellStyle); - assertEquals("The maximum number of cell styles was exceeded. " + - "You can define up to 4000 styles in a .xls workbook", e.getMessage()); - assertEquals(MAX_STYLES, wb.getNumCellStyles()); - } - } - - @Test - void setSheetOrderHSSF() throws IOException{ - Workbook wb = new HSSFWorkbook(); - Sheet s1 = wb.createSheet("first sheet"); - Sheet s2 = wb.createSheet("other sheet"); - - Name name1 = wb.createName(); - name1.setNameName("name1"); - name1.setRefersToFormula("'first sheet'!D1"); - - Name name2 = wb.createName(); - name2.setNameName("name2"); - name2.setRefersToFormula("'other sheet'!C1"); - - - Row s1r1 = s1.createRow(2); - Cell c1 = s1r1.createCell(3); - c1.setCellValue(30); - Cell c2 = s1r1.createCell(2); - c2.setCellFormula("SUM('other sheet'!C1,'first sheet'!C1)"); - - Row s2r1 = s2.createRow(0); - Cell c3 = s2r1.createCell(1); - c3.setCellFormula("'first sheet'!D3"); - Cell c4 = s2r1.createCell(2); - c4.setCellFormula("'other sheet'!D3"); - - // conditional formatting - SheetConditionalFormatting sheetCF = s1.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule( - CFRuleRecord.ComparisonOperator.BETWEEN, "'first sheet'!D1", "'other sheet'!D1"); - - ConditionalFormattingRule [] cfRules = { rule1 }; - - CellRangeAddress[] regions = { - new CellRangeAddress(2, 4, 0, 0), // A3:A5 - }; - sheetCF.addConditionalFormatting(regions, cfRules); - - wb.setSheetOrder("other sheet", 0); - - // names - //noinspection ConstantConditions - assertEquals("'first sheet'!D1", wb.getName("name1").getRefersToFormula()); - //noinspection ConstantConditions - assertEquals("'other sheet'!C1", wb.getName("name2").getRefersToFormula()); - - // cells - assertEquals("SUM('other sheet'!C1,'first sheet'!C1)", c2.getCellFormula()); - assertEquals("'first sheet'!D3", c3.getCellFormula()); - assertEquals("'other sheet'!D3", c4.getCellFormula()); - - // conditional formatting - ConditionalFormatting cf = sheetCF.getConditionalFormattingAt(0); - assertEquals("'first sheet'!D1", cf.getRule(0).getFormula1()); - assertEquals("'other sheet'!D1", cf.getRule(0).getFormula2()); - - wb.close(); - } - - @Test - void clonePictures() throws IOException { - HSSFWorkbook wb = openSampleWorkbook("SimpleWithImages.xls"); - InternalWorkbook iwb = wb.getWorkbook(); - iwb.findDrawingGroup(); - - for(int pictureIndex=1; pictureIndex <= 4; pictureIndex++){ - EscherBSERecord bse = iwb.getBSERecord(pictureIndex); - assertEquals(1, bse.getRef()); - } - - wb.cloneSheet(0); - for(int pictureIndex=1; pictureIndex <= 4; pictureIndex++){ - EscherBSERecord bse = iwb.getBSERecord(pictureIndex); - assertEquals(2, bse.getRef()); - } - - wb.cloneSheet(0); - for(int pictureIndex=1; pictureIndex <= 4; pictureIndex++){ - EscherBSERecord bse = iwb.getBSERecord(pictureIndex); - assertEquals(3, bse.getRef()); - } - - wb.close(); - } - - // Should throw exception about invalid POIFSFileSystem - @Test - void emptyDirectoryNode() throws IOException { - try (POIFSFileSystem fs = new POIFSFileSystem()) { - assertThrows(IllegalArgumentException.class, () -> new HSSFWorkbook(fs).close()); - } - } - - @Test - void selectedSheetShort() throws IOException { - HSSFWorkbook wb=new HSSFWorkbook(); - - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("Sheet3"); - HSSFSheet sheet4 = wb.createSheet("Sheet4"); - - confirmActiveSelected(sheet1, true); - confirmActiveSelected(sheet2, false); - confirmActiveSelected(sheet3, false); - confirmActiveSelected(sheet4, false); - - wb.setSelectedTab((short)1); - - // Demonstrate bug 44525: - // Well... not quite, since isActive + isSelected were also added in the same bug fix - assertFalse(sheet1.isSelected(), "Identified bug 44523 a"); - wb.setActiveSheet(1); - assertFalse(sheet1.isActive(), "Identified bug 44523 b"); - - confirmActiveSelected(sheet1, false); - confirmActiveSelected(sheet2, true); - confirmActiveSelected(sheet3, false); - confirmActiveSelected(sheet4, false); - - assertEquals(0, wb.getFirstVisibleTab()); - wb.setFirstVisibleTab((short)2); - assertEquals(2, wb.getFirstVisibleTab()); - - wb.close(); - } - - @Test - void names() throws IOException { - HSSFWorkbook wb=new HSSFWorkbook(); - - IllegalStateException ex1 = assertThrows(IllegalStateException.class, () -> wb.getNameAt(0)); - assertTrue(ex1.getMessage().contains("no defined names")); - - HSSFName name = wb.createName(); - assertNotNull(name); - - assertNull(wb.getName("somename")); - - name.setNameName("myname"); - assertNotNull(wb.getName("myname")); - - assertEquals(0, wb.getNameIndex(name)); - assertEquals(0, wb.getNameIndex("myname")); - - IllegalArgumentException ex2 = assertThrows(IllegalArgumentException.class, () -> wb.getNameAt(5)); - assertTrue(ex2.getMessage().contains("outside the allowable range")); - - IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> wb.getNameAt(-3)); - assertTrue(ex.getMessage().contains("outside the allowable range")); - - wb.close(); - } - - @Test - void testMethods() throws IOException { - try (HSSFWorkbook wb=new HSSFWorkbook()) { - assertDoesNotThrow(wb::insertChartRecord); - //wb.dumpDrawingGroupRecords(true); - //wb.dumpDrawingGroupRecords(false); - } - } - - @Test - void writeProtection() throws IOException { - HSSFWorkbook wb=new HSSFWorkbook(); - - assertFalse(wb.isWriteProtected()); - - wb.writeProtectWorkbook("mypassword", "myuser"); - assertTrue(wb.isWriteProtected()); - - wb.unwriteProtectWorkbook(); - assertFalse(wb.isWriteProtected()); - - wb.close(); - } - - @Test - void bug50298() throws Exception { - HSSFWorkbook wb = openSampleWorkbook("50298.xls"); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - HSSFSheet sheet = wb.cloneSheet(0); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "Invoice (2)"); - - wb.setSheetName(wb.getSheetIndex(sheet), "copy"); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "copy"); - - wb.setSheetOrder("copy", 0); - - assertSheetOrder(wb, "copy", "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - wb.removeSheetAt(0); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - // check that the overall workbook serializes with its correct size - int expected = wb.getWorkbook().getSize(); - int written = wb.getWorkbook().serialize(0, new byte[expected*2]); - - assertEquals(expected, written, "Did not have the expected size when writing the workbook"); - - HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertSheetOrder(read, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - read.close(); - wb.close(); - } - - @Test - void bug50298a() throws Exception { - HSSFWorkbook wb = openSampleWorkbook("50298.xls"); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - HSSFSheet sheet = wb.cloneSheet(0); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "Invoice (2)"); - - wb.setSheetName(wb.getSheetIndex(sheet), "copy"); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "copy"); - - wb.setSheetOrder("copy", 0); - - assertSheetOrder(wb, "copy", "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - wb.removeSheetAt(0); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - wb.removeSheetAt(1); - - assertSheetOrder(wb, "Invoice", "Digest", "Deferred", "Received"); - - wb.setSheetOrder("Digest", 3); - - assertSheetOrder(wb, "Invoice", "Deferred", "Received", "Digest"); - - // check that the overall workbook serializes with its correct size - int expected = wb.getWorkbook().getSize(); - int written = wb.getWorkbook().serialize(0, new byte[expected*2]); - - assertEquals(expected, written, "Did not have the expected size when writing the workbook"); - - HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertSheetOrder(read, "Invoice", "Deferred", "Received", "Digest"); - read.close(); - wb.close(); - } - - @Test - void bug54500() throws Exception { - String nameName = "AName"; - String sheetName = "ASheet"; - HSSFWorkbook wb = openSampleWorkbook("54500.xls"); - - assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3"); - - wb.createSheet(sheetName); - - assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet"); - - Name n = wb.createName(); - n.setNameName(nameName); - n.setSheetIndex(3); - n.setRefersToFormula(sheetName + "!A1"); - - assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet"); - final HSSFName name = wb.getName(nameName); - assertNotNull(name); - assertEquals("ASheet!A1", name.getRefersToFormula()); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - wb.write(stream); - - assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet"); - assertEquals("ASheet!A1", name.getRefersToFormula()); - - wb.removeSheetAt(1); - - assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet"); - assertEquals("ASheet!A1", name.getRefersToFormula()); - - ByteArrayOutputStream stream2 = new ByteArrayOutputStream(); - wb.write(stream2); - - assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet"); - assertEquals("ASheet!A1", name.getRefersToFormula()); - - HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(stream.toByteArray())); - expectName(wb2, nameName, "ASheet!A1"); - HSSFWorkbook wb3 = new HSSFWorkbook(new ByteArrayInputStream(stream2.toByteArray())); - expectName(wb3, nameName, "ASheet!A1"); - wb3.close(); - wb2.close(); - wb.close(); - } - - @SuppressWarnings("SameParameterValue") - private void expectName(HSSFWorkbook wb, String name, String expect) { - final HSSFName hssfName = wb.getName(name); - assertNotNull(hssfName); - assertEquals(expect, hssfName.getRefersToFormula()); - } - - @Test - void test49423() throws Exception - { - HSSFWorkbook workbook = openSampleWorkbook("49423.xls"); - - boolean found = false; - int numSheets = workbook.getNumberOfSheets(); - for (int i = 0; i < numSheets; i++) { - HSSFSheet sheet = workbook.getSheetAt(i); - List shapes = sheet.getDrawingPatriarch().getChildren(); - for(HSSFShape shape : shapes){ - HSSFAnchor anchor = shape.getAnchor(); - - if(anchor instanceof HSSFClientAnchor){ - // absolute coordinates - HSSFClientAnchor clientAnchor = (HSSFClientAnchor)anchor; - assertNotNull(clientAnchor); - //System.out.println(clientAnchor.getRow1() + "," + clientAnchor.getRow2()); - found = true; - } else if (anchor instanceof HSSFChildAnchor){ - // shape is grouped and the anchor is expressed in the coordinate system of the group - HSSFChildAnchor childAnchor = (HSSFChildAnchor)anchor; - assertNotNull(childAnchor); - //System.out.println(childAnchor.getDy1() + "," + childAnchor.getDy2()); - found = true; - } - } - } - - assertTrue(found, "Should find some images via Client or Child anchors, but did not find any at all"); - workbook.close(); - } - - @Test - void testRewriteFileBug58480() throws IOException { - final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls"); - - try { - // create new workbook - { - final Workbook workbook = new HSSFWorkbook(); - final Sheet sheet = workbook.createSheet("foo"); - final Row row = sheet.createRow(1); - row.createCell(1).setCellValue("bar"); - - writeAndCloseWorkbook(workbook, file); - } - - // edit the workbook - { - try (POIFSFileSystem fs = new POIFSFileSystem(file, false)) { - DirectoryNode root = fs.getRoot(); - final Workbook workbook = new HSSFWorkbook(root, true); - final Sheet sheet = workbook.getSheet("foo"); - sheet.getRow(1).createCell(2).setCellValue("baz"); - - writeAndCloseWorkbook(workbook, file); - } - } - } finally { - assertTrue(file.exists()); - assertTrue(file.delete()); - } - } - - private void writeAndCloseWorkbook(Workbook workbook, File file) - throws IOException { - final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - workbook.write(bytesOut); - workbook.close(); - - final byte[] byteArray = bytesOut.toByteArray(); - bytesOut.close(); - - final FileOutputStream fileOut = new FileOutputStream(file); - fileOut.write(byteArray); - fileOut.close(); - - } - - @Test - void closeDoesNotModifyWorkbook() throws IOException { - final String filename = "SampleSS.xls"; - final File file = samples.getFile(filename); - Workbook wb; - - // File via POIFileStream (java.nio) - wb = new HSSFWorkbook(new POIFSFileSystem(file)); - assertCloseDoesNotModifyFile(filename, wb); - - // InputStream - wb = new HSSFWorkbook(new FileInputStream(file)); - assertCloseDoesNotModifyFile(filename, wb); - } - - @Test - void setSheetOrderToEnd() throws Exception { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - workbook.createSheet("A"); - workbook.createSheet("B"); - assertEquals("A", workbook.getSheetName(0)); - workbook.setSheetOrder("A", 1); - assertEquals("A", workbook.getSheetName(1)); - } - } - - @Test - void invalidInPlaceWrite() throws Exception { - // Can't work for new files - try (HSSFWorkbook wb = new HSSFWorkbook()) { - assertThrows(IllegalStateException.class, wb::write, "Shouldn't work for new files"); - } - - // Can't work for InputStream opened files - try (InputStream is = samples.openResourceAsStream("SampleSS.xls"); - HSSFWorkbook wb = new HSSFWorkbook(is)) { - assertThrows(IllegalStateException.class, wb::write, "Shouldn't work for InputStream"); - } - - // Can't work for Read-Only files - try (POIFSFileSystem fs = new POIFSFileSystem(samples.getFile("SampleSS.xls"), true); - HSSFWorkbook wb = new HSSFWorkbook(fs)) { - assertThrows(IllegalStateException.class, wb::write, "Shouldn't work for Read Only"); - } - } - - @Test - void inPlaceWrite() throws Exception { - // Setup as a copy of a known-good file - final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls"); - try (InputStream inputStream = samples.openResourceAsStream("SampleSS.xls"); - FileOutputStream outputStream = new FileOutputStream(file)) { - IOUtils.copy(inputStream, outputStream); - } - - // Open from the temp file in read-write mode - HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(file, false)); - assertEquals(3, wb.getNumberOfSheets()); - - // Change - wb.removeSheetAt(2); - wb.removeSheetAt(1); - wb.getSheetAt(0).getRow(0).getCell(0).setCellValue("Changed!"); - - // Save in-place, close, re-open and check - wb.write(); - wb.close(); - - wb = new HSSFWorkbook(new POIFSFileSystem(file)); - assertEquals(1, wb.getNumberOfSheets()); - assertEquals("Changed!", wb.getSheetAt(0).getRow(0).getCell(0).toString()); - - wb.close(); - } - - @Test - void testWriteToNewFile() throws Exception { - // Save to a new temp file - final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls"); - - // Open from a Stream - try (HSSFWorkbook wb = new HSSFWorkbook( - samples.openResourceAsStream("SampleSS.xls"))) { - wb.write(file); - } - - // Read and check - try (HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(file))) { - assertEquals(3, wb.getNumberOfSheets()); - } - } - - void createDrawing() throws Exception { - // the dimensions for this image are different than for XSSF and SXSSF - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestMatrixFormulasFromBinarySpreadsheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestMatrixFormulasFromBinarySpreadsheet.java deleted file mode 100644 index d56c3d6134..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestMatrixFormulasFromBinarySpreadsheet.java +++ /dev/null @@ -1,223 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.logging.log4j.util.Unbox.box; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.stream.Stream; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.functions.TestMathX; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -final class TestMatrixFormulasFromBinarySpreadsheet { - - private static final Logger LOG = LogManager.getLogger(TestMatrixFormulasFromBinarySpreadsheet.class); - - - private static HSSFWorkbook workbook; - private static Sheet sheet; - private static FormulaEvaluator evaluator; - private static Locale userLocale; - - /* - * Unlike TestFormulaFromSpreadsheet which this class is modified from, there is no - * differentiation between operators and functions, if more functionality is implemented with - * array formulas then it might be worth it to separate operators from functions - * - * Also, output matrices are statically 3x3, if larger matrices wanted to be tested - * then adding matrix size parameter would be useful and parsing would be based off that. - */ - - private interface Navigator { - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - String FILENAME = "MatrixFormulaEvalTestData.xls"; - /** - * Row (zero-based) in the spreadsheet where operations start - */ - int START_OPERATORS_ROW_INDEX = 1; - /** - * Column (zero-based) in the spreadsheet where operations start - */ - int START_OPERATORS_COL_INDEX = 0; - /** - * Column (zero-based) in the spreadsheet where evaluations start - */ - int START_RESULT_COL_INDEX = 7; - /** - * Column separation in the spreadsheet between evaluations and expected results - */ - int COL_OFF_EXPECTED_RESULT = 3; - /** - * Row separation in the spreadsheet between operations - */ - int ROW_OFF_NEXT_OP = 4; - /** - * Used to indicate when there are no more operations left - */ - String END_OF_TESTS = ""; - - } - - /* Parameters for test case */ - - @AfterAll - public static void closeResource() throws Exception { - LocaleUtil.setUserLocale(userLocale); - workbook.close(); - } - - /* generating parameter instances */ - public static Stream data() throws Exception { - // Function "Text" uses custom-formats which are locale specific - // can't set the locale on a per-testrun execution, as some settings have been - // already set, when we would try to change the locale by then - userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.ROOT); - - workbook = HSSFTestDataSamples.openSampleWorkbook(Navigator.FILENAME); - sheet = workbook.getSheetAt(0); - evaluator = new HSSFFormulaEvaluator(workbook); - - List data = new ArrayList<>(); - - processFunctionGroup(data); - - return data.stream(); - } - - private static void processFunctionGroup(List data) { - int startRowIndex = Navigator.START_OPERATORS_ROW_INDEX; - for (int rowIndex = startRowIndex; true; rowIndex += Navigator.ROW_OFF_NEXT_OP) { - Row r = sheet.getRow(rowIndex); - String targetFunctionName = getTargetFunctionName(r); - assertNotNull(targetFunctionName, "Test spreadsheet cell empty on row (" - + (rowIndex) + "). Expected function name or '" - + Navigator.END_OF_TESTS + "'"); - if(targetFunctionName.equals(Navigator.END_OF_TESTS)) { - // found end of functions list - break; - } - data.add(Arguments.of(targetFunctionName, rowIndex)); - } - } - - @ParameterizedTest - @MethodSource("data") - void processFunctionRow(String targetFunctionName, int formulasRowIdx) { - - int endColNum = Navigator.START_RESULT_COL_INDEX + Navigator.COL_OFF_EXPECTED_RESULT; - - for (int rowNum = formulasRowIdx; rowNum < formulasRowIdx + Navigator.ROW_OFF_NEXT_OP - 1; rowNum++) { - for (int colNum = Navigator.START_RESULT_COL_INDEX; colNum < endColNum; colNum++) { - Row r = sheet.getRow(rowNum); - - /* mainly to escape row failures on MDETERM which only returns a scalar */ - if (r == null) { - continue; - } - - Cell c = sheet.getRow(rowNum).getCell(colNum); - - if (c == null || c.getCellType() != CellType.FORMULA) { - continue; - } - - CellValue actValue = evaluator.evaluate(c); - Cell expValue = sheet.getRow(rowNum).getCell(colNum + Navigator.COL_OFF_EXPECTED_RESULT); - - String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" - , targetFunctionName, c.getCellFormula(), rowNum, colNum); - - assertNotNull(expValue, msg + " - Bad setup data expected value is null"); - assertNotNull(actValue, msg + " - actual value was null"); - - final CellType cellType = expValue.getCellType(); - switch (cellType) { - case BLANK: - assertEquals(CellType.BLANK, actValue.getCellType(), msg); - break; - case BOOLEAN: - assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); - assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); - break; - case ERROR: - assertEquals(CellType.ERROR, actValue.getCellType(), msg); - assertEquals(ErrorEval.getText(expValue.getErrorCellValue()), ErrorEval.getText(actValue.getErrorValue()), msg); - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - fail("Cannot expect formula as result of formula evaluation: " + msg); - break; - case NUMERIC: - assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); - TestMathX.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); - break; - case STRING: - assertEquals(CellType.STRING, actValue.getCellType(), msg); - assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); - break; - default: - fail("Unexpected cell type: " + cellType); - } - } - } - } - - /** - * @return null if cell is missing, empty or blank - */ - private static String getTargetFunctionName(Row r) { - if(r == null) { - LOG.atWarn().log("Warning - given null row, can't figure out function name"); - return null; - } - Cell cell = r.getCell(Navigator.START_OPERATORS_COL_INDEX); - LOG.atInfo().log("{}", box(Navigator.START_OPERATORS_COL_INDEX)); - if(cell == null) { - LOG.atWarn().log("Row {} has no cell " + Navigator.START_OPERATORS_COL_INDEX + ", can't figure out function name", box(r.getRowNum())); - return null; - } - - CellType ct = cell.getCellType(); - assertTrue(ct == CellType.BLANK || ct == CellType.STRING, - "Bad cell type for 'function name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null; - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java b/src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java deleted file mode 100644 index 6f8bc8dfbb..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java +++ /dev/null @@ -1,134 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.junit.jupiter.api.Test; - -/** - * Tests for how HSSFWorkbook behaves with XLS files - * with a WORKBOOK or BOOK directory entry (instead of - * the more usual, Workbook) - */ -final class TestNonStandardWorkbookStreamNames { - private final String xlsA = "WORKBOOK_in_capitals.xls"; - private final String xlsB = "BOOK_in_capitals.xls"; - - /** - * Test that we can open a file with WORKBOOK - */ - @Test - void testOpenWORKBOOK() throws IOException { - // Try to open the workbook - InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA); - HSSFWorkbook wb = new HSSFWorkbook(is); - is.close(); - DirectoryNode root = wb.getDirectory(); - - // Ensure that we have a WORKBOOK entry and a summary - assertTrue(root.hasEntry("WORKBOOK")); - assertTrue(root.hasEntry(SummaryInformation.DEFAULT_STREAM_NAME)); - - // But not a Workbook one - assertFalse(root.hasEntry("Workbook")); - - wb.close(); - } - - /** - * Test that we can open a file with BOOK - */ - @Test - void testOpenBOOK() throws IOException { - // Try to open the workbook - InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsB); - HSSFWorkbook wb = new HSSFWorkbook(is); - is.close(); - DirectoryNode root = wb.getDirectory(); - - // Ensure that we have a BOOK entry - assertTrue(root.hasEntry("BOOK")); - - // But not a Workbook one and not a Summary one - assertFalse(root.hasEntry("Workbook")); - assertFalse(root.hasEntry(SummaryInformation.DEFAULT_STREAM_NAME)); - - wb.close(); - } - - /** - * Test that when we write out, we go back to the correct case - */ - @Test - void testWrite() throws IOException { - for (String file : new String[] {xlsA, xlsB}) { - // Open the workbook, not preserving nodes - InputStream is = HSSFTestDataSamples.openSampleFileStream(file); - HSSFWorkbook wb = new HSSFWorkbook(is, false); - is.close(); - - // Check now it can be opened - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - - DirectoryNode root = wb2.getDirectory(); - - // Check that we have the new entries - assertTrue(root.hasEntry("Workbook")); - assertFalse(root.hasEntry("BOOK")); - assertFalse(root.hasEntry("WORKBOOK")); - - wb2.close(); - } - } - - /** - * Test that when we write out preserving nodes, we go back to the - * correct case - */ - @Test - void testWritePreserve() throws IOException { - // Open the workbook, not preserving nodes - InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA); - HSSFWorkbook wb = new HSSFWorkbook(is,true); - is.close(); - - // Check now it can be opened - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - - DirectoryNode root = wb2.getDirectory(); - - // Check that we have the new entries - assertTrue(root.hasEntry("Workbook")); - assertFalse(root.hasEntry("BOOK")); - assertFalse(root.hasEntry("WORKBOOK")); - - // As we preserved, should also have a few other streams - assertTrue(root.hasEntry(SummaryInformation.DEFAULT_STREAM_NAME)); - wb2.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java b/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java deleted file mode 100644 index 1183c5f6b5..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java +++ /dev/null @@ -1,156 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Ole10Native; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -final class TestOLE2Embeding { - - @Test - void testEmbeding() throws Exception { - // This used to break, until bug #43116 was fixed - try (HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls")) { - // Check we can get at the Escher layer still - assertDoesNotThrow(workbook::getAllPictures); - } - } - - @Test - void testEmbeddedObjects() throws Exception { - try (HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls")) { - List objects = workbook.getAllEmbeddedObjects(); - assertEquals(2, objects.size(), "Wrong number of objects"); - assertEquals("MBD06CAB431", objects.get(0).getDirectory().getName(), "Wrong name for first object"); - assertEquals("MBD06CAC85A", objects.get(1).getDirectory().getName(), "Wrong name for second object"); - } - } - - @Test - void testReallyEmbedSomething() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png"); - byte[] picturePPT = POIDataSamples.getSlideShowInstance().readFile("clock.jpg"); - int imgIdx = wb1.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG); - POIFSFileSystem pptPoifs = getSamplePPT(); - int pptIdx = wb1.addOlePackage(pptPoifs, "Sample-PPT", "sample.ppt", "sample.ppt"); - POIFSFileSystem xlsPoifs = getSampleXLS(); - int imgPPT = wb1.addPicture(picturePPT, HSSFWorkbook.PICTURE_TYPE_JPEG); - int xlsIdx = wb1.addOlePackage(xlsPoifs, "Sample-XLS", "sample.xls", "sample.xls"); - int txtIdx = wb1.addOlePackage(getSampleTXT(), "Sample-TXT", "sample.txt", "sample.txt"); - - int rowoffset = 5; - int coloffset = 5; - - CreationHelper ch = wb1.getCreationHelper(); - HSSFClientAnchor anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(2+coloffset), 1+rowoffset, 0, 0, (short)(3+coloffset), 5+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - patriarch.createObjectData(anchor, pptIdx, imgPPT); - - anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(5+coloffset), 1+rowoffset, 0, 0, (short)(6+coloffset), 5+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - patriarch.createObjectData(anchor, xlsIdx, imgIdx); - - anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(3+coloffset), 10+rowoffset, 0, 0, (short)(5+coloffset), 11+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - patriarch.createObjectData(anchor, txtIdx, imgIdx); - - anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(1+coloffset), -2+rowoffset, 0, 0, (short)(7+coloffset), 14+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - HSSFSimpleShape circle = patriarch.createSimpleShape(anchor); - circle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL); - circle.setNoFill(true); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - HSSFObjectData od = wb2.getAllEmbeddedObjects().get(0); - Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory()); - bos.reset(); - pptPoifs.writeFilesystem(bos); - assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray()); - - od = wb2.getAllEmbeddedObjects().get(1); - ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory()); - bos.reset(); - xlsPoifs.writeFilesystem(bos); - assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray()); - - od = wb2.getAllEmbeddedObjects().get(2); - ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory()); - assertArrayEquals(ole10.getDataBuffer(), getSampleTXT()); - - xlsPoifs.close(); - pptPoifs.close(); - wb2.close(); - } - - static POIFSFileSystem getSamplePPT() throws IOException { - // scratchpad classes are not available, so we use something pre-cooked - InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream("with_textbox.ppt"); - POIFSFileSystem poifs = new POIFSFileSystem(is); - is.close(); - - return poifs; - } - - static POIFSFileSystem getSampleXLS() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - sheet.createRow(5).createCell(2).setCellValue("yo dawg i herd you like embeddet objekts, so we put a ole in your ole so you can save a file while you save a file"); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - wb.write(bos); - wb.close(); - - return new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - } - - static byte[] getSampleTXT() { - return "All your base are belong to us".getBytes(LocaleUtil.CHARSET_1252); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java deleted file mode 100644 index 6d62955f0c..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java +++ /dev/null @@ -1,115 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hpsf.*; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.HexDump; -import org.junit.jupiter.api.Test; - -/** - * Old-style setting of POIFS properties doesn't work with POI 3.0.2 - */ -class TestPOIFSProperties { - private static final String title = "Testing POIFS properties"; - - @Test - void testFail() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - { // read the workbook, adjust the SummaryInformation and write the data to a byte array - POIFSFileSystem fs = openFileSystem(); - - HSSFWorkbook wb = new HSSFWorkbook(fs); - - //set POIFS properties after constructing HSSFWorkbook - //(a piece of code that used to work up to POI 3.0.2) - setTitle(fs); - - //save the workbook and read the property - wb.write(out); - out.close(); - wb.close(); - } - - // process the byte array - checkFromByteArray(out.toByteArray()); - } - - @Test - void testOK() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - { // read the workbook, adjust the SummaryInformation and write the data to a byte array - POIFSFileSystem fs = openFileSystem(); - - //set POIFS properties before constructing HSSFWorkbook - setTitle(fs); - - HSSFWorkbook wb = new HSSFWorkbook(fs); - - wb.write(out); - out.close(); - wb.close(); - } - - // process the byte array - checkFromByteArray(out.toByteArray()); - } - - private POIFSFileSystem openFileSystem() throws IOException { - InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls"); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - return fs; - } - - private void setTitle(POIFSFileSystem fs) throws NoPropertySetStreamException, MarkUnsupportedException, IOException, WritingNotSupportedException { - SummaryInformation summary1 = (SummaryInformation) PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); - assertNotNull(summary1); - - summary1.setTitle(title); - //write the modified property back to POIFS - fs.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME).delete(); - fs.createDocument(summary1.toInputStream(), SummaryInformation.DEFAULT_STREAM_NAME); - - // check that the information was added successfully to the filesystem object - SummaryInformation summaryCheck = (SummaryInformation) PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); - assertNotNull(summaryCheck); - } - - private void checkFromByteArray(byte[] bytes) throws IOException, NoPropertySetStreamException, MarkUnsupportedException { - // on some environments in CI we see strange failures, let's verify that the size is exactly right - // this can be removed again after the problem is identified - assertEquals(5120, bytes.length, "Had: " + HexDump.toHex(bytes)); - - POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes)); - SummaryInformation summary2 = (SummaryInformation) PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); - assertNotNull(summary2); - - assertEquals(title, summary2.getTitle()); - fs2.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java deleted file mode 100644 index 341be15819..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.EscherAggregate; -import org.junit.jupiter.api.Test; - -class TestPatriarch { - @Test - void testGetPatriarch(){ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - assertNull(sh.getDrawingPatriarch()); - - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - assertNotNull(patriarch); - patriarch.createSimpleShape(new HSSFClientAnchor()); - patriarch.createSimpleShape(new HSSFClientAnchor()); - - assertSame(patriarch, sh.getDrawingPatriarch()); - - EscherAggregate agg = patriarch.getBoundAggregate(); - - EscherDgRecord dg = agg.getEscherContainer().getChildById(EscherDgRecord.RECORD_ID); - assertNotNull(dg); - int lastId = dg.getLastMSOSPID(); - - assertSame(patriarch, sh.createDrawingPatriarch()); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wb.getSheetAt(0); - patriarch = sh.createDrawingPatriarch(); - dg = patriarch.getBoundAggregate().getEscherContainer().getChildById(EscherDgRecord.RECORD_ID); - - assertNotNull(dg); - assertEquals(lastId, dg.getLastMSOSPID()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java deleted file mode 100644 index 759e790a6f..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java +++ /dev/null @@ -1,283 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ddf.EscherArrayProperty; -import org.apache.poi.ddf.EscherPropertyTypes; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.ObjRecord; -import org.junit.jupiter.api.Test; - -class TestPolygon { - @Test - void testResultEqualsToAbstractShape() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPolygonDrawArea( 100, 100 ); - polygon.setPoints( new int[]{0, 90, 50}, new int[]{5, 5, 44} ); - polygon.setShapeId(1024); - - assertEquals(polygon.getEscherContainer().getChildCount(), 4); - - //sp record - byte[] expected = decompress("H4sIAAAAAAAAAGNi4PrAwQAELEDMxcAAAAU6ZlwQAAAA"); - byte[] actual = polygon.getEscherContainer().getChild(0).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPggxIANAABK4+laGgAAAA=="); - actual = polygon.getEscherContainer().getChild(2).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPzAAAQACl6c5QgAAAA="); - actual = polygon.getEscherContainer().getChild(3).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - ObjRecord obj = polygon.getObjRecord(); - - expected = decompress("H4sIAAAAAAAAAItlkGIQZRBikGNgYBBMYEADAOAV/ZkeAAAA"); - actual = obj.serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - wb.close(); - } - - @Test - void testPolygonPoints() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPolygonDrawArea( 100, 100 ); - polygon.setPoints( new int[]{0, 90, 50, 90}, new int[]{5, 5, 44, 88} ); - - EscherArrayProperty verticesProp1 = polygon.getOptRecord().lookup(EscherPropertyTypes.GEOMETRY__VERTICES); - - String expected = - "" + - "" + - "BQAFAPD/AAAFAFoABQAyACwAWgBYAAAABQA=" + - "" + - "AAAFAA==" + - "WgAFAA==" + - "MgAsAA==" + - "WgBYAA==" + - "AAAFAA==" + - "" + - ""; - String actual = verticesProp1.toXml("").replaceAll("[\r\n\t]",""); - - assertEquals(verticesProp1.getNumberOfElementsInArray(), 5); - assertEquals(expected, actual); - - polygon.setPoints(new int[]{1,2,3}, new int[] {4,5,6}); - assertArrayEquals(polygon.getXPoints(), new int[]{1, 2, 3}); - assertArrayEquals(polygon.getYPoints(), new int[]{4, 5, 6}); - - verticesProp1 = polygon.getOptRecord().lookup(EscherPropertyTypes.GEOMETRY__VERTICES); - - expected = - "" + - "" + - "BAAEAPD/AQAEAAIABQADAAYAAQAEAA==" + - "" + - "AQAEAA==" + - "AgAFAA==" + - "AwAGAA==" + - "AQAEAA==" + - ""; - actual = verticesProp1.toXml("").replaceAll("[\r\n\t]",""); - - assertEquals(verticesProp1.getNumberOfElementsInArray(), 4); - assertEquals(expected, actual); - - wb.close(); - } - - @Test - void testSetGetProperties() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPolygonDrawArea( 102, 101 ); - polygon.setPoints( new int[]{1,2,3}, new int[]{4,5,6} ); - - assertArrayEquals(polygon.getXPoints(), new int[]{1,2,3}); - assertArrayEquals(polygon.getYPoints(), new int[]{4, 5, 6}); - assertEquals(polygon.getDrawAreaHeight(), 101); - assertEquals(polygon.getDrawAreaWidth(), 102); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - polygon = (HSSFPolygon) patriarch.getChildren().get(0); - assertArrayEquals(polygon.getXPoints(), new int[]{1, 2, 3}); - assertArrayEquals(polygon.getYPoints(), new int[]{4, 5, 6}); - assertEquals(polygon.getDrawAreaHeight(), 101); - assertEquals(polygon.getDrawAreaWidth(), 102); - - polygon.setPolygonDrawArea( 1021, 1011 ); - polygon.setPoints( new int[]{11,21,31}, new int[]{41,51,61} ); - - assertArrayEquals(polygon.getXPoints(), new int[]{11, 21, 31}); - assertArrayEquals(polygon.getYPoints(), new int[]{41, 51, 61}); - assertEquals(polygon.getDrawAreaHeight(), 1011); - assertEquals(polygon.getDrawAreaWidth(), 1021); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sh = wb3.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - polygon = (HSSFPolygon) patriarch.getChildren().get(0); - - assertArrayEquals(polygon.getXPoints(), new int[]{11, 21, 31}); - assertArrayEquals(polygon.getYPoints(), new int[]{41, 51, 61}); - assertEquals(polygon.getDrawAreaHeight(), 1011); - assertEquals(polygon.getDrawAreaWidth(), 1021); - - wb3.close(); - } - - @Test - void testAddToExistingFile() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPolygonDrawArea( 102, 101 ); - polygon.setPoints( new int[]{1,2,3}, new int[]{4,5,6} ); - - HSSFPolygon polygon1 = patriarch.createPolygon(new HSSFClientAnchor()); - polygon1.setPolygonDrawArea( 103, 104 ); - polygon1.setPoints( new int[]{11,12,13}, new int[]{14,15,16} ); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 2); - - HSSFPolygon polygon2 = patriarch.createPolygon(new HSSFClientAnchor()); - polygon2.setPolygonDrawArea( 203, 204 ); - polygon2.setPoints( new int[]{21,22,23}, new int[]{24,25,26} ); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sh = wb3.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 3); - - polygon = (HSSFPolygon) patriarch.getChildren().get(0); - polygon1 = (HSSFPolygon) patriarch.getChildren().get(1); - polygon2 = (HSSFPolygon) patriarch.getChildren().get(2); - - assertArrayEquals(polygon.getXPoints(), new int[]{1, 2, 3}); - assertArrayEquals(polygon.getYPoints(), new int[]{4,5,6}); - assertEquals(polygon.getDrawAreaHeight(), 101); - assertEquals(polygon.getDrawAreaWidth(), 102); - - assertArrayEquals(polygon1.getXPoints(), new int[]{11,12,13}); - assertArrayEquals(polygon1.getYPoints(), new int[]{14,15,16}); - assertEquals(polygon1.getDrawAreaHeight(), 104); - assertEquals(polygon1.getDrawAreaWidth(), 103); - - assertArrayEquals(polygon2.getXPoints(), new int[]{21,22,23}); - assertArrayEquals(polygon2.getYPoints(), new int[]{24,25,26}); - assertEquals(polygon2.getDrawAreaHeight(), 204); - assertEquals(polygon2.getDrawAreaWidth(), 203); - - wb3.close(); - } - - @Test - void testExistingFile() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("polygon"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - - HSSFPolygon polygon = (HSSFPolygon) drawing.getChildren().get(0); - assertEquals(polygon.getDrawAreaHeight(), 2466975); - assertEquals(polygon.getDrawAreaWidth(), 3686175); - assertArrayEquals(polygon.getXPoints(), new int[]{0, 0, 31479, 16159, 19676, 20502}); - assertArrayEquals(polygon.getYPoints(), new int[]{0, 0, 36, 56, 34, 18}); - - wb.close(); - } - - @Test - void testPolygonType() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPolygonDrawArea( 102, 101 ); - polygon.setPoints( new int[]{1,2,3}, new int[]{4,5,6} ); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - HSSFPolygon polygon1 = patriarch.createPolygon(new HSSFClientAnchor()); - polygon1.setPolygonDrawArea( 102, 101 ); - polygon1.setPoints( new int[]{1,2,3}, new int[]{4,5,6} ); - - EscherSpRecord spRecord = polygon1.getEscherContainer().getChildById(EscherSpRecord.RECORD_ID); - - spRecord.setShapeType((short)77/*RANDOM*/); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sh = wb3.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 2); - assertTrue(patriarch.getChildren().get(0) instanceof HSSFPolygon); - assertTrue(patriarch.getChildren().get(1) instanceof HSSFPolygon); - wb3.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java b/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java deleted file mode 100644 index f1e9f0ef1f..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * @author Glen Stampoultzis (glens at apache.org) - */ -final class TestReadWriteChart { - - /** - * In the presence of a chart we need to make sure BOF/EOF records still exist. - */ - @Test - void testBOFandEOFRecords() throws Exception { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleChart.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFRow firstRow = sheet.getRow(0); - HSSFCell firstCell = firstRow.getCell(0); - - //System.out.println("first assertion for date"); - Calendar calExp = LocaleUtil.getLocaleCalendar(2000, 0, 1, 10, 51, 2); - Date dateAct = DateUtil.getJavaDate(firstCell.getNumericCellValue(), false); - assertEquals(calExp.getTime(), dateAct); - HSSFRow row = sheet.createRow(15); - HSSFCell cell = row.createCell(1); - - cell.setCellValue(22); - InternalSheet newSheet = workbook.getSheetAt(0).getSheet(); - List records = newSheet.getRecords(); - - assertTrue(records.get(0) instanceof BOFRecord); - assertTrue(records.get(records.size() - 1) instanceof EOFRecord); - - workbook.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.java b/src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.java deleted file mode 100644 index 5bde759a5c..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.java +++ /dev/null @@ -1,174 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.junit.jupiter.api.Test; - -/** - * Class to test row styling functionality - */ -final class TestRowStyle { - - /** - * TEST NAME: Test Write Sheet Font

- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with fonts.

- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (99,0).

- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

- */ - @Test - void testWriteSheetFont() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - HSSFFont fnt = wb.createFont(); - HSSFCellStyle cs = wb.createCellStyle(); - - fnt.setColor(HSSFFont.COLOR_RED); - fnt.setBold(true); - cs.setFont(fnt); - for (int rownum = 0; rownum < 100; rownum++) { - HSSFRow r = s.createRow(rownum); - r.setRowStyle(cs); - r.createCell(0); - } - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) { - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb2); - assertEquals(99, s.getLastRowNum(), "LAST ROW == 99"); - assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0"); - } - } - } - - /** - * Tests that is creating a file with a date or an calendar works correctly. - */ - @Test - void testDataStyle() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - HSSFCellStyle cs = wb.createCellStyle(); - HSSFRow row = s.createRow(0); - - // with Date: - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); - row.setRowStyle(cs); - row.createCell(0); - - - // with Calendar: - row = s.createRow(1); - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); - row.setRowStyle(cs); - row.createCell(0); - - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) { - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb2); - - assertEquals(1, s.getLastRowNum(), "LAST ROW"); - assertEquals(0, s.getFirstRowNum(), "FIRST ROW"); - } - } - } - - /** - * TEST NAME: Test Write Sheet Style

- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with colors - * and borders.

- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (99,0).

- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

- */ - @Test - void testWriteSheetStyle() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet s = wb.createSheet(); - HSSFFont fnt = wb.createFont(); - HSSFCellStyle cs = wb.createCellStyle(); - HSSFCellStyle cs2 = wb.createCellStyle(); - - cs.setBorderBottom(BorderStyle.THIN); - cs.setBorderLeft(BorderStyle.THIN); - cs.setBorderRight(BorderStyle.THIN); - cs.setBorderTop(BorderStyle.THIN); - cs.setFillForegroundColor((short) 0xA); - cs.setFillPattern(FillPatternType.BRICKS); - fnt.setColor((short) 0xf); - fnt.setItalic(true); - cs2.setFillForegroundColor((short) 0x0); - cs2.setFillPattern(FillPatternType.BRICKS); - cs2.setFont(fnt); - for (int rownum = 0; rownum < 100; rownum++) { - HSSFRow r = s.createRow(rownum); - r.setRowStyle(cs); - r.createCell(0); - - rownum++; - if (rownum >= 100) break; // I feel too lazy to check if this isreqd :-/ - - r = s.createRow(rownum); - r.setRowStyle(cs2); - r.createCell(0); - } - try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) { - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb2); - assertEquals(99, s.getLastRowNum(), "LAST ROW == 99"); - assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0"); - - s = wb2.getSheetAt(0); - assertNotNull(s, "Sheet is not null"); - - for (int rownum = 0; rownum < 100; rownum++) { - HSSFRow r = s.getRow(rownum); - assertNotNull(r, "Row is not null"); - - cs = r.getRowStyle(); - assertNotNull(cs); - assertEquals(BorderStyle.THIN, cs.getBorderBottom(), "Bottom Border Style for row:"); - assertEquals(BorderStyle.THIN, cs.getBorderLeft(), "Left Border Style for row:"); - assertEquals(BorderStyle.THIN, cs.getBorderRight(), "Right Border Style for row:"); - assertEquals(BorderStyle.THIN, cs.getBorderTop(), "Top Border Style for row:"); - assertEquals(0xA, cs.getFillForegroundColor(), "FillForegroundColor for row:"); - assertEquals(FillPatternType.BRICKS, cs.getFillPattern(), "FillPattern for row:"); - - rownum++; - if (rownum >= 100) break; // I feel too lazy to check if this isreqd :-/ - - r = s.getRow(rownum); - assertNotNull(r, "Row is not null"); - cs2 = r.getRowStyle(); - assertNotNull(cs2); - assertEquals(cs2.getFillForegroundColor(), (short) 0x0, "FillForegroundColor for row:"); - assertEquals(cs2.getFillPattern(), FillPatternType.BRICKS, "FillPattern for row:"); - } - } - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java b/src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java deleted file mode 100644 index 428fb3030e..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java +++ /dev/null @@ -1,128 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.BoundSheetRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.InterfaceHdrRecord; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.usermodel.SanityChecker.CheckRecord; -import org.junit.jupiter.api.Test; - -/** - * A Test case for a test utility class.
- * Okay, this may seem strange but I need to test my test logic. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -final class TestSanityChecker { - private static final Record INTERFACEHDR = new InterfaceHdrRecord(InterfaceHdrRecord.CODEPAGE); - private static BoundSheetRecord createBoundSheetRec() { - return new BoundSheetRecord("Sheet1"); - } - - @Test - void testCheckRecordOrder() { - final SanityChecker c = new SanityChecker(); - List records = new ArrayList<>(); - records.add(new BOFRecord()); - records.add(INTERFACEHDR); - records.add(createBoundSheetRec()); - records.add(EOFRecord.instance); - CheckRecord[] check = { - new CheckRecord(BOFRecord.class, '1'), - new CheckRecord(InterfaceHdrRecord.class, '0'), - new CheckRecord(BoundSheetRecord.class, 'M'), - new CheckRecord(NameRecord.class, '*'), - new CheckRecord(EOFRecord.class, '1'), - }; - // check pass - c.checkRecordOrder(records, check); - records.add(2, createBoundSheetRec()); - c.checkRecordOrder(records, check); - records.remove(1); // optional record missing - c.checkRecordOrder(records, check); - records.add(3, new NameRecord()); - records.add(3, new NameRecord()); // optional multiple record occurs more than one time - c.checkRecordOrder(records, check); - - // check fail - confirmBadRecordOrder(check, new Record[] { - new BOFRecord(), - createBoundSheetRec(), - INTERFACEHDR, - EOFRecord.instance, - }); - - confirmBadRecordOrder(check, new Record[] { - new BOFRecord(), - INTERFACEHDR, - createBoundSheetRec(), - INTERFACEHDR, - EOFRecord.instance, - }); - - confirmBadRecordOrder(check, new Record[] { - new BOFRecord(), - createBoundSheetRec(), - new NameRecord(), - EOFRecord.instance, - new NameRecord(), - }); - - confirmBadRecordOrder(check, new Record[] { - INTERFACEHDR, - createBoundSheetRec(), - EOFRecord.instance, - }); - - confirmBadRecordOrder(check, new Record[] { - new BOFRecord(), - INTERFACEHDR, - EOFRecord.instance, - }); - - confirmBadRecordOrder(check, new Record[] { - INTERFACEHDR, - createBoundSheetRec(), - new BOFRecord(), - EOFRecord.instance, - }); - - confirmBadRecordOrder(check, new Record[] { - new BOFRecord(), - createBoundSheetRec(), - INTERFACEHDR, - EOFRecord.instance, - }); - } - - private static void confirmBadRecordOrder(final SanityChecker.CheckRecord[] check, Record[] recs) { - final SanityChecker c = new SanityChecker(); - final List records = Arrays.asList(recs); - assertThrows(AssertionError.class, () -> c.checkRecordOrder(records, check)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java b/src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java deleted file mode 100644 index b02fa4fc7a..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java +++ /dev/null @@ -1,287 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.POITestCase; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherSpgrRecord; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.EscherAggregate; -import org.junit.jupiter.api.Test; - -class TestShapeGroup { - - @Test - void testSetGetCoordinates() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); - assertEquals(group.getX1(), 0); - assertEquals(group.getY1(), 0); - assertEquals(group.getX2(), 1023); - assertEquals(group.getY2(), 255); - - group.setCoordinates(1,2,3,4); - - assertEquals(group.getX1(), 1); - assertEquals(group.getY1(), 2); - assertEquals(group.getX2(), 3); - assertEquals(group.getY2(), 4); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - group = (HSSFShapeGroup) patriarch.getChildren().get(0); - assertEquals(group.getX1(), 1); - assertEquals(group.getY1(), 2); - assertEquals(group.getX2(), 3); - assertEquals(group.getY2(), 4); - wb2.close(); - } - - @Test - void testAddToExistingFile() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - HSSFShapeGroup group1 = patriarch.createGroup(new HSSFClientAnchor()); - HSSFShapeGroup group2 = patriarch.createGroup(new HSSFClientAnchor()); - - group1.setCoordinates(1,2,3,4); - group2.setCoordinates(5,6,7,8); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 2); - - HSSFShapeGroup group3 = patriarch.createGroup(new HSSFClientAnchor()); - group3.setCoordinates(9,10,11,12); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sh = wb3.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 3); - wb3.close(); - } - - @Test - void testModify() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - - // create a sheet with a text box - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFShapeGroup group1 = patriarch.createGroup(new - HSSFClientAnchor(0,0,0,0, - (short)0, 0, (short)15, 25)); - group1.setCoordinates(0, 0, 792, 612); - - HSSFTextbox textbox1 = group1.createTextbox(new - HSSFChildAnchor(100, 100, 300, 300)); - HSSFRichTextString rt1 = new HSSFRichTextString("Hello, World!"); - textbox1.setString(rt1); - - // write, read back and check that our text box is there - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - assertEquals(1, patriarch.getChildren().size()); - - group1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - assertEquals(1, group1.getChildren().size()); - textbox1 = (HSSFTextbox)group1.getChildren().get(0); - assertEquals("Hello, World!", textbox1.getString().getString()); - - // modify anchor - assertEquals(new HSSFChildAnchor(100, 100, 300, 300), - textbox1.getAnchor()); - HSSFChildAnchor newAnchor = new HSSFChildAnchor(200,200, 400, 400); - textbox1.setAnchor(newAnchor); - // modify text - textbox1.setString(new HSSFRichTextString("Hello, World! (modified)")); - - // add a new text box - HSSFTextbox textbox2 = group1.createTextbox(new - HSSFChildAnchor(400, 400, 600, 600)); - HSSFRichTextString rt2 = new HSSFRichTextString("Hello, World-2"); - textbox2.setString(rt2); - assertEquals(2, group1.getChildren().size()); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sheet = wb3.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - assertEquals(1, patriarch.getChildren().size()); - - group1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - assertEquals(2, group1.getChildren().size()); - textbox1 = (HSSFTextbox)group1.getChildren().get(0); - assertEquals("Hello, World! (modified)", - textbox1.getString().getString()); - assertEquals(new HSSFChildAnchor(200,200, 400, 400), - textbox1.getAnchor()); - - textbox2 = (HSSFTextbox)group1.getChildren().get(1); - assertEquals("Hello, World-2", textbox2.getString().getString()); - assertEquals(new HSSFChildAnchor(400, 400, 600, 600), - textbox2.getAnchor()); - - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3); - wb3.close(); - sheet = wb4.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - group1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - textbox1 = (HSSFTextbox)group1.getChildren().get(0); - textbox2 = (HSSFTextbox)group1.getChildren().get(1); - HSSFTextbox textbox3 = group1.createTextbox(new - HSSFChildAnchor(400,200, 600, 400)); - HSSFRichTextString rt3 = new HSSFRichTextString("Hello, World-3"); - textbox3.setString(rt3); - wb4.close(); - } - - @Test - void testAddShapesToGroup() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - - // create a sheet with a text box - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); - int index = wb1.addPicture(new byte[]{1,2,3}, HSSFWorkbook.PICTURE_TYPE_JPEG); - group.createPicture(new HSSFChildAnchor(), index); - HSSFPolygon polygon = group.createPolygon(new HSSFChildAnchor()); - polygon.setPoints(new int[]{1,100, 1}, new int[]{1, 50, 100}); - group.createTextbox(new HSSFChildAnchor()); - group.createShape(new HSSFChildAnchor()); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - assertEquals(1, patriarch.getChildren().size()); - - assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup); - group = (HSSFShapeGroup) patriarch.getChildren().get(0); - - assertEquals(group.getChildren().size(), 4); - - assertTrue(group.getChildren().get(0) instanceof HSSFPicture); - assertTrue(group.getChildren().get(1) instanceof HSSFPolygon); - assertTrue(group.getChildren().get(2) instanceof HSSFTextbox); - assertTrue(group.getChildren().get(3) instanceof HSSFSimpleShape); - - HSSFShapeGroup group2 = patriarch.createGroup(new HSSFClientAnchor()); - - index = wb2.addPicture(new byte[]{2,2,2}, HSSFWorkbook.PICTURE_TYPE_JPEG); - group2.createPicture(new HSSFChildAnchor(), index); - polygon = group2.createPolygon(new HSSFChildAnchor()); - polygon.setPoints(new int[]{1,100, 1}, new int[]{1, 50, 100}); - group2.createTextbox(new HSSFChildAnchor()); - group2.createShape(new HSSFChildAnchor()); - group2.createShape(new HSSFChildAnchor()); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sheet = wb3.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - assertEquals(2, patriarch.getChildren().size()); - - group = (HSSFShapeGroup) patriarch.getChildren().get(1); - - assertEquals(group.getChildren().size(), 5); - - assertTrue(group.getChildren().get(0) instanceof HSSFPicture); - assertTrue(group.getChildren().get(1) instanceof HSSFPolygon); - assertTrue(group.getChildren().get(2) instanceof HSSFTextbox); - assertTrue(group.getChildren().get(3) instanceof HSSFSimpleShape); - assertTrue(group.getChildren().get(4) instanceof HSSFSimpleShape); - - group.getShapeId(); - wb3.close(); - } - - @Test - void testSpgrRecord() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - // create a sheet with a text box - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); - assertSame(((EscherContainerRecord)group.getEscherContainer().getChild(0)).getChildById(EscherSpgrRecord.RECORD_ID), getSpgrRecord(group)); - wb.close(); - } - - private static EscherSpgrRecord getSpgrRecord(HSSFShapeGroup group) { - return POITestCase.getFieldValue(HSSFShapeGroup.class, group, EscherSpgrRecord.class, "_spgrRecord"); - } - - @Test - void testClearShapes() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); - - group.createShape(new HSSFChildAnchor()); - group.createShape(new HSSFChildAnchor()); - - EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch); - - assertEquals(agg.getShapeToObjMapping().size(), 5); - assertEquals(agg.getTailRecords().size(), 0); - assertEquals(group.getChildren().size(), 2); - - group.clear(); - - assertEquals(agg.getShapeToObjMapping().size(), 1); - assertEquals(agg.getTailRecords().size(), 0); - assertEquals(group.getChildren().size(), 0); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - group = (HSSFShapeGroup) patriarch.getChildren().get(0); - - assertEquals(agg.getShapeToObjMapping().size(), 1); - assertEquals(agg.getTailRecords().size(), 0); - assertEquals(group.getChildren().size(), 0); - wb2.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java b/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java deleted file mode 100644 index 2bda96ce2c..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.ss.usermodel.BaseTestSheetHiding; -import org.apache.poi.ss.usermodel.SheetVisibility; -import org.junit.jupiter.api.Test; - -final class TestSheetHiding extends BaseTestSheetHiding { - public TestSheetHiding() { - super(HSSFITestDataProvider.instance, - "TwoSheetsOneHidden.xls", "TwoSheetsNoneHidden.xls"); - } - - @Test - void testInternalWorkbookHidden() { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("MySheet"); - InternalWorkbook intWb = wb.getWorkbook(); - - assertFalse(intWb.isSheetHidden(0)); - assertFalse(intWb.isSheetVeryHidden(0)); - assertEquals(SheetVisibility.VISIBLE, intWb.getSheetVisibility(0)); - - intWb.setSheetHidden(0, SheetVisibility.HIDDEN); - assertTrue(intWb.isSheetHidden(0)); - assertFalse(intWb.isSheetVeryHidden(0)); - assertEquals(SheetVisibility.HIDDEN, intWb.getSheetVisibility(0)); - - // InternalWorkbook currently behaves slightly different - // than HSSFWorkbook, but it should not have effect in normal usage - // as checked limits are more strict in HSSFWorkbook - - // check sheet-index with one more will work and add the sheet - intWb.setSheetHidden(1, SheetVisibility.HIDDEN); - assertTrue(intWb.isSheetHidden(1)); - assertFalse(intWb.isSheetVeryHidden(1)); - assertEquals(SheetVisibility.HIDDEN, intWb.getSheetVisibility(1)); - - // check sheet-index with index out of bounds => throws exception - assertThrows(RuntimeException.class, () -> wb.setSheetVisibility(10, SheetVisibility.HIDDEN)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestText.java b/src/testcases/org/apache/poi/hssf/usermodel/TestText.java deleted file mode 100644 index a7065cda2e..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestText.java +++ /dev/null @@ -1,214 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.record.TextObjectRecord; -import org.junit.jupiter.api.Test; - -/** - * @author Evgeniy Berlog - * @date 25.06.12 - */ -class TestText { - - @Test - void testResultEqualsToNonExistingAbstractShape() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor()); - - assertEquals(textbox.getEscherContainer().getChildCount(), 5); - - //sp record - byte[] expected = decompress("H4sIAAAAAAAAAFvEw/WBg4GBgZEFSHAxMAAA9gX7nhAAAAA="); - byte[] actual = textbox.getEscherContainer().getChild(0).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPggxIANAABK4+laGgAAAA=="); - actual = textbox.getEscherContainer().getChild(2).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPzAAAQACl6c5QgAAAA="); - actual = textbox.getEscherContainer().getChild(3).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNg4P3AAAQA6pyIkQgAAAA="); - actual = textbox.getEscherContainer().getChild(4).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - ObjRecord obj = textbox.getObjRecord(); - - expected = decompress("H4sIAAAAAAAAAItlkGIQZRBiYGNgZBBMYEADAOdCLuweAAAA"); - actual = obj.serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - TextObjectRecord tor = textbox.getTextObjectRecord(); - - expected = decompress("H4sIAAAAAAAAANvGKMQgxMSABgBGi8T+FgAAAA=="); - actual = tor.serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - wb.close(); - } - - @Test - void testAddTextToExistingFile() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor()); - textbox.setString(new HSSFRichTextString("just for test")); - HSSFTextbox textbox2 = patriarch.createTextbox(new HSSFClientAnchor()); - textbox2.setString(new HSSFRichTextString("just for test2")); - - assertEquals(patriarch.getChildren().size(), 2); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 2); - HSSFTextbox text3 = patriarch.createTextbox(new HSSFClientAnchor()); - text3.setString(new HSSFRichTextString("text3")); - assertEquals(patriarch.getChildren().size(), 3); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sh = wb3.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 3); - assertEquals(((HSSFTextbox) patriarch.getChildren().get(0)).getString().getString(), "just for test"); - assertEquals(((HSSFTextbox) patriarch.getChildren().get(1)).getString().getString(), "just for test2"); - assertEquals(((HSSFTextbox) patriarch.getChildren().get(2)).getString().getString(), "text3"); - - wb3.close(); - } - - @Test - void testSetGetProperties() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor()); - textbox.setString(new HSSFRichTextString("test")); - assertEquals(textbox.getString().getString(), "test"); - - textbox.setHorizontalAlignment((short) 5); - assertEquals(textbox.getHorizontalAlignment(), 5); - - textbox.setVerticalAlignment((short) 6); - assertEquals(textbox.getVerticalAlignment(), (short) 6); - - textbox.setMarginBottom(7); - assertEquals(textbox.getMarginBottom(), 7); - - textbox.setMarginLeft(8); - assertEquals(textbox.getMarginLeft(), 8); - - textbox.setMarginRight(9); - assertEquals(textbox.getMarginRight(), 9); - - textbox.setMarginTop(10); - assertEquals(textbox.getMarginTop(), 10); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - textbox = (HSSFTextbox) patriarch.getChildren().get(0); - assertEquals(textbox.getString().getString(), "test"); - assertEquals(textbox.getHorizontalAlignment(), 5); - assertEquals(textbox.getVerticalAlignment(), (short) 6); - assertEquals(textbox.getMarginBottom(), 7); - assertEquals(textbox.getMarginLeft(), 8); - assertEquals(textbox.getMarginRight(), 9); - assertEquals(textbox.getMarginTop(), 10); - - textbox.setString(new HSSFRichTextString("test1")); - textbox.setHorizontalAlignment(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED); - textbox.setVerticalAlignment(HSSFTextbox.VERTICAL_ALIGNMENT_TOP); - textbox.setMarginBottom(71); - textbox.setMarginLeft(81); - textbox.setMarginRight(91); - textbox.setMarginTop(101); - - assertEquals(textbox.getString().getString(), "test1"); - assertEquals(textbox.getHorizontalAlignment(), HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED); - assertEquals(textbox.getVerticalAlignment(), HSSFTextbox.VERTICAL_ALIGNMENT_TOP); - assertEquals(textbox.getMarginBottom(), 71); - assertEquals(textbox.getMarginLeft(), 81); - assertEquals(textbox.getMarginRight(), 91); - assertEquals(textbox.getMarginTop(), 101); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sh = wb3.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - textbox = (HSSFTextbox) patriarch.getChildren().get(0); - - assertEquals(textbox.getString().getString(), "test1"); - assertEquals(textbox.getHorizontalAlignment(), HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED); - assertEquals(textbox.getVerticalAlignment(), HSSFTextbox.VERTICAL_ALIGNMENT_TOP); - assertEquals(textbox.getMarginBottom(), 71); - assertEquals(textbox.getMarginLeft(), 81); - assertEquals(textbox.getMarginRight(), 91); - assertEquals(textbox.getMarginTop(), 101); - - wb3.close(); - } - - @Test - void testExistingFileWithText() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("text"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - HSSFTextbox textbox = (HSSFTextbox) drawing.getChildren().get(0); - assertEquals(textbox.getHorizontalAlignment(), HSSFTextbox.HORIZONTAL_ALIGNMENT_LEFT); - assertEquals(textbox.getVerticalAlignment(), HSSFTextbox.VERTICAL_ALIGNMENT_TOP); - assertEquals(textbox.getMarginTop(), 0); - assertEquals(textbox.getMarginBottom(), 3600000); - assertEquals(textbox.getMarginLeft(), 3600000); - assertEquals(textbox.getMarginRight(), 0); - assertEquals(textbox.getString().getString(), "teeeeesssstttt"); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java deleted file mode 100644 index 76701fd1dd..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.format.CellFormat; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * @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. - */ -final class TestUnfixedBugs { - @Test - void testFormulaRecordAggregate_1() throws Exception { - // fails at formula "=MEHRFACH.OPERATIONEN(E$3;$B$5;$D4)" - try (Workbook wb = HSSFTestDataSamples.openSampleWorkbook("44958_1.xls")) { - for (int i = 0; i < wb.getNumberOfSheets(); i++) { - Sheet sheet = wb.getSheetAt(i); - assertNotNull(wb.getSheet(sheet.getSheetName())); - sheet.groupColumn((short) 4, (short) 5); - sheet.setColumnGroupCollapsed(4, true); - sheet.setColumnGroupCollapsed(4, false); - - for (Row row : sheet) { - for (Cell cell : row) { - try { - assertNotNull(cell.toString()); - } catch (Exception e) { - throw new Exception("While handling: " + sheet.getSheetName() + "/" + row.getRowNum() + "/" + cell.getColumnIndex(), e); - } - } - } - } - } - } - - @Test - void testFormulaRecordAggregate() throws Exception { - // fails at formula "=MEHRFACH.OPERATIONEN(E$3;$B$5;$D4)" - try (Workbook wb = HSSFTestDataSamples.openSampleWorkbook("44958.xls")) { - for (int i = 0; i < wb.getNumberOfSheets(); i++) { - Sheet sheet = wb.getSheetAt(i); - assertNotNull(wb.getSheet(sheet.getSheetName())); - sheet.groupColumn((short) 4, (short) 5); - sheet.setColumnGroupCollapsed(4, true); - sheet.setColumnGroupCollapsed(4, false); - - for (Row row : sheet) { - for (Cell cell : row) { - try { - assertNotNull(cell.toString()); - } catch (Exception e) { - throw new Exception("While handling: " + sheet.getSheetName() + "/" + row.getRowNum() + "/" + cell.getColumnIndex(), e); - } - } - } - } - } - } - - @Test - void testBug57074() throws IOException { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("57074.xls"); - Sheet sheet = wb.getSheet("Sheet1"); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - - HSSFColor bgColor = (HSSFColor) cell.getCellStyle().getFillBackgroundColorColor(); - String bgColorStr = bgColor.getTriplet()[0]+", "+bgColor.getTriplet()[1]+", "+bgColor.getTriplet()[2]; - //System.out.println(bgColorStr); - assertEquals("215, 228, 188", bgColorStr); - - HSSFColor fontColor = (HSSFColor) cell.getCellStyle().getFillForegroundColorColor(); - String fontColorStr = fontColor.getTriplet()[0]+", "+fontColor.getTriplet()[1]+", "+fontColor.getTriplet()[2]; - //System.out.println(fontColorStr); - assertEquals("0, 128, 128", fontColorStr); - wb.close(); - } - - @Test - void testBug62242() { - CellFormat cfUK = CellFormat.getInstance("_ * #,##0.00_ ;_ * \\-#,##0.00_ ;_ * \"-\"??_ ;_ @_"); - assertEquals(" - ", cfUK.apply((double) 0).text); - } - - @Test - void testDataFormattingWithQuestionMarkBug62242() { - // The question mark in the format should be replaced by blanks, but - // this is currently not handled when producing the Java formatting and - // so we end up with a trailing zero here - CellFormat cfUK = CellFormat.getInstance("??"); - assertEquals(" ", cfUK.apply((double) 0).text); - } - - @Test - void testDataFormattingWithQuestionMarkAndPoundBug62242() { - char pound = '\u00A3'; - - // The question mark in the format should be replaced by blanks, but - // this is currently not handled when producing the Java formatting and - // so we end up with a trailing zero here - CellFormat cfUK = CellFormat.getInstance("_-[$£-809]* \"-\"??_-"); - assertEquals(" "+pound+" - ", cfUK.apply((double) 0).text); - - cfUK = CellFormat.getInstance("_-[$£-809]* \"-\"??_-a"); - assertEquals(" "+pound+" - a", cfUK.apply((double) 0).text); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java deleted file mode 100644 index 1ced954a27..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -final class TestUnicodeWorkbook { - - /** - * Tests Bug38230 - * That a Umlat is written and then read back. - * It should have been written as a compressed unicode. - */ - @Test - void testUmlatReadWrite() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - - //Create a unicode sheet name (euro symbol) - HSSFSheet s = wb1.createSheet("test"); - - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(1); - c.setCellValue(new HSSFRichTextString("\u00e4")); - - //Confirm that the sring will be compressed - assertEquals(c.getRichStringCellValue().getUnicodeString().getOptionFlags(), 0); - - try (HSSFWorkbook wb = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - - //Test the sheetname - s = wb.getSheet("test"); - assertNotNull(s); - - c = r.getCell(1); - assertEquals(c.getRichStringCellValue().getString(), "\u00e4"); - } - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java deleted file mode 100644 index e3ca2f4247..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java +++ /dev/null @@ -1,632 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.BackupRecord; -import org.apache.poi.hssf.record.LabelSSTRecord; -import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Test; - -/** - * Class to test Workbook functionality - */ -final class TestWorkbook { - private static final String LAST_NAME_KEY = "lastName"; - private static final String FIRST_NAME_KEY = "firstName"; - private static final String SSN_KEY = "ssn"; - private static final String REPLACE_ME = "replaceMe"; - private static final String REPLACED = "replaced"; - private static final String DO_NOT_REPLACE = "doNotReplace"; - private static final String EMPLOYEE_INFORMATION = "Employee Info"; - private static final String LAST_NAME_VALUE = "Bush"; - private static final String FIRST_NAME_VALUE = "George"; - private static final String SSN_VALUE = "555555555"; - private final SanityChecker sanityChecker = new SanityChecker(); - - - private static HSSFWorkbook openSample(String sampleFileName) { - return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - /** - * TEST NAME: Test Write Sheet Simple

- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values.

- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (99,0).

- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

- */ - @Test - void testWriteSheetSimple() throws IOException { - try (HSSFWorkbook wb1 = new HSSFWorkbook()) { - HSSFSheet s = wb1.createSheet(); - - populateSheet(s); - - try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { - sanityChecker.checkHSSFWorkbook(wb1); - assertEquals(99, s.getLastRowNum(), "LAST ROW == 99"); - assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0"); - - sanityChecker.checkHSSFWorkbook(wb2); - s = wb2.getSheetAt(0); - assertEquals(99, s.getLastRowNum(), "LAST ROW == 99"); - assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0"); - } - } - } - - /** - * TEST NAME: Test Write/Modify Sheet Simple

- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values, - * remove some rows, yet still have a valid file/data.

- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (74,25).

- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

- */ - @Test - void testWriteModifySheetSimple() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - - populateSheet(s); - - for (int rownum = 0; rownum < 25; rownum++) { - HSSFRow r = s.getRow(rownum); - s.removeRow(r); - } - for (int rownum = 75; rownum < 100; rownum++) { - HSSFRow r = s.getRow(rownum); - s.removeRow(r); - } - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - sanityChecker.checkHSSFWorkbook(wb1); - assertEquals(74, s.getLastRowNum(), "LAST ROW == 74"); - assertEquals(25, s.getFirstRowNum(), "FIRST ROW == 25"); - - sanityChecker.checkHSSFWorkbook(wb2); - s = wb2.getSheetAt(0); - assertEquals(74, s.getLastRowNum(), "LAST ROW == 74"); - assertEquals(25, s.getFirstRowNum(), "FIRST ROW == 25"); - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Read Simple

- * OBJECTIVE: Test that HSSF can read a simple spreadsheet (Simple.xls).

- * SUCCESS: HSSF reads the sheet. Matches values in their particular positions.

- * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values - * in the sheet in their known positions.

- */ - @Test - void testReadSimple() throws IOException { - HSSFWorkbook wb = openSample("Simple.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - - HSSFCell cell = sheet.getRow(0).getCell(0); - assertEquals(REPLACE_ME, cell .getRichStringCellValue().getString()); - wb.close(); - } - - /** - * TEST NAME: Test Read Simple w/ Data Format

- * OBJECTIVE: Test that HSSF can read a simple spreadsheet (SimpleWithDataFormat.xls).

- * SUCCESS: HSSF reads the sheet. Matches values in their particular positions and format is correct

- * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values - * in the sheet in their known positions.

- */ - @Test - void testReadSimpleWithDataFormat() throws IOException { - HSSFWorkbook wb = openSample("SimpleWithDataFormat.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFDataFormat format = wb.createDataFormat(); - HSSFCell cell = sheet.getRow(0).getCell(0); - - assertEquals(1.25,cell.getNumericCellValue(), 1e-10); - - assertEquals(format.getFormat(cell.getCellStyle().getDataFormat()), "0.0"); - - wb.close(); - } - -/** - * TEST NAME: Test Read/Write Simple w/ Data Format

- * OBJECTIVE: Test that HSSF can write a sheet with custom data formats and then read it and get the proper formats.

- * SUCCESS: HSSF reads the sheet. Matches values in their particular positions and format is correct

- * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values - * in the sheet in their known positions.

- */ - @Test - void testWriteDataFormat() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s1 = wb1.createSheet(); - HSSFDataFormat format = wb1.createDataFormat(); - HSSFCellStyle cs = wb1.createCellStyle(); - - short df = format.getFormat("0.0"); - cs.setDataFormat(df); - - HSSFCell c1 = s1.createRow(0).createCell(0); - c1.setCellStyle(cs); - c1.setCellValue(1.25); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - HSSFSheet s2 = wb2.getSheetAt(0); - HSSFCell c2 = s2.getRow(0).getCell(0); - format = wb2.createDataFormat(); - - assertEquals(1.25, c2.getNumericCellValue(), 1e-10); - - assertEquals(format.getFormat(df), "0.0"); - - assertEquals(format, wb2.createDataFormat()); - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Read Employee Simple

- * OBJECTIVE: Test that HSSF can read a simple spreadsheet (Employee.xls).

- * SUCCESS: HSSF reads the sheet. Matches values in their particular positions.

- * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values - * in the sheet in their known positions.

- * - */ - @Test - void testReadEmployeeSimple() throws IOException { - HSSFWorkbook wb = openSample("Employee.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - - assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getRichStringCellValue().getString()); - assertEquals(LAST_NAME_KEY, sheet.getRow(3).getCell(2).getRichStringCellValue().getString()); - assertEquals(FIRST_NAME_KEY, sheet.getRow(4).getCell(2).getRichStringCellValue().getString()); - assertEquals(SSN_KEY, sheet.getRow(5).getCell(2).getRichStringCellValue().getString()); - - wb.close(); - } - - /** - * TEST NAME: Test Modify Sheet Simple

- * OBJECTIVE: Test that HSSF can read a simple spreadsheet with a string value and replace - * it with another string value.

- * SUCCESS: HSSF reads a sheet. HSSF replaces the cell value with another cell value. HSSF - * writes the sheet out to another file. HSSF reads the result and ensures the value - * has been properly replaced.

- * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts. - * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value - * is incorrect or has not been replaced.

- */ - @Test - void testModifySimple() throws IOException { - HSSFWorkbook wb1 = openSample("Simple.xls"); - HSSFSheet sheet = wb1.getSheetAt(0); - HSSFCell cell = sheet.getRow(0).getCell(0); - - cell.setCellValue(new HSSFRichTextString(REPLACED)); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - sheet = wb2.getSheetAt(0); - cell = sheet.getRow(0).getCell(0); - assertEquals(REPLACED, cell.getRichStringCellValue().getString()); - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Modify Sheet Simple With Skipped cells

- * OBJECTIVE: Test that HSSF can read a simple spreadsheet with string values and replace - * them with other string values while not replacing other cells.

- * SUCCESS: HSSF reads a sheet. HSSF replaces the cell value with another cell value. HSSF - * writes the sheet out to another file. HSSF reads the result and ensures the value - * has been properly replaced and unreplaced values are still unreplaced.

- * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts. - * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value - * is incorrect or has not been replaced or the incorrect cell has its value replaced - * or is incorrect.

- */ - @Test - void testModifySimpleWithSkip() throws IOException { - HSSFWorkbook wb1 = openSample("SimpleWithSkip.xls"); - HSSFSheet sheet = wb1.getSheetAt(0); - HSSFCell cell = sheet.getRow(0).getCell(1); - - cell.setCellValue(new HSSFRichTextString(REPLACED)); - cell = sheet.getRow(1).getCell(0); - cell.setCellValue(new HSSFRichTextString(REPLACED)); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - sheet = wb2.getSheetAt(0); - cell = sheet.getRow(0).getCell(1); - assertEquals(REPLACED, cell.getRichStringCellValue().getString()); - cell = sheet.getRow(0).getCell(0); - assertEquals(DO_NOT_REPLACE, cell.getRichStringCellValue().getString()); - cell = sheet.getRow(1).getCell(0); - assertEquals(REPLACED, cell.getRichStringCellValue().getString()); - cell = sheet.getRow(1).getCell(1); - assertEquals(DO_NOT_REPLACE, cell.getRichStringCellValue().getString()); - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Modify Sheet With Styling

- * OBJECTIVE: Test that HSSF can read a simple spreadsheet with string values and replace - * them with other string values despite any styling. In this release of HSSF styling will - * probably be lost and is NOT tested.

- * SUCCESS: HSSF reads a sheet. HSSF replaces the cell values with other cell values. HSSF - * writes the sheet out to another file. HSSF reads the result and ensures the value - * has been properly replaced.

- * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts. - * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value - * is incorrect or has not been replaced.

- */ - @Test - void testModifySimpleWithStyling() throws IOException { - HSSFWorkbook wb1 = openSample("SimpleWithStyling.xls"); - HSSFSheet sheet = wb1.getSheetAt(0); - - for (int k = 0; k < 4; k++) { - HSSFCell cell = sheet.getRow(k).getCell(0); - cell.setCellValue(new HSSFRichTextString(REPLACED)); - } - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - sheet = wb2.getSheetAt(0); - for (int k = 0; k < 4; k++) { - HSSFCell cell = sheet.getRow(k).getCell(0); - assertEquals(REPLACED, cell.getRichStringCellValue().getString()); - } - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Modify Employee Sheet

- * OBJECTIVE: Test that HSSF can read a simple spreadsheet with string values and replace - * them with other string values despite any styling. In this release of HSSF styling will - * probably be lost and is NOT tested.

- * SUCCESS: HSSF reads a sheet. HSSF replaces the cell values with other cell values. HSSF - * writes the sheet out to another file. HSSF reads the result and ensures the value - * has been properly replaced.

- * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts. - * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value - * is incorrect or has not been replaced.

- */ - @Test - void testModifyEmployee() throws IOException { - HSSFWorkbook wb1 = openSample("Employee.xls"); - HSSFSheet sheet = wb1.getSheetAt(0); - HSSFCell cell = sheet.getRow(3).getCell(2); - - cell.setCellValue(new HSSFRichTextString(LAST_NAME_VALUE)); - cell = sheet.getRow(4).getCell(2); - cell.setCellValue(new HSSFRichTextString(FIRST_NAME_VALUE)); - cell = sheet.getRow(5).getCell(2); - cell.setCellValue(new HSSFRichTextString(SSN_VALUE)); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - sheet = wb2.getSheetAt(0); - assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getRichStringCellValue().getString()); - assertEquals(LAST_NAME_VALUE, sheet.getRow(3).getCell(2).getRichStringCellValue().getString()); - assertEquals(FIRST_NAME_VALUE, sheet.getRow(4).getCell(2).getRichStringCellValue().getString()); - assertEquals(SSN_VALUE, sheet.getRow(5).getCell(2).getRichStringCellValue().getString()); - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Read Sheet with an RK number

- * OBJECTIVE: Test that HSSF can read a simple spreadsheet with and RKRecord and correctly - * identify the cell as numeric and convert it to a NumberRecord.

- * SUCCESS: HSSF reads a sheet. HSSF returns that the cell is a numeric type cell.

- * FAILURE: HSSF does not read a sheet or excepts. HSSF incorrectly identifies the cell

- */ - @Test - void testReadSheetWithRK() throws IOException { - HSSFWorkbook wb = openSample("rk.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFCell c = s.getRow(0).getCell(0); - - assertEquals(CellType.NUMERIC, c.getCellType()); - - wb.close(); - } - - /** - * TEST NAME: Test Write/Modify Sheet Simple

- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values, - * remove some rows, yet still have a valid file/data.

- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (74,25).

- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

- */ - @Test - void testWriteModifySheetMerged() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - - populateSheet(s); - - assertEquals(0, s.addMergedRegion(new CellRangeAddress(0, 10, 0, 10))); - assertEquals(1, s.addMergedRegion(new CellRangeAddress(30, 40, 5, 15))); - sanityChecker.checkHSSFWorkbook(wb1); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - s = wb2.getSheetAt(0); - CellRangeAddress r1 = s.getMergedRegion(0); - CellRangeAddress r2 = s.getMergedRegion(1); - - confirmRegion(new CellRangeAddress(0, 10, 0, 10), r1); - confirmRegion(new CellRangeAddress(30, 40,5, 15), r2); - - wb2.close(); - wb1.close(); - } - - private void populateSheet(Sheet s) { - for (int rownum = 0; rownum < 100; rownum++) { - Row r = s.createRow(rownum); - - for (int cellnum = 0; cellnum < 50; cellnum += 2) { - Cell c = r.createCell(cellnum); - c.setCellValue(rownum * 10000 + cellnum - + ((( double ) rownum / 1000) - + (( double ) cellnum / 10000))); - c = r.createCell(cellnum + 1); - c.setCellValue(new HSSFRichTextString("TEST")); - } - } - } - - private static void confirmRegion(CellRangeAddress ra, CellRangeAddress rb) { - assertEquals(ra.getFirstRow(), rb.getFirstRow()); - assertEquals(ra.getLastRow(), rb.getLastRow()); - assertEquals(ra.getFirstColumn(), rb.getFirstColumn()); - assertEquals(ra.getLastColumn(), rb.getLastColumn()); - } - - /** - * Test the backup field gets set as expected. - */ - @Test - void testBackupRecord() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet(); - InternalWorkbook workbook = wb.getWorkbook(); - BackupRecord record = workbook.getBackupRecord(); - - assertEquals(0, record.getBackup()); - assertFalse(wb.getBackupFlag()); - wb.setBackupFlag(true); - assertEquals(1, record.getBackup()); - assertTrue(wb.getBackupFlag()); - wb.setBackupFlag(false); - assertEquals(0, record.getBackup()); - assertFalse(wb.getBackupFlag()); - - wb.close(); - } - - private static final class RecordCounter implements RecordVisitor { - private int _count; - - public RecordCounter() { - _count=0; - } - public int getCount() { - return _count; - } - @Override - public void visitRecord(org.apache.poi.hssf.record.Record r) { - if (r instanceof LabelSSTRecord) { - _count++; - } - } - } - - /** - * This tests is for bug [ #506658 ] Repeating output. - * - * We need to make sure only one LabelSSTRecord is produced. - */ - @Test - void testRepeatingBug() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Design Variants"); - HSSFRow row = sheet.createRow(2); - HSSFCell cell = row.createCell(1); - - cell.setCellValue(new HSSFRichTextString("Class")); - cell = row.createCell(2); - assertNotNull(cell); - - RecordCounter rc = new RecordCounter(); - sheet.getSheet().visitContainedRecords(rc, 0); - assertEquals(1, rc.getCount()); - - workbook.close(); - } - - - /** - * Test for row indexes beyond {@link Short#MAX_VALUE}. - * This bug was first fixed in svn r352609. - */ - @Test - void testRowIndexesBeyond32768() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFRow row; - HSSFCell cell; - for (int i = 32700; i < 32771; i++) { - row = sheet.createRow(i); - cell = row.createCell(0); - cell.setCellValue(i); - } - sanityChecker.checkHSSFWorkbook(wb1); - assertEquals(32770, sheet.getLastRowNum(), "LAST ROW == 32770"); - cell = sheet.getRow(32770).getCell(0); - double lastVal = cell.getNumericCellValue(); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - HSSFSheet s = wb2.getSheetAt(0); - row = s.getRow(32770); - cell = row.getCell(0); - assertEquals(lastVal, cell.getNumericCellValue(), 0, "Value from last row == 32770"); - assertEquals(32770, s.getLastRowNum(), "LAST ROW == 32770"); - - wb2.close(); - wb1.close(); - } - - /** - * Generate a file to verify repeating rows and cols made it - */ - @Test - void testRepeatingColsRows() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet("Test Print Titles"); - - HSSFRow row = sheet.createRow(0); - - HSSFCell cell = row.createCell(1); - cell.setCellValue(new HSSFRichTextString("hi")); - - CellRangeAddress cra = CellRangeAddress.valueOf("A1:B1"); - sheet.setRepeatingColumns(cra); - sheet.setRepeatingRows(cra); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - sheet = wb2.getSheetAt(0); - assertEquals("A:B", sheet.getRepeatingColumns().formatAsString()); - assertEquals("1:1", sheet.getRepeatingRows().formatAsString()); - - wb2.close(); - wb1.close(); - } - - /** - * Test setRepeatingRowsAndColumns when startRow and startColumn are -1. - */ - @Test - void testRepeatingColsRowsMinusOne() throws IOException - { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test Print Titles"); - - HSSFRow row = sheet.createRow(0); - - HSSFCell cell = row.createCell(1); - cell.setCellValue(new HSSFRichTextString("hi")); - CellRangeAddress cra = new CellRangeAddress(-1, 1, -1, 1); - assertThrows(IllegalArgumentException.class, () -> sheet.setRepeatingColumns(cra), "invalid start index is ignored"); - assertThrows(IllegalArgumentException.class, () -> sheet.setRepeatingRows(cra), "invalid start index is ignored"); - - sheet.setRepeatingColumns(null); - sheet.setRepeatingRows(null); - - HSSFTestDataSamples.writeOutAndReadBack(workbook).close(); - - workbook.close(); - } - - @Test - void testBug58085RemoveSheetWithNames() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - Sheet sheet1 = wb1.createSheet("sheet1"); - Sheet sheet2 = wb1.createSheet("sheet2"); - Sheet sheet3 = wb1.createSheet("sheet3"); - - sheet1.createRow(0).createCell((short) 0).setCellValue("val1"); - sheet2.createRow(0).createCell((short) 0).setCellValue("val2"); - sheet3.createRow(0).createCell((short) 0).setCellValue("val3"); - - Name namedCell1 = wb1.createName(); - namedCell1.setNameName("name1"); - String reference1 = "sheet1!$A$1"; - namedCell1.setRefersToFormula(reference1); - - Name namedCell2= wb1.createName(); - namedCell2.setNameName("name2"); - String reference2 = "sheet2!$A$1"; - namedCell2.setRefersToFormula(reference2); - - Name namedCell3 = wb1.createName(); - namedCell3.setNameName("name3"); - String reference3 = "sheet3!$A$1"; - namedCell3.setRefersToFormula(reference3); - - Workbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - Name nameCell = wb2.getName("name1"); - assertNotNull(nameCell); - assertEquals("sheet1!$A$1", nameCell.getRefersToFormula()); - nameCell = wb2.getName("name2"); - assertNotNull(nameCell); - assertEquals("sheet2!$A$1", nameCell.getRefersToFormula()); - nameCell = wb2.getName("name3"); - assertNotNull(nameCell); - assertEquals("sheet3!$A$1", nameCell.getRefersToFormula()); - - wb2.removeSheetAt(wb2.getSheetIndex("sheet1")); - - nameCell = wb2.getName("name1"); - assertNotNull(nameCell); - assertEquals("#REF!$A$1", nameCell.getRefersToFormula()); - nameCell = wb2.getName("name2"); - assertNotNull(nameCell); - assertEquals("sheet2!$A$1", nameCell.getRefersToFormula()); - nameCell = wb2.getName("name3"); - assertNotNull(nameCell); - assertEquals("sheet3!$A$1", nameCell.getRefersToFormula()); - - wb2.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java b/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java deleted file mode 100644 index 1fe92ec022..0000000000 --- a/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java +++ /dev/null @@ -1,309 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.InputStream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.TestHSSFWorkbook; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.MemFuncPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.UnionPtg; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; - -final class TestAreaReference { - - @Test - void testAreaRef1() { - AreaReference ar = new AreaReference("$A$1:$B$2", SpreadsheetVersion.EXCEL97); - assertFalse(ar.isSingleCell(), "Two cells expected"); - CellReference cf = ar.getFirstCell(); - assertEquals(0, cf.getRow(), "row is 4"); - assertEquals(0, cf.getCol(), "col is 1"); - assertTrue(cf.isRowAbsolute(), "row is abs"); - assertTrue(cf.isColAbsolute(), "col is abs"); - assertEquals("$A$1", cf.formatAsString(), "string is $A$1"); - - cf = ar.getLastCell(); - assertEquals(1, cf.getRow(), "row is 4"); - assertEquals(1, cf.getCol(), "col is 1"); - assertTrue(cf.isRowAbsolute(), "row is abs"); - assertTrue(cf.isColAbsolute(), "col is abs"); - assertEquals("$B$2", cf.formatAsString(), "string is $B$2"); - - CellReference[] refs = ar.getAllReferencedCells(); - assertEquals(4, refs.length); - - assertEquals(0, refs[0].getRow()); - assertEquals(0, refs[0].getCol()); - assertNull(refs[0].getSheetName()); - - assertEquals(0, refs[1].getRow()); - assertEquals(1, refs[1].getCol()); - assertNull(refs[1].getSheetName()); - - assertEquals(1, refs[2].getRow()); - assertEquals(0, refs[2].getCol()); - assertNull(refs[2].getSheetName()); - - assertEquals(1, refs[3].getRow()); - assertEquals(1, refs[3].getCol()); - assertNull(refs[3].getSheetName()); - } - - /** - * References failed when sheet names were being used Reported by - * Arne.Clauss@gedas.de - */ - @Test - void testReferenceWithSheet() { - AreaReference ar; - - ar = new AreaReference("Tabelle1!B5:B5", SpreadsheetVersion.EXCEL97); - assertTrue(ar.isSingleCell()); - TestCellReference.confirmCell(ar.getFirstCell(), "Tabelle1", 4, 1, false, false, "Tabelle1!B5"); - - assertEquals(1, ar.getAllReferencedCells().length); - - ar = new AreaReference("Tabelle1!$B$5:$B$7", SpreadsheetVersion.EXCEL97); - assertFalse(ar.isSingleCell()); - - TestCellReference.confirmCell(ar.getFirstCell(), "Tabelle1", 4, 1, true, true, "Tabelle1!$B$5"); - TestCellReference.confirmCell(ar.getLastCell(), "Tabelle1", 6, 1, true, true, "Tabelle1!$B$7"); - - // And all that make it up - CellReference[] allCells = ar.getAllReferencedCells(); - assertEquals(3, allCells.length); - TestCellReference.confirmCell(allCells[0], "Tabelle1", 4, 1, true, true, "Tabelle1!$B$5"); - TestCellReference.confirmCell(allCells[1], "Tabelle1", 5, 1, true, true, "Tabelle1!$B$6"); - TestCellReference.confirmCell(allCells[2], "Tabelle1", 6, 1, true, true, "Tabelle1!$B$7"); - } - - @Test - void testContiguousReferences() { - String refSimple = "$C$10:$C$10"; - String ref2D = "$C$10:$D$11"; - String refDCSimple = "$C$10:$C$10,$D$12:$D$12,$E$14:$E$14"; - String refDC2D = "$C$10:$C$11,$D$12:$D$12,$E$14:$E$20"; - String refDC3D = "Tabelle1!$C$10:$C$14,Tabelle1!$D$10:$D$12"; - String refComma = "'A,Sheet'!$A$1:$A$1,'A,Sheet'!$A$4:$A$5"; - String refCommaExp = "'!Sheet,Comma!'!$A$1:$B$1"; - - // Check that we detect as contiguous properly - assertTrue(AreaReference.isContiguous(refSimple)); - assertTrue(AreaReference.isContiguous(ref2D)); - assertFalse(AreaReference.isContiguous(refDCSimple)); - assertFalse(AreaReference.isContiguous(refDC2D)); - assertFalse(AreaReference.isContiguous(refDC3D)); - assertFalse(AreaReference.isContiguous(refComma)); - assertTrue(AreaReference.isContiguous(refCommaExp)); - - // Check we can only create contiguous entries - new AreaReference(refSimple, SpreadsheetVersion.EXCEL97); - new AreaReference(ref2D, SpreadsheetVersion.EXCEL97); - assertThrows(IllegalArgumentException.class, () -> new AreaReference(refDCSimple, SpreadsheetVersion.EXCEL97)); - assertThrows(IllegalArgumentException.class, () -> new AreaReference(refDC2D, SpreadsheetVersion.EXCEL97)); - assertThrows(IllegalArgumentException.class, () -> new AreaReference(refDC3D, SpreadsheetVersion.EXCEL97)); - - // Test that we split as expected - AreaReference[] refs; - - refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refSimple); - assertEquals(1, refs.length); - assertTrue(refs[0].isSingleCell()); - assertEquals("$C$10", refs[0].formatAsString()); - - refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, ref2D); - assertEquals(1, refs.length); - assertFalse(refs[0].isSingleCell()); - assertEquals("$C$10:$D$11", refs[0].formatAsString()); - - refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refDCSimple); - assertEquals(3, refs.length); - assertTrue(refs[0].isSingleCell()); - assertTrue(refs[1].isSingleCell()); - assertTrue(refs[2].isSingleCell()); - assertEquals("$C$10", refs[0].formatAsString()); - assertEquals("$D$12", refs[1].formatAsString()); - assertEquals("$E$14", refs[2].formatAsString()); - - refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refDC2D); - assertEquals(3, refs.length); - assertFalse(refs[0].isSingleCell()); - assertTrue(refs[1].isSingleCell()); - assertFalse(refs[2].isSingleCell()); - assertEquals("$C$10:$C$11", refs[0].formatAsString()); - assertEquals("$D$12", refs[1].formatAsString()); - assertEquals("$E$14:$E$20", refs[2].formatAsString()); - - refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refDC3D); - assertEquals(2, refs.length); - assertFalse(refs[0].isSingleCell()); - assertFalse(refs[0].isSingleCell()); - assertEquals("Tabelle1!$C$10:$C$14", refs[0].formatAsString()); - assertEquals("Tabelle1!$D$10:$D$12", refs[1].formatAsString()); - assertEquals("Tabelle1", refs[0].getFirstCell().getSheetName()); - assertEquals("Tabelle1", refs[0].getLastCell().getSheetName()); - assertEquals("Tabelle1", refs[1].getFirstCell().getSheetName()); - assertEquals("Tabelle1", refs[1].getLastCell().getSheetName()); - - refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refComma); - assertEquals(2, refs.length); - System.out.println(refs[0].formatAsString()); - assertTrue(refs[0].isSingleCell()); - assertEquals("'A,Sheet'!$A$1", refs[0].formatAsString()); - assertEquals("A,Sheet", refs[0].getLastCell().getSheetName()); - assertEquals("'A,Sheet'!$A$4:$A$5", refs[1].formatAsString()); - assertEquals("A,Sheet", refs[1].getLastCell().getSheetName()); - - refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refCommaExp); - assertEquals(1, refs.length); - assertFalse(refs[0].isSingleCell()); - assertEquals("'!Sheet,Comma!'!$A$1:$B$1", refs[0].formatAsString()); - assertEquals("!Sheet,Comma!", refs[0].getLastCell().getSheetName()); - } - - @Test - void testDiscontinousReference() throws Exception { - try (InputStream is = HSSFTestDataSamples.openSampleFileStream("44167.xls"); - HSSFWorkbook wb = new HSSFWorkbook(is)) { - InternalWorkbook workbook = TestHSSFWorkbook.getInternalWorkbook(wb); - HSSFEvaluationWorkbook eb = HSSFEvaluationWorkbook.create(wb); - - assertEquals(1, wb.getNumberOfNames()); - String sheetName = "Tabelle1"; - String rawRefA = "$C$10:$C$14"; - String rawRefB = "$C$16:$C$18"; - String refA = sheetName + "!" + rawRefA; - String refB = sheetName + "!" + rawRefB; - String ref = refA + "," + refB; - - // Check the low level record - NameRecord nr = workbook.getNameRecord(0); - assertNotNull(nr); - assertEquals("test", nr.getNameText()); - - Ptg[] def = nr.getNameDefinition(); - assertEquals(4, def.length); - - MemFuncPtg ptgA = (MemFuncPtg) def[0]; - Area3DPtg ptgB = (Area3DPtg) def[1]; - Area3DPtg ptgC = (Area3DPtg) def[2]; - UnionPtg ptgD = (UnionPtg) def[3]; - assertEquals("", ptgA.toFormulaString()); - assertEquals(refA, ptgB.toFormulaString(eb)); - assertEquals(refB, ptgC.toFormulaString(eb)); - assertEquals(",", ptgD.toFormulaString()); - - assertEquals(ref, HSSFFormulaParser.toFormulaString(wb, nr.getNameDefinition())); - - // Check the high level definition - HSSFName aNamedCell = wb.getName("test"); - - // Should have 2 references - assertNotNull(aNamedCell); - String formulaRefs = aNamedCell.getRefersToFormula(); - assertNotNull(formulaRefs); - assertEquals(ref, formulaRefs); - - // Check the parsing of the reference into cells - assertFalse(AreaReference.isContiguous(formulaRefs)); - AreaReference[] arefs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, formulaRefs); - assertEquals(2, arefs.length); - assertEquals(refA, arefs[0].formatAsString()); - assertEquals(refB, arefs[1].formatAsString()); - - for (AreaReference ar : arefs) { - confirmResolveCellRef(wb, ar.getFirstCell()); - confirmResolveCellRef(wb, ar.getLastCell()); - } - } - } - - private static void confirmResolveCellRef(HSSFWorkbook wb, CellReference cref) { - HSSFSheet s = wb.getSheet(cref.getSheetName()); - HSSFRow r = s.getRow(cref.getRow()); - HSSFCell c = r.getCell(cref.getCol()); - assertNotNull(c); - } - - @Test - void testSpecialSheetNames() { - AreaReference ar; - ar = new AreaReference("'Sheet A'!A1:A1", SpreadsheetVersion.EXCEL97); - confirmAreaSheetName(ar, "Sheet A", "'Sheet A'!A1"); - - ar = new AreaReference("'Hey! Look Here!'!A1:A1", SpreadsheetVersion.EXCEL97); - confirmAreaSheetName(ar, "Hey! Look Here!", "'Hey! Look Here!'!A1"); - - ar = new AreaReference("'O''Toole'!A1:B2", SpreadsheetVersion.EXCEL97); - confirmAreaSheetName(ar, "O'Toole", "'O''Toole'!A1:B2"); - - ar = new AreaReference("'one:many'!A1:B2", SpreadsheetVersion.EXCEL97); - confirmAreaSheetName(ar, "one:many", "'one:many'!A1:B2"); - - ar = new AreaReference("'O,Comma'!A1:B1", SpreadsheetVersion.EXCEL97); - confirmAreaSheetName(ar, "O,Comma", "'O,Comma'!A1:B1"); - } - - private static void confirmAreaSheetName(AreaReference ar, String sheetName, String expectedFullText) { - CellReference[] cells = ar.getAllReferencedCells(); - assertEquals(sheetName, cells[0].getSheetName()); - assertEquals(expectedFullText, ar.formatAsString()); - } - - @Test - void testWholeColumnRefs() { - confirmWholeColumnRef("A:A", 0, 0, false, false); - confirmWholeColumnRef("$C:D", 2, 3, true, false); - confirmWholeColumnRef("AD:$AE", 29, 30, false, true); - } - - private static void confirmWholeColumnRef(String ref, int firstCol, int lastCol, boolean firstIsAbs, boolean lastIsAbs) { - AreaReference ar = new AreaReference(ref, SpreadsheetVersion.EXCEL97); - confirmCell(ar.getFirstCell(), 0, firstCol, true, firstIsAbs); - confirmCell(ar.getLastCell(), 0xFFFF, lastCol, true, lastIsAbs); - } - - private static void confirmCell(CellReference cell, int row, int col, boolean isRowAbs, boolean isColAbs) { - assertEquals(row, cell.getRow()); - assertEquals(col, cell.getCol()); - assertEquals(isRowAbs, cell.isRowAbsolute()); - assertEquals(isColAbs, cell.isColAbsolute()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/util/TestCellReference.java b/src/testcases/org/apache/poi/hssf/util/TestCellReference.java deleted file mode 100644 index f761e251dd..0000000000 --- a/src/testcases/org/apache/poi/hssf/util/TestCellReference.java +++ /dev/null @@ -1,165 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.ss.util.CellReference.NameType; -import org.junit.jupiter.api.Test; - -/** - * Tests for the HSSF and SS versions of CellReference. - * See also {@link org.apache.poi.ss.util.TestCellReference} - */ -final class TestCellReference { - @Test - void testColNumConversion() { - assertEquals(0, CellReference.convertColStringToIndex("A")); - assertEquals(1, CellReference.convertColStringToIndex("B")); - assertEquals(25, CellReference.convertColStringToIndex("Z")); - assertEquals(26, CellReference.convertColStringToIndex("AA")); - assertEquals(27, CellReference.convertColStringToIndex("AB")); - assertEquals(51, CellReference.convertColStringToIndex("AZ")); - assertEquals(701, CellReference.convertColStringToIndex("ZZ")); - assertEquals(702, CellReference.convertColStringToIndex("AAA")); - assertEquals(18277, CellReference.convertColStringToIndex("ZZZ")); - - assertEquals("A", CellReference.convertNumToColString(0)); - assertEquals("B", CellReference.convertNumToColString(1)); - assertEquals("Z", CellReference.convertNumToColString(25)); - assertEquals("AA", CellReference.convertNumToColString(26)); - assertEquals("ZZ", CellReference.convertNumToColString(701)); - assertEquals("AAA", CellReference.convertNumToColString(702)); - assertEquals("ZZZ", CellReference.convertNumToColString(18277)); - - // Absolute references are allowed for the string ones - assertEquals(0, CellReference.convertColStringToIndex("$A")); - assertEquals(25, CellReference.convertColStringToIndex("$Z")); - assertEquals(26, CellReference.convertColStringToIndex("$AA")); - - // $ sign isn't allowed elsewhere though - assertThrows(IllegalArgumentException.class, () -> CellReference.convertColStringToIndex("A$B$"), - "Column reference is invalid and shouldn't be accepted"); - } - - @Test - void testAbsRef1(){ - CellReference cf = new CellReference("$B$5"); - confirmCell(cf, null, 4, 1, true, true, "$B$5"); - } - - @Test - void testAbsRef2(){ - CellReference cf = new CellReference(4,1,true,true); - confirmCell(cf, null, 4, 1, true, true, "$B$5"); - } - - @Test - void testAbsRef3(){ - CellReference cf = new CellReference("B$5"); - confirmCell(cf, null, 4, 1, true, false, "B$5"); - } - - @Test - void testAbsRef4(){ - CellReference cf = new CellReference(4,1,true,false); - confirmCell(cf, null, 4, 1, true, false, "B$5"); - } - - @Test - void testAbsRef5(){ - CellReference cf = new CellReference("$B5"); - confirmCell(cf, null, 4, 1, false, true, "$B5"); - } - - @Test - void testAbsRef6(){ - CellReference cf = new CellReference(4,1,false,true); - confirmCell(cf, null, 4, 1, false, true, "$B5"); - } - - @Test - void testAbsRef7(){ - CellReference cf = new CellReference("B5"); - confirmCell(cf, null, 4, 1, false, false, "B5"); - } - - @Test - void testAbsRef8(){ - CellReference cf = new CellReference(4,1,false,false); - confirmCell(cf, null, 4, 1, false, false, "B5"); - } - - @Test - void testSpecialSheetNames() { - CellReference cf; - cf = new CellReference("'profit + loss'!A1"); - confirmCell(cf, "profit + loss", 0, 0, false, false, "'profit + loss'!A1"); - - cf = new CellReference("'O''Brien''s Sales'!A1"); - confirmCell(cf, "O'Brien's Sales", 0, 0, false, false, "'O''Brien''s Sales'!A1"); - - cf = new CellReference("'Amazing!'!A1"); - confirmCell(cf, "Amazing!", 0, 0, false, false, "'Amazing!'!A1"); - } - - /* package */ static void confirmCell(CellReference cf, String expSheetName, int expRow, - int expCol, boolean expIsRowAbs, boolean expIsColAbs, String expText) { - - assertEquals(expSheetName, cf.getSheetName()); - assertEquals(expRow, cf.getRow(), "row index is wrong"); - assertEquals(expCol, cf.getCol(), "col index is wrong"); - assertEquals(expIsRowAbs, cf.isRowAbsolute(), "isRowAbsolute is wrong"); - assertEquals(expIsColAbs, cf.isColAbsolute(), "isColAbsolute is wrong"); - assertEquals(expText, cf.formatAsString(), "text is wrong"); - } - - @Test - void testClassifyCellReference() { - confirmNameType("a1", NameType.CELL); - confirmNameType("pfy1", NameType.NAMED_RANGE); - confirmNameType("pf1", NameType.NAMED_RANGE); // (col) out of cell range - confirmNameType("fp1", NameType.CELL); - confirmNameType("pf$1", NameType.BAD_CELL_OR_NAMED_RANGE); - confirmNameType("_A1", NameType.NAMED_RANGE); - confirmNameType("A_1", NameType.NAMED_RANGE); - confirmNameType("A1_", NameType.NAMED_RANGE); - confirmNameType(".A1", NameType.BAD_CELL_OR_NAMED_RANGE); - confirmNameType("A.1", NameType.NAMED_RANGE); - confirmNameType("A1.", NameType.NAMED_RANGE); - } - - @Test - void testClassificationOfRowReferences(){ - confirmNameType("10", NameType.ROW); - confirmNameType("$10", NameType.ROW); - confirmNameType("65536", NameType.ROW); - - confirmNameType("65537", NameType.BAD_CELL_OR_NAMED_RANGE); - confirmNameType("$100000", NameType.BAD_CELL_OR_NAMED_RANGE); - confirmNameType("$1$1", NameType.BAD_CELL_OR_NAMED_RANGE); - } - - private void confirmNameType(String ref, NameType expectedResult) { - NameType actualResult = CellReference.classifyCellReference(ref, SpreadsheetVersion.EXCEL97); - assertEquals(expectedResult, actualResult); - } -} diff --git a/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java b/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java deleted file mode 100644 index ff3ec06277..0000000000 --- a/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Map; - -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.junit.jupiter.api.Test; - -final class TestHSSFColor { - @Test - void testBasics() { - assertTrue(HSSFColorPredefined.YELLOW.getIndex() > 0); - assertTrue(HSSFColorPredefined.YELLOW.getIndex2() > 0); - } - - @Test - void testContents() { - short[] triplet = HSSFColorPredefined.YELLOW.getTriplet(); - assertEquals(3, triplet.length); - assertEquals(255, triplet[0]); - assertEquals(255, triplet[1]); - assertEquals(0, triplet[2]); - - assertEquals("FFFF:FFFF:0", HSSFColorPredefined.YELLOW.getHexString()); - } - - @Test - void testTripletHash() { - Map triplets = HSSFColor.getTripletHash(); - - assertEquals( - HSSFColorPredefined.MAROON.getColor(), - triplets.get(HSSFColorPredefined.MAROON.getHexString()) - ); - assertEquals( - HSSFColorPredefined.YELLOW.getColor(), - triplets.get(HSSFColorPredefined.YELLOW.getHexString()) - ); - } -} diff --git a/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java b/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java deleted file mode 100644 index 15190f93ab..0000000000 --- a/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** - * Tests the {@link RKUtil} class. - */ -final class TestRKUtil { - - /** - * Check we can decode correctly. - */ - @Test - void testDecode() { - - int[] values = { 1074266112, 1081384961, 1081397249, - 0x3FF00000, 0x405EC001, 0x02F1853A, 0x02F1853B, 0xFCDD699A, - }; - double[] rvalues = { 3.0, 3.3, 3.33, - 1, 1.23, 12345678, 123456.78, -13149594, - }; - - for (int j = 0; j < values.length; j++) { - - int intBits = values[j]; - double expectedValue = rvalues[j]; - double actualValue = RKUtil.decodeNumber(intBits); - assertEquals(expectedValue, actualValue, 0); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java b/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java deleted file mode 100644 index 959565cfeb..0000000000 --- a/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java +++ /dev/null @@ -1,211 +0,0 @@ -/* ==================================================================== - 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.poifs.crypt; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.io.InputStream; - -import javax.crypto.spec.SecretKeySpec; - -import org.apache.poi.hssf.record.crypto.Biff8DecryptingStream; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Biff8DecryptingStream} - */ -final class TestBiff8DecryptingStream { - - /** - * A mock {@link InputStream} that keeps track of position and also produces - * slightly interesting data. Each successive data byte value is one greater - * than the previous. - */ - private static final class MockStream extends InputStream { - private final int _initialValue; - private int _position; - - public MockStream(int initialValue) { - _initialValue = initialValue; - } - - @Override - public int read() { - return (_initialValue+_position++) & 0xFF; - } - } - - private static final class StreamTester { - private final Biff8DecryptingStream _bds; - - /** - * @param expectedFirstInt expected value of the first int read from the decrypted stream - */ - public StreamTester(MockStream ms, String keyDigestHex, int expectedFirstInt) { - byte[] keyDigest = HexRead.readFromString(keyDigestHex); - EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4); - Decryptor dec = ei.getDecryptor(); - dec.setSecretKey(new SecretKeySpec(keyDigest, "RC4")); - - _bds = new Biff8DecryptingStream(ms, 0, ei); - assertEquals(expectedFirstInt, _bds.readInt()); - } - - public Biff8DecryptingStream getBDS() { - return _bds; - } - - /** - * Used to 'skip over' the uninteresting middle bits of the key blocks. - * Also confirms that read position of the underlying stream is aligned. - */ - void rollForward(int fromPosition, int toPosition) { - assertEquals(fromPosition, _bds.getPosition()); - for (int i = fromPosition; i < toPosition; i++) { - _bds.readByte(); - } - assertEquals(toPosition, _bds.getPosition()); - } - - void confirmByte(int expVal) { - assertEquals(expVal, _bds.readUByte()); - } - - void confirmShort(int expVal) { - assertEquals((short)expVal, _bds.readShort()); - } - - void confirmUShort(int expVal) { - assertEquals(expVal, _bds.readUShort()); - } - - public short readShort() { - return _bds.readShort(); - } - - public int readUShort() { - return _bds.readUShort(); - } - - void confirmInt(int expVal) { - assertEquals(expVal, _bds.readInt()); - } - - void confirmLong(long expVal) { - assertEquals(expVal, _bds.readLong()); - } - - void confirmData(String expHexData) { - - byte[] expData = HexRead.readFromString(expHexData); - byte[] actData = new byte[expData.length]; - _bds.readFully(actData); - assertArrayEquals(expData, actData, "Data mismatch"); - } - } - - /** - * Tests reading of 64,32,16 and 8 bit integers aligned with key changing boundaries - */ - @Test - void readsAlignedWithBoundary() { - StreamTester st = createStreamTester(); - - st.rollForward(0x0004, 0x03FF); - st.confirmByte(0x3E); - st.confirmByte(0x28); - st.rollForward(0x0401, 0x07FE); - st.confirmShort(0x76CC); - st.confirmShort(0xD83E); - st.rollForward(0x0802, 0x0BFC); - st.confirmInt(0x25F280EB); - st.confirmInt(0xB549E99B); - st.rollForward(0x0C04, 0x0FF8); - st.confirmLong(0x6AA2D5F6B975D10CL); - st.confirmLong(0x34248ADF7ED4F029L); - // check for signed/unsigned shorts #58069 - st.rollForward(0x1008, 0x7213); - st.confirmUShort(0xFFFF); - st.rollForward(0x7215, 0x1B9AD); - st.confirmShort(-1); - st.rollForward(0x1B9AF, 0x37D99); - assertEquals(0xFFFF, st.readUShort()); - st.rollForward(0x37D9B, 0x4A6F2); - assertEquals(-1, st.readShort()); - } - - /** - * Tests reading of 64,32 and 16 bit integers across key changing boundaries - */ - @Test - void readsSpanningBoundary() { - StreamTester st = createStreamTester(); - - st.rollForward(0x0004, 0x03FC); - st.confirmLong(0x885243283E2A5EEFL); - st.rollForward(0x0404, 0x07FE); - st.confirmInt(0xD83E76CC); - st.rollForward(0x0802, 0x0BFF); - st.confirmShort(0x9B25); - } - - /** - * Checks that the BIFF header fields (sid, size) get read without applying decryption, - * and that the RC4 stream stays aligned during these calls - */ - @Test - void readHeaderUShort() { - StreamTester st = createStreamTester(); - - st.rollForward(0x0004, 0x03FF); - - Biff8DecryptingStream bds = st.getBDS(); - int hval = bds.readDataSize(); // unencrypted - int nextInt = bds.readInt(); - assertNotEquals(0x8F534029, nextInt, "Indentified bug in key alignment after call to readHeaderUShort()"); - assertEquals(0x16885243, nextInt); - assertNotEquals(0x283E, hval, "readHeaderUShort() incorrectly decrypted result"); - assertEquals(0x504F, hval); - - // confirm next key change - st.rollForward(0x0405, 0x07FC); - st.confirmInt(0x76CC1223); - st.confirmInt(0x4842D83E); - } - - /** - * Tests reading of byte sequences across and aligned with key changing boundaries - */ - @Test - void readByteArrays() { - StreamTester st = createStreamTester(); - - st.rollForward(0x0004, 0x2FFC); - st.confirmData("66 A1 20 B1 04 A3 35 F5"); // 4 bytes on either side of boundary - st.rollForward(0x3004, 0x33F8); - st.confirmData("F8 97 59 36"); // last 4 bytes in block - st.confirmData("01 C2 4E 55"); // first 4 bytes in next block - } - - private static StreamTester createStreamTester() { - return new StreamTester(new MockStream(0x50), "BA AD F0 0D 00", 0x96C66829); - } -} diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java b/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java deleted file mode 100644 index 22452a0efd..0000000000 --- a/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java +++ /dev/null @@ -1,45 +0,0 @@ -/* ==================================================================== - 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.poifs.crypt; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.apache.poi.EncryptedDocumentException; -import org.junit.jupiter.api.Test; - -class TestCipherAlgorithm { - @Test - void validInputs() { - assertEquals(128, CipherAlgorithm.aes128.defaultKeySize); - - for(CipherAlgorithm alg : CipherAlgorithm.values()) { - assertEquals(alg, CipherAlgorithm.valueOf(alg.toString())); - } - - assertEquals(CipherAlgorithm.aes128, CipherAlgorithm.fromEcmaId(0x660E)); - assertEquals(CipherAlgorithm.aes192, CipherAlgorithm.fromXmlId("AES", 192)); - } - - @Test - void invalidInputs() { - assertThrows(EncryptedDocumentException.class, () -> CipherAlgorithm.fromEcmaId(0)); - assertThrows(EncryptedDocumentException.class, () -> CipherAlgorithm.fromXmlId("AES", 1)); - assertThrows(EncryptedDocumentException.class, () -> CipherAlgorithm.fromXmlId("RC1", 0x40)); - } -} diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java b/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java deleted file mode 100644 index 2bca550236..0000000000 --- a/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - 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.poifs.crypt; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.FilePassRecord; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.HexRead; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -class TestXorEncryption { - - private static final HSSFTestDataSamples samples = new HSSFTestDataSamples(); - - @Test - void testXorEncryption() { - // Xor-Password: abc - // 2.5.343 XORObfuscation - // key = 20810 - // verifier = 52250 - int verifier = CryptoFunctions.createXorVerifier1("abc"); - int key = CryptoFunctions.createXorKey1("abc"); - assertEquals(20810, key); - assertEquals(52250, verifier); - - byte[] xorArrAct = CryptoFunctions.createXorArray1("abc"); - byte[] xorArrExp = HexRead.readFromString("AC-CC-A4-AB-D6-BA-C3-BA-D6-A3-2B-45-D3-79-29-BB"); - assertThat(xorArrExp, equalTo(xorArrAct)); - } - - @SuppressWarnings("static-access") - @Test - void testUserFile() throws IOException { - File f = samples.getSampleFile("xor-encryption-abc.xls"); - Biff8EncryptionKey.setCurrentUserPassword("abc"); - try (POIFSFileSystem fs = new POIFSFileSystem(f, true); - HSSFWorkbook hwb = new HSSFWorkbook(fs.getRoot(), true)) { - HSSFSheet sh = hwb.getSheetAt(0); - assertEquals(1.0, sh.getRow(0).getCell(0).getNumericCellValue(), 0.0); - assertEquals(2.0, sh.getRow(1).getCell(0).getNumericCellValue(), 0.0); - assertEquals(3.0, sh.getRow(2).getCell(0).getNumericCellValue(), 0.0); - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } - - @Test - @Disabled("currently not supported") - void encrypt() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - try (HSSFWorkbook hwb = HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")) { - Biff8EncryptionKey.setCurrentUserPassword("abc"); - hwb.getInternalWorkbook().getWorkbookRecordList() - .add(1, new FilePassRecord(EncryptionMode.xor)); - hwb.write(bos); - } - try (HSSFWorkbook hwb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { - assertEquals(3, hwb.getNumberOfSheets()); - } - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java b/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java deleted file mode 100644 index 42a607c130..0000000000 --- a/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java +++ /dev/null @@ -1,100 +0,0 @@ -/* ==================================================================== - 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.poifs.crypt.binaryrc4; - -import static org.apache.poi.util.HexRead.readFromString; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.security.GeneralSecurityException; - -import javax.crypto.SecretKey; - -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.junit.jupiter.api.Test; - -class TestBinaryRC4 { - @Test - void createKeyDigest() { - byte[] docIdData = readFromString("17 F6 D1 6B 09 B1 5F 7B 4C 9D 03 B4 81 B5 B4 4A"); - byte[] expResult = readFromString("C2 D9 56 B2 6B"); - - EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4); - BinaryRC4EncryptionVerifier ver = (BinaryRC4EncryptionVerifier)ei.getVerifier(); - ver.setSalt(docIdData); - SecretKey sk = BinaryRC4Decryptor.generateSecretKey("MoneyForNothing", ver); - - assertArrayEquals(expResult, sk.getEncoded(), "keyDigest mismatch"); - } - - @Test - void testValidateWithDefaultPassword() throws GeneralSecurityException { - - String docIdSuffixA = "F 35 52 38 0D 75 4A E6 85 C2 FD 78 CE 3D D1 B6"; // valid prefix is 'D' - String saltHashA = "30 38 BE 5E 93 C5 7E B4 5F 52 CD A1 C6 8F B6 2A"; - String saltDataA = "D4 04 43 EC B7 A7 6F 6A D2 68 C7 DF CF A8 80 68"; - - String docIdB = "39 D7 80 41 DA E4 74 2C 8C 84 F9 4D 39 9A 19 2D"; - String saltDataSuffixB = "3 EA 8D 52 11 11 37 D2 BD 55 4C 01 0A 47 6E EB"; // valid prefix is 'C' - String saltHashB = "96 19 F5 D0 F1 63 08 F1 3E 09 40 1E 87 F0 4E 16"; - - confirmValid(true, "D" + docIdSuffixA, saltDataA, saltHashA); - confirmValid(true, docIdB, "C" + saltDataSuffixB, saltHashB); - confirmValid(false, "E" + docIdSuffixA, saltDataA, saltHashA); - confirmValid(false, docIdB, "B" + saltDataSuffixB, saltHashB); - } - - @Test - void testValidateWithSuppliedPassword() throws GeneralSecurityException { - - String docId = "DF 35 52 38 0D 75 4A E6 85 C2 FD 78 CE 3D D1 B6"; - String saltData = "D4 04 43 EC B7 A7 6F 6A D2 68 C7 DF CF A8 80 68"; - String saltHashA = "8D C2 63 CC E1 1D E0 05 20 16 96 AF 48 59 94 64"; // for password '5ecret' - String saltHashB = "31 0B 0D A4 69 55 8E 27 A1 03 AD C9 AE F8 09 04"; // for password '5ecret' - - confirmValid(true, docId, saltData, saltHashA, "5ecret"); - confirmValid(false, docId, saltData, saltHashA, "Secret"); - confirmValid(true, docId, saltData, saltHashB, "Secret"); - confirmValid(false, docId, saltData, saltHashB, "secret"); - } - - - private static void confirmValid(boolean expectedResult, - String docIdHex, String saltDataHex, String saltHashHex) throws GeneralSecurityException { - confirmValid(expectedResult, docIdHex, saltDataHex, saltHashHex, null); - } - - private static void confirmValid(boolean expectedResult, String docIdHex, - String saltDataHex, String saltHashHex, String password) throws GeneralSecurityException { - byte[] docId = readFromString(docIdHex); - byte[] saltData = readFromString(saltDataHex); - byte[] saltHash = readFromString(saltHashHex); - - EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4); - BinaryRC4EncryptionVerifier ver = (BinaryRC4EncryptionVerifier)ei.getVerifier(); - ver.setSalt(docId); - ver.setEncryptedVerifier(saltData); - ver.setEncryptedVerifierHash(saltHash); - - String pass = password == null ? Decryptor.DEFAULT_PASSWORD : password; - boolean actResult = ei.getDecryptor().verifyPassword(pass); - assertEquals(expectedResult, actResult, expectedResult ? "validate failed" : "validate succeeded unexpectedly"); - } -} diff --git a/src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java b/src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java deleted file mode 100644 index 1fa1802bea..0000000000 --- a/src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java +++ /dev/null @@ -1,192 +0,0 @@ -/* ==================================================================== - 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.poifs.dev; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.security.Permission; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.NotOLE2FileException; -import org.apache.poi.poifs.filesystem.OfficeXmlFileException; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.poifs.property.PropertyTable; -import org.apache.poi.util.NullPrintStream; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -public class TestPOIFSDump { - - private static PrintStream SYSTEM; - @BeforeAll - public static void setUp() throws UnsupportedEncodingException { - SYSTEM = System.out; - System.setOut(new NullPrintStream()); - } - - @AfterAll - public static void resetSystemOut() { - System.setOut(SYSTEM); - } - - private static final String TEST_FILE = HSSFTestDataSamples.getSampleFile("46515.xls").getAbsolutePath(); - private static final String INVALID_FILE = HSSFTestDataSamples.getSampleFile("48936-strings.txt").getAbsolutePath(); - private static final String INVALID_XLSX_FILE = HSSFTestDataSamples.getSampleFile("47668.xlsx").getAbsolutePath(); - - private static final String[] DUMP_OPTIONS = { - "-dumprops", - "-dump-props", - "-dump-properties", - "-dumpmini", - "-dump-mini", - "-dump-ministream", - "-dump-mini-stream", - }; - - @AfterEach - void tearDown() throws IOException { - // clean up the directory that POIFSDump writes to - deleteDirectory(new File(new File(TEST_FILE+"_dump").getName())); - } - - public static void deleteDirectory(File directory) throws IOException { - if (!directory.exists()) { - return; - } - - cleanDirectory(directory); - - if (!directory.delete()) { - String message = - "Unable to delete directory " + directory + "."; - throw new IOException(message); - } - } - - private static void cleanDirectory(File directory) throws IOException { - if (!directory.isDirectory()) { - String message = directory + " is not a directory"; - throw new IllegalArgumentException(message); - } - - File[] files = directory.listFiles(); - if (files == null) { // null if security restricted - throw new IOException("Failed to list contents of " + directory); - } - - IOException exception = null; - for (File file : files) { - try { - forceDelete(file); - } catch (IOException ioe) { - exception = ioe; - } - } - - if (null != exception) { - throw exception; - } - } - - private static void forceDelete(File file) throws IOException { - if (file.isDirectory()) { - deleteDirectory(file); - } else { - boolean filePresent = file.exists(); - if (!file.delete()) { - if (!filePresent){ - throw new FileNotFoundException("File does not exist: " + file); - } - String message = - "Unable to delete file: " + file; - throw new IOException(message); - } - } - } - - @Test - void testMain() throws Exception { - POIFSDump.main(new String[]{TEST_FILE}); - - for(String option : DUMP_OPTIONS) { - assertDoesNotThrow(() -> POIFSDump.main(new String[]{option, TEST_FILE})); - } - } - @Test - void testInvalidFile() { - assertThrows(NotOLE2FileException.class, () -> POIFSDump.main(new String[]{INVALID_FILE})); - assertThrows(OfficeXmlFileException.class, () -> POIFSDump.main(new String[]{INVALID_XLSX_FILE})); - - for(String option : DUMP_OPTIONS) { - assertThrows(NotOLE2FileException.class, () -> POIFSDump.main(new String[]{option, INVALID_FILE})); - assertThrows(OfficeXmlFileException.class, () -> POIFSDump.main(new String[]{option, INVALID_XLSX_FILE})); - } - } - - @Test - void testMainNoArgs() throws Exception { - SecurityManager sm = System.getSecurityManager(); - try { - System.setSecurityManager(new SecurityManager() { - @Override - public void checkExit(int status) { - throw new SecurityException(); - } - - @Override - public void checkPermission(Permission perm) { - // Allow other activities by default - } - }); - - assertThrows(SecurityException.class, () -> POIFSDump.main(new String[]{})); - } finally { - System.setSecurityManager(sm); - } - } - - @Test - void testFailToWrite() throws IOException { - File dir = TempFile.createTempFile("TestPOIFSDump", ".tst"); - assertTrue(dir.exists(), "Had: " + dir); - assertTrue(dir.delete(), "Had: " + dir); - assertTrue(dir.mkdirs(), "Had: " + dir); - - FileInputStream is = new FileInputStream(TEST_FILE); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - - PropertyTable props = fs.getPropertyTable(); - assertNotNull(props); - - // try with an invalid startBlock to trigger an exception - // to validate that file-handles are closed properly - assertThrows(IndexOutOfBoundsException.class, () -> POIFSDump.dump(fs, 999999999, "mini-stream", dir)); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/poifs/eventfilesystem/Listener.java b/src/testcases/org/apache/poi/poifs/eventfilesystem/Listener.java deleted file mode 100644 index 4b597c1719..0000000000 --- a/src/testcases/org/apache/poi/poifs/eventfilesystem/Listener.java +++ /dev/null @@ -1,45 +0,0 @@ - -/* ==================================================================== - 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.poifs.eventfilesystem; - -/** - * Class Listener - * - * @author Marc Johnson (mjohnson at apache dot org) - * @version %I%, %G% - */ - -class Listener - implements POIFSReaderListener -{ - - /** - * Process a POIFSReaderEvent that this listener had registered - * for - * - * @param event the POIFSReaderEvent - */ - - @Override - public void processPOIFSReaderEvent(POIFSReaderEvent event) - { - } -} // end class Listener - diff --git a/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java b/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java deleted file mode 100644 index 1eb939f961..0000000000 --- a/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java +++ /dev/null @@ -1,156 +0,0 @@ -/* ==================================================================== - 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.poifs.eventfilesystem; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; -import org.junit.jupiter.api.Test; - -/** - * Class to test POIFSReaderRegistry functionality - * - * @author Marc Johnson - */ -final class TestPOIFSReaderRegistry { - private final POIFSReaderListener[] listeners = - { - new Listener(), new Listener(), new Listener(), new Listener() - }; - private final POIFSDocumentPath[] paths = - { - new POIFSDocumentPath(), new POIFSDocumentPath(new String[] - { - "a" - }), new POIFSDocumentPath(new String[] - { - "b" - }), new POIFSDocumentPath(new String[] - { - "c" - }) - }; - private final String[] names = - { - "a0", "a1", "a2", "a3" - }; - - /** - * Test empty registry - */ - @Test - void testEmptyRegistry() { - POIFSReaderRegistry registry = new POIFSReaderRegistry(); - - for (POIFSDocumentPath path : paths) { - for (String name : names) { - Iterator listeners = - registry.getListeners(path, name).iterator(); - - assertFalse(listeners.hasNext()); - } - } - } - - /** - * Test mixed registration operations - */ - @Test - void testMixedRegistrationOperations() { - POIFSReaderRegistry registry = new POIFSReaderRegistry(); - - for (int j = 0; j < listeners.length; j++) - { - for (int k = 0; k < paths.length; k++) - { - for (int n = 0; n < names.length; n++) - { - if ((j != k) && (k != n)) - { - registry.registerListener( - listeners[ j ], paths[ k ], names[ n ]); - } - } - } - } - for (int k = 0; k < paths.length; k++) - { - for (int n = 0; n < names.length; n++) - { - Iterable listeners = - registry.getListeners(paths[ k ], names[ n ]); - - if (k == n) - { - assertFalse(listeners.iterator().hasNext()); - } - else - { - Set registeredListeners = - new HashSet<>(); - - for (POIFSReaderListener rl : listeners) { - registeredListeners.add(rl); - } - assertEquals(this.listeners.length - 1, - registeredListeners.size()); - for (int j = 0; j < this.listeners.length; j++) - { - if (j == k) - { - assertFalse(registeredListeners - .contains(this.listeners[j])); - } - else - { - assertTrue(registeredListeners - .contains(this.listeners[ j ])); - } - } - } - } - } - for (POIFSReaderListener listener : listeners) { - registry.registerListener(listener); - } - for (POIFSDocumentPath path : paths) { - for (String name : names) { - Iterable listeners = - registry.getListeners(path, name); - Set registeredListeners = - new HashSet<>(); - - for (POIFSReaderListener rl : listeners) { - registeredListeners.add(rl); - } - assertEquals(this.listeners.length, - registeredListeners.size()); - for (POIFSReaderListener listener : this.listeners) { - assertTrue(registeredListeners - .contains(listener)); - } - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java b/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java deleted file mode 100644 index ed2ce941ab..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java +++ /dev/null @@ -1,170 +0,0 @@ - -/* ==================================================================== - 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.poifs.filesystem; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.util.IOUtils; - -/** - * Test (Proof of concept) program that employs the - * POIFSReaderListener and POIFSWriterListener interfaces - * - * @author Marc Johnson (mjohnson at apache dot org) - */ - -public final class ReaderWriter - implements POIFSReaderListener, POIFSWriterListener -{ - private final DirectoryEntry root; - - // keys are DocumentDescriptors, values are byte[]s - private final Map dataMap = new HashMap<>(); - - private ReaderWriter(final POIFSFileSystem filesystem) { - root = filesystem.getRoot(); - } - - public static void main(String [] args) throws IOException - { - if (args.length != 2) - { - System.err.println( - "two arguments required: one input file name and one output file name"); - } - else - { - POIFSReader reader = new POIFSReader(); - POIFSFileSystem filesystem = new POIFSFileSystem(); - - reader.registerListener(new ReaderWriter(filesystem)); - - reader.read(new File(args[ 0 ])); - FileOutputStream ostream = new FileOutputStream(args[ 1 ]); - - filesystem.writeFilesystem(ostream); - ostream.close(); - - filesystem.close(); - } - } - - /* ********** START implementation of POIFSReaderListener ********** */ - - /** - * Process a POIFSReaderEvent that this listener had registered - * for - * - * @param event the POIFSReaderEvent - */ - - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - @SuppressWarnings("resource") - DocumentInputStream istream = event.getStream(); - POIFSDocumentPath path = event.getPath(); - String name = event.getName(); - - try { - byte[] data = IOUtils.toByteArray(istream); - int size = data.length; - - DocumentDescriptor descriptor = new DocumentDescriptor(path, - name); - - System.out.println("adding document: " + descriptor + " (" + size - + " bytes)"); - dataMap.put(descriptor, data); - //int pathLength = path.length(); - DirectoryEntry entry = root; - - for (int k = 0; k < path.length(); k++) - { - String componentName = path.getComponent(k); - Entry nextEntry = null; - - try - { - nextEntry = entry.getEntry(componentName); - } - catch (FileNotFoundException ignored) - { - try - { - nextEntry = entry.createDirectory(componentName); - } - catch (IOException e) - { - System.out.println("Unable to create directory"); - e.printStackTrace(); - System.exit(1); - } - } - entry = ( DirectoryEntry ) nextEntry; - } - entry.createDocument(name, size, this); - } - catch (IOException ignored) - { - } - } - - /* ********** END implementation of POIFSReaderListener ********** */ - /* ********** START implementation of POIFSWriterListener ********** */ - - /** - * Process a POIFSWriterEvent that this listener had registered - * for - * - * @param event the POIFSWriterEvent - */ - - @Override - public void processPOIFSWriterEvent(final POIFSWriterEvent event) - { - try - { - DocumentDescriptor descriptor = - new DocumentDescriptor(event.getPath(), event.getName()); - - System.out.println("looking up document: " + descriptor + " (" - + event.getLimit() + " bytes)"); - event.getStream().write(dataMap.get(descriptor)); - } - catch (IOException e) - { - System.out.println("Unable to write document"); - e.printStackTrace(); - System.exit(1); - } - } - - /* ********** END implementation of POIFSWriterListener ********** */ -} // end public class ReaderWriter - diff --git a/src/testcases/org/apache/poi/poifs/filesystem/SlowInputStream.java b/src/testcases/org/apache/poi/poifs/filesystem/SlowInputStream.java deleted file mode 100644 index f818d21978..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/SlowInputStream.java +++ /dev/null @@ -1,41 +0,0 @@ - -/* ==================================================================== - 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.poifs.filesystem; - -import java.io.*; -import java.util.Random; - -/** - * Returns a random amount of requested data. Used to check conformance with - * InputStream API contracts. - */ -public class SlowInputStream extends FilterInputStream -{ - private final Random r = new Random(0); - - public SlowInputStream(InputStream in) { - super(in); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - return super.read(b, off, r.nextInt(len) + 1); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java deleted file mode 100644 index 9212aa6c8f..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java +++ /dev/null @@ -1,208 +0,0 @@ - -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Iterator; - -import org.apache.poi.poifs.property.DirectoryProperty; -import org.apache.poi.poifs.property.DocumentProperty; -import org.junit.jupiter.api.Test; - -/** - * Class to test DirectoryNode functionality - */ -final class TestDirectoryNode { - - /** - * test trivial constructor (a DirectoryNode with no children) - */ - @Test - void testEmptyConstructor() throws IOException { - try (POIFSFileSystem fs = new POIFSFileSystem()) { - DirectoryProperty property1 = new DirectoryProperty("parent"); - DirectoryProperty property2 = new DirectoryProperty("child"); - DirectoryNode parent = new DirectoryNode(property1, fs, null); - DirectoryNode node = new DirectoryNode(property2, fs, parent); - - assertEquals(0, parent.getPath().length()); - assertEquals(1, node.getPath().length()); - assertEquals("child", node.getPath().getComponent(0)); - - // verify that getEntries behaves correctly - int count = 0; - Iterator iter = node.getEntries(); - - while (iter.hasNext()) { - count++; - iter.next(); - } - assertEquals(0, count); - - // verify behavior of isEmpty - assertTrue(node.isEmpty()); - - // verify behavior of getEntryCount - assertEquals(0, node.getEntryCount()); - - // verify behavior of getEntry - assertThrows(FileNotFoundException.class, () -> node.getEntry("foo")); - - // verify behavior of isDirectoryEntry - assertTrue(node.isDirectoryEntry()); - - // verify behavior of getName - assertEquals(property2.getName(), node.getName()); - - // verify behavior of isDocumentEntry - assertFalse(node.isDocumentEntry()); - - // verify behavior of getParent - assertEquals(parent, node.getParent()); - } - } - - /** - * test non-trivial constructor (a DirectoryNode with children) - */ - @Test - void testNonEmptyConstructor() throws IOException { - DirectoryProperty property1 = new DirectoryProperty("parent"); - DirectoryProperty property2 = new DirectoryProperty("child1"); - - property1.addChild(property2); - property1.addChild(new DocumentProperty("child2", 2000)); - property2.addChild(new DocumentProperty("child3", 30000)); - - try (POIFSFileSystem fs = new POIFSFileSystem()) { - DirectoryNode node = new DirectoryNode(property1, fs, null); - - // verify that getEntries behaves correctly - int count = 0; - Iterator iter = node.getEntries(); - - while (iter.hasNext()) { - count++; - iter.next(); - } - assertEquals(2, count); - - // verify behavior of isEmpty - assertFalse(node.isEmpty()); - - // verify behavior of getEntryCount - assertEquals(2, node.getEntryCount()); - - // verify behavior of getEntry - DirectoryNode child1 = (DirectoryNode) node.getEntry("child1"); - - child1.getEntry("child3"); - node.getEntry("child2"); - assertThrows(FileNotFoundException.class, () -> node.getEntry("child3")); - - // verify behavior of isDirectoryEntry - assertTrue(node.isDirectoryEntry()); - - // verify behavior of getName - assertEquals(property1.getName(), node.getName()); - - // verify behavior of isDocumentEntry - assertFalse(node.isDocumentEntry()); - - // verify behavior of getParent - assertNull(node.getParent()); - } - } - - /** - * test deletion methods - */ - @Test - void testDeletion() throws IOException { - try (POIFSFileSystem fs = new POIFSFileSystem()) { - DirectoryEntry root = fs.getRoot(); - - // verify cannot delete the root directory - assertFalse(root.delete()); - assertTrue(root.isEmpty()); - - DirectoryEntry dir = fs.createDirectory("myDir"); - - assertFalse(root.isEmpty()); - assertTrue(dir.isEmpty()); - - // verify can delete empty directory - assertFalse(root.delete()); - assertTrue(dir.delete()); - - // Now look at a non-empty one - dir = fs.createDirectory("NextDir"); - DocumentEntry doc = - dir.createDocument("foo", - new ByteArrayInputStream(new byte[1])); - - assertFalse(root.isEmpty()); - assertFalse(dir.isEmpty()); - - // verify cannot delete non-empty directory - assertFalse(dir.delete()); - - // but we can delete it if we remove the document - assertTrue(doc.delete()); - assertTrue(dir.isEmpty()); - assertTrue(dir.delete()); - - // It's really gone! - assertTrue(root.isEmpty()); - - } - } - - /** - * test change name methods - */ - @Test - void testRename() throws IOException { - try (POIFSFileSystem fs = new POIFSFileSystem()) { - DirectoryEntry root = fs.getRoot(); - - // verify cannot rename the root directory - assertFalse(root.renameTo("foo")); - DirectoryEntry dir = fs.createDirectory("myDir"); - - assertTrue(dir.renameTo("foo")); - assertEquals("foo", dir.getName()); - DirectoryEntry dir2 = fs.createDirectory("myDir"); - - assertFalse(dir2.renameTo("foo")); - assertEquals("myDir", dir2.getName()); - assertTrue(dir.renameTo("FirstDir")); - assertTrue(dir2.renameTo("foo")); - assertEquals("foo", dir2.getName()); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java deleted file mode 100644 index 15edc14e92..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java +++ /dev/null @@ -1,147 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.apache.poi.poifs.common.POIFSConstants.LARGER_BIG_BLOCK_SIZE; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.stream.IntStream; - -import org.apache.poi.poifs.property.DocumentProperty; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.apache.poi.util.IOUtils; -import org.junit.jupiter.api.Test; - -/** - * Class to test POIFSDocument functionality - */ -class TestDocument { - - /** - * Integration test -- really about all we can do - */ - @Test - void testPOIFSDocument() throws IOException { - - try (POIFSFileSystem poifs = new POIFSFileSystem()) { - - // verify correct number of blocks get created for document - // that is exact multiple of block size - checkDocument(poifs, LARGER_BIG_BLOCK_SIZE); - - // verify correct number of blocks get created for document - // that is not an exact multiple of block size - checkDocument(poifs, LARGER_BIG_BLOCK_SIZE + 1); - - // verify correct number of blocks get created for document - // that is small - checkDocument(poifs, LARGER_BIG_BLOCK_SIZE - 1); - - // verify correct number of blocks get created for document - // that is rather small - checkDocument(poifs, 199); - - - // verify that output is correct - POIFSDocument document = checkDocument(poifs, LARGER_BIG_BLOCK_SIZE + 1); - DocumentProperty property = document.getDocumentProperty(); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - property.writeData(stream); - byte[] output = stream.toByteArray(); - byte[] array2 = RawDataUtil.decompress("H4sIAAAAAAAAAEtlyGMoYShiqGSwYCAH8DEwMf5HAsToMQdiRgEIGwCDyzEQgAAAAA=="); - - assertArrayEquals(array2, output); - } - } - - private static POIFSDocument checkDocument(final POIFSFileSystem poifs, final int size) throws IOException { - final byte[] input = new byte[size]; - IntStream.range(0, size).forEach(i -> input[i] = (byte)i); - - POIFSDocument document = ((DocumentNode)poifs.createDocument( - new SlowInputStream(new ByteArrayInputStream(input)), - "entry"+poifs.getRoot().getEntryCount())).getDocument(); - - final int blockSize = (size >= 4096) ? 512 : 64; - final int blockCount = (size + (blockSize-1)) / blockSize; - - final byte[] bytCpy = checkValues(blockCount, document, input); - final POIFSDocument copied = makeCopy(document,bytCpy); - - checkValues(blockCount, copied, input); - - return document; - } - - private static POIFSDocument makeCopy(POIFSDocument document, byte[] input) throws IOException { - POIFSFileSystem poifs = document.getFileSystem(); - String name = "test" + input.length; - DirectoryNode root = poifs.getRoot(); - if (root.hasEntry(name)) { - root.deleteEntry((EntryNode)root.getEntry(name)); - } - return ((DocumentNode)root - .createDocument(name, new ByteArrayInputStream(input))) - .getDocument(); - } - - private static byte[] checkValues(final int blockCountExp, POIFSDocument document, byte[] input) throws IOException { - assertNotNull(document); - assertNotNull(document.getDocumentProperty().getDocument()); - assertEquals(document, document.getDocumentProperty().getDocument()); - - ByteArrayInputStream bis = new ByteArrayInputStream(input); - - int blockCountAct = 0, bytesRemaining = input.length; - for (ByteBuffer bb : document) { - assertTrue(bytesRemaining > 0); - int bytesAct = Math.min(bb.remaining(), bytesRemaining); - assertTrue(bytesAct <= document.getDocumentBlockSize()); - byte[] bufAct = new byte[bytesAct]; - bb.get(bufAct); - - byte[] bufExp = new byte[bytesAct]; - int bytesExp = bis.read(bufExp, 0, bytesAct); - assertEquals(bytesExp, bytesAct); - - assertArrayEquals(bufExp, bufAct); - blockCountAct++; - bytesRemaining -= bytesAct; - } - - assertEquals(blockCountExp, blockCountAct); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - try (DocumentInputStream dis = document.getFileSystem().createDocumentInputStream( - document.getDocumentProperty().getName())) { - IOUtils.copy(dis, stream); - } - - byte[] output = stream.toByteArray(); - assertArrayEquals(input, stream.toByteArray()); - return output; - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java deleted file mode 100644 index 17c1b572d5..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java +++ /dev/null @@ -1,110 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.junit.jupiter.api.Test; - -/** - * Class to test DocumentDescriptor functionality - */ -final class TestDocumentDescriptor { - - /** - * test equality - */ - @Test - void testEquality() { - String[] names = { "c1", "c2", "c3", "c4", "c5" }; - POIFSDocumentPath a1 = new POIFSDocumentPath(); - POIFSDocumentPath a2 = new POIFSDocumentPath(null); - POIFSDocumentPath a3 = new POIFSDocumentPath(new String[ 0 ]); - POIFSDocumentPath a4 = new POIFSDocumentPath(a1, null); - POIFSDocumentPath a5 = new POIFSDocumentPath(a1, - new String[ 0 ]); - POIFSDocumentPath[] paths = { a1, a2, a3, a4, a5 }; - - for (int j = 0; j < paths.length; j++) { - for (int k = 0; k < paths.length; k++) { - for (int m = 0; m < names.length; m++) { - DocumentDescriptor d1 = new DocumentDescriptor(paths[ j ], names[ m ]); - - for (int n = 0; n < names.length; n++) { - DocumentDescriptor d2 = new DocumentDescriptor(paths[ k ], names[ n ]); - - if (m == n) { - assertEquals(d1, d2, "" + j + "," + k + "," + m + "," + n); - } else { - assertNotEquals(d1, d2); - } - } - } - } - } - a2 = new POIFSDocumentPath(a1, new String[]{"foo"}); - a3 = new POIFSDocumentPath(a2, new String[]{"bar"}); - a4 = new POIFSDocumentPath(a3, new String[]{"fubar"}); - a5 = new POIFSDocumentPath(a4, new String[]{"foobar"}); - POIFSDocumentPath[] builtUpPaths = {a1, a2, a3, a4, a5}; - POIFSDocumentPath[] fullPaths = { - new POIFSDocumentPath(), - new POIFSDocumentPath(new String[]{"foo"}), - new POIFSDocumentPath(new String[]{"foo", "bar"}), - new POIFSDocumentPath(new String[]{"foo", "bar", "fubar"}), - new POIFSDocumentPath(new String[]{"foo", "bar", "fubar", "foobar"}) - }; - - for (int k = 0; k < builtUpPaths.length; k++) { - for (int j = 0; j < fullPaths.length; j++) { - for (int m = 0; m < names.length; m++) { - DocumentDescriptor d1 = new DocumentDescriptor(fullPaths[ j ], names[ m ]); - - for (int n = 0; n < names.length; n++) { - DocumentDescriptor d2 = new DocumentDescriptor(builtUpPaths[ k ], names[ n ]); - - if ((k == j) && (m == n)) { - assertEquals(d1, d2, "" + j + "," + k + "," + m + "," + n); - } else { - assertNotEquals(d1, d2); - } - } - } - } - } - POIFSDocumentPath[] badPaths = { - new POIFSDocumentPath(new String[]{"_foo"}), - new POIFSDocumentPath(new String[]{"foo", "_bar"}), - new POIFSDocumentPath(new String[]{"foo", "bar", "_fubar"}), - new POIFSDocumentPath(new String[]{"foo", "bar", "fubar", "_foobar"}) - }; - - for (POIFSDocumentPath builtUpPath : builtUpPaths) { - for (POIFSDocumentPath badPath : badPaths) { - for (String s : names) { - DocumentDescriptor d1 = new DocumentDescriptor(badPath, s); - for (String name : names) { - DocumentDescriptor d2 = new DocumentDescriptor(builtUpPath, name); - assertNotEquals(d1, d2); - } - } - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java deleted file mode 100644 index c0d4de1353..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java +++ /dev/null @@ -1,410 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.SuppressForbidden; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Class to test DocumentInputStream functionality - */ -final class TestDocumentInputStream { - private DocumentNode _workbook_n; - private byte[] _workbook_data; - private static final int _workbook_size = 5000; - - // non-even division of _workbook_size, also non-even division of - // any block size - private static final int _buffer_size = 6; - - @BeforeEach - void setUp() throws Exception { - int blocks = (_workbook_size + 511) / 512; - - _workbook_data = new byte[512 * blocks]; - Arrays.fill(_workbook_data, (byte) -1); - for (int j = 0; j < _workbook_size; j++) { - _workbook_data[j] = (byte) (j * j); - } - - // Now create the POIFS Version - byte[] _workbook_data_only = Arrays.copyOf(_workbook_data, _workbook_size); - - POIFSFileSystem poifs = new POIFSFileSystem(); - // Make it easy when debugging to see what isn't the doc - byte[] minus1 = new byte[512]; - Arrays.fill(minus1, (byte) -1); - poifs.getBlockAt(-1).put(minus1); - poifs.getBlockAt(0).put(minus1); - poifs.getBlockAt(1).put(minus1); - - // Create the POIFS document - _workbook_n = (DocumentNode) poifs.createDocument( - new ByteArrayInputStream(_workbook_data_only), - "Workbook" - ); - } - - /** - * test constructor - */ - @Test - void testConstructor() throws IOException { - try (DocumentInputStream nstream = new DocumentInputStream(_workbook_n)) { - assertEquals(_workbook_size, _workbook_n.getSize()); - assertEquals(_workbook_size, available(nstream)); - } - } - - /** - * test available() behavior - */ - @Test - void testAvailable() throws IOException { - DocumentInputStream nstream = new DocumentInputStream(_workbook_n); - assertEquals(_workbook_size, available(nstream)); - nstream.close(); - - assertThrows(IllegalStateException.class, () -> available(nstream)); - } - - /** - * test mark/reset/markSupported. - */ - @SuppressWarnings("ResultOfMethodCallIgnored") - @Test - void testMarkFunctions() throws IOException { - byte[] buffer = new byte[_workbook_size / 5]; - byte[] small_buffer = new byte[212]; - - DocumentInputStream stream = new DocumentInputStream(_workbook_n); - // Read a fifth of it, and check all's correct - stream.read(buffer); - for (int j = 0; j < buffer.length; j++) { - assertEquals(_workbook_data[j], buffer[j], "checking byte " + j); - } - assertEquals(_workbook_size - buffer.length, available(stream)); - - // Reset, and check the available goes back to being the - // whole of the stream - stream.reset(); - assertEquals(_workbook_size, available(stream)); - - - // Read part of a block - stream.read(small_buffer); - for (int j = 0; j < small_buffer.length; j++) { - assertEquals(_workbook_data[j], small_buffer[j], "checking byte " + j); - } - assertEquals(_workbook_size - small_buffer.length, available(stream)); - stream.mark(0); - - // Read the next part - stream.read(small_buffer); - for (int j = 0; j < small_buffer.length; j++) { - assertEquals(_workbook_data[j + small_buffer.length], small_buffer[j], "checking byte " + j); - } - assertEquals(_workbook_size - 2 * small_buffer.length, available(stream)); - - // Reset, check it goes back to where it was - stream.reset(); - assertEquals(_workbook_size - small_buffer.length, available(stream)); - - // Read - stream.read(small_buffer); - for (int j = 0; j < small_buffer.length; j++) { - assertEquals(_workbook_data[j + small_buffer.length], small_buffer[j], "checking byte " + j); - } - assertEquals(_workbook_size - 2 * small_buffer.length, available(stream)); - - - // Now read at various points - Arrays.fill(small_buffer, (byte) 0); - stream.read(small_buffer, 6, 8); - stream.read(small_buffer, 100, 10); - stream.read(small_buffer, 150, 12); - int pos = small_buffer.length * 2; - for (int j = 0; j < small_buffer.length; j++) { - byte exp = 0; - if (j >= 6 && j < 6 + 8) { - exp = _workbook_data[pos]; - pos++; - } - if (j >= 100 && j < 100 + 10) { - exp = _workbook_data[pos]; - pos++; - } - if (j >= 150 && j < 150 + 12) { - exp = _workbook_data[pos]; - pos++; - } - - assertEquals(exp, small_buffer[j], "checking byte " + j); - } - - // Now repeat it with spanning multiple blocks - stream = new DocumentInputStream(_workbook_n); - // Read several blocks work - buffer = new byte[_workbook_size / 5]; - stream.read(buffer); - for (int j = 0; j < buffer.length; j++) { - assertEquals(_workbook_data[j], buffer[j], "checking byte " + j); - } - assertEquals(_workbook_size - buffer.length, available(stream)); - - // Read all of it again, check it began at the start again - stream.reset(); - assertEquals(_workbook_size, available(stream)); - - stream.read(buffer); - for (int j = 0; j < buffer.length; j++) { - assertEquals(_workbook_data[j], buffer[j], "checking byte " + j); - } - - // Mark our position, and read another whole buffer - stream.mark(12); - stream.read(buffer); - assertEquals(_workbook_size - (2 * buffer.length), available(stream)); - for (int j = buffer.length; j < (2 * buffer.length); j++) { - assertEquals(_workbook_data[j], buffer[j - buffer.length], "checking byte " + j); - } - - // Reset, should go back to only one buffer full read - stream.reset(); - assertEquals(_workbook_size - buffer.length, available(stream)); - - // Read the buffer again - stream.read(buffer); - assertEquals(_workbook_size - (2 * buffer.length), available(stream)); - for (int j = buffer.length; j < (2 * buffer.length); j++) { - assertEquals(_workbook_data[j], buffer[j - buffer.length], "checking byte " + j); - } - assertTrue(stream.markSupported()); - } - - /** - * test simple read method - */ - @SuppressWarnings("ResultOfMethodCallIgnored") - @Test - void testReadSingleByte() throws IOException { - DocumentInputStream stream = new DocumentInputStream(_workbook_n); - int remaining = _workbook_size; - - // Try and read each byte in turn - for (int j = 0; j < _workbook_size; j++) { - int b = stream.read(); - assertTrue(b >= 0, "checking sign of " + j); - assertEquals(_workbook_data[j], (byte) b, "validating byte " + j); - remaining--; - assertEquals(remaining, available(stream), "checking remaining after reading byte " + j); - } - - // Ensure we fell off the end - assertEquals(-1, stream.read()); - - // Check that after close we can no longer read - stream.close(); - assertThrows(IOException.class, stream::read); - } - - /** - * Test buffered read - */ - @SuppressWarnings("ResultOfMethodCallIgnored") - @Test - void testBufferRead() throws IOException { - DocumentInputStream stream = new DocumentInputStream(_workbook_n); - // Need to give a byte array to read - assertThrows(NullPointerException.class, () -> stream.read(null)); - - // test reading zero length buffer - assertEquals(0, stream.read(new byte[0])); - assertEquals(_workbook_size, available(stream)); - byte[] buffer = new byte[_buffer_size]; - int offset = 0; - - while (available(stream) >= buffer.length) { - assertEquals(_buffer_size, stream.read(buffer)); - for (byte element : buffer) { - assertEquals(_workbook_data[offset], element, "in main loop, byte " + offset); - offset++; - } - assertEquals(_workbook_size - offset, available(stream), "offset " + offset); - } - assertEquals(_workbook_size % _buffer_size, available(stream)); - Arrays.fill(buffer, (byte) 0); - int count = stream.read(buffer); - - assertEquals(_workbook_size % _buffer_size, count); - for (int j = 0; j < count; j++) { - assertEquals(_workbook_data[offset], buffer[j], "past main loop, byte " + offset); - offset++; - } - assertEquals(_workbook_size, offset); - for (int j = count; j < buffer.length; j++) { - assertEquals(0, buffer[j], "checking remainder, byte " + j); - } - assertEquals(-1, stream.read(buffer)); - stream.close(); - - assertThrows(IOException.class, () -> stream.read(buffer)); - } - - /** - * Test complex buffered read - */ - @SuppressWarnings("ResultOfMethodCallIgnored") - @Test - void testComplexBufferRead() throws IOException { - DocumentInputStream stream = new DocumentInputStream(_workbook_n); - assertThrows(IllegalArgumentException.class, () -> stream.read(null, 0, 1)); - - // test illegal offsets and lengths - assertThrows(IndexOutOfBoundsException.class, () -> stream.read(new byte[5], -4, 0)); - assertThrows(IndexOutOfBoundsException.class, () -> stream.read(new byte[5], 0, -4)); - assertThrows(IndexOutOfBoundsException.class, () -> stream.read(new byte[5], 0, 6)); - - // test reading zero - assertEquals(0, stream.read(new byte[5], 0, 0)); - assertEquals(_workbook_size, available(stream)); - byte[] buffer = new byte[_workbook_size]; - int offset = 0; - - while (available(stream) >= _buffer_size) { - Arrays.fill(buffer, (byte) 0); - assertEquals(_buffer_size, stream.read(buffer, offset, _buffer_size)); - for (int j = 0; j < offset; j++) { - assertEquals(0, buffer[j], "checking byte " + j); - } - for (int j = offset; j < (offset + _buffer_size); j++) { - assertEquals(_workbook_data[j], buffer[j], "checking byte " + j); - } - for (int j = offset + _buffer_size; j < buffer.length; j++) { - assertEquals(0, buffer[j], "checking byte " + j); - } - offset += _buffer_size; - assertEquals(_workbook_size - offset, available(stream), "offset " + offset); - } - assertEquals(_workbook_size % _buffer_size, available(stream)); - Arrays.fill(buffer, (byte) 0); - int count = stream.read(buffer, offset, _workbook_size % _buffer_size); - - assertEquals(_workbook_size % _buffer_size, count); - for (int j = 0; j < offset; j++) { - assertEquals(0, buffer[j], "checking byte " + j); - } - for (int j = offset; j < buffer.length; j++) { - assertEquals(_workbook_data[j], buffer[j], "checking byte " + j); - } - assertEquals(_workbook_size, offset + count); - for (int j = count; j < offset; j++) { - assertEquals(0, buffer[j], "byte " + j); - } - - assertEquals(-1, stream.read(buffer, 0, 1)); - stream.close(); - - assertThrows(IOException.class, () -> stream.read(buffer, 0, 1)); - } - - /** - * Tests that we can skip within the stream - */ - @Test - void testSkip() throws IOException { - DocumentInputStream stream = new DocumentInputStream(_workbook_n); - assertEquals(_workbook_size, available(stream)); - int count = available(stream); - - while (available(stream) >= _buffer_size) { - assertEquals(_buffer_size, stream.skip(_buffer_size)); - count -= _buffer_size; - assertEquals(count, available(stream)); - } - assertEquals(_workbook_size % _buffer_size, - stream.skip(_buffer_size)); - assertEquals(0, available(stream)); - stream.reset(); - assertEquals(_workbook_size, available(stream)); - assertEquals(_workbook_size, stream.skip(_workbook_size * 2)); - assertEquals(0, available(stream)); - stream.reset(); - assertEquals(_workbook_size, available(stream)); - assertEquals(_workbook_size, - stream.skip(2 + (long) Integer.MAX_VALUE)); - assertEquals(0, available(stream)); - } - - /** - * Test that we can read files at multiple levels down the tree - */ - @Test - void testReadMultipleTreeLevels() throws Exception { - final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); - File sample = _samples.getFile("Sample.pub"); - - DocumentInputStream stream; - - try (POIFSFileSystem poifs = new POIFSFileSystem(sample)) { - // Ensure we have what we expect on the root - assertEquals(poifs, poifs.getRoot().getFileSystem()); - - // Check inside - DirectoryNode root = poifs.getRoot(); - // Top Level - Entry top = root.getEntry("Contents"); - assertTrue(top.isDocumentEntry()); - stream = root.createDocumentInputStream(top); - assertNotEquals(-1, stream.read()); - - // One Level Down - DirectoryNode escher = (DirectoryNode) root.getEntry("Escher"); - Entry one = escher.getEntry("EscherStm"); - assertTrue(one.isDocumentEntry()); - stream = escher.createDocumentInputStream(one); - assertNotEquals(-1, stream.read()); - - // Two Levels Down - DirectoryNode quill = (DirectoryNode) root.getEntry("Quill"); - DirectoryNode quillSub = (DirectoryNode) quill.getEntry("QuillSub"); - Entry two = quillSub.getEntry("CONTENTS"); - assertTrue(two.isDocumentEntry()); - stream = quillSub.createDocumentInputStream(two); - assertNotEquals(-1, stream.read()); - } - } - - @SuppressForbidden("just for testing") - private static int available(InputStream is) throws IOException { - return is.available(); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java deleted file mode 100644 index d2815e0254..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java +++ /dev/null @@ -1,124 +0,0 @@ - -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.util.IOUtils; -import org.junit.jupiter.api.Test; - -/** - * Class to test DocumentOutputStream functionality - */ -final class TestDocumentOutputStream { - - /** - * test write(int) behavior - */ - @Test - void testWrite1() throws IOException { - final byte[] expected = data(25); - - POIFSWriterListener l = (event) -> { - DocumentOutputStream dstream = event.getStream(); - - try { - for (byte b : expected) { - dstream.write((int)b); - } - } catch (IOException ignored) { - fail("stream exhausted too early"); - } - - assertThrows(IOException.class, () -> dstream.write(0)); - }; - - compare(l, expected); - } - - /** - * test write(byte[]) behavior - */ - @Test - void testWrite2() throws IOException { - final byte[] expected = data(24); - - POIFSWriterListener l = (event) -> { - DocumentOutputStream dstream = event.getStream(); - - try { - dstream.write(expected); - } catch (IOException ignored) { - fail("stream exhausted too early"); - } - - assertThrows(IOException.class, () -> dstream.write(new byte[]{'7','7','7','7'})); - }; - - compare(l, expected); - } - - /** - * test write(byte[], int, int) behavior - */ - @Test - void testWrite3() throws IOException { - byte[] input = data(50); - byte[] expected = Arrays.copyOfRange(input, 1, 1+25); - - POIFSWriterListener l = (event) -> { - DocumentOutputStream dstream = event.getStream(); - try { - dstream.write(input, 1, 25); - } catch (IOException ignored) { - fail("stream exhausted too early"); - } - assertThrows(IOException.class, () -> dstream.write(input, 0, 1)); - }; - - compare(l, expected); - } - - private static byte[] data(int len) { - byte[] input = new byte[len]; - for (int i = 0; i < len; i++) { - input[i] = (byte)('0' + (i%10)); - } - return input; - } - - private void compare(POIFSWriterListener l, byte[] expected) throws IOException { - try (POIFSFileSystem poifs = new POIFSFileSystem()) { - DirectoryNode root = poifs.getRoot(); - root.createDocument("foo", expected.length, l); - - try (DocumentInputStream is = root.createDocumentInputStream("foo")) { - final ByteArrayOutputStream bos = new ByteArrayOutputStream(expected.length); - IOUtils.copy(is, bos); - assertArrayEquals(expected, bos.toByteArray()); - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java b/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java deleted file mode 100644 index c594fb513d..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.stream.Stream; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.util.IOUtils; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -final class TestEmptyDocument { - private static final Logger LOG = LogManager.getLogger(TestEmptyDocument.class); - - private interface EmptyDoc { - void handle(DirectoryEntry dir) throws IOException; - } - - public static Stream emptySupplier() { - return Stream.of( - Arguments.of("SingleEmptyDocument", (EmptyDoc)TestEmptyDocument::SingleEmptyDocument), - Arguments.of("SingleEmptyDocumentEvent", (EmptyDoc)TestEmptyDocument::SingleEmptyDocumentEvent), - Arguments.of("EmptyDocumentWithFriend", (EmptyDoc)TestEmptyDocument::EmptyDocumentWithFriend), - Arguments.of("EmptyDocumentEventWithFriend", (EmptyDoc)TestEmptyDocument::EmptyDocumentEventWithFriend) - ); - } - - private static void SingleEmptyDocument(DirectoryEntry dir) throws IOException { - dir.createDocument("Foo", new ByteArrayInputStream(new byte[]{})); - } - - private static void SingleEmptyDocumentEvent(DirectoryEntry dir) throws IOException { - dir.createDocument("Foo", 0, event -> LOG.atWarn().log("written")); - } - - private static void EmptyDocumentWithFriend(DirectoryEntry dir) throws IOException { - dir.createDocument("Bar", new ByteArrayInputStream(new byte[]{0})); - dir.createDocument("Foo", new ByteArrayInputStream(new byte[]{})); - } - - private static void EmptyDocumentEventWithFriend(DirectoryEntry dir) throws IOException { - dir.createDocument("Bar", 1, event -> { - try { - event.getStream().write(0); - } catch (IOException exception) { - throw new RuntimeException("exception on write: " + exception); - } - }); - dir.createDocument("Foo", 0, event -> {}); - } - - - @ParameterizedTest(name = "{index} {0}") - @MethodSource("emptySupplier") - void testFoo(String testName, EmptyDoc emptyDoc) throws IOException { - try (POIFSFileSystem fs = new POIFSFileSystem()) { - DirectoryEntry dir = fs.getRoot(); - emptyDoc.handle(dir); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - fs.writeFilesystem(out); - assertDoesNotThrow(() -> new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()))); - } - } - - @Test - void testEmptyDocumentBug11744() throws Exception { - byte[] testData = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try (POIFSFileSystem fs = new POIFSFileSystem()) { - fs.createDocument(new ByteArrayInputStream(new byte[0]), "Empty"); - fs.createDocument(new ByteArrayInputStream(testData), "NotEmpty"); - fs.writeFilesystem(out); - } - - // This line caused the error. - try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()))) { - DocumentEntry entry = (DocumentEntry) fs.getRoot().getEntry("Empty"); - assertEquals(0, entry.getSize(), "Expected zero size"); - byte[] actualReadbackData; - actualReadbackData = IOUtils.toByteArray(new DocumentInputStream(entry)); - assertEquals(0, actualReadbackData.length, "Expected zero read from stream"); - - entry = (DocumentEntry) fs.getRoot().getEntry("NotEmpty"); - actualReadbackData = IOUtils.toByteArray(new DocumentInputStream(entry)); - assertEquals(testData.length, entry.getSize(), "Expected size was wrong"); - assertArrayEquals(testData, actualReadbackData, "Expected same data read from stream"); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java b/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java deleted file mode 100644 index b85550cc15..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java +++ /dev/null @@ -1,211 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -class TestEntryUtils { - private static final byte[] dataSmallA = new byte[] { 12, 42, 11, -12, -121 }; - private static final byte[] dataSmallB = new byte[] { 11, 73, 21, -92, -103 }; - - @Test - void testCopyRecursively() throws IOException { - POIFSFileSystem fsD = new POIFSFileSystem(); - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry dirA = fs.createDirectory("DirA"); - DirectoryEntry dirB = fs.createDirectory("DirB"); - - DocumentEntry entryR = fs.createDocument(new ByteArrayInputStream(dataSmallA), "EntryRoot"); - DocumentEntry entryA1 = dirA.createDocument("EntryA1", new ByteArrayInputStream(dataSmallA)); - DocumentEntry entryA2 = dirA.createDocument("EntryA2", new ByteArrayInputStream(dataSmallB)); - - // Copy docs - assertEquals(0, fsD.getRoot().getEntryCount()); - EntryUtils.copyNodeRecursively(entryR, fsD.getRoot()); - - assertEquals(1, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("EntryRoot")); - - EntryUtils.copyNodeRecursively(entryA1, fsD.getRoot()); - assertEquals(2, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("EntryRoot")); - assertNotNull(fsD.getRoot().getEntry("EntryA1")); - - EntryUtils.copyNodeRecursively(entryA2, fsD.getRoot()); - assertEquals(3, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("EntryRoot")); - assertNotNull(fsD.getRoot().getEntry("EntryA1")); - assertNotNull(fsD.getRoot().getEntry("EntryA2")); - - fsD.close(); - - // Copy directories - fsD = new POIFSFileSystem(); - assertEquals(0, fsD.getRoot().getEntryCount()); - - EntryUtils.copyNodeRecursively(dirB, fsD.getRoot()); - assertEquals(1, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("DirB")); - assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount()); - - EntryUtils.copyNodeRecursively(dirA, fsD.getRoot()); - assertEquals(2, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("DirB")); - assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("DirA")); - assertEquals(2, ((DirectoryEntry)fsD.getRoot().getEntry("DirA")).getEntryCount()); - fsD.close(); - - // Copy the whole lot - fsD = new POIFSFileSystem(); - assertEquals(0, fsD.getRoot().getEntryCount()); - - EntryUtils.copyNodes(fs, fsD, new ArrayList<>()); - assertEquals(3, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry(dirA.getName())); - assertNotNull(fsD.getRoot().getEntry(dirB.getName())); - assertNotNull(fsD.getRoot().getEntry(entryR.getName())); - assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount()); - assertEquals(2, ((DirectoryEntry)fsD.getRoot().getEntry("DirA")).getEntryCount()); - fsD.close(); - fs.close(); - } - - @Test - void testAreDocumentsIdentical() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry dirA = fs.createDirectory("DirA"); - DirectoryEntry dirB = fs.createDirectory("DirB"); - - DocumentEntry entryA1 = dirA.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); - DocumentEntry entryA1b = dirA.createDocument("Entry1b", new ByteArrayInputStream(dataSmallA)); - DocumentEntry entryA2 = dirA.createDocument("Entry2", new ByteArrayInputStream(dataSmallB)); - DocumentEntry entryB1 = dirB.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); - - - // Names must match - assertNotEquals(entryA1.getName(), entryA1b.getName()); - assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA1b)); - - // Contents must match - assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA2)); - - // Parents don't matter if contents + names are the same - assertNotEquals(entryA1.getParent(), entryB1.getParent()); - assertTrue(EntryUtils.areDocumentsIdentical(entryA1, entryB1)); - - - // Can work with POIFS - ByteArrayOutputStream tmpO = new ByteArrayOutputStream(); - fs.writeFilesystem(tmpO); - - ByteArrayInputStream tmpI = new ByteArrayInputStream(tmpO.toByteArray()); - POIFSFileSystem nfs = new POIFSFileSystem(tmpI); - - DirectoryEntry dN1 = (DirectoryEntry)nfs.getRoot().getEntry("DirA"); - DirectoryEntry dN2 = (DirectoryEntry)nfs.getRoot().getEntry("DirB"); - DocumentEntry eNA1 = (DocumentEntry)dN1.getEntry(entryA1.getName()); - DocumentEntry eNA2 = (DocumentEntry)dN1.getEntry(entryA2.getName()); - DocumentEntry eNB1 = (DocumentEntry)dN2.getEntry(entryB1.getName()); - - assertFalse(EntryUtils.areDocumentsIdentical(eNA1, eNA2)); - assertTrue(EntryUtils.areDocumentsIdentical(eNA1, eNB1)); - - assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA1b)); - assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA2)); - - assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryA1)); - assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryB1)); - nfs.close(); - fs.close(); - } - - @Test - void testAreDirectoriesIdentical() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry dirA = fs.createDirectory("DirA"); - DirectoryEntry dirB = fs.createDirectory("DirB"); - - // Names must match - assertFalse(EntryUtils.areDirectoriesIdentical(dirA, dirB)); - - // Empty dirs are fine - DirectoryEntry dirA1 = dirA.createDirectory("TheDir"); - DirectoryEntry dirB1 = dirB.createDirectory("TheDir"); - assertEquals(0, dirA1.getEntryCount()); - assertEquals(0, dirB1.getEntryCount()); - assertTrue(EntryUtils.areDirectoriesIdentical(dirA1, dirB1)); - - // Otherwise children must match - dirA1.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); - assertFalse(EntryUtils.areDirectoriesIdentical(dirA1, dirB1)); - - dirB1.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); - assertTrue(EntryUtils.areDirectoriesIdentical(dirA1, dirB1)); - - dirA1.createDirectory("DD"); - assertFalse(EntryUtils.areDirectoriesIdentical(dirA1, dirB1)); - dirB1.createDirectory("DD"); - assertTrue(EntryUtils.areDirectoriesIdentical(dirA1, dirB1)); - - - // Excludes support - List excl = Arrays.asList("Ignore1", "IgnDir/Ign2"); - FilteringDirectoryNode fdA = new FilteringDirectoryNode(dirA1, excl); - FilteringDirectoryNode fdB = new FilteringDirectoryNode(dirB1, excl); - - assertTrue(EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - // Add an ignored doc, no notice is taken - fdA.createDocument("Ignore1", new ByteArrayInputStream(dataSmallA)); - assertTrue(EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - // Add a directory with filtered contents, not the same - DirectoryEntry dirAI = dirA1.createDirectory("IgnDir"); - assertFalse(EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - DirectoryEntry dirBI = dirB1.createDirectory("IgnDir"); - assertTrue(EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - // Add something to the filtered subdir that gets ignored - dirAI.createDocument("Ign2", new ByteArrayInputStream(dataSmallA)); - assertTrue(EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - // And something that doesn't - dirAI.createDocument("IgnZZ", new ByteArrayInputStream(dataSmallA)); - assertFalse(EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - dirBI.createDocument("IgnZZ", new ByteArrayInputStream(dataSmallA)); - assertTrue(EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - fs.close(); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java b/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java deleted file mode 100644 index 456ca076ac..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java +++ /dev/null @@ -1,183 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Random; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.Test; - -class TestFileMagic { - @Test - void testFileMagic() { - assertEquals(FileMagic.XML, FileMagic.valueOf("XML")); - assertEquals(FileMagic.XML, FileMagic.valueOf(" FileMagic.valueOf("some string")); - } - - @Test - void testFileMagicFile() throws IOException { - assertEquals(FileMagic.OLE2, FileMagic.valueOf(POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xls"))); - assertEquals(FileMagic.OOXML, FileMagic.valueOf(POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xlsx"))); - } - - @Test - void testFileMagicStream() throws IOException { - try (InputStream stream = new BufferedInputStream(new FileInputStream(POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xls")))) { - assertEquals(FileMagic.OLE2, FileMagic.valueOf(stream)); - } - try (InputStream stream = new BufferedInputStream(new FileInputStream(POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xlsx")))) { - assertEquals(FileMagic.OOXML, FileMagic.valueOf(stream)); - } - } - - @Test - void testPrepare() throws IOException { - try (InputStream stream = new BufferedInputStream(new FileInputStream(POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xlsx")))) { - assertSame(stream, FileMagic.prepareToCheckMagic(stream)); - } - - try (InputStream stream = new InputStream() { - @Override - public int read() { - return 0; - } - }) { - assertNotSame(stream, FileMagic.prepareToCheckMagic(stream)); - } - } - - @Test - void testMatchingButTooLessData() { - // this matches JPG, but is not long enough, previously this caused an Exception - byte[] data = new byte[] { -1, -40, -1, -32, 0, 16, 74, 70 }; - - assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf(data)); - } - - @Test - void testShortFile() throws IOException { - // having a file shorter than 8 bytes previously caused an exception - fetchMagicFromData(new byte[] { -1, -40, -1, -32, 0 }); - fetchMagicFromData(new byte[] { -1, -40, -1, -32 }); - fetchMagicFromData(new byte[] { -1, -40, -1 }); - fetchMagicFromData(new byte[] { -1, -40 }); - fetchMagicFromData(new byte[] { -1 }); - fetchMagicFromData(new byte[0]); - } - - private void fetchMagicFromData(byte[] data) throws IOException { - File file = TempFile.createTempFile("TestFileMagic", ".bin"); - try { - try (FileOutputStream fos = new FileOutputStream(file)) { - fos.write(data); - } - - assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf(file)); - } finally { - assertTrue(file.delete()); - } - } - - @Test - void testMarkRequired() throws IOException { - byte[] data = new byte[] { -1, -40, -1, -32, 0 }; - - File file = TempFile.createTempFile("TestFileMagic", ".bin"); - try { - try (FileOutputStream fos = new FileOutputStream(file)) { - fos.write(data); - } - - // a FileInputStream does not support "marking" - try (FileInputStream str = new FileInputStream(file)) { - assertFalse(str.markSupported()); - - assertThrows(IOException.class, () -> FileMagic.valueOf(str)); - } - } finally { - assertTrue(file.delete()); - } - } - - @Test - void testPatterns() { - // just try to trash the functionality with some byte-patterns - for(int i = 0; i < 256;i++) { - final byte[] data = new byte[12]; - for(int j = 0;j < 12; j++) { - data[j] = (byte)i; - - assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf(data)); - } - } - } - - @Test - void testRandomPatterns() { - Random random = new Random(); - - // just try to trash the functionality with some byte-patterns - for(int i = 0; i < 1000;i++) { - final byte[] data = new byte[12]; - random.nextBytes(data); - - // we cannot check for UNKNOWN as we might hit valid byte-patterns here as well - try { - assertNotNull(FileMagic.valueOf(data)); - } catch (Exception e) { - throw new IllegalStateException("Failed with pattern " + Arrays.toString(data), e); - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java b/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java deleted file mode 100644 index ef504aca69..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java +++ /dev/null @@ -1,179 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.poi.POIDataSamples; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -/** - * Tests bugs for POIFSFileSystem - */ -final class TestFileSystemBugs { - private static final POIDataSamples _samples = POIDataSamples.getPOIFSInstance(); - private static final POIDataSamples _ssSamples = POIDataSamples.getSpreadSheetInstance(); - - private List openedFSs; - - @AfterEach - void tearDown() { - if (openedFSs != null && !openedFSs.isEmpty()) { - for (POIFSFileSystem fs : openedFSs) { - try { - fs.close(); - } catch (Exception e) { - System.err.println("Error closing FS: " + e); - } - } - } - openedFSs = null; - } - - private DirectoryNode openSample(String name) throws Exception { - try (InputStream inps = _samples.openResourceAsStream(name)) { - return openSample(inps); - } - } - - @SuppressWarnings("SameParameterValue") - private DirectoryNode openSSSample(String name) throws Exception { - try (InputStream inps = _ssSamples.openResourceAsStream(name)) { - return openSample(inps); - } - } - - private DirectoryNode openSample(InputStream inps) throws Exception { - POIFSFileSystem nfs = new POIFSFileSystem(inps); - if (openedFSs == null) { - openedFSs = new ArrayList<>(); - } - openedFSs.add(nfs); - - return nfs.getRoot(); - } - - /** - * Test that we can open files that come via Lotus notes. - * These have a top level directory without a name.... - */ - @Test - void testNotesOLE2Files() throws Exception { - // Check the contents - DirectoryNode root = openSample("Notes.ole2"); - assertEquals(1, root.getEntryCount()); - - Entry entry = root.getEntries().next(); - assertTrue(entry.isDirectoryEntry()); - assertTrue(entry instanceof DirectoryEntry); - - // The directory lacks a name! - DirectoryEntry dir = (DirectoryEntry)entry; - assertEquals("", dir.getName()); - - // Has two children - assertEquals(2, dir.getEntryCount()); - - // Check them - Iterator it = dir.getEntries(); - entry = it.next(); - assertTrue(entry.isDocumentEntry()); - assertEquals(Ole10Native.OLE10_NATIVE, entry.getName()); - - entry = it.next(); - assertTrue(entry.isDocumentEntry()); - assertEquals("\u0001CompObj", entry.getName()); - } - - /** - * Ensure that a file with a corrupted property in the - * properties table can still be loaded, and the remaining - * properties used - * Note - only works for POIFSFileSystem - * can't cope with this level of corruption - */ - @Test - void testCorruptedProperties() throws Exception { - DirectoryNode root = openSample("unknown_properties.msg"); - assertEquals(42, root.getEntryCount()); - } - - /** - * With heavily nested documents, ensure we still re-write the same - */ - @Test - void testHeavilyNestedReWrite() throws Exception { - DirectoryNode root = openSSSample("ex42570-20305.xls"); - // Record the structure - Map entries = new HashMap<>(); - fetchSizes("/", root, entries); - - // Prepare to copy - DirectoryNode dest = new POIFSFileSystem().getRoot(); - - // Copy over - EntryUtils.copyNodes(root, dest); - - // Re-load - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - root.getFileSystem().writeFilesystem(baos); - - POIFSFileSystem read = new POIFSFileSystem( - new ByteArrayInputStream(baos.toByteArray())); - - // Check the structure matches - checkSizes("/", read.getRoot(), entries); - } - - private void fetchSizes(String path, DirectoryNode dir, Map entries) { - for (Entry entry : dir) { - if (entry instanceof DirectoryNode) { - String ourPath = path + entry.getName() + "/"; - entries.put(ourPath, -1); - fetchSizes(ourPath, (DirectoryNode)entry, entries); - } else { - DocumentNode doc = (DocumentNode)entry; - entries.put(path+entry.getName(), doc.getSize()); - } - } - } - private void checkSizes(String path, DirectoryNode dir, Map entries) { - for (Entry entry : dir) { - if (entry instanceof DirectoryNode) { - String ourPath = path + entry.getName() + "/"; - assertTrue(entries.containsKey(ourPath)); - assertEquals(-1, entries.get(ourPath).intValue()); - checkSizes(ourPath, (DirectoryNode)entry, entries); - } else { - DocumentNode doc = (DocumentNode)entry; - assertEquals(entries.get(path+entry.getName()).intValue(), doc.getSize()); - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java b/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java deleted file mode 100644 index aa9c8883af..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java +++ /dev/null @@ -1,164 +0,0 @@ - -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Class to test FilteringDirectoryNode functionality - */ -final class TestFilteringDirectoryNode { - private POIFSFileSystem fs; - private DirectoryEntry dirA; - private DirectoryEntry dirAA; - private DirectoryEntry dirB; - private DocumentEntry eRoot; - private DocumentEntry eA; - private DocumentEntry eAA; - - @BeforeEach - void setUp() throws Exception { - fs = new POIFSFileSystem(); - dirA = fs.createDirectory("DirA"); - dirB = fs.createDirectory("DirB"); - dirAA = dirA.createDirectory("DirAA"); - eRoot = fs.getRoot().createDocument("Root", new ByteArrayInputStream(new byte[]{})); - eA = dirA.createDocument("NA", new ByteArrayInputStream(new byte[]{})); - eAA = dirAA.createDocument("NAA", new ByteArrayInputStream(new byte[]{})); - } - - @Test - void testNoFiltering() throws Exception { - FilteringDirectoryNode d = new FilteringDirectoryNode(fs.getRoot(), new HashSet<>()); - assertEquals(3, d.getEntryCount()); - assertEquals(dirA.getName(), d.getEntry(dirA.getName()).getName()); - - assertTrue(d.getEntry(dirA.getName()).isDirectoryEntry()); - assertFalse(d.getEntry(dirA.getName()).isDocumentEntry()); - - assertTrue(d.getEntry(dirB.getName()).isDirectoryEntry()); - assertFalse(d.getEntry(dirB.getName()).isDocumentEntry()); - - assertFalse(d.getEntry(eRoot.getName()).isDirectoryEntry()); - assertTrue(d.getEntry(eRoot.getName()).isDocumentEntry()); - - Iterator i = d.getEntries(); - assertEquals(dirA, i.next()); - assertEquals(dirB, i.next()); - assertEquals(eRoot, i.next()); - assertThrows(NoSuchElementException.class, i::next, "Should throw NoSuchElementException when depleted"); - } - - @Test - void testChildFiltering() throws Exception { - List excl = Arrays.asList("NotThere", "AlsoNotThere", eRoot.getName()); - FilteringDirectoryNode d1 = new FilteringDirectoryNode(fs.getRoot(), excl); - - assertEquals(2, d1.getEntryCount()); - assertTrue(d1.hasEntry(dirA.getName())); - assertTrue(d1.hasEntry(dirB.getName())); - assertFalse(d1.hasEntry(eRoot.getName())); - - assertEquals(dirA, d1.getEntry(dirA.getName())); - assertEquals(dirB, d1.getEntry(dirB.getName())); - assertThrows(FileNotFoundException.class, () -> d1.getEntry(eRoot.getName())); - - Iterator i = d1.getEntries(); - assertEquals(dirA, i.next()); - assertEquals(dirB, i.next()); - assertThrows(NoSuchElementException.class, i::next, "Should throw NoSuchElementException when depleted"); - - - // Filter more - excl = Arrays.asList("NotThere", "AlsoNotThere", eRoot.getName(), dirA.getName()); - FilteringDirectoryNode d2 = new FilteringDirectoryNode(fs.getRoot(), excl); - - assertEquals(1, d2.getEntryCount()); - assertFalse(d2.hasEntry(dirA.getName())); - assertTrue(d2.hasEntry(dirB.getName())); - assertFalse(d2.hasEntry(eRoot.getName())); - assertThrows(FileNotFoundException.class, () -> d2.getEntry(dirA.getName()), "Should be filtered"); - assertEquals(dirB, d2.getEntry(dirB.getName())); - assertThrows(FileNotFoundException.class, () -> d2.getEntry(eRoot.getName()), "Should be filtered"); - - i = d2.getEntries(); - assertEquals(dirB, i.next()); - assertThrows(NoSuchElementException.class, i::next, "Should throw NoSuchElementException when depleted"); - - // Filter everything - excl = Arrays.asList("NotThere", eRoot.getName(), dirA.getName(), dirB.getName()); - FilteringDirectoryNode d3 = new FilteringDirectoryNode(fs.getRoot(), excl); - - assertEquals(0, d3.getEntryCount()); - assertFalse(d3.hasEntry(dirA.getName())); - assertFalse(d3.hasEntry(dirB.getName())); - assertFalse(d3.hasEntry(eRoot.getName())); - assertThrows(FileNotFoundException.class, () -> d3.getEntry(dirA.getName()), "Should be filtered"); - assertThrows(FileNotFoundException.class, () -> d3.getEntry(dirB.getName()), "Should be filtered"); - assertThrows(FileNotFoundException.class, () -> d3.getEntry(eRoot.getName()), "Should be filtered"); - - i = d3.getEntries(); - assertThrows(NoSuchElementException.class, i::next, "Should throw NoSuchElementException when depleted"); - } - - @Test - void testNestedFiltering() throws Exception { - List excl = Arrays.asList(dirA.getName() + "/" + "MadeUp", - dirA.getName() + "/" + eA.getName(), - dirA.getName() + "/" + dirAA.getName() + "/Test", - eRoot.getName()); - FilteringDirectoryNode d = new FilteringDirectoryNode(fs.getRoot(), excl); - - // Check main - assertEquals(2, d.getEntryCount()); - assertTrue(d.hasEntry(dirA.getName())); - assertTrue(d.hasEntry(dirB.getName())); - assertFalse(d.hasEntry(eRoot.getName())); - - // Check filtering down - assertTrue(d.getEntry(dirA.getName()) instanceof FilteringDirectoryNode); - assertFalse(d.getEntry(dirB.getName()) instanceof FilteringDirectoryNode); - - DirectoryEntry fdA = (DirectoryEntry) d.getEntry(dirA.getName()); - assertFalse(fdA.hasEntry(eA.getName())); - assertTrue(fdA.hasEntry(dirAA.getName())); - - DirectoryEntry fdAA = (DirectoryEntry) fdA.getEntry(dirAA.getName()); - assertTrue(fdAA.hasEntry(eAA.getName())); - } - - @Test - void testNullDirectory() { - assertThrows(IllegalArgumentException.class, () -> new FilteringDirectoryNode(null, null)); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestNotOLE2Exception.java b/src/testcases/org/apache/poi/poifs/filesystem/TestNotOLE2Exception.java deleted file mode 100644 index 42d6534dc6..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestNotOLE2Exception.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.OldExcelFormatException; -import org.junit.jupiter.api.Test; - -/** - * Class to test that POIFS complains when given older non-OLE2 - * formats. See also {@link TestOfficeXMLException} for OOXML - * checks - */ -class TestNotOLE2Exception { - private static InputStream openXLSSampleStream(String sampleFileName) { - return HSSFTestDataSamples.openSampleFileStream(sampleFileName); - } - private static InputStream openDOCSampleStream(String sampleFileName) { - return POIDataSamples.getDocumentInstance().openResourceAsStream(sampleFileName); - } - - @Test - void testRawXMLException() throws IOException { - try (InputStream in = openXLSSampleStream("SampleSS.xml")) { - NotOLE2FileException e = assertThrows(NotOLE2FileException.class, () -> new POIFSFileSystem(in)); - assertContains(e.getMessage(), "The supplied data appears to be a raw XML file"); - assertContains(e.getMessage(), "Formats such as Office 2003 XML"); - } - } - - @Test - void testMSWriteException() throws IOException { - try (InputStream in = openDOCSampleStream("MSWriteOld.wri")) { - NotOLE2FileException e = assertThrows(NotOLE2FileException.class, () -> new POIFSFileSystem(in)); - assertContains(e.getMessage(), "The supplied data appears to be in the old MS Write"); - assertContains(e.getMessage(), "doesn't currently support"); - } - } - - @Test - void testBiff3Exception() throws IOException { - try (InputStream in = openXLSSampleStream("testEXCEL_3.xls")) { - OldExcelFormatException e = assertThrows(OldExcelFormatException.class, () -> new POIFSFileSystem(in)); - assertContains(e.getMessage(), "The supplied data appears to be in BIFF3 format"); - assertContains(e.getMessage(), "try OldExcelExtractor"); - } - } - - @Test - void testBiff4Exception() throws IOException { - try (InputStream in = openXLSSampleStream("testEXCEL_4.xls")) { - OldExcelFormatException e = assertThrows(OldExcelFormatException.class, () -> new POIFSFileSystem(in)); - assertContains(e.getMessage(), "The supplied data appears to be in BIFF4 format"); - assertContains(e.getMessage(), "try OldExcelExtractor"); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java b/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java deleted file mode 100644 index 8e4dd48298..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java +++ /dev/null @@ -1,126 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * Class to test that POIFS complains when given an Office 2003 XML - * of Office Open XML (OOXML, 2007+) document - */ -class TestOfficeXMLException { - - private static InputStream openSampleStream(String sampleFileName) { - return HSSFTestDataSamples.openSampleFileStream(sampleFileName); - } - - @Test - void testOOXMLException() throws IOException { - try (InputStream in = openSampleStream("sample.xlsx")) { - OfficeXmlFileException ex = assertThrows(OfficeXmlFileException.class, () -> new POIFSFileSystem(in)); - assertTrue(ex.getMessage().contains("You are calling the part of POI that deals with OLE2 Office Documents")); - } - } - - @Test - void test2003XMLException() throws IOException { - try (InputStream in = openSampleStream("SampleSS.xml")) { - NotOLE2FileException ex = assertThrows(NotOLE2FileException.class, () -> new POIFSFileSystem(in)); - assertTrue(ex.getMessage().contains("The supplied data appears to be a raw XML file")); - } - } - - @Test - void testDetectAsPOIFS() throws IOException { - // ooxml file isn't - confirmIsPOIFS("SampleSS.xlsx", FileMagic.OOXML); - - // 2003 xml file isn't - confirmIsPOIFS("SampleSS.xml", FileMagic.XML); - - // xls file is - confirmIsPOIFS("SampleSS.xls", FileMagic.OLE2); - - // older biff formats aren't - confirmIsPOIFS("testEXCEL_3.xls", FileMagic.BIFF3); - confirmIsPOIFS("testEXCEL_4.xls", FileMagic.BIFF4); - - // newer excel formats are - confirmIsPOIFS("testEXCEL_5.xls", FileMagic.OLE2); - confirmIsPOIFS("testEXCEL_95.xls", FileMagic.OLE2); - - // text file isn't - confirmIsPOIFS("SampleSS.txt", FileMagic.UNKNOWN); - } - - private void confirmIsPOIFS(String sampleFileName, FileMagic expected) throws IOException { - final File file = HSSFTestDataSamples.getSampleFile(sampleFileName); - assertEquals(expected, FileMagic.valueOf(file)); - } - - @Test - void testFileCorruption() throws Exception { - - // create test InputStream - byte[] testData = {1, 2, 3}; - InputStream testInput = new ByteArrayInputStream(testData); - - // detect header - InputStream in = FileMagic.prepareToCheckMagic(testInput); - - assertNotEquals(FileMagic.OLE2, FileMagic.valueOf(in)); - - // check if InputStream is still intact - byte[] test = new byte[3]; - assertEquals(3, in.read(test)); - assertArrayEquals(testData, test); - assertEquals(-1, in.read()); - } - - - @Test - void testFileCorruptionOPOIFS() throws Exception { - - // create test InputStream - byte[] testData = {(byte) 1, (byte) 2, (byte) 3}; - InputStream testInput = new ByteArrayInputStream(testData); - - // detect header - InputStream in = FileMagic.prepareToCheckMagic(testInput); - assertNotEquals(FileMagic.OLE2, FileMagic.valueOf(in)); - assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf(in)); - - // check if InputStream is still intact - byte[] test = new byte[3]; - assertEquals(3, in.read(test)); - assertArrayEquals(testData, test); - assertEquals(-1, in.read()); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java b/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java deleted file mode 100644 index 6becf23aa1..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.RecordFormatException; -import org.junit.jupiter.api.Test; - -class TestOle10Native { - private static final POIDataSamples dataSamples = POIDataSamples.getPOIFSInstance(); - - @Test - void testOleNative() throws IOException, Ole10NativeException { - POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("oleObject1.bin")); - - Ole10Native ole = Ole10Native.createFromEmbeddedOleObject(fs); - - assertEquals("File1.svg", ole.getLabel()); - assertEquals("D:\\Documents and Settings\\rsc\\My Documents\\file1.svg", ole.getCommand()); - } - - @Test - void testFiles() throws IOException, Ole10NativeException { - File[] files = { - // bug 51891 - POIDataSamples.getPOIFSInstance().getFile("multimedia.doc"), - // tika bug 1072 - POIDataSamples.getPOIFSInstance().getFile("20-Force-on-a-current-S00.doc"), - // other files containing ole10native records ... - POIDataSamples.getDocumentInstance().getFile("Bug53380_3.doc"), - POIDataSamples.getDocumentInstance().getFile("Bug47731.doc") - }; - - for (File f : files) { - POIFSFileSystem fs = new POIFSFileSystem(f, true); - List entries = new ArrayList<>(); - findOle10(entries, fs.getRoot(), "/"); - - for (Entry e : entries) { - ByteArrayOutputStream bosExp = new ByteArrayOutputStream(); - InputStream is = ((DirectoryNode)e.getParent()).createDocumentInputStream(e); - IOUtils.copy(is,bosExp); - is.close(); - - Ole10Native ole = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)e.getParent()); - - ByteArrayOutputStream bosAct = new ByteArrayOutputStream(); - ole.writeOut(bosAct); - - assertThat(bosExp.toByteArray(), equalTo(bosAct.toByteArray())); - } - - fs.close(); - } - } - - private void findOle10(List entries, DirectoryNode dn, String path) { - Iterator iter = dn.getEntries(); - while (iter.hasNext()) { - Entry e = iter.next(); - if (Ole10Native.OLE10_NATIVE.equals(e.getName())) { - if (entries != null) entries.add(e); - // System.out.println(filename+" : "+path); - } else if (e.isDirectoryEntry()) { - findOle10(entries, (DirectoryNode)e, path+e.getName()+"/"); - } - } - } - - @Test - void testOleNativeOOM() throws IOException { - try (POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("60256.bin"))) { - RecordFormatException ex = assertThrows( - RecordFormatException.class, - () -> Ole10Native.createFromEmbeddedOleObject(fs) - ); - assertTrue(ex.getMessage().contains("Tried to allocate")); - } - } - -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java deleted file mode 100644 index 94d8e73e9c..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java +++ /dev/null @@ -1,189 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.Arrays; - -import org.junit.jupiter.api.Test; - -/** - * Class to test POIFSDocumentPath functionality - */ -final class TestPOIFSDocumentPath { - - - /** - * Test default constructor - */ - @Test - void testDefaultConstructor() { - POIFSDocumentPath path = new POIFSDocumentPath(); - - assertEquals(0, path.length()); - } - - /** - * Test full path constructor - */ - @Test - void testFullPathConstructor() { - String[] components = {"foo", "bar", "foobar", "fubar"}; - - for (int j = 0; j < components.length; j++) { - String[] params = Arrays.copyOf(components, j); - POIFSDocumentPath path = new POIFSDocumentPath(params); - - assertEquals(j, path.length()); - for (int k = 0; k < j; k++) { - assertEquals(components[ k ], path.getComponent(k)); - } - if (j == 0) { - assertNull(path.getParent()); - } else { - POIFSDocumentPath parent = path.getParent(); - - assertNotNull(parent); - assertEquals(j - 1, parent.length()); - for (int k = 0; k < j - 1; k++) { - assertEquals(components[ k ], parent.getComponent(k)); - } - } - } - - // test weird variants - assertEquals(0, new POIFSDocumentPath(null).length()); - assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(new String[]{"fu", ""})); - assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(new String[]{"fu", null})); - } - - /** - * Test relative path constructor - */ - @Test - void testRelativePathConstructor() { - String[] initialComponents = {"a", "b", "c"}; - - for (int n = 0; n < initialComponents.length; n++) { - String[] initialParams = Arrays.copyOf(initialComponents, n); - POIFSDocumentPath base = new POIFSDocumentPath(initialParams); - String[] components = {"foo", "bar", "foobar", "fubar"}; - - for (int j = 0; j < components.length; j++) { - String[] params = Arrays.copyOf(components, j); - POIFSDocumentPath path = new POIFSDocumentPath(base, params); - - assertEquals(j + n, path.length()); - for (int k = 0; k < n; k++) { - assertEquals(initialComponents[ k ], path.getComponent(k)); - } - for (int k = 0; k < j; k++) { - assertEquals(components[ k ], path.getComponent(k + n)); - } - if ((j + n) == 0) { - assertNull(path.getParent()); - } else { - POIFSDocumentPath parent = path.getParent(); - - assertNotNull(parent); - assertEquals(j + n - 1, parent.length()); - for (int k = 0; k < (j + n - 1); k++) { - assertEquals(path.getComponent(k), parent.getComponent(k)); - } - } - } - - // Test weird variants - - // This one is allowed, even if it's really odd - assertEquals(n, new POIFSDocumentPath(base, null).length()); - new POIFSDocumentPath(base, new String[]{"fu", ""}); - - // This one is allowed too - new POIFSDocumentPath(base, new String[]{"", "fu"}); - - // This one shouldn't be allowed - assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(base, new String[]{"fu", null})); - - // Ditto - assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(base, new String[]{null, "fu"})); - } - } - - /** - * test equality - */ - @Test - void testEquality() { - POIFSDocumentPath a1 = new POIFSDocumentPath(); - POIFSDocumentPath a2 = new POIFSDocumentPath(null); - POIFSDocumentPath a3 = new POIFSDocumentPath(new String[ 0 ]); - POIFSDocumentPath a4 = new POIFSDocumentPath(a1, null); - POIFSDocumentPath a5 = new POIFSDocumentPath(a1, new String[ 0 ]); - - POIFSDocumentPath[] paths = {a1, a2, a3, a4, a5}; - - for (int j = 0; j < paths.length; j++) { - for (int k = 0; k < paths.length; k++) { - assertEquals(paths[ j ], paths[ k ], j + "<>" + k); - } - } - a2 = new POIFSDocumentPath(a1, new String[]{"foo"}); - a3 = new POIFSDocumentPath(a2, new String[]{"bar"}); - a4 = new POIFSDocumentPath(a3, new String[]{"fubar"}); - a5 = new POIFSDocumentPath(a4, new String[]{"foobar"}); - POIFSDocumentPath[] builtUpPaths = - { - a1, a2, a3, a4, a5 - }; - POIFSDocumentPath[] fullPaths = { - new POIFSDocumentPath(), new POIFSDocumentPath(new String[]{"foo"}), - new POIFSDocumentPath(new String[]{"foo", "bar"}), - new POIFSDocumentPath(new String[]{"foo", "bar", "fubar"}), - new POIFSDocumentPath(new String[]{"foo", "bar", "fubar", "foobar"}) - }; - - for (int k = 0; k < builtUpPaths.length; k++) { - for (int j = 0; j < fullPaths.length; j++) { - if (k == j) { - assertEquals(fullPaths[ j ], builtUpPaths[ k ], j + "<>" + k); - } else { - assertNotEquals(fullPaths[j], builtUpPaths[k]); - } - } - } - POIFSDocumentPath[] badPaths = { - new POIFSDocumentPath(new String[]{"_foo"}), - new POIFSDocumentPath(new String[]{"foo", "_bar"}), - new POIFSDocumentPath(new String[]{"foo", "bar", "_fubar"}), - new POIFSDocumentPath(new String[]{"foo", "bar", "fubar", "_foobar"}) - }; - - for (int k = 0; k < builtUpPaths.length; k++) - { - for (POIFSDocumentPath badPath : badPaths) { - assertNotEquals(fullPaths[k], badPath); - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java deleted file mode 100644 index c644fb1c60..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java +++ /dev/null @@ -1,350 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.util.HashMap; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.Property; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.Section; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.common.POIFSBigBlockSize; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.storage.BATBlock; -import org.apache.poi.poifs.storage.HeaderBlock; -import org.apache.poi.util.IOUtils; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.ValueSource; - -/** - * Tests for the older OPOIFS-based POIFSFileSystem - */ -final class TestPOIFSFileSystem { - private final POIDataSamples _samples = POIDataSamples.getPOIFSInstance(); - - /** - * Mock exception used to ensure correct error handling - */ - private static final class MyEx extends RuntimeException { - MyEx() { - // no fields to initialise - } - } - /** - * Helps facilitate testing. Keeps track of whether close() was called. - * Also can throw an exception at a specific point in the stream. - */ - private static final class TestIS extends InputStream { - - private final InputStream _is; - private final int _failIndex; - private int _currentIx; - private boolean _isClosed; - - TestIS(InputStream is, int failIndex) { - _is = is; - _failIndex = failIndex; - _currentIx = 0; - _isClosed = false; - } - - @Override - public int read() throws IOException { - int result = _is.read(); - if(result >=0) { - checkRead(1); - } - return result; - } - @Override - public int read(byte[] b, int off, int len) throws IOException { - int result = _is.read(b, off, len); - checkRead(result); - return result; - } - - private void checkRead(int nBytes) { - _currentIx += nBytes; - if(_failIndex > 0 && _currentIx > _failIndex) { - throw new MyEx(); - } - } - @Override - public void close() throws IOException { - _isClosed = true; - _is.close(); - } - boolean isClosed() { - return _isClosed; - } - } - - /** - * Test for undesired behaviour observable as of svn revision 618865 (5-Feb-2008). - * POIFSFileSystem was not closing the input stream. - */ - @Test - void testAlwaysClose() throws IOException { - // Normal case - read until EOF and close - try (TestIS testIS = new TestIS(openSampleStream("13224.xls"), -1); - POIFSFileSystem ignored = new POIFSFileSystem(testIS)){ - assertTrue(testIS.isClosed(), "input stream was not closed"); - } - - // intended to crash after reading 10000 bytes - try (TestIS testIS = new TestIS(openSampleStream("13224.xls"), 10000)){ - assertThrows(MyEx.class, () -> new POIFSFileSystem(testIS)); - // but still should close - assertTrue(testIS.isClosed(), "input stream was not closed"); - } - } - - /** - * Test for bug # 48898 - problem opening an OLE2 - * file where the last block is short (i.e. not a full - * multiple of 512 bytes) - * - * As yet, this problem remains. One school of thought is - * not not issue an EOF when we discover the last block - * is short, but this seems a bit wrong. - * The other is to fix the handling of the last block in - * POIFS, since it seems to be slight wrong - */ - @ParameterizedTest - @CsvSource({ "ShortLastBlock.qwp, 1303681", "ShortLastBlock.wps, 140787" }) - void testShortLastBlock(String file, int size) throws Exception { - // Open the file up - try (POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream(file))) { - - // Write it into a temp output array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - fs.writeFilesystem(baos); - - // Check sizes - assertEquals(size, baos.size()); - } - } - - /** - * Check that we do the right thing when the list of which - * sectors are BAT blocks points off the list of - * sectors that exist in the file. - */ - @Test - void testFATandDIFATsectors() throws Exception { - try (InputStream stream = _samples.openResourceAsStream("ReferencesInvalidSectors.mpp")) { - IndexOutOfBoundsException ex = assertThrows( - IndexOutOfBoundsException.class, - () -> new POIFSFileSystem(stream), - "File is corrupt and shouldn't have been opened" - ); - assertTrue(ex.getMessage().contains("Block 1148 not found")); - } - } - - /** - * Tests that we can write and read a file that contains XBATs - * as well as regular BATs. - * However, because a file needs to be at least 6.875mb big - * to have an XBAT in it, we don't have a test one. So, generate it. - */ - @Test - void testBATandXBAT() throws Exception { - byte[] hugeStream = new byte[8*1024*1024]; - POIFSFileSystem fs = new POIFSFileSystem(); - fs.getRoot().createDocument( - "BIG", new ByteArrayInputStream(hugeStream) - ); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - fs.writeFilesystem(baos); - byte[] fsData = baos.toByteArray(); - - - // Check the header was written properly - InputStream inp = new ByteArrayInputStream(fsData); - HeaderBlock header = new HeaderBlock(inp); - assertEquals(109+21, header.getBATCount()); - assertEquals(1, header.getXBATCount()); - - - // We should have 21 BATs in the XBAT - ByteBuffer xbatData = ByteBuffer.allocate(512); - xbatData.put(fsData, (1+header.getXBATIndex())*512, 512); - xbatData.position(0); - BATBlock xbat = BATBlock.createBATBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, xbatData); - for(int i=0; i<21; i++) { - assertTrue(xbat.getValueAt(i) != POIFSConstants.UNUSED_BLOCK); - } - for(int i=21; i<127; i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, xbat.getValueAt(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, xbat.getValueAt(127)); - - - // Now load it and check - fs = new POIFSFileSystem( - new ByteArrayInputStream(fsData) - ); - - DirectoryNode root = fs.getRoot(); - assertEquals(1, root.getEntryCount()); - DocumentNode big = (DocumentNode)root.getEntry("BIG"); - assertEquals(hugeStream.length, big.getSize()); - } - - /** - * Most OLE2 files use 512byte blocks. However, a small number - * use 4k blocks. Check that we can open these. - */ - @Test - void test4KBlocks() throws Exception { - POIDataSamples _samples = POIDataSamples.getPOIFSInstance(); - try (InputStream inp = _samples.openResourceAsStream("BlockSize4096.zvi")) { - // First up, check that we can process the header properly - HeaderBlock header_block = new HeaderBlock(inp); - POIFSBigBlockSize bigBlockSize = header_block.getBigBlockSize(); - assertEquals(4096, bigBlockSize.getBigBlockSize()); - - // Check the fat info looks sane - assertEquals(1, header_block.getBATArray().length); - assertEquals(1, header_block.getBATCount()); - assertEquals(0, header_block.getXBATCount()); - - // Now try and open properly - POIFSFileSystem fs = new POIFSFileSystem( - _samples.openResourceAsStream("BlockSize4096.zvi")); - assertTrue(fs.getRoot().getEntryCount() > 3); - - // Check we can get at all the contents - checkAllDirectoryContents(fs.getRoot()); - - // Finally, check we can do a similar 512byte one too - fs = new POIFSFileSystem( - _samples.openResourceAsStream("BlockSize512.zvi")); - assertTrue(fs.getRoot().getEntryCount() > 3); - checkAllDirectoryContents(fs.getRoot()); - } - } - private void checkAllDirectoryContents(DirectoryEntry dir) throws IOException { - for(Entry entry : dir) { - if(entry instanceof DirectoryEntry) { - checkAllDirectoryContents((DirectoryEntry)entry); - } else { - DocumentNode doc = (DocumentNode) entry; - try (DocumentInputStream dis = new DocumentInputStream(doc)) { - IOUtils.toByteArray(dis); - } - } - } - } - - @SuppressWarnings("SameParameterValue") - private static InputStream openSampleStream(String sampleFileName) { - return HSSFTestDataSamples.openSampleFileStream(sampleFileName); - } - - @Test - public void fileMagics() { - for (FileMagic fm : FileMagic.values()) { - if (fm == FileMagic.UNKNOWN) { - continue; - } - for (byte[] b : fm.magic) { - assertEquals(fm, FileMagic.valueOf(b)); - } - } - - assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf("foobaa".getBytes(UTF_8))); - } - - @Test - void test64322() throws NoPropertySetStreamException, IOException { - try (POIFSFileSystem poiFS = new POIFSFileSystem(_samples.getFile("64322.ole2"))) { - int count = recurseDir(poiFS.getRoot()); - - assertEquals(1285, count, "Expecting a fixed number of entries being found in the test-document"); - } - } - - @Test - void test64322a() throws NoPropertySetStreamException, IOException { - try (POIFSFileSystem poiFS = new POIFSFileSystem(_samples.openResourceAsStream("64322.ole2"))) { - int count = recurseDir(poiFS.getRoot()); - - assertEquals(1285, count, "Expecting a fixed number of entries being found in the test-document"); - } - } - - private static int recurseDir(DirectoryEntry dir) throws IOException, NoPropertySetStreamException { - int count = 0; - for (Entry entry : dir) { - count++; - if (entry instanceof DirectoryEntry) { - count += recurseDir((DirectoryEntry) entry); - } - if (entry instanceof DocumentEntry) { - DocumentEntry de = (DocumentEntry) entry; - HashMap props = new HashMap<>(); - try (DocumentInputStream dis = new DocumentInputStream(de)) { - props.put("name", de.getName()); - - if (PropertySet.isPropertySetStream(dis)) { - dis.mark(10000000); - PropertySet ps = null; - try { - ps = new PropertySet(dis); - - } catch (UnsupportedEncodingException e) { - // ignore - } - if (ps != null) { - for (Section section : ps.getSections()) { - for (Property p : section.getProperties()) { - String prop = section.getDictionary() != null - ? section.getDictionary().get(p.getID()) - : String.valueOf(p.getID()); - if (p.getValue() != null) - props.put("property_" + prop, p.getValue().toString()); - } - } - } - dis.reset(); - } - } - assertTrue(props.size() > 0); - } - } - return count; - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSMiniStore.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSMiniStore.java deleted file mode 100644 index fcc1e4bcf1..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSMiniStore.java +++ /dev/null @@ -1,473 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.nio.ByteBuffer; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.util.IOUtils; -import org.junit.jupiter.api.Test; - -/** - * Tests for the Mini Store in the NIO POIFS - */ -@SuppressWarnings("CatchMayIgnoreException") -final class TestPOIFSMiniStore { - private static final POIDataSamples _inst = POIDataSamples.getPOIFSInstance(); - - /** - * Check that for a given mini block, we can correctly figure - * out what the next one is - */ - @Test - void testNextBlock() throws Exception { - // It's the same on 512 byte and 4096 byte block files! - POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - POIFSFileSystem fsC = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - POIFSFileSystem fsD = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB, fsC, fsD}) { - POIFSMiniStore ministore = fs.getMiniStore(); - - // 0 -> 51 is one stream - for (int i = 0; i < 50; i++) { - assertEquals(i + 1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50)); - - // 51 -> 103 is the next - for (int i = 51; i < 103; i++) { - assertEquals(i + 1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(103)); - - // Then there are 3 one block ones - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(104)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(105)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(106)); - - // 107 -> 154 is the next - for (int i = 107; i < 154; i++) { - assertEquals(i + 1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(154)); - - // 155 -> 160 is the next - for (int i = 155; i < 160; i++) { - assertEquals(i + 1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(160)); - - // 161 -> 166 is the next - for (int i = 161; i < 166; i++) { - assertEquals(i + 1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(166)); - - // 167 -> 172 is the next - for (int i = 167; i < 172; i++) { - assertEquals(i + 1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(172)); - - // Now some short ones - assertEquals(174, ministore.getNextBlock(173)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(174)); - - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(175)); - - assertEquals(177, ministore.getNextBlock(176)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(177)); - - assertEquals(179, ministore.getNextBlock(178)); - assertEquals(180, ministore.getNextBlock(179)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180)); - - // 181 onwards is free - for (int i = 181; i < fs.getBigBlockSizeDetails().getBATEntriesPerBlock(); i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i)); - } - } - fsD.close(); - fsC.close(); - fsB.close(); - fsA.close(); - } - - /** - * Check we get the right data back for each block - */ - @Test - void testGetBlock() throws Exception { - // It's the same on 512 byte and 4096 byte block files! - POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - POIFSFileSystem fsC = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - POIFSFileSystem fsD = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB, fsC, fsD}) { - // Mini stream should be at big block zero - assertEquals(0, fs._get_property_table().getRoot().getStartBlock()); - - // Grab the ministore - POIFSMiniStore ministore = fs.getMiniStore(); - ByteBuffer b; - - // Runs from the start of the data section in 64 byte chungs - b = ministore.getBlockAt(0); - assertEquals((byte) 0x9e, b.get()); - assertEquals((byte) 0x75, b.get()); - assertEquals((byte) 0x97, b.get()); - assertEquals((byte) 0xf6, b.get()); - assertEquals((byte) 0xff, b.get()); - assertEquals((byte) 0x21, b.get()); - assertEquals((byte) 0xd2, b.get()); - assertEquals((byte) 0x11, b.get()); - - // And the next block - b = ministore.getBlockAt(1); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x03, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x12, b.get()); - assertEquals((byte) 0x02, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - - // Check the last data block - b = ministore.getBlockAt(180); - assertEquals((byte) 0x30, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x80, b.get()); - - // And the rest until the end of the big block is zeros - for (int i = 181; i < 184; i++) { - b = ministore.getBlockAt(i); - assertEquals((byte) 0, b.get()); - assertEquals((byte) 0, b.get()); - assertEquals((byte) 0, b.get()); - assertEquals((byte) 0, b.get()); - assertEquals((byte) 0, b.get()); - assertEquals((byte) 0, b.get()); - assertEquals((byte) 0, b.get()); - assertEquals((byte) 0, b.get()); - } - } - fsD.close(); - fsC.close(); - fsB.close(); - fsA.close(); - } - - /** - * Ask for free blocks where there are some already - * to be had from the SFAT - */ - @Test - void testGetFreeBlockWithSpare() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - POIFSMiniStore ministore = fs.getMiniStore(); - - // Our 2nd SBAT block has spares - assertFalse(ministore.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertTrue(ministore.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - - // First free one at 181 - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(181)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(182)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(183)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(184)); - - // Ask, will get 181 - assertEquals(181, ministore.getFreeBlock()); - - // Ask again, will still get 181 as not written to - assertEquals(181, ministore.getFreeBlock()); - - // Allocate it, then ask again - ministore.setNextBlock(181, POIFSConstants.END_OF_CHAIN); - assertEquals(182, ministore.getFreeBlock()); - - fs.close(); - } - - /** - * Ask for free blocks where no free ones exist, and so the - * stream needs to be extended and another SBAT added - */ - @Test - void testGetFreeBlockWithNoneSpare() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - POIFSMiniStore ministore = fs.getMiniStore(); - - // We've spare ones from 181 to 255 - for (int i = 181; i < 256; i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i)); - } - - // Check our SBAT free stuff is correct - assertFalse(ministore.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertTrue(ministore.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - - // Allocate all the spare ones - for (int i = 181; i < 256; i++) { - ministore.setNextBlock(i, POIFSConstants.END_OF_CHAIN); - } - - // SBAT are now full, but there's only the two - assertFalse(ministore.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertFalse(ministore.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> ministore.getBATBlockAndIndex(256), "Should only be two SBATs"); - - // Now ask for a free one, will need to extend the SBAT chain - assertEquals(256, ministore.getFreeBlock()); - - assertFalse(ministore.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertFalse(ministore.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - assertTrue(ministore.getBATBlockAndIndex(256).getBlock().hasFreeSectors()); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(254)); // 2nd SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(255)); // 2nd SBAT - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(256)); // 3rd SBAT - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(257)); // 3rd SBAT - - fs.close(); - } - - /** - * Test that we will extend the underlying chain of - * big blocks that make up the ministream as needed - */ - @Test - void testCreateBlockIfNeeded() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - POIFSMiniStore ministore = fs.getMiniStore(); - - // 178 -> 179 -> 180, 181+ is free - assertEquals(179, ministore.getNextBlock(178)); - assertEquals(180, ministore.getNextBlock(179)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180)); - for (int i = 181; i < 256; i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i)); - } - - // However, the ministore data only covers blocks to 183 - for (int i = 0; i <= 183; i++) { - ministore.getBlockAt(i); - } - assertThrows(NoSuchElementException.class, () -> ministore.getBlockAt(184), "No block at 184"); - - // The ministore itself is made up of 23 big blocks - Iterator it = new POIFSStream(fs, fs.getRoot().getProperty().getStartBlock()).getBlockIterator(); - int count = 0; - while (it.hasNext()) { - count++; - it.next(); - } - assertEquals(23, count); - - // Ask it to get block 184 with creating, it will do - ministore.createBlockIfNeeded(184); - - // The ministore should be one big block bigger now - it = new POIFSStream(fs, fs.getRoot().getProperty().getStartBlock()).getBlockIterator(); - count = 0; - while (it.hasNext()) { - count++; - it.next(); - } - assertEquals(24, count); - - // The mini block block counts now run to 191 - for (int i = 0; i <= 191; i++) { - ministore.getBlockAt(i); - } - - assertThrows(NoSuchElementException.class, () -> ministore.getBlockAt(192), "No block at 192"); - - // Now try writing through to 192, check that the SBAT and blocks are there - byte[] data = new byte[15 * 64]; - POIFSStream stream = new POIFSStream(ministore, 178); - stream.updateContents(data); - - // Check now - assertEquals(179, ministore.getNextBlock(178)); - assertEquals(180, ministore.getNextBlock(179)); - assertEquals(181, ministore.getNextBlock(180)); - assertEquals(182, ministore.getNextBlock(181)); - assertEquals(183, ministore.getNextBlock(182)); - assertEquals(184, ministore.getNextBlock(183)); - assertEquals(185, ministore.getNextBlock(184)); - assertEquals(186, ministore.getNextBlock(185)); - assertEquals(187, ministore.getNextBlock(186)); - assertEquals(188, ministore.getNextBlock(187)); - assertEquals(189, ministore.getNextBlock(188)); - assertEquals(190, ministore.getNextBlock(189)); - assertEquals(191, ministore.getNextBlock(190)); - assertEquals(192, ministore.getNextBlock(191)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(192)); - for (int i = 193; i < 256; i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i)); - } - - fs.close(); - } - - @Test - void testCreateMiniStoreFirst() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(); - POIFSMiniStore ministore = fs.getMiniStore(); - DocumentInputStream dis; - DocumentEntry entry; - - // Initially has Properties + BAT but nothing else - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(2)); - // Ministore has no blocks, so can't iterate until used - try { - ministore.getNextBlock(0); - } catch (IndexOutOfBoundsException e) { - } - - // Write a very small new document, will populate the ministore for us - byte[] data = new byte[8]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i + 42); - } - fs.getRoot().createDocument("mini", new ByteArrayInputStream(data)); - - // Should now have a mini-fat and a mini-stream - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(3)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(4)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(0)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(1)); - - // Re-fetch the mini store, and add it a second time - ministore = fs.getMiniStore(); - fs.getRoot().createDocument("mini2", new ByteArrayInputStream(data)); - - // Main unchanged, ministore has a second - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(3)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(4)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(0)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(2)); - - // Check the data is unchanged and the right length - entry = (DocumentEntry) fs.getRoot().getEntry("mini"); - assertEquals(data.length, entry.getSize()); - byte[] rdata = new byte[data.length]; - dis = new DocumentInputStream(entry); - IOUtils.readFully(dis, rdata); - assertArrayEquals(data, rdata); - dis.close(); - - entry = (DocumentEntry) fs.getRoot().getEntry("mini2"); - assertEquals(data.length, entry.getSize()); - rdata = new byte[data.length]; - dis = new DocumentInputStream(entry); - IOUtils.readFully(dis, rdata); - assertArrayEquals(data, rdata); - dis.close(); - - // Done - fs.close(); - } - - @Test - void testMultiBlockStream() throws Exception { - byte[] data1B = new byte[63]; - byte[] data2B = new byte[64 + 14]; - for (int i = 0; i < data1B.length; i++) { - data1B[i] = (byte) (i + 2); - } - for (int i = 0; i < data2B.length; i++) { - data2B[i] = (byte) (i + 4); - } - - // New filesystem and store to use - POIFSFileSystem fs = new POIFSFileSystem(); - - // Initially has Properties + BAT but nothing else - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(2)); - - // Store the 2 block one, should use 2 mini blocks, and request - // the use of 2 big blocks - POIFSMiniStore ministore = fs.getMiniStore(); - fs.getRoot().createDocument("mini2", new ByteArrayInputStream(data2B)); - - // Check - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); // SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(3)); // Mini - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(4)); - - // First 2 Mini blocks will be used - assertEquals(2, ministore.getFreeBlock()); - - // Add one more mini-stream, and check - fs.getRoot().createDocument("mini1", new ByteArrayInputStream(data1B)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); // SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(3)); // Mini - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(4)); - - // One more mini-block will be used - assertEquals(3, ministore.getFreeBlock()); - - // Check the contents too - byte[] r1 = new byte[data1B.length]; - DocumentInputStream dis = fs.createDocumentInputStream("mini1"); - IOUtils.readFully(dis, r1); - dis.close(); - assertArrayEquals(data1B, r1); - - byte[] r2 = new byte[data2B.length]; - dis = fs.createDocumentInputStream("mini2"); - IOUtils.readFully(dis, r2); - dis.close(); - assertArrayEquals(data2B, r2); - fs.close(); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java deleted file mode 100644 index 2a2a8122d1..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java +++ /dev/null @@ -1,2792 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.property.DirectoryProperty; -import org.apache.poi.poifs.property.Property; -import org.apache.poi.poifs.property.PropertyTable; -import org.apache.poi.poifs.property.RootProperty; -import org.apache.poi.poifs.storage.BATBlock; -import org.apache.poi.poifs.storage.HeaderBlock; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link POIFSStream} - */ -final class TestPOIFSStream { - private static final POIDataSamples _inst = POIDataSamples.getPOIFSInstance(); - - /** - * Read a single block stream - */ - @Test - void testReadTinyStream() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - // 98 is actually the last block in a two block stream... - POIFSStream stream = new POIFSStream(fs, 98); - Iterator i = stream.getBlockIterator(); - assertTrue(i.hasNext()); - ByteBuffer b = i.next(); - assertFalse(i.hasNext()); - - // Check the contents - assertEquals((byte) 0x81, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x82, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - - fs.close(); - } - - /** - * Read a stream with only two blocks in it - */ - @Test - void testReadShortStream() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - // 97 -> 98 -> end - POIFSStream stream = new POIFSStream(fs, 97); - Iterator i = stream.getBlockIterator(); - assertTrue(i.hasNext()); - ByteBuffer b97 = i.next(); - assertTrue(i.hasNext()); - ByteBuffer b98 = i.next(); - assertFalse(i.hasNext()); - - // Check the contents of the 1st block - assertEquals((byte) 0x01, b97.get()); - assertEquals((byte) 0x00, b97.get()); - assertEquals((byte) 0x00, b97.get()); - assertEquals((byte) 0x00, b97.get()); - assertEquals((byte) 0x02, b97.get()); - assertEquals((byte) 0x00, b97.get()); - assertEquals((byte) 0x00, b97.get()); - assertEquals((byte) 0x00, b97.get()); - - // Check the contents of the 2nd block - assertEquals((byte) 0x81, b98.get()); - assertEquals((byte) 0x00, b98.get()); - assertEquals((byte) 0x00, b98.get()); - assertEquals((byte) 0x00, b98.get()); - assertEquals((byte) 0x82, b98.get()); - assertEquals((byte) 0x00, b98.get()); - assertEquals((byte) 0x00, b98.get()); - assertEquals((byte) 0x00, b98.get()); - - fs.close(); - } - - /** - * Read a stream with many blocks - */ - @Test - void testReadLongerStream() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - ByteBuffer b0 = null; - ByteBuffer b1 = null; - ByteBuffer b22 = null; - - // The stream at 0 has 23 blocks in it - POIFSStream stream = new POIFSStream(fs, 0); - Iterator i = stream.getBlockIterator(); - int count = 0; - while (i.hasNext()) { - ByteBuffer b = i.next(); - if (count == 0) { - b0 = b; - } - if (count == 1) { - b1 = b; - } - if (count == 22) { - b22 = b; - } - - count++; - } - assertEquals(23, count); - - // Check the contents - // 1st block is at 0 - assertNotNull(b0); - assertEquals((byte) 0x9e, b0.get()); - assertEquals((byte) 0x75, b0.get()); - assertEquals((byte) 0x97, b0.get()); - assertEquals((byte) 0xf6, b0.get()); - - // 2nd block is at 1 - assertNotNull(b1); - assertEquals((byte) 0x86, b1.get()); - assertEquals((byte) 0x09, b1.get()); - assertEquals((byte) 0x22, b1.get()); - assertEquals((byte) 0xfb, b1.get()); - - // last block is at 89 - assertNotNull(b22); - assertEquals((byte) 0xfe, b22.get()); - assertEquals((byte) 0xff, b22.get()); - assertEquals((byte) 0x00, b22.get()); - assertEquals((byte) 0x00, b22.get()); - assertEquals((byte) 0x05, b22.get()); - assertEquals((byte) 0x01, b22.get()); - assertEquals((byte) 0x02, b22.get()); - assertEquals((byte) 0x00, b22.get()); - - fs.close(); - } - - /** - * Read a stream with several blocks in a 4096 byte block file - */ - @Test - void testReadStream4096() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - - // 0 -> 1 -> 2 -> end - POIFSStream stream = new POIFSStream(fs, 0); - Iterator i = stream.getBlockIterator(); - assertTrue(i.hasNext()); - ByteBuffer b0 = i.next(); - assertTrue(i.hasNext()); - ByteBuffer b1 = i.next(); - assertTrue(i.hasNext()); - ByteBuffer b2 = i.next(); - assertFalse(i.hasNext()); - - // Check the contents of the 1st block - assertEquals((byte) 0x9E, b0.get()); - assertEquals((byte) 0x75, b0.get()); - assertEquals((byte) 0x97, b0.get()); - assertEquals((byte) 0xF6, b0.get()); - assertEquals((byte) 0xFF, b0.get()); - assertEquals((byte) 0x21, b0.get()); - assertEquals((byte) 0xD2, b0.get()); - assertEquals((byte) 0x11, b0.get()); - - // Check the contents of the 2nd block - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x03, b1.get()); - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x00, b1.get()); - - // Check the contents of the 3rd block - assertEquals((byte) 0x6D, b2.get()); - assertEquals((byte) 0x00, b2.get()); - assertEquals((byte) 0x00, b2.get()); - assertEquals((byte) 0x00, b2.get()); - assertEquals((byte) 0x03, b2.get()); - assertEquals((byte) 0x00, b2.get()); - assertEquals((byte) 0x46, b2.get()); - assertEquals((byte) 0x00, b2.get()); - - fs.close(); - } - - /** - * Craft a nasty file with a loop, and ensure we don't get stuck - */ - @Test - void testReadFailsOnLoop() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - // Hack the FAT so that it goes 0->1->2->0 - fs.setNextBlock(0, 1); - fs.setNextBlock(1, 2); - fs.setNextBlock(2, 0); - - // Now try to read - POIFSStream stream = new POIFSStream(fs, 0); - Iterator i = stream.getBlockIterator(); - assertTrue(i.hasNext()); - - // 1st read works - i.next(); - assertTrue(i.hasNext()); - - // 2nd read works - i.next(); - assertTrue(i.hasNext()); - - // 3rd read works - i.next(); - assertTrue(i.hasNext()); - - // 4th read blows up as it loops back to 0 - assertThrows(RuntimeException.class, i::next, "Loop should have been detected but wasn't!"); - assertTrue(i.hasNext()); - - fs.close(); - } - - /** - * Tests that we can load some streams that are - * stored in the mini stream. - */ - @Test - void testReadMiniStreams() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - POIFSMiniStore ministore = fs.getMiniStore(); - - // 178 -> 179 -> 180 -> end - POIFSStream stream = new POIFSStream(ministore, 178); - Iterator i = stream.getBlockIterator(); - assertTrue(i.hasNext()); - ByteBuffer b178 = i.next(); - assertTrue(i.hasNext()); - ByteBuffer b179 = i.next(); - assertTrue(i.hasNext()); - ByteBuffer b180 = i.next(); - assertFalse(i.hasNext()); - - // Check the contents of the 1st block - assertEquals((byte) 0xfe, b178.get()); - assertEquals((byte) 0xff, b178.get()); - assertEquals((byte) 0x00, b178.get()); - assertEquals((byte) 0x00, b178.get()); - assertEquals((byte) 0x05, b178.get()); - assertEquals((byte) 0x01, b178.get()); - assertEquals((byte) 0x02, b178.get()); - assertEquals((byte) 0x00, b178.get()); - - // And the 2nd - assertEquals((byte) 0x6c, b179.get()); - assertEquals((byte) 0x00, b179.get()); - assertEquals((byte) 0x00, b179.get()); - assertEquals((byte) 0x00, b179.get()); - assertEquals((byte) 0x28, b179.get()); - assertEquals((byte) 0x00, b179.get()); - assertEquals((byte) 0x00, b179.get()); - assertEquals((byte) 0x00, b179.get()); - - // And the 3rd - assertEquals((byte) 0x30, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x80, b180.get()); - - fs.close(); - } - - /** - * Writing the same amount of data as before - */ - @Test - void testReplaceStream() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - - byte[] data = new byte[512]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); - } - - // 98 is actually the last block in a two block stream... - POIFSStream stream = new POIFSStream(fs, 98); - stream.updateContents(data); - - // Check the reading of blocks - Iterator it = stream.getBlockIterator(); - assertTrue(it.hasNext()); - ByteBuffer b = it.next(); - assertFalse(it.hasNext()); - - // Now check the contents - data = new byte[512]; - b.get(data); - for (int i = 0; i < data.length; i++) { - byte exp = (byte) (i % 256); - assertEquals(exp, data[i]); - } - - fs.close(); - } - - /** - * Writes less data than before, some blocks will need - * to be freed - */ - @Test - void testReplaceStreamWithLess() throws Exception { - try (InputStream is = _inst.openResourceAsStream("BlockSize512.zvi"); - POIFSFileSystem fs = new POIFSFileSystem(is)) { - - byte[] data = new byte[512]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); - } - - // 97 -> 98 -> end - assertEquals(98, fs.getNextBlock(97)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98)); - - // Create a 2 block stream, will become a 1 block one - POIFSStream stream = new POIFSStream(fs, 97); - stream.updateContents(data); - - // 97 should now be the end, and 98 free - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(97)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(98)); - - // Check the reading of blocks - Iterator it = stream.getBlockIterator(); - assertTrue(it.hasNext()); - ByteBuffer b = it.next(); - assertFalse(it.hasNext()); - - // Now check the contents - data = new byte[512]; - b.get(data); - for (int i = 0; i < data.length; i++) { - byte exp = (byte) (i % 256); - assertEquals(exp, data[i]); - } - } - } - - /** - * Writes more data than before, new blocks will be needed - */ - @Test - void testReplaceStreamWithMore() throws Exception { - try (InputStream is = _inst.openResourceAsStream("BlockSize512.zvi"); - POIFSFileSystem fs = new POIFSFileSystem(is)) { - - byte[] data = new byte[512 * 3]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); - } - - // 97 -> 98 -> end - assertEquals(98, fs.getNextBlock(97)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98)); - - // 100 is our first free one - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); - - // Create a 2 block stream, will become a 3 block one - POIFSStream stream = new POIFSStream(fs, 97); - stream.updateContents(data); - - // 97 -> 98 -> 100 -> end - assertEquals(98, fs.getNextBlock(97)); - assertEquals(100, fs.getNextBlock(98)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100)); - - // Check the reading of blocks - Iterator it = stream.getBlockIterator(); - int count = 0; - while (it.hasNext()) { - ByteBuffer b = it.next(); - data = new byte[512]; - b.get(data); - for (int i = 0; i < data.length; i++) { - byte exp = (byte) (i % 256); - assertEquals(exp, data[i]); - } - count++; - } - assertEquals(3, count); - } - } - - /** - * Writes to a new stream in the file - */ - @Test - void testWriteNewStream() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - - // 100 is our first free one - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); - - - // Add a single block one - byte[] data = new byte[512]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); - } - - POIFSStream stream = new POIFSStream(fs); - stream.updateContents(data); - - // Check it was allocated properly - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); - - // And check the contents - Iterator it = stream.getBlockIterator(); - int count = 0; - while (it.hasNext()) { - ByteBuffer b = it.next(); - data = new byte[512]; - b.get(data); - for (int i = 0; i < data.length; i++) { - byte exp = (byte) (i % 256); - assertEquals(exp, data[i]); - } - count++; - } - assertEquals(1, count); - - - // And a multi block one - data = new byte[512 * 3]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); - } - - stream = new POIFSStream(fs); - stream.updateContents(data); - - // Check it was allocated properly - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100)); - assertEquals(102, fs.getNextBlock(101)); - assertEquals(103, fs.getNextBlock(102)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(103)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); - - // And check the contents - it = stream.getBlockIterator(); - count = 0; - while (it.hasNext()) { - ByteBuffer b = it.next(); - data = new byte[512]; - b.get(data); - for (int i = 0; i < data.length; i++) { - byte exp = (byte) (i % 256); - assertEquals(exp, data[i]); - } - count++; - } - assertEquals(3, count); - - // Free it - stream.free(); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); - - fs.close(); - } - - /** - * Writes to a new stream in the file, where we've not enough - * free blocks so new FAT segments will need to be allocated - * to support this - */ - @Test - void testWriteNewStreamExtraFATs() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - - // Allocate almost all the blocks - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127)); - for (int i = 100; i < 127; i++) { - fs.setNextBlock(i, POIFSConstants.END_OF_CHAIN); - } - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127)); - assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - - - // Write a 3 block stream - byte[] data = new byte[512 * 3]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); - } - POIFSStream stream = new POIFSStream(fs); - stream.updateContents(data); - - // Check we got another BAT - assertFalse(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertTrue(fs.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - - // the BAT will be in the first spot of the new block - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(126)); - assertEquals(129, fs.getNextBlock(127)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(128)); - assertEquals(130, fs.getNextBlock(129)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(130)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(131)); - - fs.close(); - } - - /** - * Replaces data in an existing stream, with a bit - * more data than before, in a 4096 byte block file - */ - @Test - void testWriteStream4096() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - - // 0 -> 1 -> 2 -> end - assertEquals(1, fs.getNextBlock(0)); - assertEquals(2, fs.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); - assertEquals(4, fs.getNextBlock(3)); - - // First free one is at 15 - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(15)); - - - // Write a 5 block file - byte[] data = new byte[4096 * 5]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); - } - POIFSStream stream = new POIFSStream(fs, 0); - stream.updateContents(data); - - - // Check it - assertEquals(1, fs.getNextBlock(0)); - assertEquals(2, fs.getNextBlock(1)); - assertEquals(15, fs.getNextBlock(2)); // Jumps - assertEquals(4, fs.getNextBlock(3)); // Next stream - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14)); - assertEquals(16, fs.getNextBlock(15)); // Continues - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(16)); // Ends - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(17)); // Free - - // Check the contents too - Iterator it = stream.getBlockIterator(); - int count = 0; - while (it.hasNext()) { - ByteBuffer b = it.next(); - data = new byte[512]; - b.get(data); - for (int i = 0; i < data.length; i++) { - byte exp = (byte) (i % 256); - assertEquals(exp, data[i]); - } - count++; - } - assertEquals(5, count); - - fs.close(); - } - - /** - * Tests that we can write into the mini stream - */ - @Test - void testWriteMiniStreams() throws Exception { - try (InputStream is = _inst.openResourceAsStream("BlockSize512.zvi"); - POIFSFileSystem fs = new POIFSFileSystem(is)) { - - POIFSMiniStore ministore = fs.getMiniStore(); - - // 178 -> 179 -> 180 -> end - assertEquals(179, ministore.getNextBlock(178)); - assertEquals(180, ministore.getNextBlock(179)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180)); - - - // Try writing 3 full blocks worth - byte[] data = new byte[64 * 3]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) i; - } - POIFSStream stream = new POIFSStream(ministore, 178); - stream.updateContents(data); - - // Check - assertEquals(179, ministore.getNextBlock(178)); - assertEquals(180, ministore.getNextBlock(179)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180)); - - stream = new POIFSStream(ministore, 178); - Iterator it = stream.getBlockIterator(); - ByteBuffer b178 = it.next(); - ByteBuffer b179 = it.next(); - ByteBuffer b180 = it.next(); - assertFalse(it.hasNext()); - - assertEquals((byte) 0x00, b178.get()); - assertEquals((byte) 0x01, b178.get()); - assertEquals((byte) 0x40, b179.get()); - assertEquals((byte) 0x41, b179.get()); - assertEquals((byte) 0x80, b180.get()); - assertEquals((byte) 0x81, b180.get()); - - - // Try writing just into 3 blocks worth - data = new byte[64 * 2 + 12]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i + 4); - } - stream = new POIFSStream(ministore, 178); - stream.updateContents(data); - - // Check - assertEquals(179, ministore.getNextBlock(178)); - assertEquals(180, ministore.getNextBlock(179)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180)); - - stream = new POIFSStream(ministore, 178); - it = stream.getBlockIterator(); - b178 = it.next(); - b179 = it.next(); - b180 = it.next(); - assertFalse(it.hasNext()); - - assertEquals((byte) 0x04, b178.get(0)); - assertEquals((byte) 0x05, b178.get(1)); - assertEquals((byte) 0x44, b179.get(0)); - assertEquals((byte) 0x45, b179.get(1)); - assertEquals((byte) 0x84, b180.get(0)); - assertEquals((byte) 0x85, b180.get(1)); - - - // Try writing 1, should truncate - data = new byte[12]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i + 9); - } - stream = new POIFSStream(ministore, 178); - stream.updateContents(data); - - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(178)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(179)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(180)); - - stream = new POIFSStream(ministore, 178); - it = stream.getBlockIterator(); - b178 = it.next(); - assertFalse(it.hasNext()); - - assertEquals((byte) 0x09, b178.get(0)); - assertEquals((byte) 0x0a, b178.get(1)); - - - // Try writing 5, should extend - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(178)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(179)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(180)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(181)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(182)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(183)); - - data = new byte[64 * 4 + 12]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i + 3); - } - stream = new POIFSStream(ministore, 178); - stream.updateContents(data); - - assertEquals(179, ministore.getNextBlock(178)); - assertEquals(180, ministore.getNextBlock(179)); - assertEquals(181, ministore.getNextBlock(180)); - assertEquals(182, ministore.getNextBlock(181)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(182)); - - stream = new POIFSStream(ministore, 178); - it = stream.getBlockIterator(); - b178 = it.next(); - b179 = it.next(); - b180 = it.next(); - ByteBuffer b181 = it.next(); - ByteBuffer b182 = it.next(); - assertFalse(it.hasNext()); - - assertEquals((byte) 0x03, b178.get(0)); - assertEquals((byte) 0x04, b178.get(1)); - assertEquals((byte) 0x43, b179.get(0)); - assertEquals((byte) 0x44, b179.get(1)); - assertEquals((byte) 0x83, b180.get(0)); - assertEquals((byte) 0x84, b180.get(1)); - assertEquals((byte) 0xc3, b181.get(0)); - assertEquals((byte) 0xc4, b181.get(1)); - assertEquals((byte) 0x03, b182.get(0)); - assertEquals((byte) 0x04, b182.get(1)); - - - // Write lots, so it needs another big block - ministore.getBlockAt(183); - assertThrows(NoSuchElementException.class, () -> ministore.getBlockAt(184), "Block 184 should be off the end of the list"); - - data = new byte[64 * 6 + 12]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i + 1); - } - stream = new POIFSStream(ministore, 178); - stream.updateContents(data); - - // Should have added 2 more blocks to the chain - assertEquals(179, ministore.getNextBlock(178)); - assertEquals(180, ministore.getNextBlock(179)); - assertEquals(181, ministore.getNextBlock(180)); - assertEquals(182, ministore.getNextBlock(181)); - assertEquals(183, ministore.getNextBlock(182)); - assertEquals(184, ministore.getNextBlock(183)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(184)); - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(185)); - - // Block 184 should exist - ministore.getBlockAt(183); - ministore.getBlockAt(184); - ministore.getBlockAt(185); - - // Check contents - stream = new POIFSStream(ministore, 178); - it = stream.getBlockIterator(); - b178 = it.next(); - b179 = it.next(); - b180 = it.next(); - b181 = it.next(); - b182 = it.next(); - ByteBuffer b183 = it.next(); - ByteBuffer b184 = it.next(); - assertFalse(it.hasNext()); - - assertEquals((byte) 0x01, b178.get(0)); - assertEquals((byte) 0x02, b178.get(1)); - assertEquals((byte) 0x41, b179.get(0)); - assertEquals((byte) 0x42, b179.get(1)); - assertEquals((byte) 0x81, b180.get(0)); - assertEquals((byte) 0x82, b180.get(1)); - assertEquals((byte) 0xc1, b181.get(0)); - assertEquals((byte) 0xc2, b181.get(1)); - assertEquals((byte) 0x01, b182.get(0)); - assertEquals((byte) 0x02, b182.get(1)); - assertEquals((byte) 0x41, b183.get(0)); - assertEquals((byte) 0x42, b183.get(1)); - assertEquals((byte) 0x81, b184.get(0)); - assertEquals((byte) 0x82, b184.get(1)); - - } - } - - /** - * Craft a nasty file with a loop, and ensure we don't get stuck - */ - @Test - void testWriteFailsOnLoop() throws Exception { - try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) { - - // Hack the FAT so that it goes 0->1->2->0 - fs.setNextBlock(0, 1); - fs.setNextBlock(1, 2); - fs.setNextBlock(2, 0); - - // Try to write a large amount, should fail on the write - POIFSStream stream1 = new POIFSStream(fs, 0); - assertThrows(IllegalStateException.class, - () -> stream1.updateContents(new byte[512 * 4]), "Loop should have been detected but wasn't!"); - - // Now reset, and try on a small bit - // Should fail during the freeing set - fs.setNextBlock(0, 1); - fs.setNextBlock(1, 2); - fs.setNextBlock(2, 0); - - POIFSStream stream2 = new POIFSStream(fs, 0); - assertThrows(IllegalStateException.class, - () -> stream2.updateContents(new byte[512]), "Loop should have been detected but wasn't!"); - } - } - - /** - * Tests adding a new stream, writing and reading it. - */ - @Test - void testReadWriteNewStream() throws Exception { - try (POIFSFileSystem fs = new POIFSFileSystem()) { - POIFSStream stream = new POIFSStream(fs); - - // Check our filesystem has Properties then BAT - assertEquals(2, fs.getFreeBlock()); - BATBlock bat = fs.getBATBlockAndIndex(0).getBlock(); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(2)); - - // Check the stream as-is - assertEquals(POIFSConstants.END_OF_CHAIN, stream.getStartBlock()); - assertThrows(IllegalStateException.class, stream::getBlockIterator, - "Shouldn't be able to get an iterator before writing"); - - // Write in two blocks - byte[] data = new byte[512 + 20]; - for (int i = 0; i < 512; i++) { - data[i] = (byte) (i % 256); - } - for (int i = 512; i < data.length; i++) { - data[i] = (byte) (i % 256 + 100); - } - stream.updateContents(data); - - // Check now - assertEquals(4, fs.getFreeBlock()); - bat = fs.getBATBlockAndIndex(0).getBlock(); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(3, bat.getValueAt(2)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(4)); - - - Iterator it = stream.getBlockIterator(); - assertTrue(it.hasNext()); - ByteBuffer b = it.next(); - - byte[] read = new byte[512]; - b.get(read); - for (int i = 0; i < read.length; i++) { - assertEquals(data[i], read[i], "Wrong value at " + i); - } - - assertTrue(it.hasNext()); - b = it.next(); - - read = new byte[512]; - b.get(read); - for (int i = 0; i < 20; i++) { - assertEquals(data[i + 512], read[i]); - } - for (int i = 20; i < read.length; i++) { - assertEquals(0, read[i]); - } - - assertFalse(it.hasNext()); - } - } - - /** - * Writes a stream, then replaces it - */ - @Test - void testWriteThenReplace() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(); - - // Starts empty, other that Properties and BAT - BATBlock bat = fs.getBATBlockAndIndex(0).getBlock(); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(2)); - - // Write something that uses a main stream - byte[] main4106 = new byte[4106]; - main4106[0] = -10; - main4106[4105] = -11; - fs.getRoot().createDocument("Normal", new ByteArrayInputStream(main4106)); - - // Should have used 9 blocks - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(3, bat.getValueAt(2)); - assertEquals(4, bat.getValueAt(3)); - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(10, bat.getValueAt(9)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); - - DocumentEntry normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4106, normal.getSize()); - assertEquals(4106, ((DocumentNode) normal).getProperty().getSize()); - - - // Replace with one still big enough for a main stream, but one block smaller - byte[] main4096 = new byte[4096]; - main4096[0] = -10; - main4096[4095] = -11; - - DocumentOutputStream nout = new DocumentOutputStream(normal); - nout.write(main4096); - nout.close(); - - // Will have dropped to 8 - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(3, bat.getValueAt(2)); - assertEquals(4, bat.getValueAt(3)); - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4096, normal.getSize()); - assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); - - - // Write and check - fs = writeOutAndReadBack(fs); - bat = fs.getBATBlockAndIndex(0).getBlock(); - - // No change after write - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); // Properties - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(3, bat.getValueAt(2)); - assertEquals(4, bat.getValueAt(3)); - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9)); // End of Normal - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4096, normal.getSize()); - assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); - - - // Make longer, take 1 block at the end - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - nout = new DocumentOutputStream(normal); - nout.write(main4106); - nout.close(); - - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(3, bat.getValueAt(2)); - assertEquals(4, bat.getValueAt(3)); - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(10, bat.getValueAt(9)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10)); // Normal - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4106, normal.getSize()); - assertEquals(4106, ((DocumentNode) normal).getProperty().getSize()); - - - // Make it small, will trigger the SBAT stream and free lots up - byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - nout = new DocumentOutputStream(normal); - nout.write(mini); - nout.close(); - - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(4)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(5)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(6)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(7)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(8)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(9)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(7, normal.getSize()); - assertEquals(7, ((DocumentNode) normal).getProperty().getSize()); - - - // Finally back to big again - nout = new DocumentOutputStream(normal); - nout.write(main4096); - nout.close(); - - // Will keep the mini stream, now empty - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(10, bat.getValueAt(9)); - assertEquals(11, bat.getValueAt(10)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4096, normal.getSize()); - assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); - - - // Save, re-load, re-check - fs = writeOutAndReadBack(fs); - bat = fs.getBATBlockAndIndex(0).getBlock(); - - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(10, bat.getValueAt(9)); - assertEquals(11, bat.getValueAt(10)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4096, normal.getSize()); - assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); - - fs.close(); - } - - - /** - * Returns test files with 512 byte and 4k block sizes, loaded - * both from InputStreams and Files - */ - private POIFSFileSystem[] get512and4kFileAndInput() throws IOException { - POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - POIFSFileSystem fsC = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - POIFSFileSystem fsD = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - return new POIFSFileSystem[]{fsA, fsB, fsC, fsD}; - } - - private static void assertBATCount(POIFSFileSystem fs, int expectedBAT, int expectedXBAT) throws IOException { - int foundBAT = 0; - int foundXBAT = 0; - int sz = (int) (fs.size() / fs.getBigBlockSize()); - for (int i = 0; i < sz; i++) { - if (fs.getNextBlock(i) == POIFSConstants.FAT_SECTOR_BLOCK) { - foundBAT++; - } - if (fs.getNextBlock(i) == POIFSConstants.DIFAT_SECTOR_BLOCK) { - foundXBAT++; - } - } - assertEquals(expectedBAT, foundBAT, "Wrong number of BATs"); - assertEquals(expectedXBAT, foundXBAT, "Wrong number of XBATs with " + expectedBAT + " BATs"); - } - - private void assertContentsMatches(byte[] expected, DocumentEntry doc) throws IOException { - DocumentInputStream inp = new DocumentInputStream(doc); - byte[] contents = new byte[doc.getSize()]; - assertEquals(doc.getSize(), inp.read(contents)); - inp.close(); - - if (expected != null) { - assertThat(expected, equalTo(contents)); - } - } - - private static HeaderBlock writeOutAndReadHeader(POIFSFileSystem fs) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - fs.writeFilesystem(baos); - - return new HeaderBlock(new ByteArrayInputStream(baos.toByteArray())); - } - - private static POIFSFileSystem writeOutAndReadBack(POIFSFileSystem original) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - original.writeFilesystem(baos); - return new POIFSFileSystem(new ByteArrayInputStream(baos.toByteArray())); - } - - private static POIFSFileSystem writeOutFileAndReadBack(POIFSFileSystem original) throws IOException { - final File file = TempFile.createTempFile("TestPOIFS", ".ole2"); - try (OutputStream fout = new FileOutputStream(file)) { - original.writeFilesystem(fout); - } - return new POIFSFileSystem(file, false); - } - - @Test - void basicOpen() throws IOException { - POIFSFileSystem fsA, fsB; - - // With a simple 512 block file - fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { - assertEquals(512, fs.getBigBlockSize()); - } - fsA.close(); - fsB.close(); - - // Now with a simple 4096 block file - fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { - assertEquals(4096, fs.getBigBlockSize()); - } - fsA.close(); - fsB.close(); - } - - @Test - void propertiesAndFatOnRead() throws IOException { - POIFSFileSystem fsA, fsB; - - // With a simple 512 block file - fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { - // Check the FAT was properly processed: - // Verify we only got one block - fs.getBATBlockAndIndex(0); - fs.getBATBlockAndIndex(1); - assertThrows(IndexOutOfBoundsException.class, () -> fs.getBATBlockAndIndex(140), - "Should only be one BAT, but a 2nd was found"); - - // Verify a few next offsets - // 97 -> 98 -> END - assertEquals(98, fs.getNextBlock(97)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98)); - - - // Check the properties - PropertyTable props = fs._get_property_table(); - assertEquals(90, props.getStartBlock()); - assertEquals(7, props.countBlocks()); - - // Root property tells us about the Mini Stream - RootProperty root = props.getRoot(); - assertEquals("Root Entry", root.getName()); - assertEquals(11564, root.getSize()); - assertEquals(0, root.getStartBlock()); - - // Check its children too - Property prop; - Iterator pi = root.getChildren(); - prop = pi.next(); - assertEquals("Thumbnail", prop.getName()); - prop = pi.next(); - assertEquals("\u0005DocumentSummaryInformation", prop.getName()); - prop = pi.next(); - assertEquals("\u0005SummaryInformation", prop.getName()); - prop = pi.next(); - assertEquals("Image", prop.getName()); - prop = pi.next(); - assertEquals("Tags", prop.getName()); - assertFalse(pi.hasNext()); - - - // Check the SBAT (Small Blocks FAT) was properly processed - POIFSMiniStore ministore = fs.getMiniStore(); - - // Verify we only got two SBAT blocks - ministore.getBATBlockAndIndex(0); - ministore.getBATBlockAndIndex(128); - assertThrows(IndexOutOfBoundsException.class, () -> ministore.getBATBlockAndIndex(256), - "Should only be two SBATs, but a 3rd was found"); - - // Verify a few offsets: 0->50 is a stream - for (int i = 0; i < 50; i++) { - assertEquals(i + 1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50)); - - fs.close(); - } - - // Now with a simple 4096 block file - fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { - // Check the FAT was properly processed - // Verify we only got one block - fs.getBATBlockAndIndex(0); - fs.getBATBlockAndIndex(1); - assertThrows(IndexOutOfBoundsException.class, () -> fs.getBATBlockAndIndex(1040), - "Should only be one BAT, but a 2nd was found"); - - // Verify a few next offsets - // 0 -> 1 -> 2 -> END - assertEquals(1, fs.getNextBlock(0)); - assertEquals(2, fs.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); - - - // Check the properties - PropertyTable props = fs._get_property_table(); - assertEquals(12, props.getStartBlock()); - assertEquals(1, props.countBlocks()); - - // Root property tells us about the Mini Stream - RootProperty root = props.getRoot(); - assertEquals("Root Entry", root.getName()); - assertEquals(11564, root.getSize()); - assertEquals(0, root.getStartBlock()); - - // Check its children too - Property prop; - Iterator pi = root.getChildren(); - prop = pi.next(); - assertEquals("Thumbnail", prop.getName()); - prop = pi.next(); - assertEquals("\u0005DocumentSummaryInformation", prop.getName()); - prop = pi.next(); - assertEquals("\u0005SummaryInformation", prop.getName()); - prop = pi.next(); - assertEquals("Image", prop.getName()); - prop = pi.next(); - assertEquals("Tags", prop.getName()); - assertFalse(pi.hasNext()); - - - // Check the SBAT (Small Blocks FAT) was properly processed - POIFSMiniStore ministore = fs.getMiniStore(); - - // Verify we only got one SBAT block - ministore.getBATBlockAndIndex(0); - ministore.getBATBlockAndIndex(128); - ministore.getBATBlockAndIndex(1023); - assertThrows(IndexOutOfBoundsException.class, () -> ministore.getBATBlockAndIndex(1024), - "Should only be one SBAT, but a 2nd was found"); - - // Verify a few offsets: 0->50 is a stream - for (int i = 0; i < 50; i++) { - assertEquals(i + 1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50)); - - fs.close(); - } - } - - /** - * Check that for a given block, we can correctly figure - * out what the next one is - */ - @Test - void nextBlock() throws IOException { - POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { - // 0 -> 21 are simple - for (int i = 0; i < 21; i++) { - assertEquals(i + 1, fs.getNextBlock(i)); - } - // 21 jumps to 89, then ends - assertEquals(89, fs.getNextBlock(21)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(89)); - - // 22 -> 88 simple sequential stream - for (int i = 22; i < 88; i++) { - assertEquals(i + 1, fs.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(88)); - - // 90 -> 96 is another stream - for (int i = 90; i < 96; i++) { - assertEquals(i + 1, fs.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(96)); - - // 97+98 is another - assertEquals(98, fs.getNextBlock(97)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98)); - - // 99 is our FAT block - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - - // 100 onwards is free - for (int i = 100; i < fs.getBigBlockSizeDetails().getBATEntriesPerBlock(); i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(i)); - } - - fs.close(); - } - - // Quick check on 4096 byte blocks too - fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { - // 0 -> 1 -> 2 -> end - assertEquals(1, fs.getNextBlock(0)); - assertEquals(2, fs.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); - - // 4 -> 11 then end - for (int i = 4; i < 11; i++) { - assertEquals(i + 1, fs.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(11)); - - fs.close(); - } - } - - /** - * Check we get the right data back for each block - */ - @Test - void getBlock() throws IOException { - POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { - ByteBuffer b; - - // The 0th block is the first data block - b = fs.getBlockAt(0); - assertEquals((byte) 0x9e, b.get()); - assertEquals((byte) 0x75, b.get()); - assertEquals((byte) 0x97, b.get()); - assertEquals((byte) 0xf6, b.get()); - - // And the next block - b = fs.getBlockAt(1); - assertEquals((byte) 0x86, b.get()); - assertEquals((byte) 0x09, b.get()); - assertEquals((byte) 0x22, b.get()); - assertEquals((byte) 0xfb, b.get()); - - // Check the final block too - b = fs.getBlockAt(99); - assertEquals((byte) 0x01, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x02, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - - fs.close(); - } - - // Quick check on 4096 byte blocks too - fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { - ByteBuffer b; - - // The 0th block is the first data block - b = fs.getBlockAt(0); - assertEquals((byte) 0x9e, b.get()); - assertEquals((byte) 0x75, b.get()); - assertEquals((byte) 0x97, b.get()); - assertEquals((byte) 0xf6, b.get()); - - // And the next block - b = fs.getBlockAt(1); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x03, b.get()); - assertEquals((byte) 0x00, b.get()); - - // The 14th block is the FAT - b = fs.getBlockAt(14); - assertEquals((byte) 0x01, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x02, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - - fs.close(); - } - } - - /** - * Ask for free blocks where there are some already - * to be had from the FAT - */ - @Test - void getFreeBlockWithSpare() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - // Our first BAT block has spares - assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - - // First free one is 100 - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); - - // Ask, will get 100 - assertEquals(100, fs.getFreeBlock()); - - // Ask again, will still get 100 as not written to - assertEquals(100, fs.getFreeBlock()); - - // Allocate it, then ask again - fs.setNextBlock(100, POIFSConstants.END_OF_CHAIN); - assertEquals(101, fs.getFreeBlock()); - - // All done - fs.close(); - } - - /** - * Ask for free blocks where no free ones exist, and so the - * file needs to be extended and another BAT/XBAT added - */ - @Test - void getFreeBlockWithNoneSpare() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - int free; - - // We have one BAT at block 99 - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(99)); - assertBATCount(fs1, 1, 0); - - // We've spare ones from 100 to 128 - for (int i = 100; i < 128; i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(i)); - } - - // Check our BAT knows it's free - assertTrue(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - - // Allocate all the spare ones - for (int i = 100; i < 128; i++) { - fs1.setNextBlock(i, POIFSConstants.END_OF_CHAIN); - } - - // BAT is now full, but there's only the one - assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(128), "Should only be one BAT"); - assertBATCount(fs1, 1, 0); - - - // Now ask for a free one, will need to extend the file - assertEquals(129, fs1.getFreeBlock()); - - assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertTrue(fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(128)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(129)); - - // We now have 2 BATs, but no XBATs - assertBATCount(fs1, 2, 0); - - - // Fill up to hold 109 BAT blocks - for (int i = 0; i < 109; i++) { - fs1.getFreeBlock(); - int startOffset = i * 128; - while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) { - free = fs1.getFreeBlock(); - fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN); - } - } - - assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(109 * 128), "Should only be 109 BATs"); - - // We now have 109 BATs, but no XBATs - assertBATCount(fs1, 109, 0); - - - // Ask for it to be written out, and check the header - HeaderBlock header = writeOutAndReadHeader(fs1); - assertEquals(109, header.getBATCount()); - assertEquals(0, header.getXBATCount()); - - - // Ask for another, will get our first XBAT - free = fs1.getFreeBlock(); - assertTrue(free > 0, "Had: " + free); - - assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors()); - assertTrue(fs1.getBATBlockAndIndex(110 * 128 - 1).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(110 * 128), "Should only be 110 BATs"); - assertBATCount(fs1, 110, 1); - - header = writeOutAndReadHeader(fs1); - assertEquals(110, header.getBATCount()); - assertEquals(1, header.getXBATCount()); - - - // Fill the XBAT, which means filling 127 BATs - for (int i = 109; i < 109 + 127; i++) { - fs1.getFreeBlock(); - int startOffset = i * 128; - while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) { - free = fs1.getFreeBlock(); - fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN); - } - assertBATCount(fs1, i + 1, 1); - } - - // Should now have 109+127 = 236 BATs - assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(236 * 128), "Should only be 236 BATs"); - assertBATCount(fs1, 236, 1); - - - // Ask for another, will get our 2nd XBAT - free = fs1.getFreeBlock(); - assertTrue(free > 0, "Had: " + free); - - assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors()); - assertTrue(fs1.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs"); - - - // Check the counts now - assertBATCount(fs1, 237, 2); - - // Check the header - header = writeOutAndReadHeader(fs1); - assertNotNull(header); - - // Now, write it out, and read it back in again fully - POIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - - // Check that it is seen correctly - assertBATCount(fs2, 237, 2); - - assertFalse(fs2.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors()); - assertTrue(fs2.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs2.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs"); - - // All done - fs2.close(); - } - - /** - * Test that we can correctly get the list of directory - * entries, and the details on the files in them - */ - @Test - void listEntries() throws IOException { - for (POIFSFileSystem fs : get512and4kFileAndInput()) { - DirectoryEntry root = fs.getRoot(); - assertEquals(5, root.getEntryCount()); - - // Check by the names - Entry thumbnail = root.getEntry("Thumbnail"); - Entry dsi = root.getEntry("\u0005DocumentSummaryInformation"); - Entry si = root.getEntry("\u0005SummaryInformation"); - Entry image = root.getEntry("Image"); - Entry tags = root.getEntry("Tags"); - - assertFalse(thumbnail.isDirectoryEntry()); - assertFalse(dsi.isDirectoryEntry()); - assertFalse(si.isDirectoryEntry()); - assertTrue(image.isDirectoryEntry()); - assertFalse(tags.isDirectoryEntry()); - - // Check via the iterator - Iterator it = root.getEntries(); - assertEquals(thumbnail.getName(), it.next().getName()); - assertEquals(dsi.getName(), it.next().getName()); - assertEquals(si.getName(), it.next().getName()); - assertEquals(image.getName(), it.next().getName()); - assertEquals(tags.getName(), it.next().getName()); - - // Look inside another - DirectoryEntry imageD = (DirectoryEntry) image; - assertEquals(7, imageD.getEntryCount()); - - fs.close(); - } - } - - /** - * Tests that we can get the correct contents for - * a document in the filesystem - */ - @Test - void getDocumentEntry() throws Exception { - for (POIFSFileSystem fs : get512and4kFileAndInput()) { - DirectoryEntry root = fs.getRoot(); - Entry si = root.getEntry("\u0005SummaryInformation"); - - assertTrue(si.isDocumentEntry()); - DocumentNode doc = (DocumentNode) si; - - // Check we can read it - assertContentsMatches(null, doc); - - // Now try to build the property set - DocumentInputStream inp = new DocumentInputStream(doc); - PropertySet ps = PropertySetFactory.create(inp); - SummaryInformation inf = (SummaryInformation) ps; - - // Check some bits in it - assertNull(inf.getApplicationName()); - assertNull(inf.getAuthor()); - assertNull(inf.getSubject()); - assertEquals(131333, inf.getOSVersion()); - - // Finish with this one - inp.close(); - - - // Try the other summary information - si = root.getEntry("\u0005DocumentSummaryInformation"); - assertTrue(si.isDocumentEntry()); - doc = (DocumentNode) si; - assertContentsMatches(null, doc); - - inp = new DocumentInputStream(doc); - ps = PropertySetFactory.create(inp); - DocumentSummaryInformation dinf = (DocumentSummaryInformation) ps; - assertEquals(131333, dinf.getOSVersion()); - - fs.close(); - } - } - - /** - * Read a file, write it and read it again. - * Then, alter+add some streams, write and read - */ - @Test - void readWriteRead() throws Exception { - SummaryInformation sinf; - DocumentSummaryInformation dinf; - DirectoryEntry root, testDir; - - for (POIFSFileSystem fs1 : get512and4kFileAndInput()) { - // Check we can find the entries we expect - root = fs1.getRoot(); - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Tags")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - - // Write out, re-load - POIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - - // Check they're still there - root = fs2.getRoot(); - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Tags")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - - // Check the contents of them - parse the summary block and check - sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); - - dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); - - - // Add a test mini stream - testDir = root.createDirectory("Testing 123"); - testDir.createDirectory("Testing 456"); - testDir.createDirectory("Testing 789"); - byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; - testDir.createDocument("Mini", new ByteArrayInputStream(mini)); - - - // Write out, re-load - POIFSFileSystem fs3 = writeOutAndReadBack(fs2); - fs2.close(); - - root = fs3.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); - assertEquals(6, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Tags")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - - // Check old and new are there - sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); - - dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); - - assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); - - - // Write out and read once more, just to be sure - POIFSFileSystem fs4 = writeOutAndReadBack(fs3); - fs3.close(); - - root = fs4.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); - assertEquals(6, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Tags")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); - - dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); - - assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); - - - // Add a full stream, delete a full stream - byte[] main4096 = new byte[4096]; - main4096[0] = -10; - main4096[4095] = -11; - testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); - - root.getEntry("Tags").delete(); - - - // Write out, re-load - POIFSFileSystem fs5 = writeOutAndReadBack(fs4); - fs4.close(); - - // Check it's all there - root = fs5.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - - // Check old and new are there - sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); - - dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); - - assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); - assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096")); - - - // Delete a directory, and add one more - testDir.getEntry("Testing 456").delete(); - testDir.createDirectory("Testing ABC"); - - - // Save - POIFSFileSystem fs6 = writeOutAndReadBack(fs5); - fs5.close(); - - // Check - root = fs6.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); - - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - assertEquals(4, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - - - // Add another mini stream - byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42}; - testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); - - // Save, load, check - POIFSFileSystem fs7 = writeOutAndReadBack(fs6); - fs6.close(); - - root = fs7.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); - - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - assertEquals(5, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini")); - assertThat(testDir.getEntryNames(), hasItem("Mini2")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - - assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); - assertContentsMatches(mini2, (DocumentEntry) testDir.getEntry("Mini2")); - assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096")); - - - // Delete a mini stream, add one more - testDir.getEntry("Mini").delete(); - - byte[] mini3 = new byte[]{42, 0, 42, 0, 42, 0, 42}; - testDir.createDocument("Mini3", new ByteArrayInputStream(mini3)); - - - // Save, load, check - POIFSFileSystem fs8 = writeOutAndReadBack(fs7); - fs7.close(); - - root = fs8.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); - - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - assertEquals(5, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini2")); - assertThat(testDir.getEntryNames(), hasItem("Mini3")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - - assertContentsMatches(mini2, (DocumentEntry) testDir.getEntry("Mini2")); - assertContentsMatches(mini3, (DocumentEntry) testDir.getEntry("Mini3")); - assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096")); - - - // Change some existing streams - POIFSDocument mini2Doc = new POIFSDocument((DocumentNode) testDir.getEntry("Mini2")); - mini2Doc.replaceContents(new ByteArrayInputStream(mini)); - - byte[] main4106 = new byte[4106]; - main4106[0] = 41; - main4106[4105] = 42; - POIFSDocument mainDoc = new POIFSDocument((DocumentNode) testDir.getEntry("Normal4096")); - mainDoc.replaceContents(new ByteArrayInputStream(main4106)); - - - // Re-check - POIFSFileSystem fs9 = writeOutAndReadBack(fs8); - fs8.close(); - - root = fs9.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); - - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - assertEquals(5, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini2")); - assertThat(testDir.getEntryNames(), hasItem("Mini3")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - - assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini2")); - assertContentsMatches(mini3, (DocumentEntry) testDir.getEntry("Mini3")); - assertContentsMatches(main4106, (DocumentEntry) testDir.getEntry("Normal4096")); - - - // All done - fs9.close(); - } - } - - /** - * Create a new file, write it and read it again - * Then, add some streams, write and read - */ - @Test - void createWriteRead() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(); - DocumentEntry miniDoc; - DocumentEntry normDoc; - - // Initially has Properties + BAT but not SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2)); - - // Check that the SBAT is empty - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getRoot().getProperty().getStartBlock()); - - // Check that properties table was given block 0 - assertEquals(0, fs1._get_property_table().getStartBlock()); - - // Write and read it - POIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - - // No change, SBAT remains empty - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(2)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(3)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getRoot().getProperty().getStartBlock()); - assertEquals(0, fs2._get_property_table().getStartBlock()); - fs2.close(); - - // Check the same but with saving to a file - POIFSFileSystem fs3 = new POIFSFileSystem(); - POIFSFileSystem fs4 = writeOutFileAndReadBack(fs3); - fs3.close(); - - // Same, no change, SBAT remains empty - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(2)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(3)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); - assertEquals(0, fs4._get_property_table().getStartBlock()); - - - // Put everything within a new directory - DirectoryEntry testDir = fs4.createDirectory("Test Directory"); - - // Add a new Normal Stream (Normal Streams minimum 4096 bytes) - byte[] main4096 = new byte[4096]; - main4096[0] = -10; - main4096[4095] = -11; - testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(3, fs4.getNextBlock(2)); - assertEquals(4, fs4.getNextBlock(3)); - assertEquals(5, fs4.getNextBlock(4)); - assertEquals(6, fs4.getNextBlock(5)); - assertEquals(7, fs4.getNextBlock(6)); - assertEquals(8, fs4.getNextBlock(7)); - assertEquals(9, fs4.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(11)); - // SBAT still unused - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); - - - // Add a bigger Normal Stream - byte[] main5124 = new byte[5124]; - main5124[0] = -22; - main5124[5123] = -33; - testDir.createDocument("Normal5124", new ByteArrayInputStream(main5124)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(3, fs4.getNextBlock(2)); - assertEquals(4, fs4.getNextBlock(3)); - assertEquals(5, fs4.getNextBlock(4)); - assertEquals(6, fs4.getNextBlock(5)); - assertEquals(7, fs4.getNextBlock(6)); - assertEquals(8, fs4.getNextBlock(7)); - assertEquals(9, fs4.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); - - assertEquals(11, fs4.getNextBlock(10)); - assertEquals(12, fs4.getNextBlock(11)); - assertEquals(13, fs4.getNextBlock(12)); - assertEquals(14, fs4.getNextBlock(13)); - assertEquals(15, fs4.getNextBlock(14)); - assertEquals(16, fs4.getNextBlock(15)); - assertEquals(17, fs4.getNextBlock(16)); - assertEquals(18, fs4.getNextBlock(17)); - assertEquals(19, fs4.getNextBlock(18)); - assertEquals(20, fs4.getNextBlock(19)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(21)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(22)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); - - - // Now Add a mini stream - byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; - testDir.createDocument("Mini", new ByteArrayInputStream(mini)); - - // Mini stream will get one block for fat + one block for data - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(3, fs4.getNextBlock(2)); - assertEquals(4, fs4.getNextBlock(3)); - assertEquals(5, fs4.getNextBlock(4)); - assertEquals(6, fs4.getNextBlock(5)); - assertEquals(7, fs4.getNextBlock(6)); - assertEquals(8, fs4.getNextBlock(7)); - assertEquals(9, fs4.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); - - assertEquals(11, fs4.getNextBlock(10)); - assertEquals(12, fs4.getNextBlock(11)); - assertEquals(13, fs4.getNextBlock(12)); - assertEquals(14, fs4.getNextBlock(13)); - assertEquals(15, fs4.getNextBlock(14)); - assertEquals(16, fs4.getNextBlock(15)); - assertEquals(17, fs4.getNextBlock(16)); - assertEquals(18, fs4.getNextBlock(17)); - assertEquals(19, fs4.getNextBlock(18)); - assertEquals(20, fs4.getNextBlock(19)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(21)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(22)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(23)); - - // Check the mini stream location was set - // (21 is mini fat, 22 is first mini stream block) - assertEquals(22, fs4.getRoot().getProperty().getStartBlock()); - - - // Write and read back - POIFSFileSystem fs5 = writeOutAndReadBack(fs4); - fs4.close(); - HeaderBlock header = writeOutAndReadHeader(fs5); - - // Check the header has the right points in it - assertEquals(1, header.getBATCount()); - assertEquals(1, header.getBATArray()[0]); - assertEquals(0, header.getPropertyStart()); - assertEquals(1, header.getSBATCount()); - assertEquals(21, header.getSBATStart()); - assertEquals(22, fs5._get_property_table().getRoot().getStartBlock()); - - // Block use should be almost the same, except the properties - // stream will have grown out to cover 2 blocks - // Check the block use is all unchanged - assertEquals(23, fs5.getNextBlock(0)); // Properties now extends over 2 blocks - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs5.getNextBlock(1)); - - assertEquals(3, fs5.getNextBlock(2)); - assertEquals(4, fs5.getNextBlock(3)); - assertEquals(5, fs5.getNextBlock(4)); - assertEquals(6, fs5.getNextBlock(5)); - assertEquals(7, fs5.getNextBlock(6)); - assertEquals(8, fs5.getNextBlock(7)); - assertEquals(9, fs5.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(9)); // End of normal4096 - - assertEquals(11, fs5.getNextBlock(10)); - assertEquals(12, fs5.getNextBlock(11)); - assertEquals(13, fs5.getNextBlock(12)); - assertEquals(14, fs5.getNextBlock(13)); - assertEquals(15, fs5.getNextBlock(14)); - assertEquals(16, fs5.getNextBlock(15)); - assertEquals(17, fs5.getNextBlock(16)); - assertEquals(18, fs5.getNextBlock(17)); - assertEquals(19, fs5.getNextBlock(18)); - assertEquals(20, fs5.getNextBlock(19)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(20)); // End of normal5124 - - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(21)); // Mini Stream FAT - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(22)); // Mini Stream data - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(23)); // Properties #2 - assertEquals(POIFSConstants.UNUSED_BLOCK, fs5.getNextBlock(24)); - - - // Check some data - assertEquals(1, fs5.getRoot().getEntryCount()); - testDir = (DirectoryEntry) fs5.getRoot().getEntry("Test Directory"); - assertEquals(3, testDir.getEntryCount()); - - miniDoc = (DocumentEntry) testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); - - normDoc = (DocumentEntry) testDir.getEntry("Normal4096"); - assertContentsMatches(main4096, normDoc); - - normDoc = (DocumentEntry) testDir.getEntry("Normal5124"); - assertContentsMatches(main5124, normDoc); - - - // Delete a couple of streams - miniDoc.delete(); - normDoc.delete(); - - - // Check - will have un-used sectors now - POIFSFileSystem fs6 = writeOutAndReadBack(fs5); - fs5.close(); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(0)); // Props back in 1 block - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs6.getNextBlock(1)); - - assertEquals(3, fs6.getNextBlock(2)); - assertEquals(4, fs6.getNextBlock(3)); - assertEquals(5, fs6.getNextBlock(4)); - assertEquals(6, fs6.getNextBlock(5)); - assertEquals(7, fs6.getNextBlock(6)); - assertEquals(8, fs6.getNextBlock(7)); - assertEquals(9, fs6.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(9)); // End of normal4096 - - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(12)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(13)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(14)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(15)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(16)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(17)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(18)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(19)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(20)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(21)); // Mini Stream FAT - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(22)); // Mini Stream data - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(23)); // Properties gone - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(24)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(25)); - - // All done - fs6.close(); - } - - @Test - void addBeforeWrite() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(); - DocumentEntry miniDoc; - DocumentEntry normDoc; - HeaderBlock hdr; - - // Initially has Properties + BAT but nothing else - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2)); - - hdr = writeOutAndReadHeader(fs1); - // No mini stream, and no xbats - // Will have fat then properties stream - assertEquals(1, hdr.getBATCount()); - assertEquals(1, hdr.getBATArray()[0]); - assertEquals(0, hdr.getPropertyStart()); - assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getSBATStart()); - assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex()); - assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 3, fs1.size()); - fs1.close(); - - // Get a clean filesystem to start with - fs1 = new POIFSFileSystem(); - - // Put our test files in a non-standard place - DirectoryEntry parentDir = fs1.createDirectory("Parent Directory"); - DirectoryEntry testDir = parentDir.createDirectory("Test Directory"); - - - // Add to the mini stream - byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; - testDir.createDocument("Mini", new ByteArrayInputStream(mini)); - - // Add to the main stream - byte[] main4096 = new byte[4096]; - main4096[0] = -10; - main4096[4095] = -11; - testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); - - - // Check the mini stream was added, then the main stream - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(2)); // Mini Fat - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(3)); // Mini Stream - assertEquals(5, fs1.getNextBlock(4)); // Main Stream - assertEquals(6, fs1.getNextBlock(5)); - assertEquals(7, fs1.getNextBlock(6)); - assertEquals(8, fs1.getNextBlock(7)); - assertEquals(9, fs1.getNextBlock(8)); - assertEquals(10, fs1.getNextBlock(9)); - assertEquals(11, fs1.getNextBlock(10)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(12)); - assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 13, fs1.size()); - - - // Check that we can read the right data pre-write - miniDoc = (DocumentEntry) testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); - - normDoc = (DocumentEntry) testDir.getEntry("Normal4096"); - assertContentsMatches(main4096, normDoc); - - - // Write, read, check - hdr = writeOutAndReadHeader(fs1); - POIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - - // Check the header details - will have the sbat near the start, - // then the properties at the end - assertEquals(1, hdr.getBATCount()); - assertEquals(1, hdr.getBATArray()[0]); - assertEquals(2, hdr.getSBATStart()); - assertEquals(0, hdr.getPropertyStart()); - assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex()); - - // Check the block allocation is unchanged, other than - // the properties stream going in at the end - assertEquals(12, fs2.getNextBlock(0)); // Properties - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(2)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(3)); - assertEquals(5, fs2.getNextBlock(4)); - assertEquals(6, fs2.getNextBlock(5)); - assertEquals(7, fs2.getNextBlock(6)); - assertEquals(8, fs2.getNextBlock(7)); - assertEquals(9, fs2.getNextBlock(8)); - assertEquals(10, fs2.getNextBlock(9)); - assertEquals(11, fs2.getNextBlock(10)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(11)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(12)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(13)); - assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 14, fs2.size()); - - - // Check the data - DirectoryEntry fsRoot = fs2.getRoot(); - assertEquals(1, fsRoot.getEntryCount()); - - parentDir = (DirectoryEntry) fsRoot.getEntry("Parent Directory"); - assertEquals(1, parentDir.getEntryCount()); - - testDir = (DirectoryEntry) parentDir.getEntry("Test Directory"); - assertEquals(2, testDir.getEntryCount()); - - miniDoc = (DocumentEntry) testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); - - normDoc = (DocumentEntry) testDir.getEntry("Normal4096"); - assertContentsMatches(main4096, normDoc); - - - // Add one more stream to each, then save and re-load - byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42}; - testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); - - // Add to the main stream - byte[] main4106 = new byte[4106]; - main4106[0] = 41; - main4106[4105] = 42; - testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106)); - - - // Recheck the data in all 4 streams - POIFSFileSystem fs3 = writeOutAndReadBack(fs2); - fs2.close(); - - fsRoot = fs3.getRoot(); - assertEquals(1, fsRoot.getEntryCount()); - - parentDir = (DirectoryEntry) fsRoot.getEntry("Parent Directory"); - assertEquals(1, parentDir.getEntryCount()); - - testDir = (DirectoryEntry) parentDir.getEntry("Test Directory"); - assertEquals(4, testDir.getEntryCount()); - - miniDoc = (DocumentEntry) testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); - - miniDoc = (DocumentEntry) testDir.getEntry("Mini2"); - assertContentsMatches(mini2, miniDoc); - - normDoc = (DocumentEntry) testDir.getEntry("Normal4106"); - assertContentsMatches(main4106, normDoc); - - // All done - fs3.close(); - } - - @Test - void readZeroLengthEntries() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("only-zero-byte-streams.ole2")); - DirectoryNode testDir = fs.getRoot(); - assertEquals(3, testDir.getEntryCount()); - DocumentEntry entry; - - entry = (DocumentEntry) testDir.getEntry("test-zero-1"); - assertNotNull(entry); - assertEquals(0, entry.getSize()); - - entry = (DocumentEntry) testDir.getEntry("test-zero-2"); - assertNotNull(entry); - assertEquals(0, entry.getSize()); - - entry = (DocumentEntry) testDir.getEntry("test-zero-3"); - assertNotNull(entry); - assertEquals(0, entry.getSize()); - - // Check properties, all have zero length, no blocks - PropertyTable props = fs._get_property_table(); - assertEquals(POIFSConstants.END_OF_CHAIN, props.getRoot().getStartBlock()); - for (Property prop : props.getRoot()) { - assertEquals("test-zero-", prop.getName().substring(0, 10)); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); - } - - // All done - fs.close(); - } - - @Test - void writeZeroLengthEntries() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(); - DirectoryNode testDir = fs1.getRoot(); - DocumentEntry miniDoc; - DocumentEntry normDoc; - DocumentEntry emptyDoc; - - // Add mini and normal sized entries to start - byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42}; - testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); - - // Add to the main stream - byte[] main4106 = new byte[4106]; - main4106[0] = 41; - main4106[4105] = 42; - testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106)); - - // Now add some empty ones - byte[] empty = new byte[0]; - testDir.createDocument("empty-1", new ByteArrayInputStream(empty)); - testDir.createDocument("empty-2", new ByteArrayInputStream(empty)); - testDir.createDocument("empty-3", new ByteArrayInputStream(empty)); - - // Check - miniDoc = (DocumentEntry) testDir.getEntry("Mini2"); - assertContentsMatches(mini2, miniDoc); - - normDoc = (DocumentEntry) testDir.getEntry("Normal4106"); - assertContentsMatches(main4106, normDoc); - - emptyDoc = (DocumentEntry) testDir.getEntry("empty-1"); - assertContentsMatches(empty, emptyDoc); - - emptyDoc = (DocumentEntry) testDir.getEntry("empty-2"); - assertContentsMatches(empty, emptyDoc); - - emptyDoc = (DocumentEntry) testDir.getEntry("empty-3"); - assertContentsMatches(empty, emptyDoc); - - // Look at the properties entry, and check the empty ones - // have zero size and no start block - PropertyTable props = fs1._get_property_table(); - Iterator propsIt = props.getRoot().getChildren(); - - Property prop = propsIt.next(); - assertEquals("Mini2", prop.getName()); - assertEquals(0, prop.getStartBlock()); - assertEquals(7, prop.getSize()); - - prop = propsIt.next(); - assertEquals("Normal4106", prop.getName()); - assertEquals(4, prop.getStartBlock()); // BAT, Props, SBAT, MIni - assertEquals(4106, prop.getSize()); - - prop = propsIt.next(); - assertEquals("empty-1", prop.getName()); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); - assertEquals(0, prop.getSize()); - - prop = propsIt.next(); - assertEquals("empty-2", prop.getName()); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); - assertEquals(0, prop.getSize()); - - prop = propsIt.next(); - assertEquals("empty-3", prop.getName()); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); - assertEquals(0, prop.getSize()); - - - // Save and re-check - POIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - testDir = fs2.getRoot(); - - miniDoc = (DocumentEntry) testDir.getEntry("Mini2"); - assertContentsMatches(mini2, miniDoc); - - normDoc = (DocumentEntry) testDir.getEntry("Normal4106"); - assertContentsMatches(main4106, normDoc); - - emptyDoc = (DocumentEntry) testDir.getEntry("empty-1"); - assertContentsMatches(empty, emptyDoc); - - emptyDoc = (DocumentEntry) testDir.getEntry("empty-2"); - assertContentsMatches(empty, emptyDoc); - - emptyDoc = (DocumentEntry) testDir.getEntry("empty-3"); - assertContentsMatches(empty, emptyDoc); - - // Check that a mini-stream was assigned, with one block used - assertEquals(3, testDir.getProperty().getStartBlock()); - assertEquals(64, testDir.getProperty().getSize()); - - // All done - fs2.close(); - } - - /** - * Test that we can read a file with POIFS, create a new POIFS instance, - * write it out, read it with POIFS, and see the original data - */ - @Test - void POIFSReadCopyWritePOIFSRead() throws IOException { - File testFile = POIDataSamples.getSpreadSheetInstance().getFile("Simple.xls"); - POIFSFileSystem src = new POIFSFileSystem(testFile); - byte[] wbDataExp = IOUtils.toByteArray(src.createDocumentInputStream("Workbook")); - - POIFSFileSystem nfs = new POIFSFileSystem(); - EntryUtils.copyNodes(src.getRoot(), nfs.getRoot()); - src.close(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - nfs.writeFilesystem(bos); - nfs.close(); - - POIFSFileSystem pfs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - byte[] wbDataAct = IOUtils.toByteArray(pfs.createDocumentInputStream("Workbook")); - - assertThat(wbDataExp, equalTo(wbDataAct)); - pfs.close(); - } - - /** - * Ensure that you can recursively delete directories and their - * contents - */ - @Test - void RecursiveDelete() throws IOException { - File testFile = POIDataSamples.getSpreadSheetInstance().getFile("SimpleMacro.xls"); - POIFSFileSystem src = new POIFSFileSystem(testFile); - - // Starts out with 5 entries: - // _VBA_PROJECT_CUR - // SummaryInformation <(0x05)SummaryInformation> - // DocumentSummaryInformation <(0x05)DocumentSummaryInformation> - // Workbook - // CompObj <(0x01)CompObj> - assertEquals(5, _countChildren(src._get_property_table().getRoot())); - assertEquals(5, src.getRoot().getEntryCount()); - - // Grab the VBA project root - DirectoryEntry vbaProj = (DirectoryEntry) src.getRoot().getEntry("_VBA_PROJECT_CUR"); - assertEquals(3, vbaProj.getEntryCount()); - // Can't delete yet, has stuff - assertFalse(vbaProj.delete()); - // Recursively delete - _recursiveDeletee(vbaProj); - - // Entries gone - assertEquals(4, _countChildren(src._get_property_table().getRoot())); - assertEquals(4, src.getRoot().getEntryCount()); - - // Done - src.close(); - } - - private void _recursiveDeletee(Entry entry) throws IOException { - if (entry.isDocumentEntry()) { - assertTrue(entry.delete()); - return; - } - - DirectoryEntry dir = (DirectoryEntry) entry; - String[] names = dir.getEntryNames().toArray(new String[dir.getEntryCount()]); - for (String name : names) { - Entry ce = dir.getEntry(name); - _recursiveDeletee(ce); - } - assertTrue(dir.delete()); - } - - @SuppressWarnings("unused") - private int _countChildren(DirectoryProperty p) { - int count = 0; - for (Property cp : p) { - count++; - } - return count; - } - - /** - * To ensure we can create a file >2gb in size, as well as to - * extend existing files past the 2gb boundary. - *

- * Note that to run this test, you will require 2.5+gb of free - * space on your TMP/TEMP partition/disk - *

- * Note that to run this test, you need to be able to mmap 2.5+gb - * files, which may need bigger kernel.shmmax and vm.max_map_count - * settings on Linux. - *

- * TODO Fix this to work... - */ - @Test - @Disabled("Work in progress test for #60670") - void creationAndExtensionPast2GB() throws Exception { - File big = TempFile.createTempFile("poi-test-", ".ole2"); - assumeTrue(big.getFreeSpace() > 2.5 * 1024 * 1024 * 1024, - "2.5gb of free space is required on your tmp/temp partition/disk to run large file tests"); - System.out.println("Slow, memory heavy test in progress...."); - - int s100mb = 100 * 1024 * 1024; - int s512mb = 512 * 1024 * 1024; - long s2gb = 2L * 1024 * 1024 * 1024; - DocumentEntry entry; - POIFSFileSystem fs; - - // Create a just-sub 2gb file - fs = POIFSFileSystem.create(big); - for (int i = 0; i < 19; i++) { - fs.createDocument(new DummyDataInputStream(s100mb), "Entry" + i); - } - fs.writeFilesystem(); - fs.close(); - - // Extend it past the 2gb mark - fs = new POIFSFileSystem(big, false); - for (int i = 0; i < 19; i++) { - entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); - assertNotNull(entry); - assertEquals(s100mb, entry.getSize()); - } - - fs.createDocument(new DummyDataInputStream(s512mb), "Bigger"); - fs.writeFilesystem(); - fs.close(); - - // Check it still works - fs = new POIFSFileSystem(big, false); - for (int i = 0; i < 19; i++) { - entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); - assertNotNull(entry); - assertEquals(s100mb, entry.getSize()); - } - entry = (DocumentEntry) fs.getRoot().getEntry("Bigger"); - assertNotNull(entry); - assertEquals(s512mb, entry.getSize()); - - // Tidy - fs.close(); - assertTrue(big.delete()); - - - // Create a >2gb file - fs = POIFSFileSystem.create(big); - for (int i = 0; i < 4; i++) { - fs.createDocument(new DummyDataInputStream(s512mb), "Entry" + i); - } - fs.writeFilesystem(); - fs.close(); - - // Read it - fs = new POIFSFileSystem(big, false); - for (int i = 0; i < 4; i++) { - entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); - assertNotNull(entry); - assertEquals(s512mb, entry.getSize()); - } - - // Extend it - fs.createDocument(new DummyDataInputStream(s512mb), "Entry4"); - fs.writeFilesystem(); - fs.close(); - - // Check it worked - fs = new POIFSFileSystem(big, false); - for (int i = 0; i < 5; i++) { - entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); - assertNotNull(entry); - assertEquals(s512mb, entry.getSize()); - } - - // Tidy - fs.close(); - assertTrue(big.delete()); - - // Create a file with a 2gb entry - fs = POIFSFileSystem.create(big); - fs.createDocument(new DummyDataInputStream(s100mb), "Small"); - // TODO Check we get a helpful error about the max size - fs.createDocument(new DummyDataInputStream(s2gb), "Big"); - } - - private static final class DummyDataInputStream extends InputStream { - private final long maxSize; - private long size; - - private DummyDataInputStream(long maxSize) { - this.maxSize = maxSize; - this.size = 0; - } - - public int read() { - if (size >= maxSize) return -1; - size++; - return (int) (size % 128); - } - - public int read(byte[] b) { - return read(b, 0, b.length); - } - - public int read(byte[] b, int offset, int len) { - if (size >= maxSize) return -1; - int sz = (int) Math.min(len, maxSize - size); - for (int i = 0; i < sz; i++) { - b[i + offset] = (byte) ((size + i) % 128); - } - size += sz; - return sz; - } - } - - @Disabled("Takes a long time to run") - @Test - void performance() throws Exception { - int iterations = 200;//1_000; - - System.out.println("NPOI:"); - long start = System.currentTimeMillis(); - - for (int i = 0; i < iterations; i++) { - - try (InputStream inputStream = POIDataSamples.getHSMFInstance().openResourceAsStream("lots-of-recipients.msg"); - POIFSFileSystem srcFileSystem = new POIFSFileSystem(inputStream); - POIFSFileSystem destFileSystem = new POIFSFileSystem()) { - - copyAllEntries(srcFileSystem.getRoot(), destFileSystem.getRoot()); - - File file = File.createTempFile("npoi", ".dat"); - try (OutputStream outputStream = new FileOutputStream(file)) { - destFileSystem.writeFilesystem(outputStream); - } - - assertTrue(file.delete()); - if (i % 10 == 0) System.out.print("."); - } - } - - System.out.println(); - System.out.println("NPOI took: " + (System.currentTimeMillis() - start)); - - System.out.println(); - System.out.println(); - } - - private static void copyAllEntries(DirectoryEntry srcDirectory, DirectoryEntry destDirectory) throws IOException { - Iterator iterator = srcDirectory.getEntries(); - - while (iterator.hasNext()) { - Entry entry = iterator.next(); - - if (entry.isDirectoryEntry()) { - DirectoryEntry childDest = destDirectory.createDirectory(entry.getName()); - copyAllEntries((DirectoryEntry) entry, childDest); - - } else { - DocumentEntry srcEntry = (DocumentEntry) entry; - - try (InputStream inputStream = new DocumentInputStream(srcEntry)) { - destDirectory.createDocument(entry.getName(), inputStream); - } - } - } - } - -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java deleted file mode 100644 index 29ed3001f0..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - 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.poifs.filesystem; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.property.DirectoryProperty; -import org.apache.poi.poifs.property.Property; -import org.junit.jupiter.api.Test; - -/** - * Verify the order of entries DirectoryProperty . - *

- * In particular it is important to serialize ROOT._VBA_PROJECT_CUR.VBA node. - * See bug 39234 in bugzilla. Thanks to Bill Seddon for providing the solution. - *

- */ -final class TestPropertySorter { - - //the correct order of entries in the test file - 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", - }; - - 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 - */ - @Test - void testSortProperties() throws IOException { - 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 comparator - Arrays.sort(props, TestPropertySorter::oldCaseSensitivePropertyCompareTo); - - String exp = String.join("", _entries); - String actOld = Stream.of(props).map(Property::getName).collect(Collectors.joining()); - - assertNotEquals("expected old case-sensitive property comparator to return properties in wrong order", exp, actOld); - - // (2) Verify that the fixed property comparator works right - Arrays.sort(props, new DirectoryProperty.PropertyComparator()); - String[] actNew = Stream.of(props).map(Property::getName).toArray(String[]::new); - - assertArrayEquals(_entries, actNew); - } - - private static int oldCaseSensitivePropertyCompareTo(Property o1, Property o2) { - String name1 = o1.getName(); - String name2 = o2.getName(); - int result = name1.length() - name2.length(); - return (result != 0) ? result : name1.compareTo(name2); - } - - /** - * Serialize file system and verify that the order of properties is the same as in the original file. - */ - @Test - void testSerialization() throws IOException { - POIFSFileSystem fs = openSampleFS(); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - fs.writeFilesystem(out); - out.close(); - InputStream is = new ByteArrayInputStream(out.toByteArray()); - fs = new POIFSFileSystem(is); - is.close(); - Property[] props = getVBAProperties(fs); - Arrays.sort(props, new DirectoryProperty.PropertyComparator()); - - String[] act = Stream.of(props).map(Property::getName).toArray(String[]::new); - assertArrayEquals(_entries, act); - } - - /** - * @return array of properties read from ROOT._VBA_PROJECT_CUR.VBA node - */ - private Property[] getVBAProperties(POIFSFileSystem fs) throws IOException { - String _VBA_PROJECT_CUR = "_VBA_PROJECT_CUR"; - String VBA = "VBA"; - - DirectoryEntry root = fs.getRoot(); - DirectoryEntry vba_project = (DirectoryEntry)root.getEntry(_VBA_PROJECT_CUR); - - DirectoryNode vba = (DirectoryNode)vba_project.getEntry(VBA); - DirectoryProperty p = (DirectoryProperty)vba.getProperty(); - - List lst = new ArrayList<>(); - for (Iterator it = p.getChildren(); it.hasNext();){ - Property ch = it.next(); - lst.add(ch); - } - return lst.toArray(new Property[ 0 ]); - } -} diff --git a/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java b/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java deleted file mode 100644 index 57e9ed814e..0000000000 --- a/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java +++ /dev/null @@ -1,320 +0,0 @@ -/* ==================================================================== - 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.poifs.macros; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.StringUtil; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -class TestVBAMacroReader { - private static final Map expectedMacroContents; - - private static String readVBA(POIDataSamples poiDataSamples) { - File macro = poiDataSamples.getFile("SimpleMacro.vba"); - final byte[] bytes; - try { - try (FileInputStream stream = new FileInputStream(macro)) { - bytes = IOUtils.toByteArray(stream); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - - String testMacroContents = new String(bytes, StringUtil.UTF8); - - if (! testMacroContents.startsWith("Sub ")) { - throw new IllegalArgumentException("Not a macro"); - } - - return testMacroContents.substring(testMacroContents.indexOf("()")+3); - } - - static { - final Map _expectedMacroContents = new HashMap<>(); - final POIDataSamples[] dataSamples = { - POIDataSamples.getSpreadSheetInstance(), - POIDataSamples.getSlideShowInstance(), - POIDataSamples.getDocumentInstance(), - POIDataSamples.getDiagramInstance() - }; - for (POIDataSamples sample : dataSamples) { - _expectedMacroContents.put(sample, readVBA(sample)); - } - expectedMacroContents = Collections.unmodifiableMap(_expectedMacroContents); - } - - //////////////////////////////// From Stream ///////////////////////////// - @Test - void HSSFFromStream() throws Exception { - fromStream(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xls"); - } - @Test - void XSSFFromStream() throws Exception { - fromStream(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xlsm"); - } - @Disabled("bug 59302: Found 0 macros; See org.apache.poi.hslf.usermodel.TestBugs.getMacrosFromHSLF()" + - "for an example of how to get macros out of ppt. TODO: make integration across file formats more elegant") - @Test - void HSLFFromStream() throws Exception { - fromStream(POIDataSamples.getSlideShowInstance(), "SimpleMacro.ppt"); - } - @Test - void XSLFFromStream() throws Exception { - fromStream(POIDataSamples.getSlideShowInstance(), "SimpleMacro.pptm"); - } - @Test - void HWPFFromStream() throws Exception { - fromStream(POIDataSamples.getDocumentInstance(), "SimpleMacro.doc"); - } - @Test - void XWPFFromStream() throws Exception { - fromStream(POIDataSamples.getDocumentInstance(), "SimpleMacro.docm"); - } - @Disabled("Found 0 macros") - @Test - void HDGFFromStream() throws Exception { - fromStream(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd"); - } - @Test - void XDGFFromStream() throws Exception { - fromStream(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsdm"); - } - - //////////////////////////////// From File ///////////////////////////// - @Test - void HSSFFromFile() throws Exception { - fromFile(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xls"); - } - @Test - void XSSFFromFile() throws Exception { - fromFile(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xlsm"); - } - @Disabled("bug 59302: Found 0 macros; See org.apache.poi.hslf.usermodel.TestBugs.getMacrosFromHSLF()" + - "for an example of how to get macros out of ppt. TODO: make integration across file formats more elegant") - @Test - void HSLFFromFile() throws Exception { - fromFile(POIDataSamples.getSlideShowInstance(), "SimpleMacro.ppt"); - } - @Test - void XSLFFromFile() throws Exception { - fromFile(POIDataSamples.getSlideShowInstance(), "SimpleMacro.pptm"); - } - @Test - void HWPFFromFile() throws Exception { - fromFile(POIDataSamples.getDocumentInstance(), "SimpleMacro.doc"); - } - @Test - void XWPFFromFile() throws Exception { - fromFile(POIDataSamples.getDocumentInstance(), "SimpleMacro.docm"); - } - @Disabled("Found 0 macros") - @Test - void HDGFFromFile() throws Exception { - fromFile(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd"); - } - @Test - void XDGFFromFile() throws Exception { - fromFile(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsdm"); - } - - //////////////////////////////// From POIFS ///////////////////////////// - @Test - void HSSFFromPOIFS() throws Exception { - fromPOIFS(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xls"); - } - @Disabled("bug 59302: Found 0 macros") - @Test - void HSLFFromPOIFS() throws Exception { - fromPOIFS(POIDataSamples.getSlideShowInstance(), "SimpleMacro.ppt"); - } - @Test - void HWPFFromPOIFS() throws Exception { - fromPOIFS(POIDataSamples.getDocumentInstance(), "SimpleMacro.doc"); - } - @Disabled("Found 0 macros") - @Test - void HDGFFromPOIFS() throws Exception { - fromPOIFS(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd"); - } - - private void fromFile(POIDataSamples dataSamples, String filename) throws IOException { - File f = dataSamples.getFile(filename); - try (VBAMacroReader r = new VBAMacroReader(f)) { - assertMacroContents(dataSamples, r); - } - } - - private void fromStream(POIDataSamples dataSamples, String filename) throws IOException { - try (InputStream fis = dataSamples.openResourceAsStream(filename)) { - try (VBAMacroReader r = new VBAMacroReader(fis)) { - assertMacroContents(dataSamples, r); - } - } - } - - private void fromPOIFS(POIDataSamples dataSamples, String filename) throws IOException { - File f = dataSamples.getFile(filename); - try (POIFSFileSystem fs = new POIFSFileSystem(f)) { - try (VBAMacroReader r = new VBAMacroReader(fs)) { - assertMacroContents(dataSamples, r); - } - } - } - - private void assertMacroContents(POIDataSamples samples, VBAMacroReader r) throws IOException { - assertNotNull(r); - Map contents = r.readMacroModules(); - assertNotNull(contents); - assertFalse(contents.isEmpty(), "Found 0 macros"); - /* - assertEquals(5, contents.size()); - - // Check the ones without scripts - String[] noScripts = new String[] { "ThisWorkbook", - "Sheet1", "Sheet2", "Sheet3" }; - for (String entry : noScripts) { - assertTrue(entry, contents.containsKey(entry)); - - String content = contents.get(entry); - assertContains(content, "Attribute VB_Exposed = True"); - assertContains(content, "Attribute VB_Customizable = True"); - assertContains(content, "Attribute VB_TemplateDerived = False"); - assertContains(content, "Attribute VB_GlobalNameSpace = False"); - assertContains(content, "Attribute VB_Exposed = True"); - } - */ - - // Check the script one - assertContains(contents, "Module1"); - Module module = contents.get("Module1"); - assertNotNull(module); - String content = module.getContent(); - assertContains(content, "Attribute VB_Name = \"Module1\""); - //assertContains(content, "Attribute TestMacro.VB_Description = \"This is a test macro\""); - - assertEquals(Module.ModuleType.Module, module.geModuleType()); - // And the macro itself - String testMacroNoSub = expectedMacroContents.get(samples); - assertContains(content, testMacroNoSub); - } - - @Test - void bug59830() throws IOException { - //test file is "609751.xls" in govdocs1 - File f = POIDataSamples.getSpreadSheetInstance().getFile("59830.xls"); - VBAMacroReader r = new VBAMacroReader(f); - Map macros = r.readMacros(); - assertEquals(29, macros.size()); - assertNotNull(macros.get("Module20")); - assertContains(macros.get("Module20"), "here start of superscripting"); - r.close(); - } - - @Test - void bug59858() throws IOException { - File f = POIDataSamples.getSpreadSheetInstance().getFile("59858.xls"); - VBAMacroReader r = new VBAMacroReader(f); - Map macros = r.readMacros(); - assertEquals(11, macros.size()); - assertNotNull(macros.get("Sheet4")); - assertContains(macros.get("Sheet4"), "intentional constituent"); - r.close(); - } - - @Test - void bug60158() throws IOException { - File f = POIDataSamples.getDocumentInstance().getFile("60158.docm"); - VBAMacroReader r = new VBAMacroReader(f); - Map macros = r.readMacros(); - assertEquals(2, macros.size()); - assertNotNull(macros.get("NewMacros")); - assertContains(macros.get("NewMacros"), "' dirty"); - r.close(); - } - - @Test - void bug60273() throws IOException { - //test file derives from govdocs1 147240.xls - File f = POIDataSamples.getSpreadSheetInstance().getFile("60273.xls"); - VBAMacroReader r = new VBAMacroReader(f); - Map macros = r.readMacros(); - assertEquals(2, macros.size()); - assertNotNull(macros.get("Module1")); - assertContains(macros.get("Module1"), "9/8/2004"); - r.close(); - } - - @Test - void bug60279() throws IOException { - File f = POIDataSamples.getDocumentInstance().getFile("60279.doc"); - VBAMacroReader r = new VBAMacroReader(f); - Map macros = r.readMacros(); - assertEquals(1, macros.size()); - String content = macros.get("ThisDocument"); - assertContains(content, "Attribute VB_Base = \"1Normal.ThisDocument\""); - assertContains(content, "Attribute VB_Customizable = True"); - r.close(); - } - - @Test - void bug62624() throws IOException { - //macro comes from Common Crawl: HRLOXHGMGLFIJQQU27RIWXOARRHAAAAS - File f = POIDataSamples.getSpreadSheetInstance().getFile("62624.bin"); - VBAMacroReader r = new VBAMacroReader(f); - - Map macros = r.readMacroModules(); - assertEquals(13, macros.size()); - assertNotNull(macros.get("M\u00F3dulo1")); - assertContains(macros.get("M\u00F3dulo1").getContent(), "Calcula_tributos"); - assertEquals(Module.ModuleType.Module, macros.get("M\u00F3dulo1").geModuleType()); - r.close(); - } - - @Test - void bug62625() throws IOException { - //macro comes from Common Crawl: 4BZ22N5QG5R2SUU2MNN47PO7VBQLNYIQ - //A REFERENCE_NAME can sometimes only have an ascii string without - //a reserved byte followed by the unicode string. - //See https://github.com/decalage2/oletools/blob/master/oletools/olevba.py#L1516 - //and https://github.com/decalage2/oletools/pull/135 from (@c1fe) - - - File f = POIDataSamples.getSpreadSheetInstance().getFile("62625.bin"); - VBAMacroReader r = new VBAMacroReader(f); - - Map macros = r.readMacroModules(); - assertEquals(20, macros.size()); - r.close(); - } -} diff --git a/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java b/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java deleted file mode 100644 index 3845ce75fe..0000000000 --- a/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java +++ /dev/null @@ -1,249 +0,0 @@ - -/* ==================================================================== - 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.poifs.nio; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.Test; - -/** - * Tests for the datasource implementations - */ -class TestDataSource { - private static final POIDataSamples data = POIDataSamples.getPOIFSInstance(); - - @Test - void testFile() throws Exception { - File f = data.getFile("Notes.ole2"); - - try (FileBackedDataSource ds = new FileBackedDataSource(f)) { - checkDataSource(ds, false); - } - - // try a second time - try (FileBackedDataSource ds = new FileBackedDataSource(f)) { - checkDataSource(ds, false); - } - } - - @Test - void testFileWritable() throws Exception { - File temp = TempFile.createTempFile("TestDataSource", ".test"); - try { - writeDataToFile(temp); - - try (FileBackedDataSource ds = new FileBackedDataSource(temp, false)) { - checkDataSource(ds, true); - } - - // try a second time - try (FileBackedDataSource ds = new FileBackedDataSource(temp, false)) { - checkDataSource(ds, true); - } - - writeDataToFile(temp); - } finally { - assertTrue(temp.exists()); - assertTrue(temp.delete(), "Could not delete file " + temp); - } - } - - - @Test - void testRewritableFile() throws Exception { - File temp = TempFile.createTempFile("TestDataSource", ".test"); - try { - writeDataToFile(temp); - - ; - try (FileBackedDataSource ds = new FileBackedDataSource(temp, true)) { - ByteBuffer buf = ds.read(0, 10); - assertNotNull(buf); - buf = ds.read(8, 0x400); - assertNotNull(buf); - } - - // try a second time - ; - try (FileBackedDataSource ds = new FileBackedDataSource(temp, true)) { - ByteBuffer buf = ds.read(0, 10); - assertNotNull(buf); - buf = ds.read(8, 0x400); - assertNotNull(buf); - } - - writeDataToFile(temp); - } finally { - assertTrue(temp.exists()); - assertTrue(temp.delete()); - } - } - - private void writeDataToFile(File temp) throws IOException { - try (OutputStream str = new FileOutputStream(temp)) { - try (InputStream in = data.openResourceAsStream("Notes.ole2")) { - IOUtils.copy(in, str); - } - } - } - - private void checkDataSource(FileBackedDataSource ds, boolean writeable) throws IOException { - assertEquals(writeable, ds.isWriteable()); - assertNotNull(ds.getChannel()); - - // rewriting changes the size - if (writeable) { - assertTrue(ds.size() == 8192 || ds.size() == 8198, "Had: " + ds.size()); - } else { - assertEquals(8192, ds.size()); - } - - // Start of file - ByteBuffer bs; - bs = ds.read(4, 0); - assertEquals(4, bs.capacity()); - assertEquals(0, bs.position()); - assertEquals(0xd0 - 256, bs.get(0)); - assertEquals(0xcf - 256, bs.get(1)); - assertEquals(0x11, bs.get(2)); - assertEquals(0xe0 - 256, bs.get(3)); - assertEquals(0xd0 - 256, bs.get()); - assertEquals(0xcf - 256, bs.get()); - assertEquals(0x11, bs.get()); - assertEquals(0xe0 - 256, bs.get()); - - // Mid way through - bs = ds.read(8, 0x400); - assertEquals(8, bs.capacity()); - assertEquals(0, bs.position()); - assertEquals((byte) 'R', bs.get(0)); - assertEquals(0, bs.get(1)); - assertEquals((byte) 'o', bs.get(2)); - assertEquals(0, bs.get(3)); - assertEquals((byte) 'o', bs.get(4)); - assertEquals(0, bs.get(5)); - assertEquals((byte) 't', bs.get(6)); - assertEquals(0, bs.get(7)); - - // Can go to the end, but not past it - bs = ds.read(8, 8190); - // TODO How best to warn of a short read? - assertEquals(0, bs.position()); - - // Can't go off the end - assertThrows(IndexOutOfBoundsException.class, () -> ds.read(4, ds.size()), - "Shouldn't be able to read off the end of the file"); - } - - @Test - void testByteArray() { - byte[] data = new byte[256]; - byte b; - for (int i = 0; i < data.length; i++) { - b = (byte) i; - data[i] = b; - } - - ByteArrayBackedDataSource ds = new ByteArrayBackedDataSource(data); - - // Start - ByteBuffer bs; - bs = ds.read(4, 0); - assertEquals(0, bs.position()); - assertEquals(0x00, bs.get()); - assertEquals(0x01, bs.get()); - assertEquals(0x02, bs.get()); - assertEquals(0x03, bs.get()); - - // Middle - bs = ds.read(4, 100); - assertEquals(100, bs.position()); - assertEquals(100, bs.get()); - assertEquals(101, bs.get()); - assertEquals(102, bs.get()); - assertEquals(103, bs.get()); - - // End - bs = ds.read(4, 252); - assertEquals(-4, bs.get()); - assertEquals(-3, bs.get()); - assertEquals(-2, bs.get()); - assertEquals(-1, bs.get()); - - // Off the end - bs = ds.read(4, 254); - assertEquals(-2, bs.get()); - assertEquals(-1, bs.get()); - assertThrows(BufferUnderflowException.class, bs::get, "Shouldn't be able to read off the end"); - - // Past the end - assertThrows(IndexOutOfBoundsException.class, () -> ds.read(4, 256), "Shouldn't be able to read off the end"); - - - // Overwrite - bs = ByteBuffer.allocate(4); - bs.put(0, (byte) -55); - bs.put(1, (byte) -54); - bs.put(2, (byte) -53); - bs.put(3, (byte) -52); - - assertEquals(256, ds.size()); - ds.write(bs, 40); - assertEquals(256, ds.size()); - bs = ds.read(4, 40); - - assertEquals(-55, bs.get()); - assertEquals(-54, bs.get()); - assertEquals(-53, bs.get()); - assertEquals(-52, bs.get()); - - // Append - bs = ByteBuffer.allocate(4); - bs.put(0, (byte) -55); - bs.put(1, (byte) -54); - bs.put(2, (byte) -53); - bs.put(3, (byte) -52); - - assertEquals(256, ds.size()); - ds.write(bs, 256); - assertEquals(260, ds.size()); - - bs = ds.read(4, 256); - assertEquals(256, bs.position()); - assertEquals(-55, bs.get()); - assertEquals(-54, bs.get()); - assertEquals(-53, bs.get()); - assertEquals(-52, bs.get()); - } -} diff --git a/src/testcases/org/apache/poi/poifs/property/LocalProperty.java b/src/testcases/org/apache/poi/poifs/property/LocalProperty.java deleted file mode 100644 index f578129b68..0000000000 --- a/src/testcases/org/apache/poi/poifs/property/LocalProperty.java +++ /dev/null @@ -1,60 +0,0 @@ - -/* ==================================================================== - 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.poifs.property; - -class LocalProperty - extends Property -{ - - /** - * Constructor LocalProperty - * - * @param index - */ - - LocalProperty(int index) - { - super(); - setName("foo" + index); - setIndex(index); - } - - /** - * Method preWrite - */ - - @Override - protected void preWrite() - { - } - - /** - * Method isDirectory - * - * @return false - */ - - @Override - public boolean isDirectory() - { - return false; - } -} // end package-scope class LocalProperty - diff --git a/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java b/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java deleted file mode 100644 index 49b6553012..0000000000 --- a/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java +++ /dev/null @@ -1,273 +0,0 @@ -/* ==================================================================== - 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.poifs.property; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.poifs.storage.RawDataUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * Class to test DirectoryProperty functionality - */ -final class TestDirectoryProperty { - private DirectoryProperty _property; - private byte[] _testblock; - - /** - * Test constructing DirectoryProperty - */ - @Test - void testConstructor() throws IOException { - createBasicDirectoryProperty(); - verifyProperty(); - } - - /** - * Test pre-write functionality - */ - @Test - void testPreWrite() throws IOException { - createBasicDirectoryProperty(); - _property.preWrite(); - - // shouldn't change anything at all - verifyProperty(); - verifyChildren(0); - - // now try adding 1 property - createBasicDirectoryProperty(); - _property.addChild(new LocalProperty(1)); - _property.preWrite(); - - // update children index - _testblock[ 0x4C ] = 1; - _testblock[ 0x4D ] = 0; - _testblock[ 0x4E ] = 0; - _testblock[ 0x4F ] = 0; - verifyProperty(); - verifyChildren(1); - - // now try adding 2 properties - createBasicDirectoryProperty(); - _property.addChild(new LocalProperty(1)); - _property.addChild(new LocalProperty(2)); - _property.preWrite(); - - // update children index - _testblock[ 0x4C ] = 2; - _testblock[ 0x4D ] = 0; - _testblock[ 0x4E ] = 0; - _testblock[ 0x4F ] = 0; - verifyProperty(); - verifyChildren(2); - - // beat on the children allocation code - for (int count = 1; count < 100; count++) - { - createBasicDirectoryProperty(); - for (int j = 1; j < (count + 1); j++) - { - _property.addChild(new LocalProperty(j)); - } - _property.preWrite(); - verifyChildren(count); - } - } - - private void verifyChildren(int count) { - Iterator iter = _property.getChildren(); - List children = new ArrayList<>(); - - while (iter.hasNext()) - { - children.add(iter.next()); - } - assertEquals(count, children.size()); - if (count != 0) - { - boolean[] found = new boolean[ count ]; - - found[ _property.getChildIndex() - 1 ] = true; - int total_found = 1; - - Arrays.fill(found, false); - iter = children.iterator(); - while (iter.hasNext()) - { - Property child = iter.next(); - Child next = child.getNextChild(); - - if (next != null) - { - int index = (( Property ) next).getIndex(); - - if (index != -1) - { - assertFalse(found[index - 1]); - found[ index - 1 ] = true; - total_found++; - } - } - Child previous = child.getPreviousChild(); - - if (previous != null) - { - int index = (( Property ) previous).getIndex(); - - if (index != -1) - { - assertFalse(found[index - 1]); - found[ index - 1 ] = true; - total_found++; - } - } - } - assertEquals(count, total_found); - } - } - - private void createBasicDirectoryProperty() { - final String name = "MyDirectory"; - - _property = new DirectoryProperty(name); - _testblock = new byte[ 128 ]; - int index = 0; - - for (; index < 0x40; index++) - { - _testblock[ index ] = ( byte ) 0; - } - int limit = name.length(); - - _testblock[ index++ ] = ( byte ) (2 * (limit + 1)); - _testblock[ index++ ] = ( byte ) 0; - _testblock[ index++ ] = ( byte ) 1; - _testblock[ index++ ] = ( byte ) 1; - for (; index < 0x50; index++) - { - _testblock[ index ] = ( byte ) 0xff; - } - for (; index < 0x80; index++) - { - _testblock[ index ] = ( byte ) 0; - } - byte[] name_bytes = name.getBytes(LocaleUtil.CHARSET_1252); - - for (index = 0; index < limit; index++) - { - _testblock[ index * 2 ] = name_bytes[ index ]; - } - } - - private void verifyProperty() throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(512); - - _property.writeData(stream); - byte[] output = stream.toByteArray(); - - assertEquals(_testblock.length, output.length); - for (int j = 0; j < _testblock.length; j++) - { - assertEquals(_testblock[ j ], output[ j ], "mismatch at offset " + j); - } - } - - @Test - void testAddChild() throws IOException { - createBasicDirectoryProperty(); - _property.addChild(new LocalProperty(1)); - _property.addChild(new LocalProperty(2)); - assertThrows(IOException.class, () -> _property.addChild(new LocalProperty(1))); - assertThrows(IOException.class, () -> _property.addChild(new LocalProperty(2))); - _property.addChild(new LocalProperty(3)); - } - - @Test - void testDeleteChild() throws IOException { - createBasicDirectoryProperty(); - Property p1 = new LocalProperty(1); - - _property.addChild(p1); - assertThrows(IOException.class, () -> _property.addChild(new LocalProperty(1))); - assertTrue(_property.deleteChild(p1)); - assertFalse(_property.deleteChild(p1)); - _property.addChild(new LocalProperty(1)); - } - - @Test - void testChangeName() throws IOException { - createBasicDirectoryProperty(); - Property p1 = new LocalProperty(1); - String originalName = p1.getName(); - - _property.addChild(p1); - assertTrue(_property.changeName(p1, "foobar")); - assertEquals("foobar", p1.getName()); - assertFalse(_property.changeName(p1, "foobar")); - assertEquals("foobar", p1.getName()); - Property p2 = new LocalProperty(1); - - _property.addChild(p2); - assertFalse(_property.changeName(p1, originalName)); - assertTrue(_property.changeName(p2, "foo")); - assertTrue(_property.changeName(p1, originalName)); - } - - @Test - void testReadingConstructor() { - String[] input = { - "42 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 01 01 FF FF FF FF FF FF FF FF 02 00 00 00 20 08 02 00 00 00 00 00 C0 00 00 00 00 00 00 46", - "00 00 00 00 00 00 00 00 00 00 00 00 C0 5C E8 23 9E 6B C1 01 FE FF FF FF 00 00 00 00 00 00 00 00", - }; - verifyReadingProperty(0, RawDataUtil.decode(input), 0, "Boot Entry"); - } - - private static void verifyReadingProperty(int index, byte[] input, int offset, String name) { - DirectoryProperty property = new DirectoryProperty(index, input, offset); - ByteArrayOutputStream stream = new ByteArrayOutputStream(128); - byte[] expected = Arrays.copyOfRange(input, offset, offset+128); - try { - property.writeData(stream); - } catch (IOException e) { - throw new RuntimeException(e); - } - byte[] output = stream.toByteArray(); - - assertEquals(128, output.length); - for (int j = 0; j < 128; j++) { - assertEquals(expected[j], output[j], "mismatch at offset " + j); - } - assertEquals(index, property.getIndex()); - assertEquals(name, property.getName()); - assertFalse(property.getChildren().hasNext()); - } -} diff --git a/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java b/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java deleted file mode 100644 index 17145cd9db..0000000000 --- a/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java +++ /dev/null @@ -1,160 +0,0 @@ -/* ==================================================================== - 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.poifs.property; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * Class to test DocumentProperty functionality - */ -final class TestDocumentProperty { - - @Test - void testConstructor() throws IOException { - // test with short name, small file - verifyProperty("foo", 1234); - - // test with just long enough name, small file - verifyProperty("A.really.long.long.long.name123", 2345); - - // test with longer name, just small enough file - verifyProperty("A.really.long.long.long.name1234", 4095); - - // test with just long enough file - verifyProperty("A.really.long.long.long.name123", 4096); - } - - @Test - void testReadingConstructor() throws IOException { - String[] hexData = { - "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 05 01 FF FF FF FF FF FF FF FF 02 00 00 00 20 08 02 00 00 00 00 00 C0 00 00 00 00 00 00 46", - "00 00 00 00 00 00 00 00 00 00 00 00 C0 5C E8 23 9E 6B C1 01 FE FF FF FF 00 00 00 00 00 00 00 00", - "57 00 6F 00 72 00 6B 00 62 00 6F 00 6F 00 6B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "12 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00", - "05 00 53 00 75 00 6D 00 6D 00 61 00 72 00 79 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00", - "69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 01 00 00 00 03 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 10 00 00 00 00 00 00", - "05 00 44 00 6F 00 63 00 75 00 6D 00 65 00 6E 00 74 00 53 00 75 00 6D 00 6D 00 61 00 72 00 79 00", - "49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00", - "38 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 10 00 00 00 00 00 00", - }; - byte[] input = RawDataUtil.decode(hexData); - - verifyReadingProperty(1, input, 128, "Workbook"); - verifyReadingProperty(2, input, 256, SummaryInformation.DEFAULT_STREAM_NAME); - verifyReadingProperty(3, input, 384, DocumentSummaryInformation.DEFAULT_STREAM_NAME); - } - - private void verifyReadingProperty(int index, byte[] input, int offset, String name) - throws IOException { - DocumentProperty property = new DocumentProperty(index, input, - offset); - ByteArrayOutputStream stream = new ByteArrayOutputStream(128); - byte[] expected = Arrays.copyOfRange(input, offset, offset+128); - property.writeData(stream); - byte[] output = stream.toByteArray(); - - assertEquals(128, output.length); - for (int j = 0; j < 128; j++) { - assertEquals(expected[ j ], output[ j ], "mismatch at offset " + j); - } - assertEquals(index, property.getIndex()); - assertEquals(name, property.getName()); - } - - private void verifyProperty(String name, int size) throws IOException { - DocumentProperty property = new DocumentProperty(name, size); - - if (size >= 4096) - { - assertFalse(property.shouldUseSmallBlocks()); - } - else - { - assertTrue(property.shouldUseSmallBlocks()); - } - byte[] testblock = new byte[ 128 ]; - int index = 0; - - for (; index < 0x40; index++) - { - testblock[ index ] = ( byte ) 0; - } - int limit = Math.min(31, name.length()); - - testblock[ index++ ] = ( byte ) (2 * (limit + 1)); - testblock[ index++ ] = ( byte ) 0; - testblock[ index++ ] = ( byte ) 2; - testblock[ index++ ] = ( byte ) 1; - for (; index < 0x50; index++) - { - testblock[ index ] = ( byte ) 0xFF; - } - for (; index < 0x78; index++) - { - testblock[ index ] = ( byte ) 0; - } - int sz = size; - - testblock[ index++ ] = ( byte ) sz; - sz /= 256; - testblock[ index++ ] = ( byte ) sz; - sz /= 256; - testblock[ index++ ] = ( byte ) sz; - sz /= 256; - testblock[ index++ ] = ( byte ) sz; - for (; index < 0x80; index++) - { - testblock[ index ] = ( byte ) 0x0; - } - byte[] name_bytes = name.getBytes(LocaleUtil.CHARSET_1252); - - for (index = 0; index < limit; index++) - { - testblock[ index * 2 ] = name_bytes[ index ]; - } - ByteArrayOutputStream stream = new ByteArrayOutputStream(512); - - property.writeData(stream); - byte[] output = stream.toByteArray(); - - assertEquals(testblock.length, output.length); - for (int j = 0; j < testblock.length; j++) - { - assertEquals(testblock[ j ], output[ j ], "mismatch at offset " + j); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java b/src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java deleted file mode 100644 index 6d67310ff6..0000000000 --- a/src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java +++ /dev/null @@ -1,164 +0,0 @@ -/* ==================================================================== - 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.poifs.property; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.poifs.storage.RawDataUtil; -import org.junit.jupiter.api.Test; - -/** - * Class to test PropertyFactory functionality - */ -final class TestPropertyFactory { - - @Test - void testConvertToProperties() throws IOException { - - // real data from a real file! - String hexData = - "H4sIAAAAAAAAANWZ624TRxTHxymXcm2ahjRNUrJAoCGESxFCCPEB22lSqoRECbGE+slxNvEqcYx2bUQ/lUfphz5BnwBegw88" + - "Ac8A/M/ZWe/E3svMbKjEseIdbyz/zpk5cy6z66KNV0c44jdxgKsv/hImMiaOi09SzuV8983Sv+8/uG9L32D8+Gx4bwH0huiK" + - "lnCZ7+COi2tdeGJfBLn8y0KUPimS9J1//r7+7fPa29Ib51e+qv+rwmIXtA54bWjgiKf4RNroyZQGv18+4nvzqfwF/vSl+afl" + - "eBm0gOd9A6OX4G4b6eAU5EckRyzyihPfRMYK8/v9r4aRjzkJ1yNPdPwviX9Mjiuwv4FXEzoE0vvrmAfyQ9Jqi7VJl9mC/EH7" + - "l/nOnuZKOEfOj2fgGWLRixwvvGbJP5HKL+PTNla/o/NT4qIGP4o7r39/OBB/NrHqtMIqlyz3ZQTME1v/q8hxlb28w7wGs5d4" + - "Jly+E0elJ3jfwbhf7mrwI7uT7I9XOyL4WIuYnG9/qcf/KeU7Pf5/6xl8GgWYAx/kFwb8IYpB5IdCd/4p9pyS4w2mu7z3yzIX" + - "OLwq25rxd6g0guucAf8M/uL9F9lfhf/5rMEBZkG3CpgCf5L10OdT6j8px6ugdhDl2rgecO4JfZ8y0b6SidIqgXnwr+L6iwGf" + - "6pRLcryC33+FtW5xDKAsSLWHfg00Af4orsMG/PP4O57Dd8Qa70GPPSFdZuF/47heMeB/J5LWXyfaDsoo+BdYD33+sMLfgN1b" + - "StQ3lRHM/y1cpw343yt82mktvDx4WNCLdjXWpasxG9j/xvF3ROEvguRz/WM//6b8Hw7xNzH3FPXJ18Laz5PZMJqPrCp81sL+" + - "0Uy+WR6YA5/8eULor/9H5XsLHHm2OAbHXuiBuCt1oZzcYE3aCZXYXfDJny4Z8C8o9le47vM44wacBcz8YMpi/ccU/ibXmD5H" + - "233OPcuszR7rUpcxeY27hIC9YlfWx6E8suCr81/m36MKJDDuvUjGLfg/KvarVbaDFd7JtHZQ5iz44wq/jPmuKhk/v+M9LDb7" + - "X53/qtzh5Nu01+qGujiF+U2uc7d7Ga8h/aHOcx/dbXFl3BnoSu5j/80IqgP09x/VidH8JzNDP3gOpsu6pcushf0TQvU/l6vu" + - "dVxbsvrPtniAX7ouuA/Qtn9S4YfRtt7rvTyugcNqTEeXe+DflGxd/pQBPy8TU/2HHkzcNrD/Z4X/DDNfwy607z+GSneEmf0X" + - "RVb8/4PvEH+nl3nSdbllkX+nxeH6y+fzB6pDdm3qjxLFU5pTXb4jVP8n+7qyBgr3XY118bRWwWb/Ua5ek+NVMJoy+tMe3FH6" + - "EBeVed4pwAzsp3qeaipdPtXqcf1Z534ryr9xx72Ie25KVIzlgYX9M0Z8Opd7Jc8FB3fjQ9h/Q4R7Wpd/1Yif3Zfes7CfevWo" + - "/wzjLvnbnnHuJRkumP9U/6uyHj5nHZ97QZfPZNoZFci8BZ965Tj/+fz70Sls1A9FNVmeXC5oP+W/XX4C4Ymk86a8aHxH5/xJ" + - "nvsknf+sc9zt8Kw3ZIbrXwmKytdkb97fDd0veP5ZBi889QstjM5idFeh6Pkv2f+SOV1e/xXej2GUic9E0/V58L/ww8js9qKA" + - "Gn+K8Vc49xY5/ynGj5//hJ5XMX7+ZseflONV3m0V0Jvse5R/V/GuK0Xtj8+f1nrVd5nPBJvKs4is/suOPyzHSxz/uui4Y26b" + - "d35wdOffMu48fvfnQPyJn7894fqvK/1A1SvrSZAOP8n+6PlHGkc3F9o+f9T8eS0x5R+1fM38zxmfK1AAIAAA"; - - final byte[] testdata = RawDataUtil.decompress(hexData); - final ByteArrayInputStream stream = new ByteArrayInputStream(testdata); - final List properties = new ArrayList<>(); - - final byte[] buf = new byte[512]; - for (int readBytes; (readBytes = stream.read(buf)) != -1; ) { - byte[] bbuf = buf; - if (readBytes < 512) { - bbuf = Arrays.copyOf(buf, readBytes); - } - - PropertyFactory.convertToProperties(bbuf, properties); - } - - assertEquals(64, properties.size()); - String[] names = { - "Root Entry", null, null, null, null, null, null, null, null, - null, null, null, null, "Deal Information", "Deal Description", - "Sales Area Code", "Deal Currency", "Outbound Travel Dates", - "Maximum Stay", "Maximum Stay Period", "Deal Type", "Sub Deal", - "Commission Value", "Fare Type", "FUD Grid Dimensions", - "FUD Grid Information", "Double Dealing Indicator", - "Business Type", "Umbrella Links and Passengers", "Agents Name", - "Number of Passengers", "ALC Codes", "Consortia Codes", - "Child Percentage Permitted", "Percentage of Yield", - "Net Remit Permitted", "Infant Discount Permitted", - "Infant Discount Value", "TRVA Information", - "Business Justification", "Surcharge", "Nature of Variation", - "Other Refund Text", "Cancellation Fee Percentage", - "Cancellation Fee Fixed Value", "Cancellation Fee Currency", - "Remarks", "Other Carrier Sectors", "Prorate Comments", null, - null, null, null, null, null, null, null, null, null, null, null, - null, null, null - }; - assertEquals(64, names.length); - - boolean[] isRoot = { - true, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false - }; - assertEquals(64, isRoot.length); - - boolean[] isDocument = { - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, true, true, true, true, true, - true, true, true, true, true, true, true, true, true, true, true, - true, true, true, true, true, true, true, true, true, true, true, - true, true, true, true, true, true, true, true, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false - }; - assertEquals(64, isDocument.length); - - boolean[] isDirectory = { - false, false, false, false, false, false, false, false, false, - false, false, false, false, true, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false - }; - assertEquals(64, isDirectory.length); - - boolean[] isNull = { - false, true, true, true, true, true, true, true, true, true, true, - true, true, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, true, true, true, true, true, true, true, true, - true, true, true, true, true, true, true - }; - assertEquals(64, isNull.length); - - for (int j = 0; j < 64; j++) { - if (isNull[j]) { - assertNull(properties.get(j), "Checking property " + j); - } else { - assertNotNull(properties.get(j), "Checking property " + j); - if (isRoot[j]) { - assertTrue(properties.get(j) instanceof RootProperty, "Checking property " + j); - } - if (isDirectory[j]) { - assertTrue(properties.get(j) instanceof DirectoryProperty, "Checking property " + j); - } - if (isDocument[j]) { - assertTrue(properties.get(j) instanceof DocumentProperty, "Checking property " + j); - } - assertEquals(names[j], properties.get(j).getName(), "Checking property " + j); - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java b/src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java deleted file mode 100644 index e6ce6610f5..0000000000 --- a/src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java +++ /dev/null @@ -1,191 +0,0 @@ -/* ==================================================================== - 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.poifs.property; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.filesystem.POIFSStream; -import org.apache.poi.poifs.storage.HeaderBlock; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.junit.jupiter.api.Test; - -/** - * Class to test PropertyTable functionality - */ -final class TestPropertyTable { - - private static void confirmBlockEncoding(String expectedDataStr, PropertyTable table) throws IOException { - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); - byte[] expectedData = RawDataUtil.decompress(expectedDataStr); - - POIFSStream stream = new POIFSStream(null) { - @Override - public OutputStream getOutputStream() { - return bos; - } - }; - - table.write(stream); - - assertArrayEquals(expectedData, bos.toByteArray()); - } - - /** - * Test PropertyTable - *

- * Running individual tests of the PropertyTable methods, which is the - * traditional way to write unit tests (at least for me), seems somewhat - * useless in this case. Of greater relevance: if one follows the normal - * steps of creating a PropertyTable, and then checking the output, does it - * make sense? In other words, more of an integration test. - *

- * So, the test consists of creating a PropertyTable instance, adding three - * DocumentProperty instances to it, and then getting the output (including - * the preWrite phase first), and comparing it against a real property table - * extracted from a file known to be acceptable to Excel. - */ - @Test - void testWriterPropertyTable() throws IOException { - - // create the PropertyTable - HeaderBlock headerBlock = new HeaderBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - PropertyTable table = new PropertyTable(headerBlock); - - // create three DocumentProperty instances and add them to the - // PropertyTable - DocumentProperty workbook = new DocumentProperty("Workbook", 0x00046777); - - workbook.setStartBlock(0); - DocumentProperty summary1 = new DocumentProperty(SummaryInformation.DEFAULT_STREAM_NAME, 0x00001000); - - summary1.setStartBlock(0x00000234); - DocumentProperty summary2 = new DocumentProperty(DocumentSummaryInformation.DEFAULT_STREAM_NAME, 0x00001000); - - summary2.setStartBlock(0x0000023C); - table.addProperty(workbook); - RootProperty root = table.getRoot(); - - root.addChild(workbook); - table.addProperty(summary1); - root = table.getRoot(); - root.addChild(summary1); - table.addProperty(summary2); - root = table.getRoot(); - root.addChild(summary2); - table.preWrite(); - - final String testblock = - "H4sIAAAAAAAAAAtiyAfCEgYFBleGPCBdxFDJQAoQY2Bl/A8FTETq+QdUC2OHA20vYshmSAK7I5sku0FAiIEJbv9/JHMJgfJ0FjDN" + - "yhDMUMqQC4SJYL97AkMhDewmkEgJQyaQnYfHHA2g/YxAmhmIibXfBBRQAgxQ+12ANiSD3ZAKjgHS3GNBhv9tkOwHAFGXmbcAAgAA"; - confirmBlockEncoding(testblock, table); - - table.removeProperty(summary1); - root = table.getRoot(); - root.deleteChild(summary1); - table.preWrite(); - - final String testblock2 = - "H4sIAAAAAAAAAAtiyAfCEgYFBleGPCBdxFDJQAoQY2Bl/A8FTETq+QdUC2OHA20vYshmSAK7I5sku0FAiIEJbv9/JHMJ" + - "gfJ0FjDNyuACtDeZoZQhlyEVHALBYHYuQyI4LDyBYmlgN4JEShgygew8JHMsgPYzAmlS7LcBBZQAhA0Ae5Y5UIABAAA="; - // (N)POIFS only returns 384 bytes here, instead of 512 - confirmBlockEncoding(testblock2, table); - - table.addProperty(summary1); - root = table.getRoot(); - root.addChild(summary1); - table.preWrite(); - - final String testblock3 = - "H4sIAAAAAAAAAAtiyAfCEgYFBleGPCBdxFDJQAoQY2Bl/A8FzETq+QdUC2OHA20vYshmSAK7I5sku0FAiIEJbv9/JHMJgfJ0FjDNyu" + - "ACtDeZoZQhlyEVHALBYHYuQyI4LDyBYmlgN4JEShgygew8JHMsyLDfhglICDBA7SfNPnSgAbSfEUiDjCTWfhMk+wEk2TJjAAIAAA=="; - confirmBlockEncoding(testblock3, table); - } - - @Test - void testReadingConstructor() throws IOException { - - // first, we need the raw data blocks - String raw_data_array = - "H4sIAAAAAAAAAO2Z608TQRDA5wqVlreIyFMP5AMaMUAMMcYvQIVoUAivxI9HOeCkpaS9GvjmX67OzO61S1930zOpJJ2muUd" + - "u9zfv3V4PoIAfH2z4BNd4LMIdSGQCktYfLVbEMf34/dWnzjPgggM55H9G/jnqUoQ83vHBw/Pr0LkWwKrwn4o0V7INx6iDDT" + - "vI9eBMrMdrSDB/GM/pKOVncPYynKIHXGQH3vCQeKF1OcOrLGtCOtXKmuanhfxefdyCS5w/x5bvI72ILJczwUEN3MrdPD7l4" + - "8fFJ01Z1/w+Ad+6x3eQRswcfqr+tjEyLvO38c4tc204Ye+U8SqQD5r/SMBPGPxjtOwU7Qv4Nuyy96+ghOcO+5984OB1iT1z" + - "wf4o6fEfNT+QKHxTwu1vFJWqvNf8pMD+HsN+le0Oz03556FlWc5Jdad19AHeaX6vgN8LkvhvoS5FjhA9V9udAn5KwCdf6fY" + - "Dezi7jxmgLKZYHyHLgZ+sEXnEYbtLTeZ6o/kDAj7l6rw+30RuiTPO5Qyz4QvfIT+cVyq/eQ96q/k9Aj7ZHjX+9RXX2P4hAT" + - "9l8PeQcsk5ZnMuFLkPq+tDPGZ13wvzf7+Anzb439A26gCKWEBftKr2egn6/6CA32/wD9m/Lkd+g7PcYU8UMBeb+dwUG/mzm" + - "h2VPwCN/X+Ax3OjDlzsu37IXIvIfybkDxr8r2jvLUY8z3GgmFOPu6t0Ho890VyWtP/HIbr/h8CMv8t5TrarLhfe8xrxnwj4" + - "wwa/8Zqr8vA7V0IuEj8h4I+AaT/1lzJnXsA94Tr0Iu3CAv6YgD/Kdiup339lOBvIHyVNb159ik/zPRbwSdfA/ur+M8NVmGU" + - "9bgT7z4Q1BbL8p1xJ6/MjzLwTrPz2978Ja1LIp1qp5l+RmWqVU50nr/3vt/R8lT8h5JsS8DzuuMHaH7bq3OePCPn0OyGs/0" + - "SVaeTbQj75K6nPq/nXep/TTGaRPyfkU78O9j9busIoB3yu+erqEx59tf7MCPmm1O9/jtD2m0hrHwnZPy3kU73U17+MG8g48" + - "l8K+VNgrv9l7v+X3HMv2uLPC/nTBn+DmarWbV4N8iIdJpH/QsifMfjbbLcby//PhfxZuO//U+OXt1TGkL8o5M+B6f9drDdZ" + - "zZlC9i8I+aaofQ/F4ErMJhmN+fs3rgT7ni6/PX7teKnEHZ/q8Pj4+vfAzuZ+jPFzsLTxanV9eS/rL6+trKzafsE2LkPHP3T" + - "/Pezx8evH6rj+Kd0H/sVRzp+MaX8Sfjh5t9Tm+M7nrwVhNd56fNz+063/OOPj2t9p+R3zS+9d2hnXlf9DLN27g/+E6L0E/T" + - "/Rp/t5WseX3hnTe9uhmnh35WHLX544XEIAIAAA"; - - // Fake up a header - HeaderBlock header_block = new HeaderBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - header_block.setPropertyStart(0); - - List data_blocks = new ArrayList<>(); - try (InputStream is = new ByteArrayInputStream(RawDataUtil.decompress(raw_data_array))) { - byte[] buf = new byte[header_block.getBigBlockSize().getBigBlockSize()]; - - for (int readBytes; (readBytes = is.read(buf)) != -1; ) { - data_blocks.add(ByteBuffer.wrap(buf.clone(), 0, readBytes)); - } - } - - - // get property table from the document - PropertyTable table = new PropertyTable(header_block, data_blocks); - - assertEquals(30 * 64, table.getRoot().getSize()); - int count = 0; - Property lastChild = null; - for (Property p : table.getRoot()) { - assertNotNull(p); - lastChild = p; - ++count; - } - - assertNotNull(lastChild, "no children found"); - assertEquals(1, count); - assertTrue(lastChild.isDirectory()); - count = 0; - for (Property p : (DirectoryProperty) lastChild) { - assertNotNull(p); - ++count; - } - assertEquals(35, count); - } -} diff --git a/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java b/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java deleted file mode 100644 index 4b311a8ec8..0000000000 --- a/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java +++ /dev/null @@ -1,136 +0,0 @@ -/* ==================================================================== - 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.poifs.property; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * Class to test RootProperty functionality - * - * @author Marc Johnson - */ -final class TestRootProperty { - private RootProperty _property; - private byte[] _testblock; - - @Test - void testConstructor() throws IOException { - createBasicRootProperty(); - verifyProperty(); - } - - private void createBasicRootProperty() { - _property = new RootProperty(); - _testblock = new byte[128]; - int index = 0; - - for (; index < 0x40; index++) { - _testblock[index] = (byte) 0; - } - String name = "Root Entry"; - int limit = name.length(); - - _testblock[index++] = (byte) (2 * (limit + 1)); - _testblock[index++] = (byte) 0; - _testblock[index++] = (byte) 5; - _testblock[index++] = (byte) 1; - for (; index < 0x50; index++) { - _testblock[index] = (byte) 0xff; - } - for (; index < 0x74; index++) { - _testblock[index] = (byte) 0; - } - _testblock[index++] = (byte) POIFSConstants.END_OF_CHAIN; - for (; index < 0x78; index++) { - _testblock[index] = (byte) 0xff; - } - for (; index < 0x80; index++) { - _testblock[index] = (byte) 0; - } - byte[] name_bytes = name.getBytes(LocaleUtil.CHARSET_1252); - - for (index = 0; index < limit; index++) { - _testblock[index * 2] = name_bytes[index]; - } - } - - private void verifyProperty() throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(512); - - _property.writeData(stream); - byte[] output = stream.toByteArray(); - - assertEquals(_testblock.length, output.length); - for (int j = 0; j < _testblock.length; j++) { - assertEquals(_testblock[j], output[j], "mismatch at offset " + j); - } - } - - @Test - void testSetSize() { - for (int j = 0; j < 10; j++) { - createBasicRootProperty(); - _property.setSize(j); - assertEquals(j * 64, _property.getSize(), "trying block count of " + j); - } - } - - @Test - void testReadingConstructor() { - String[] input = { - "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 05 01 FF FF FF FF FF FF FF FF 02 00 00 00 20 08 02 00 00 00 00 00 C0 00 00 00 00 00 00 46", - "00 00 00 00 00 00 00 00 00 00 00 00 C0 5C E8 23 9E 6B C1 01 FE FF FF FF 00 00 00 00 00 00 00 00", - }; - verifyReadingProperty(0, RawDataUtil.decode(input), 0, "Root Entry", - "{00020820-0000-0000-C000-000000000046}"); - } - - private void verifyReadingProperty(int index, byte[] input, int offset, String name, - String sClsId) { - RootProperty property = new RootProperty(index, input, offset); - ByteArrayOutputStream stream = new ByteArrayOutputStream(128); - byte[] expected = Arrays.copyOfRange(input, offset, offset+128); - try { - property.writeData(stream); - } catch (IOException e) { - throw new RuntimeException(e); - } - byte[] output = stream.toByteArray(); - - assertEquals(128, output.length); - for (int j = 0; j < 128; j++) { - assertEquals(expected[j], output[j], "mismatch at offset " + j); - } - assertEquals(index, property.getIndex()); - assertEquals(name, property.getName()); - assertFalse(property.getChildren().hasNext()); - assertEquals(property.getStorageClsid().toString(), sClsId); - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/LocalProperty.java b/src/testcases/org/apache/poi/poifs/storage/LocalProperty.java deleted file mode 100644 index 13a1c52306..0000000000 --- a/src/testcases/org/apache/poi/poifs/storage/LocalProperty.java +++ /dev/null @@ -1,59 +0,0 @@ - -/* ==================================================================== - 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.poifs.storage; - -import org.apache.poi.poifs.property.Property; - -class LocalProperty - extends Property -{ - - /** - * Constructor TestProperty - * - * @param name name of the property - */ - - LocalProperty(String name) - { - super(); - setName(name); - } - - /** - * do nothing - */ - - @Override - protected void preWrite() - { - } - - /** - * @return false - */ - - @Override - public boolean isDirectory() - { - return false; - } -} // end package scope class LocalProperty - diff --git a/src/testcases/org/apache/poi/poifs/storage/RawDataUtil.java b/src/testcases/org/apache/poi/poifs/storage/RawDataUtil.java deleted file mode 100644 index b04741fb06..0000000000 --- a/src/testcases/org/apache/poi/poifs/storage/RawDataUtil.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ==================================================================== - 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.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Base64; -import java.util.zip.GZIPInputStream; - -import org.apache.poi.util.HexRead; -import org.apache.poi.util.IOUtils; - -/** - * Test utility class.
- * - * Creates raw byte[] data from hex-dump String arrays. - */ -public final class RawDataUtil { - - private RawDataUtil() {} - - public static byte[] decode(String[] hexDataLines) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(hexDataLines.length * 32 + 32); - - for (String hexDataLine : hexDataLines) { - byte[] lineData = HexRead.readFromString(hexDataLine); - baos.write(lineData, 0, lineData.length); - } - return baos.toByteArray(); - } - - /** - * Decompress previously gziped/base64ed data - * - * @param data the gziped/base64ed data - * @return the raw bytes - * @throws IOException if you copy and pasted the data wrong - */ - public static byte[] decompress(String data) throws IOException { - byte[] base64Bytes = Base64.getDecoder().decode(data); - return IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(base64Bytes))); - } - - /** - * Compress raw data for test runs - usually called while debugging :) - * - * @param data the raw data - * @return the gziped/base64ed data as String - * @throws IOException usually not ... - */ - public static String compress(byte[] data) throws IOException { - java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); - java.util.zip.GZIPOutputStream gz = new java.util.zip.GZIPOutputStream(bos); - gz.write(data); - gz.finish(); - return Base64.getEncoder().encodeToString(bos.toByteArray()); - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestBATBlock.java b/src/testcases/org/apache/poi/poifs/storage/TestBATBlock.java deleted file mode 100644 index 8190b151b6..0000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestBATBlock.java +++ /dev/null @@ -1,351 +0,0 @@ -/* ==================================================================== - 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.poifs.storage; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.poifs.common.POIFSBigBlockSize; -import org.apache.poi.poifs.common.POIFSConstants; -import org.junit.jupiter.api.Test; - -/** - * Class to test BATBlock functionality - */ -final class TestBATBlock { - - - @Test - void testEntriesPerBlock() { - assertEquals(128, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS.getBATEntriesPerBlock()); - } - - @Test - void testEntriesPerXBATBlock() { - assertEquals(127, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS.getXBATEntriesPerBlock()); - } - - @Test - void testGetXBATChainOffset() { - assertEquals(508, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS.getNextXBATChainOffset()); - } - - @Test - void testCalculateMaximumSize() { - // Zero fat blocks isn't technically valid, but it'd be header only - assertEquals( - 512, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 0) - ); - assertEquals( - 4096, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 0) - ); - - // A single FAT block can address 128/1024 blocks - assertEquals( - 512 + 512 * 128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 1) - ); - assertEquals( - 4096 + 4096 * 1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 1) - ); - - assertEquals( - 512 + 4 * 512 * 128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 4) - ); - assertEquals( - 4096 + 4 * 4096 * 1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 4) - ); - - // One XBAT block holds 127/1023 individual BAT blocks, so they can address - // a fairly hefty amount of space themselves - // However, the BATs continue as before - assertEquals( - 512 + 109 * 512 * 128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 109) - ); - assertEquals( - 4096 + 109 * 4096 * 1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 109) - ); - - assertEquals( - 512 + 110 * 512 * 128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 110) - ); - assertEquals( - 4096 + 110 * 4096 * 1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 110) - ); - - assertEquals( - 512 + 112 * 512 * 128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 112) - ); - assertEquals( - 4096 + 112 * 4096 * 1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 112) - ); - - // Check for >2gb, which we only support via a File - assertEquals( - 512 + 8030L * 512 * 128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 8030) - ); - assertEquals( - 4096 + 8030L * 4096 * 1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 8030) - ); - } - - @Test - void testUsedSectors() { - POIFSBigBlockSize b512 = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS; - POIFSBigBlockSize b4096 = POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS; - - // Try first with 512 block sizes, which can hold 128 entries - BATBlock block512 = BATBlock.createEmptyBATBlock(b512, false); - assertTrue(block512.hasFreeSectors()); - assertEquals(0, block512.getUsedSectors(false)); - - // Allocate a few - block512.setValueAt(0, 42); - block512.setValueAt(10, 42); - block512.setValueAt(20, 42); - assertTrue(block512.hasFreeSectors()); - assertEquals(3, block512.getUsedSectors(false)); - - // Allocate all - for (int i = 0; i < b512.getBATEntriesPerBlock(); i++) { - block512.setValueAt(i, 82); - } - // Check - assertFalse(block512.hasFreeSectors()); - assertEquals(128, block512.getUsedSectors(false)); - assertEquals(127, block512.getUsedSectors(true)); - - // Release one - block512.setValueAt(10, POIFSConstants.UNUSED_BLOCK); - assertTrue(block512.hasFreeSectors()); - assertEquals(127, block512.getUsedSectors(false)); - assertEquals(126, block512.getUsedSectors(true)); - - - // Now repeat with 4096 block sizes - BATBlock block4096 = BATBlock.createEmptyBATBlock(b4096, false); - assertTrue(block4096.hasFreeSectors()); - assertEquals(0, block4096.getUsedSectors(false)); - - block4096.setValueAt(0, 42); - block4096.setValueAt(10, 42); - block4096.setValueAt(20, 42); - assertTrue(block4096.hasFreeSectors()); - assertEquals(3, block4096.getUsedSectors(false)); - - // Allocate all - for (int i = 0; i < b4096.getBATEntriesPerBlock(); i++) { - block4096.setValueAt(i, 82); - } - // Check - assertFalse(block4096.hasFreeSectors()); - assertEquals(1024, block4096.getUsedSectors(false)); - assertEquals(1023, block4096.getUsedSectors(true)); - } - - @Test - void testOccupiedSize() { - POIFSBigBlockSize b512 = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS; - POIFSBigBlockSize b4096 = POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS; - - // Try first with 512 block sizes, which can hold 128 entries - BATBlock block512 = BATBlock.createEmptyBATBlock(b512, false); - assertTrue(block512.hasFreeSectors()); - assertEquals(0, block512.getUsedSectors(false)); - - // Allocate a few - block512.setValueAt(0, 42); - block512.setValueAt(10, 42); - block512.setValueAt(20, 42); - assertTrue(block512.hasFreeSectors()); - assertEquals(21, block512.getOccupiedSize()); - - // Release one in the middle should not lower size - block512.setValueAt(10, POIFSConstants.UNUSED_BLOCK); - assertTrue(block512.hasFreeSectors()); - assertEquals(21, block512.getOccupiedSize()); - - // Release the last one should lower the size - block512.setValueAt(20, POIFSConstants.UNUSED_BLOCK); - assertTrue(block512.hasFreeSectors()); - assertEquals(1, block512.getOccupiedSize()); - - // Release first one should lower the size - block512.setValueAt(0, POIFSConstants.UNUSED_BLOCK); - assertTrue(block512.hasFreeSectors()); - assertEquals(0, block512.getOccupiedSize()); - - // Set the last one - block512.setValueAt(127, 42); - assertTrue(block512.hasFreeSectors()); - assertEquals(128, block512.getOccupiedSize()); - - block512.setValueAt(126, 42); - assertTrue(block512.hasFreeSectors()); - assertEquals(128, block512.getOccupiedSize()); - - block512.setValueAt(127, POIFSConstants.UNUSED_BLOCK); - assertTrue(block512.hasFreeSectors()); - assertEquals(127, block512.getOccupiedSize()); - - // Allocate all - for (int i = 0; i < b512.getBATEntriesPerBlock(); i++) { - block512.setValueAt(i, 82); - } - // Check - assertFalse(block512.hasFreeSectors()); - assertEquals(128, block512.getOccupiedSize()); - - // Release some in the beginning should not lower size - block512.setValueAt(0, POIFSConstants.UNUSED_BLOCK); - block512.setValueAt(1, POIFSConstants.UNUSED_BLOCK); - block512.setValueAt(13, POIFSConstants.UNUSED_BLOCK); - assertTrue(block512.hasFreeSectors()); - assertEquals(128, block512.getOccupiedSize()); - } - - @Test - void testGetBATBlockAndIndex() { - HeaderBlock header = new HeaderBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - List blocks = new ArrayList<>(); - int offset; - - - // First, try a one BAT block file - header.setBATCount(1); - blocks.add( - BATBlock.createBATBlock(header.getBigBlockSize(), ByteBuffer.allocate(512)) - ); - - offset = 0; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 1; - assertEquals(1, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 127; - assertEquals(127, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - - // Now go for one with multiple BAT blocks - header.setBATCount(2); - blocks.add( - BATBlock.createBATBlock(header.getBigBlockSize(), ByteBuffer.allocate(512)) - ); - - offset = 0; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 127; - assertEquals(127, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 128; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 129; - assertEquals(1, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - - // The XBAT count makes no difference, as we flatten in memory - header.setBATCount(1); - header.setXBATCount(1); - offset = 0; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 126; - assertEquals(126, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 127; - assertEquals(127, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 128; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 129; - assertEquals(1, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - - // Check with the bigger block size too - header = new HeaderBlock(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS); - - offset = 0; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 1022; - assertEquals(1022, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 1023; - assertEquals(1023, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 1024; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - // Biggr block size, back to real BATs - header.setBATCount(2); - - offset = 0; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 1022; - assertEquals(1022, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 1023; - assertEquals(1023, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - - offset = 1024; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf(BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock())); - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockReading.java b/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockReading.java deleted file mode 100644 index bb08ae3965..0000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockReading.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ==================================================================== - 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.poifs.storage; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.junit.jupiter.api.Test; - -/** - * Class to test HeaderBlockReader functionality - */ -final class TestHeaderBlockReading { - - @Test - void testConstructors() throws IOException { - String[] hexData = { - "D0 CF 11 E0 A1 B1 1A E1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3B 00 03 00 FE FF 09 00", - "06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 10 00 00 FE FF FF FF", - "01 00 00 00 FE FF FF FF 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - }; - byte[] content = RawDataUtil.decode(hexData); - HeaderBlock block = new HeaderBlock(new ByteArrayInputStream(content)); - - assertEquals(-2, block.getPropertyStart()); - - // verify we can't read a short block - byte[] shortblock = Arrays.copyOf(content, 511); - assertThrows(IOException.class, () -> new HeaderBlock(new ByteArrayInputStream(shortblock))); - - // try various forms of corruption - for (int index = 0; index < 8; index++) { - content[index] = (byte) (content[index] - 1); - assertThrows(IOException.class, () -> new HeaderBlock(new ByteArrayInputStream(content)), - "Should have caught IOException corrupting byte " + index); - - // restore byte value - content[index] = (byte) (content[index] + 1); - } - } -} diff --git a/src/testcases/org/apache/poi/sl/draw/geom/TestFormulaParser.java b/src/testcases/org/apache/poi/sl/draw/geom/TestFormulaParser.java deleted file mode 100644 index a99041c852..0000000000 --- a/src/testcases/org/apache/poi/sl/draw/geom/TestFormulaParser.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * ==================================================================== - * 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.sl.draw.geom; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** - * Date: 10/24/11 - * - * @author Yegor Kozlov - */ -class TestFormulaParser { - @Test - void testParse(){ - - Formula[] ops = { - newGuide("adj1", "val 100"), - newGuide("adj2", "val 200"), - newGuide("adj3", "val -1"), - newGuide("a1", "*/ adj1 2 adj2"), // a1 = 100*2 / 200 - newGuide("a2", "+- adj2 a1 adj1"), // a2 = 200 + a1 - 100 - newGuide("a3", "+/ adj1 adj2 adj2"), // a3 = (100 + 200) / 200 - newGuide("a4", "?: adj3 adj1 adj2"), // a4 = adj3 > 0 ? adj1 : adj2 - newGuide("a5", "abs -2"), - }; - - CustomGeometry geom = new CustomGeometry(); - Context ctx = new Context(geom, null, null); - for(Formula fmla : ops) { - ctx.evaluate(fmla); - } - - assertEquals(100.0, ctx.getValue("adj1"), 0.0); - assertEquals(200.0, ctx.getValue("adj2"), 0.0); - assertEquals(1.0, ctx.getValue("a1"), 0.0); - assertEquals(101.0, ctx.getValue("a2"), 0.0); - assertEquals(1.5, ctx.getValue("a3"), 0.0); - assertEquals(200.0, ctx.getValue("a4"), 0.0); - assertEquals(2.0, ctx.getValue("a5"), 0.0); - } - - private static Guide newGuide(String name, String fmla) { - Guide gd = new Guide(); - gd.setName(name); - gd.setFmla(fmla); - return gd; - } -} diff --git a/src/testcases/org/apache/poi/sl/draw/geom/TestPresetGeometries.java b/src/testcases/org/apache/poi/sl/draw/geom/TestPresetGeometries.java deleted file mode 100644 index 28849f77e9..0000000000 --- a/src/testcases/org/apache/poi/sl/draw/geom/TestPresetGeometries.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * ==================================================================== - * 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.sl.draw.geom; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -import java.awt.geom.Path2D; -import java.awt.geom.Rectangle2D; -import java.net.URL; -import java.util.Enumeration; - -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -class TestPresetGeometries { - @Test - void testRead(){ - PresetGeometries shapes = PresetGeometries.getInstance(); - assertEquals(187, shapes.size()); - assertEquals(0x4533584F, shapes.hashCode()); - - for(String name : shapes.keySet()) { - CustomGeometry geom = shapes.get(name); - Context ctx = new Context(geom, new Rectangle2D.Double(0, 0, 100, 100), presetName -> null); - for(Path p : geom){ - Path2D path = p.getPath(ctx); - assertNotNull(path); - } - } - - // we get the same instance on further calls - assertSame(shapes, PresetGeometries.getInstance()); - } - - @Disabled("problem solved? Turn back on if this debugging is still in process.") - void testCheckXMLParser() throws Exception{ - // Gump reports a strange error because of an unavailable XML Parser, let's try to find out where - // this comes from - // - Enumeration resources = this.getClass().getClassLoader().getResources("META-INF/services/javax.xml.stream.XMLEventFactory"); - printURLs(resources); - resources = ClassLoader.getSystemResources("META-INF/services/javax.xml.stream.XMLEventFactory"); - printURLs(resources); - resources = ClassLoader.getSystemResources("org/apache/poi/sl/draw/geom/presetShapeDefinitions.xml"); - printURLs(resources); - } - - private void printURLs(Enumeration resources) { - while(resources.hasMoreElements()) { - URL url = resources.nextElement(); - System.out.println("URL: " + url); - } - } -} diff --git a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShow.java b/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShow.java deleted file mode 100644 index 81f5931f34..0000000000 --- a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShow.java +++ /dev/null @@ -1,203 +0,0 @@ -/* ==================================================================== - 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.sl.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.common.usermodel.fonts.FontInfo; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.sl.usermodel.TabStop.TabStopType; -import org.junit.jupiter.api.Test; - -public abstract class BaseTestSlideShow< - S extends Shape, - P extends TextParagraph -> { - protected static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - - public abstract SlideShow createSlideShow(); - - public abstract SlideShow reopen(SlideShow show) throws IOException; - - @Test - void addPicture_File() throws IOException { - SlideShow show = createSlideShow(); - File f = slTests.getFile("clock.jpg"); - - assertEquals(0, show.getPictureData().size()); - PictureData picture = show.addPicture(f, PictureType.JPEG); - assertEquals(1, show.getPictureData().size()); - assertSame(picture, show.getPictureData().get(0)); - - show.close(); - } - - @Test - void addPicture_Stream() throws IOException { - try (SlideShow show = createSlideShow(); - InputStream stream = slTests.openResourceAsStream("clock.jpg")) { - assertEquals(0, show.getPictureData().size()); - PictureData picture = show.addPicture(stream, PictureType.JPEG); - assertEquals(1, show.getPictureData().size()); - assertSame(picture, show.getPictureData().get(0)); - } - } - - @Test - void addPicture_ByteArray() throws IOException { - SlideShow show = createSlideShow(); - byte[] data = slTests.readFile("clock.jpg"); - - assertEquals(0, show.getPictureData().size()); - PictureData picture = show.addPicture(data, PictureType.JPEG); - assertEquals(1, show.getPictureData().size()); - assertSame(picture, show.getPictureData().get(0)); - - show.close(); - } - - @Test - void findPicture() throws IOException { - SlideShow show = createSlideShow(); - byte[] data = slTests.readFile("clock.jpg"); - - assertNull(show.findPictureData(data)); - PictureData picture = show.addPicture(data, PictureType.JPEG); - PictureData found = show.findPictureData(data); - assertNotNull(found); - assertEquals(picture, found); - - show.close(); - } - - @Test - void addTabStops() throws IOException { - try (final SlideShow show1 = createSlideShow()) { - // first set the TabStops in the Master sheet - final MasterSheet master1 = show1.getSlideMasters().get(0); - final AutoShape master1_as = (AutoShape)master1.getPlaceholder(Placeholder.BODY); - final P master1_tp = master1_as.getTextParagraphs().get(0); - master1_tp.clearTabStops(); - int i1 = 0; - for (final TabStopType tst : TabStopType.values()) { - master1_tp.addTabStops(10+i1*10, tst); - i1++; - } - - // then set it on a normal slide - final Slide slide1 = show1.createSlide(); - final AutoShape slide1_as = slide1.createAutoShape(); - slide1_as.setText("abc"); - slide1_as.setAnchor(new Rectangle2D.Double(100,100,100,100)); - final P slide1_tp = slide1_as.getTextParagraphs().get(0); - slide1_tp.getTextRuns().get(0).setFontColor(new Color(0x563412)); - slide1_tp.clearTabStops(); - int i2 = 0; - for (final TabStopType tst : TabStopType.values()) { - slide1_tp.addTabStops(15+i2*5, tst); - i2++; - } - - try (final SlideShow show2 = reopen(show1)) { - final MasterSheet master2 = show2.getSlideMasters().get(0); - final AutoShape master2_as = (AutoShape)master2.getPlaceholder(Placeholder.BODY); - final P master2_tp = master2_as.getTextParagraphs().get(0); - final List master2_tabStops = master2_tp.getTabStops(); - assertNotNull(master2_tabStops); - int i3 = 0; - for (final TabStopType tst : TabStopType.values()) { - final TabStop ts = master2_tabStops.get(i3); - assertEquals(10+i3*10, ts.getPositionInPoints(), 0.0); - assertEquals(tst, ts.getType()); - i3++; - } - - - final Slide slide2 = show2.getSlides().get(0); - @SuppressWarnings("unchecked") - final AutoShape slide2_as = (AutoShape)slide2.getShapes().get(0); - final P slide2_tp = slide2_as.getTextParagraphs().get(0); - final List slide2_tabStops = slide2_tp.getTabStops(); - assertNotNull(slide2_tabStops); - int i4 = 0; - for (final TabStopType tst : TabStopType.values()) { - final TabStop ts = slide2_tabStops.get(i4); - assertEquals(15+i4*5, ts.getPositionInPoints(), 0.0); - assertEquals(tst, ts.getType()); - i4++; - } - } - } - } - - @Test - void shapeAndSlideName() throws IOException { - final String file = "SampleShow.ppt"+(getClass().getSimpleName().contains("XML")?"x":""); - //noinspection unchecked - try (final InputStream is = slTests.openResourceAsStream(file); - final SlideShow ppt = (SlideShow)SlideShowFactory.create(is)) { - final List shapes1 = ppt.getSlides().get(0).getShapes(); - assertEquals("The Title", shapes1.get(0).getShapeName()); - assertEquals("Another Subtitle", shapes1.get(1).getShapeName()); - final List shapes2 = ppt.getSlides().get(1).getShapes(); - assertEquals("Title 1", shapes2.get(0).getShapeName()); - assertEquals("Content Placeholder 2", shapes2.get(1).getShapeName()); - - for (final Slide slide : ppt.getSlides()) { - final String expected = slide.getSlideNumber()==1 ? "FirstSlide" : "Slide2"; - assertEquals(expected, slide.getSlideName()); - } - } - } - - @Test - void addFont() throws IOException { - try (SlideShow ppt = createSlideShow()) { - ppt.createSlide(); - try (InputStream fontData = slTests.openResourceAsStream("font.fntdata")) { - ppt.addFont(fontData); - } - - try (SlideShow ppt2 = reopen(ppt)) { - List fonts = ppt2.getFonts(); - assertFalse(fonts.isEmpty()); - FontInfo fi = fonts.get(fonts.size()-1); - assertEquals("Harlow Solid Italic", fi.getTypeface()); - } - } - } - - public static Color getColor(PaintStyle paintActual) { - return (paintActual instanceof PaintStyle.SolidPaint) - ? DrawPaint.applyColorTransform(((PaintStyle.SolidPaint)paintActual).getSolidColor()) - : null; - } - -} diff --git a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java b/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java deleted file mode 100644 index 090aeb0aa8..0000000000 --- a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java +++ /dev/null @@ -1,193 +0,0 @@ -/* ==================================================================== - 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.sl.usermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -public abstract class BaseTestSlideShowFactory { - private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - @SuppressWarnings("resource") - protected static void testFactoryFromFile(String file) throws Exception { - SlideShow ss; - // from file - ss = SlideShowFactory.create(fromFile(file)); - assertNotNull(ss); - assertCloseDoesNotModifyFile(file, ss); - } - - @SuppressWarnings("resource") - protected static void testFactoryFromStream(String file) throws Exception { - SlideShow ss; - // from stream - ss = SlideShowFactory.create(fromStream(file)); - assertNotNull(ss); - assertCloseDoesNotModifyFile(file, ss); - } - - @SuppressWarnings("resource") - protected static void testFactoryFromNative(String file) throws Exception { - assertNotNull(file); - assertTrue(file.endsWith(".ppt") || file.endsWith(".pptx"), "Unexpected file extension: " + file); - - SlideShow ss; - if (file.endsWith(".ppt")) { - // from POIFS - try (POIFSFileSystem poifs = new POIFSFileSystem(fromFile(file))) { - ss = SlideShowFactory.create(poifs); - assertNotNull(ss); - } - assertCloseDoesNotModifyFile(file, ss); - } else { - // from OPCPackage ... not implemented - throw new UnsupportedOperationException("Test not implemented"); - } - } - - @SuppressWarnings("resource") - protected static void testFactoryFromProtectedFile(String protectedFile, String password) throws Exception { - // from protected file - SlideShow ss = SlideShowFactory.create(fromFile(protectedFile), password); - assertNotNull(ss); - assertCloseDoesNotModifyFile(protectedFile, ss); - } - - @SuppressWarnings("resource") - protected static void testFactoryFromProtectedStream(String protectedFile, String password) throws Exception { - // from protected stream - SlideShow ss = SlideShowFactory.create(fromStream(protectedFile), password); - assertNotNull(ss); - assertCloseDoesNotModifyFile(protectedFile, ss); - } - - @SuppressWarnings("resource") - protected static void testFactoryFromProtectedNative(String protectedFile, String password) throws Exception { - assertTrue(protectedFile.endsWith(".ppt") || protectedFile.endsWith(".pptx"), - "Unrecognized file extension: " + protectedFile); - - SlideShow ss; - // Encryption layer is a BIFF8 binary format that can be read by POIFSFileSystem, - // used for both HSLF and XSLF - - // from protected POIFS - try (POIFSFileSystem poifs = new POIFSFileSystem(fromFile(protectedFile))) { - ss = SlideShowFactory.create(poifs.getRoot(), password); - assertNotNull(ss); - } - assertCloseDoesNotModifyFile(protectedFile, ss); - } - - @SuppressWarnings("SameParameterValue") - protected static void testFactory(String file, String protectedFile, String password) - throws Exception { - testFactoryFromFile(file); - testFactoryFromStream(file); - testFactoryFromNative(file); - - testFactoryFromProtectedFile(protectedFile, password); - testFactoryFromProtectedStream(protectedFile, password); - testFactoryFromProtectedNative(protectedFile, password); - } - - /** - * reads either a test-data file (filename) or a file outside the test-data folder (full path) - */ - private static byte[] readFile(String filename) { - byte[] bytes; - try { - bytes = _slTests.readFile(filename); - } catch (final RuntimeException e) { - if (!e.getMessage().startsWith("Sample file '" + filename + "' not found in data dir")) { - throw e; - } - bytes = readExternalFile(filename); - } - return bytes; - } - - private static byte[] readExternalFile(String path) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - try { - InputStream fis = new FileInputStream(path); - byte[] buf = new byte[512]; - while (true) { - int bytesRead = fis.read(buf); - if (bytesRead < 1) { - break; - } - baos.write(buf, 0, bytesRead); - } - fis.close(); - } catch (final IOException e) { - throw new RuntimeException(e); - } - return baos.toByteArray(); - } - - /** - * FIXME: - * bug 58779: Closing an XMLSlideShow that was created with {@link SlideShowFactory#create(File)} modifies the file - * - * @param filename the sample filename or full path of the slideshow to check before and after closing - * @param ss the slideshow to close or revert - */ - private static void assertCloseDoesNotModifyFile(String filename, SlideShow ss) throws IOException { - final byte[] before = readFile(filename); - ss.close(); - final byte[] after = readFile(filename); - - try { - assertArrayEquals(before, after, filename + " sample file was modified as a result of closing the slideshow"); - } catch (AssertionError e) { - // if the file after closing is different, then re-set - // the file to the state before in order to not have a dirty SCM - // working tree when running this test - try (FileOutputStream str = new FileOutputStream(_slTests.getFile(filename))) { - str.write(before); - } - - throw e; - } - } - - private static File fromFile(String file) { - return (file.contains("/") || file.contains("\\")) - ? new File(file) - : _slTests.getFile(file); - } - - private static InputStream fromStream(String file) throws IOException { - return (file.contains("/") || file.contains("\\")) - ? new FileInputStream(file) - : _slTests.openResourceAsStream(file); - } - -} diff --git a/src/testcases/org/apache/poi/ss/ITestDataProvider.java b/src/testcases/org/apache/poi/ss/ITestDataProvider.java deleted file mode 100644 index e258e1a4a2..0000000000 --- a/src/testcases/org/apache/poi/ss/ITestDataProvider.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss; - -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * Encapsulates a provider of test data for common HSSF / XSSF tests. - */ -public interface ITestDataProvider { - /** - * Provides HSSF / XSSF specific way for re-serialising a workbook - * - * @param wb the workbook to re-serialize - * @return the re-serialized workbook - */ - Workbook writeOutAndReadBack(Workbook wb); - - /** - * Provides way of loading HSSF / XSSF sample workbooks - * - * @param sampleFileName the file name to load - * @return an instance of Workbook loaded from the supplied file name - */ - Workbook openSampleWorkbook(String sampleFileName); - - /** - * Provides way of creating HSSF / XSSF workbooks - * @return an instance of Workbook - */ - Workbook createWorkbook(); - - - //************ SXSSF-specific methods ***************// - /** - * Provides way of creating a SXSSFWorkbook with a specific row access window size. - * Equivalent to createWorkbook on others. - * @return an instance of Workbook - */ - Workbook createWorkbook(int rowAccessWindowSize); - - /** - * Only matters for SXSSF - enables tracking of the column - * widths so that autosizing can work. No-op on others. - */ - void trackAllColumnsForAutosizing(Sheet sheet); - //************ End SXSSF-specific methods ***************// - - /** - * Creates the corresponding {@link FormulaEvaluator} for the - * type of Workbook handled by this Provider. - * - * @param wb The workbook to base the formula evaluator on. - * @return A new instance of a matching type of formula evaluator. - */ - FormulaEvaluator createFormulaEvaluator(Workbook wb); - - /** - * Opens a sample file from the standard HSSF test data directory - * - * @return an open InputStream for the specified sample file - */ - byte[] getTestDataFileContent(String fileName); - - SpreadsheetVersion getSpreadsheetVersion(); - - /** - * @return "xls" or "xlsx" - */ - String getStandardFileNameExtension(); -} diff --git a/src/testcases/org/apache/poi/ss/TestSpreadsheetVersion.java b/src/testcases/org/apache/poi/ss/TestSpreadsheetVersion.java deleted file mode 100644 index 4da0ab5b05..0000000000 --- a/src/testcases/org/apache/poi/ss/TestSpreadsheetVersion.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** - * Check that all enum values are properly set - */ -final class TestSpreadsheetVersion { - - @Test - void testExcel97(){ - SpreadsheetVersion v = SpreadsheetVersion.EXCEL97; - assertEquals(1 << 8, v.getMaxColumns()); - assertEquals(v.getMaxColumns() - 1, v.getLastColumnIndex()); - assertEquals(1 << 16, v.getMaxRows()); - assertEquals(v.getMaxRows() - 1, v.getLastRowIndex()); - assertEquals(30, v.getMaxFunctionArgs()); - assertEquals(3, v.getMaxConditionalFormats()); - assertEquals("IV", v.getLastColumnName()); - } - - @Test - void testExcel2007(){ - SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007; - assertEquals(1 << 14, v.getMaxColumns()); - assertEquals(v.getMaxColumns() - 1, v.getLastColumnIndex()); - assertEquals(1 << 20, v.getMaxRows()); - assertEquals(v.getMaxRows() - 1, v.getLastRowIndex()); - assertEquals(255, v.getMaxFunctionArgs()); - assertEquals(Integer.MAX_VALUE, v.getMaxConditionalFormats()); - assertEquals("XFD", v.getLastColumnName()); - } -} diff --git a/src/testcases/org/apache/poi/ss/format/TestCellFormat.java b/src/testcases/org/apache/poi/ss/format/TestCellFormat.java deleted file mode 100644 index 3c0476a9c3..0000000000 --- a/src/testcases/org/apache/poi/ss/format/TestCellFormat.java +++ /dev/null @@ -1,1029 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.format; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; -import java.util.stream.Stream; - -import javax.swing.JLabel; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -class TestCellFormat { - - private static TimeZone userTimeZone; - - @BeforeAll - public static void setTimeZone() { - userTimeZone = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - LocaleUtil.setUserLocale(Locale.US); - } - - @AfterAll - public static void resetTimeZone() { - LocaleUtil.setUserTimeZone(userTimeZone); - LocaleUtil.setUserLocale(Locale.ROOT); - } - - - private static final String _255_POUND_SIGNS; - static { - StringBuilder sb = new StringBuilder(); - for (int i = 1; i <= 255; i++) { - sb.append('#'); - } - _255_POUND_SIGNS = sb.toString(); - } - - @Test - void testSome() { - JLabel l = new JLabel(); - CellFormat fmt = CellFormat.getInstance("\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)"); - fmt.apply(l, 1.1); - assertEquals("$1.10 ", l.getText()); - } - - @Test - void testPositiveFormatHasOnePart() { - CellFormat fmt = CellFormat.getInstance("0.00"); - CellFormatResult result = fmt.apply(12.345); - assertEquals("12.35", result.text); - } - - @Test - void testNegativeFormatHasOnePart() { - CellFormat fmt = CellFormat.getInstance("0.00"); - CellFormatResult result = fmt.apply(-12.345); - assertEquals("-12.35", result.text); - } - - @Test - void testZeroFormatHasOnePart() { - CellFormat fmt = CellFormat.getInstance("0.00"); - CellFormatResult result = fmt.apply(0.0); - assertEquals("0.00", result.text); - } - - @Test - void testPositiveFormatHasPosAndNegParts() { - CellFormat fmt = CellFormat.getInstance("0.00;-0.00"); - CellFormatResult result = fmt.apply(12.345); - assertEquals("12.35", result.text); - } - - @Test - void testNegativeFormatHasPosAndNegParts() { - CellFormat fmt = CellFormat.getInstance("0.00;-0.00"); - CellFormatResult result = fmt.apply(-12.345); - assertEquals("-12.35", result.text); - } - - @Test - void testNegativeFormatHasPosAndNegParts2() { - CellFormat fmt = CellFormat.getInstance("0.00;(0.00)"); - CellFormatResult result = fmt.apply(-12.345); - assertEquals("(12.35)", result.text); - } - - @Test - void testZeroFormatHasPosAndNegParts() { - CellFormat fmt = CellFormat.getInstance("0.00;-0.00"); - CellFormatResult result = fmt.apply(0.0); - assertEquals("0.00", result.text); - } - - @Test - void testFormatWithThreeSections() { - CellFormat fmt = CellFormat.getInstance("0.00;-0.00;-"); - - assertEquals("12.35", fmt.apply(12.345).text); - assertEquals("-12.35", fmt.apply(-12.345).text); - assertEquals("-", fmt.apply(0.0).text); - assertEquals("abc", fmt.apply("abc").text); - } - - @Test - void testFormatWithFourSections() { - CellFormat fmt = CellFormat.getInstance("0.00;-0.00;-; @ "); - - assertEquals("12.35", fmt.apply(12.345).text); - assertEquals("-12.35", fmt.apply(-12.345).text); - assertEquals("-", fmt.apply(0.0).text); - assertEquals(" abc ", fmt.apply("abc").text); - } - - @Test - void testApplyCellForGeneralFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(2); - Cell cell3 = row.createCell(3); - Cell cell4 = row.createCell(4); - - CellFormat cf = CellFormat.getInstance("General"); - - // case CellType.BLANK - CellFormatResult result0 = cf.apply(cell0); - assertEquals("", result0.text); - - // case CellType.BOOLEAN - cell1.setCellValue(true); - CellFormatResult result1 = cf.apply(cell1); - assertEquals("TRUE", result1.text); - - // case CellType.NUMERIC - cell2.setCellValue(1.23); - CellFormatResult result2 = cf.apply(cell2); - assertEquals("1.23", result2.text); - - cell3.setCellValue(123.0); - CellFormatResult result3 = cf.apply(cell3); - assertEquals("123", result3.text); - - // case CellType.STRING - cell4.setCellValue("abc"); - CellFormatResult result4 = cf.apply(cell4); - assertEquals("abc", result4.text); - - wb.close(); - } - - @Test - void testApplyCellForAtFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(2); - Cell cell3 = row.createCell(3); - Cell cell4 = row.createCell(4); - - CellFormat cf = CellFormat.getInstance("@"); - - // case CellType.BLANK - CellFormatResult result0 = cf.apply(cell0); - assertEquals("", result0.text); - - // case CellType.BOOLEAN - cell1.setCellValue(true); - CellFormatResult result1 = cf.apply(cell1); - assertEquals("TRUE", result1.text); - - // case CellType.NUMERIC - cell2.setCellValue(1.23); - CellFormatResult result2 = cf.apply(cell2); - assertEquals("1.23", result2.text); - - cell3.setCellValue(123.0); - CellFormatResult result3 = cf.apply(cell3); - assertEquals("123", result3.text); - - // case CellType.STRING - cell4.setCellValue("abc"); - CellFormatResult result4 = cf.apply(cell4); - assertEquals("abc", result4.text); - - wb.close(); - } - - @Test - void testApplyCellForDateFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - - CellFormat cf = CellFormat.getInstance("dd/mm/yyyy"); - - cell0.setCellValue(10); - CellFormatResult result0 = cf.apply(cell0); - assertEquals("10/01/1900", result0.text); - - cell1.setCellValue(-1); - CellFormatResult result1 = cf.apply(cell1); - assertEquals(_255_POUND_SIGNS, result1.text); - - wb.close(); - } - - @Test - void testApplyCellForTimeFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("hh:mm"); - - cell.setCellValue(DateUtil.convertTime("03:04:05")); - CellFormatResult result = cf.apply(cell); - assertEquals("03:04", result.text); - - wb.close(); - } - - @Test - void testApplyCellForDateFormatAndNegativeFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - - CellFormat cf = CellFormat.getInstance("dd/mm/yyyy;(0)"); - - cell0.setCellValue(10); - CellFormatResult result0 = cf.apply(cell0); - assertEquals("10/01/1900", result0.text); - - cell1.setCellValue(-1); - CellFormatResult result1 = cf.apply(cell1); - assertEquals("(1)", result1.text); - - wb.close(); - } - - @Test - void testApplyJLabelCellForGeneralFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(2); - Cell cell3 = row.createCell(3); - Cell cell4 = row.createCell(4); - - CellFormat cf = CellFormat.getInstance("General"); - - JLabel label0 = new JLabel(); - JLabel label1 = new JLabel(); - JLabel label2 = new JLabel(); - JLabel label3 = new JLabel(); - JLabel label4 = new JLabel(); - - // case CellType.BLANK - CellFormatResult result0 = cf.apply(label0, cell0); - assertEquals("", result0.text); - assertEquals("", label0.getText()); - - // case CellType.BOOLEAN - cell1.setCellValue(true); - CellFormatResult result1 = cf.apply(label1, cell1); - assertEquals("TRUE", result1.text); - assertEquals("TRUE", label1.getText()); - - // case CellType.NUMERIC - cell2.setCellValue(1.23); - CellFormatResult result2 = cf.apply(label2, cell2); - assertEquals("1.23", result2.text); - assertEquals("1.23", label2.getText()); - - cell3.setCellValue(123.0); - CellFormatResult result3 = cf.apply(label3, cell3); - assertEquals("123", result3.text); - assertEquals("123", label3.getText()); - - // case CellType.STRING - cell4.setCellValue("abc"); - CellFormatResult result4 = cf.apply(label4, cell4); - assertEquals("abc", result4.text); - assertEquals("abc", label4.getText()); - - wb.close(); - } - - @Test - void testApplyJLabelCellForAtFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(2); - Cell cell3 = row.createCell(3); - Cell cell4 = row.createCell(4); - - CellFormat cf = CellFormat.getInstance("@"); - - JLabel label0 = new JLabel(); - JLabel label1 = new JLabel(); - JLabel label2 = new JLabel(); - JLabel label3 = new JLabel(); - JLabel label4 = new JLabel(); - - // case CellType.BLANK - CellFormatResult result0 = cf.apply(label0, cell0); - assertEquals("", result0.text); - assertEquals("", label0.getText()); - - // case CellType.BOOLEAN - cell1.setCellValue(true); - CellFormatResult result1 = cf.apply(label1, cell1); - assertEquals("TRUE", result1.text); - assertEquals("TRUE", label1.getText()); - - // case CellType.NUMERIC - cell2.setCellValue(1.23); - CellFormatResult result2 = cf.apply(label2, cell2); - assertEquals("1.23", result2.text); - assertEquals("1.23", label2.getText()); - - cell3.setCellValue(123.0); - CellFormatResult result3 = cf.apply(label3, cell3); - assertEquals("123", result3.text); - assertEquals("123", label3.getText()); - - // case CellType.STRING - cell4.setCellValue("abc"); - CellFormatResult result4 = cf.apply(label4, cell4); - assertEquals("abc", result4.text); - assertEquals("abc", label4.getText()); - - wb.close(); - } - - @Test - void testApplyJLabelCellForDateFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - - CellFormat cf = CellFormat.getInstance("dd/mm/yyyy"); - - JLabel label0 = new JLabel(); - JLabel label1 = new JLabel(); - - cell0.setCellValue(10); - CellFormatResult result0 = cf.apply(label0, cell0); - assertEquals("10/01/1900", result0.text); - assertEquals("10/01/1900", label0.getText()); - - cell1.setCellValue(-1); - CellFormatResult result1 = cf.apply(label1, cell1); - assertEquals(_255_POUND_SIGNS, result1.text); - assertEquals(_255_POUND_SIGNS, label1.getText()); - - wb.close(); - } - - @Test - void testApplyJLabelCellForTimeFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("hh:mm"); - - JLabel label = new JLabel(); - - cell.setCellValue(DateUtil.convertTime("03:04:05")); - CellFormatResult result = cf.apply(label, cell); - assertEquals("03:04", result.text); - assertEquals("03:04", label.getText()); - - wb.close(); - } - - @Test - void testApplyJLabelCellForDateFormatAndNegativeFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - - CellFormat cf = CellFormat.getInstance("dd/mm/yyyy;(0)"); - - JLabel label0 = new JLabel(); - JLabel label1 = new JLabel(); - - cell0.setCellValue(10); - CellFormatResult result0 = cf.apply(label0, cell0); - assertEquals("10/01/1900", result0.text); - assertEquals("10/01/1900", label0.getText()); - - cell1.setCellValue(-1); - CellFormatResult result1 = cf.apply(label1, cell1); - assertEquals("(1)", result1.text); - assertEquals("(1)", label1.getText()); - - wb.close(); - } - - @Test - void testApplyFormatHasOnePartAndPartHasCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10", cf.apply(cell).text); - - cell.setCellValue(0.123456789012345); - assertEquals("0.123456789", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - void testApplyFormatHasTwoPartsFirstHasCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;0.000"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue(0.123456789012345); - assertEquals("0.123", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.000", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10.000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - cell.setCellValue("TRUE"); - assertEquals("TRUE", cf.apply(cell).text); - - wb.close(); - } - - @Test - void testApplyFormatHasTwoPartsBothHaveCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;[>=10]0.000"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals(_255_POUND_SIGNS, cf.apply(cell).text); - - cell.setCellValue(-0.123456789012345); - assertEquals(_255_POUND_SIGNS, cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals(_255_POUND_SIGNS, cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - void testApplyFormatHasThreePartsFirstHasCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;0.000;0.0000"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.0000", cf.apply(cell).text); - - cell.setCellValue(0.123456789012345); - assertEquals("0.1235", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0000", cf.apply(cell).text); - - // Second format part ('0.000') is used for negative numbers - // so result does not have a minus sign - cell.setCellValue(-10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - void testApplyFormatHasThreePartsFirstTwoHaveCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;[>=10]0.000;0.0000"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0000", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10.0000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - void testApplyFormatHasThreePartsFirstIsDateFirstTwoHaveCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;[>=10]dd/mm/yyyy;0.0"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10/01/1900", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10.0", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - void testApplyFormatHasTwoPartsFirstHasConditionSecondIsGeneral() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;General"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - void testApplyFormatHasThreePartsFirstTwoHaveConditionThirdIsGeneral() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;[>=10]0.000;General"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - void testApplyFormatHasFourPartsFirstHasCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;0.000;0.0000;~~@~~"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.0000", cf.apply(cell).text); - - cell.setCellValue(0.123456789012345); - assertEquals("0.1235", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0000", cf.apply(cell).text); - - // Second format part ('0.000') is used for negative numbers - // so result does not have a minus sign - cell.setCellValue(-10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("~~abc~~", cf.apply(cell).text); - - wb.close(); - } - - @Test - void testApplyFormatHasFourPartsSecondHasCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("0.00;[>=100]0.000;0.0000;~~@~~"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.00", cf.apply(cell).text); - - cell.setCellValue(0.123456789012345); - assertEquals("0.12", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0000", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10.0000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("~~abc~~", cf.apply(cell).text); - - cell.setCellValue(true); - assertEquals("~~TRUE~~", cf.apply(cell).text); - - wb.close(); - } - - @Test - void testApplyFormatHasFourPartsFirstTwoHaveCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;[>=10]0.000;0.0000;~~@~~"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0000", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10.0000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("~~abc~~", cf.apply(cell).text); - - cell.setCellValue(true); - assertEquals("~~TRUE~~", cf.apply(cell).text); - - wb.close(); - } - - /* - * Test apply(Object value) with a number as parameter - */ - @Test - void testApplyObjectNumber() { - - CellFormat cf1 = CellFormat.getInstance("0.000"); - - assertEquals("1.235", cf1.apply(1.2345).text); - assertEquals("-1.235", cf1.apply(-1.2345).text); - - CellFormat cf2 = CellFormat.getInstance("0.000;(0.000)"); - - assertEquals("1.235", cf2.apply(1.2345).text); - assertEquals("(1.235)", cf2.apply(-1.2345).text); - - CellFormat cf3 = CellFormat.getInstance("[>1]0.000;0.0000"); - - assertEquals("1.235", cf3.apply(1.2345).text); - assertEquals("-1.2345", cf3.apply(-1.2345).text); - - CellFormat cf4 = CellFormat.getInstance("0.000;[>1]0.0000"); - - assertEquals("1.235", cf4.apply(1.2345).text); - assertEquals(_255_POUND_SIGNS, cf4.apply(-1.2345).text); - - } - - /* - * Test apply(Object value) with a Date as parameter - */ - @Test - void testApplyObjectDate() throws ParseException { - CellFormat cf1 = CellFormat.getInstance("m/d/yyyy"); - SimpleDateFormat sdf1 = new SimpleDateFormat("M/d/y", Locale.ROOT); - sdf1.setTimeZone(TimeZone.getTimeZone("CET")); - Date date1 = sdf1.parse("01/11/2012"); - assertEquals("1/11/2012", cf1.apply(date1).text); - } - - @Test - void testApplyCellForDateFormatWithConditions() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[<1]hh:mm:ss AM/PM;[>=1]dd/mm/yyyy hh:mm:ss AM/PM;General"); - - cell.setCellValue(0.5); - assertEquals("12:00:00 PM", cf.apply(cell).text); - - cell.setCellValue(1.5); - assertEquals("01/01/1900 12:00:00 PM", cf.apply(cell).text); - - cell.setCellValue(-1); - assertEquals(_255_POUND_SIGNS, cf.apply(cell).text); - - wb.close(); - } - - /* - * Test apply(Object value) with a String as parameter - */ - @Test - void testApplyObjectString() { - - CellFormat cf = CellFormat.getInstance("0.00"); - - assertEquals("abc", cf.apply("abc").text); - - } - - /* - * Test apply(Object value) with a Boolean as parameter - */ - @Test - void testApplyObjectBoolean() { - - CellFormat cf1 = CellFormat.getInstance("0"); - CellFormat cf2 = CellFormat.getInstance("General"); - CellFormat cf3 = CellFormat.getInstance("@"); - - assertEquals("TRUE", cf1.apply(true).text); - assertEquals("FALSE", cf2.apply(false).text); - assertEquals("TRUE", cf3.apply(true).text); - - } - - @Test - void testSimpleFractionFormat() throws IOException { - CellFormat cf1 = CellFormat.getInstance("# ?/?"); - // Create a workbook, row and cell to test with - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(123456.6); - //System.out.println(cf1.apply(cell).text); - assertEquals("123456 3/5", cf1.apply(cell).text); - } - } - - @Test - void testAccountingFormats() { - char pound = '\u00A3'; - char euro = '\u20AC'; - - // Accounting -> 0 decimal places, default currency symbol - String formatDft = "_-\"$\"* #,##0_-;\\-\"$\"* #,##0_-;_-\"$\"* \"-\"_-;_-@_-"; - // Accounting -> 0 decimal places, US currency symbol - String formatUS = "_-[$$-409]* #,##0_ ;_-[$$-409]* -#,##0 ;_-[$$-409]* \"-\"_-;_-@_-"; - // Accounting -> 0 decimal places, UK currency symbol - String formatUK = "_-[$"+pound+"-809]* #,##0_-;\\-[$"+pound+"-809]* #,##0_-;_-[$"+pound+"-809]* \"-\"??_-;_-@_-"; - // French style accounting, euro sign comes after not before - String formatFR = "_-#,##0* [$"+euro+"-40C]_-;\\-#,##0* [$"+euro+"-40C]_-;_-\"-\"??* [$"+euro+"-40C] _-;_-@_-"; - - // Has +ve, -ve and zero rules - CellFormat cfDft = CellFormat.getInstance(formatDft); - CellFormat cfUS = CellFormat.getInstance(formatUS); - CellFormat cfUK = CellFormat.getInstance(formatUK); - CellFormat cfFR = CellFormat.getInstance(formatFR); - - // For +ve numbers, should be Space + currency symbol + spaces + whole number with commas + space - // (Except French, which is mostly reversed...) - assertEquals(" $ 12 ", cfDft.apply(12.33).text); - assertEquals(" $ 12 ", cfUS.apply(12.33).text); - assertEquals(" "+pound+" 12 ", cfUK.apply(12.33).text); - assertEquals(" 12 "+euro+" ", cfFR.apply(12.33).text); - - assertEquals(" $ 16,789 ", cfDft.apply(16789.2).text); - assertEquals(" $ 16,789 ", cfUS.apply(16789.2).text); - assertEquals(" "+pound+" 16,789 ", cfUK.apply(16789.2).text); - assertEquals(" 16,789 "+euro+" ", cfFR.apply(16789.2).text); - - // For -ve numbers, gets a bit more complicated... - assertEquals("-$ 12 ", cfDft.apply(-12.33).text); - assertEquals(" $ -12 ", cfUS.apply(-12.33).text); - assertEquals("-"+pound+" 12 ", cfUK.apply(-12.33).text); - assertEquals("-12 "+euro+" ", cfFR.apply(-12.33).text); - - assertEquals("-$ 16,789 ", cfDft.apply(-16789.2).text); - assertEquals(" $ -16,789 ", cfUS.apply(-16789.2).text); - assertEquals("-"+pound+" 16,789 ", cfUK.apply(-16789.2).text); - assertEquals("-16,789 "+euro+" ", cfFR.apply(-16789.2).text); - - // For zero, should be Space + currency symbol + spaces + Minus + spaces - assertEquals(" $ - ", cfDft.apply((double) 0).text); - assertEquals(" $ - ", cfUS.apply((double) 0).text); - // TODO Fix these to not have an incorrect bonus 0 on the end - //assertEquals(" "+pound+" - ", cfUK.apply((double) 0).text); - //assertEquals(" - "+euro+" ", cfFR.apply((double) 0).text); - } - - @Test - void testThreePartComplexFormat1() { - // verify a rather complex format found e.g. in http://wahl.land-oberoesterreich.gv.at/Downloads/bp10.xls - CellFormatPart posPart = new CellFormatPart("[$-F400]h:mm:ss\\ AM/PM"); - assertNotNull(posPart); - assertEquals("1:00:12 AM", posPart.apply(new Date(12345)).text); - - CellFormatPart negPart = new CellFormatPart("[$-F40]h:mm:ss\\ AM/PM"); - assertNotNull(negPart); - assertEquals("1:00:12 AM", posPart.apply(new Date(12345)).text); - - //assertNotNull(new CellFormatPart("_-* \"\"??_-;_-@_-")); - - CellFormat instance = CellFormat.getInstance("[$-F400]h:mm:ss\\ AM/PM;[$-F40]h:mm:ss\\ AM/PM;_-* \"\"??_-;_-@_-"); - assertNotNull(instance); - assertEquals("1:00:12 AM", instance.apply(new Date(12345)).text); - } - - @Test - void testThreePartComplexFormat2() { - // verify a rather complex format found e.g. in http://wahl.land-oberoesterreich.gv.at/Downloads/bp10.xls - CellFormatPart posPart = new CellFormatPart("dd/mm/yyyy"); - assertNotNull(posPart); - assertEquals("01/01/1970", posPart.apply(new Date(12345)).text); - - CellFormatPart negPart = new CellFormatPart("dd/mm/yyyy"); - assertNotNull(negPart); - assertEquals("01/01/1970", posPart.apply(new Date(12345)).text); - - //assertNotNull(new CellFormatPart("_-* \"\"??_-;_-@_-")); - - CellFormat instance = CellFormat.getInstance("dd/mm/yyyy;dd/mm/yyyy;_-* \"\"??_-;_-@_-"); - assertNotNull(instance); - assertEquals("01/01/1970", instance.apply(new Date(12345)).text); - } - - @Test - void testBug62865() { - CellFormat cf = CellFormat.getInstance("\"ca. \"0"); - assertEquals("ca. 5", cf.apply((double) 5).text); - } - - @Test - void testNamedColors() { - assertTrue(CellFormatPart.NAMED_COLORS.size() >= HSSFColor.HSSFColorPredefined.values().length); - Stream.of("GREEN", "Green", "RED", "Red", "BLUE", "Blue", "YELLOW", "Yellow") - .map(CellFormatPart.NAMED_COLORS::get) - .forEach(Assertions::assertNotNull); - } -} diff --git a/src/testcases/org/apache/poi/ss/format/TestCellFormatCondition.java b/src/testcases/org/apache/poi/ss/format/TestCellFormatCondition.java deleted file mode 100644 index bf4cafc714..0000000000 --- a/src/testcases/org/apache/poi/ss/format/TestCellFormatCondition.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.format; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; - -class TestCellFormatCondition { - @Test - void testSVConditions() { - CellFormatCondition lt = CellFormatCondition.getInstance("<", "1.5"); - assertTrue(lt.pass(1.4)); - assertFalse(lt.pass(1.5)); - assertFalse(lt.pass(1.6)); - - CellFormatCondition le = CellFormatCondition.getInstance("<=", "1.5"); - assertTrue(le.pass(1.4)); - assertTrue(le.pass(1.5)); - assertFalse(le.pass(1.6)); - - CellFormatCondition gt = CellFormatCondition.getInstance(">", "1.5"); - assertFalse(gt.pass(1.4)); - assertFalse(gt.pass(1.5)); - assertTrue(gt.pass(1.6)); - - CellFormatCondition ge = CellFormatCondition.getInstance(">=", "1.5"); - assertFalse(ge.pass(1.4)); - assertTrue(ge.pass(1.5)); - assertTrue(ge.pass(1.6)); - - CellFormatCondition eqs = CellFormatCondition.getInstance("=", "1.5"); - assertFalse(eqs.pass(1.4)); - assertTrue(eqs.pass(1.5)); - assertFalse(eqs.pass(1.6)); - - CellFormatCondition eql = CellFormatCondition.getInstance("==", "1.5"); - assertFalse(eql.pass(1.4)); - assertTrue(eql.pass(1.5)); - assertFalse(eql.pass(1.6)); - - CellFormatCondition neo = CellFormatCondition.getInstance("<>", "1.5"); - assertTrue(neo.pass(1.4)); - assertFalse(neo.pass(1.5)); - assertTrue(neo.pass(1.6)); - - CellFormatCondition nen = CellFormatCondition.getInstance("!=", "1.5"); - assertTrue(nen.pass(1.4)); - assertFalse(nen.pass(1.5)); - assertTrue(nen.pass(1.6)); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/format/TestCellFormatResult.java b/src/testcases/org/apache/poi/ss/format/TestCellFormatResult.java deleted file mode 100644 index 7f19b7dcb6..0000000000 --- a/src/testcases/org/apache/poi/ss/format/TestCellFormatResult.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.format; - -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.awt.Color; - -import org.junit.jupiter.api.Test; - -class TestCellFormatResult { - - @Test - void testNullTextRaisesException() { - final boolean applies = true; - final String text = null; - final Color textColor = Color.BLACK; - assertThrows(IllegalArgumentException.class, () -> new CellFormatResult(applies, text, textColor), - "Cannot initialize CellFormatResult with null text parameter"); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/BaseTestExternalFunctions.java b/src/testcases/org/apache/poi/ss/formula/BaseTestExternalFunctions.java deleted file mode 100644 index 4e6bb88d4a..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/BaseTestExternalFunctions.java +++ /dev/null @@ -1,161 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NotImplementedException; -import org.apache.poi.ss.formula.eval.NotImplementedFunctionException; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.udf.DefaultUDFFinder; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Test setting / evaluating of Analysis Toolpack and user-defined functions - */ -public abstract class BaseTestExternalFunctions { - // define two custom user-defined functions - private static class MyFunc implements FreeRefFunction { - public MyFunc() { - // - } - - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 1 || !(args[0] instanceof StringEval)) { - return ErrorEval.VALUE_INVALID; - } - StringEval input = (StringEval) args[0]; - return new StringEval(input.getStringValue() + "abc"); - } - } - - private static class MyFunc2 implements FreeRefFunction { - public MyFunc2() { - // - } - - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 1 || !(args[0] instanceof StringEval)) { - return ErrorEval.VALUE_INVALID; - } - StringEval input = (StringEval) args[0]; - return new StringEval(input.getStringValue() + "abc2"); - } - } - - /** - * register the two test UDFs in a UDF finder, to be passed to the workbook - */ - private static UDFFinder customToolpack = new DefaultUDFFinder( - new String[] { "myFunc", "myFunc2"}, - new FreeRefFunction[] { new MyFunc(), new MyFunc2()} - ); - - - private final ITestDataProvider _testDataProvider; - private final String atpFile; - - /** - * @param testDataProvider an object that provides test data in HSSF / XSSF specific way - */ - protected BaseTestExternalFunctions(ITestDataProvider testDataProvider, String atpFile) { - _testDataProvider = testDataProvider; - this.atpFile = atpFile; - } - - @Test - void testExternalFunctions() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - - Cell cell1 = sh.createRow(0).createCell(0); - // functions from the Excel Analysis Toolpack - cell1.setCellFormula("ISODD(1)+ISEVEN(2)"); - assertEquals("ISODD(1)+ISEVEN(2)", cell1.getCellFormula()); - - Cell cell2 = sh.createRow(1).createCell(0); - // unregistered functions are parseable and renderable, but may not be evaluateable - cell2.setCellFormula("MYFUNC(\"B1\")"); - NotImplementedException e = assertThrows(NotImplementedException.class, () -> evaluator.evaluate(cell2), - "Expected NotImplementedFunctionException/NotImplementedException"); - assertTrue(e.getCause() instanceof NotImplementedFunctionException); - // Alternatively, a future implementation of evaluate could return #NAME? error to align behavior with Excel - // assertEquals(ErrorEval.NAME_INVALID, ErrorEval.valueOf(evaluator.evaluate(cell2).getErrorValue())); - - wb.addToolPack(customToolpack); - - cell2.setCellFormula("MYFUNC(\"B1\")"); - assertEquals("MYFUNC(\"B1\")", cell2.getCellFormula()); - - Cell cell3 = sh.createRow(2).createCell(0); - cell3.setCellFormula("MYFUNC2(\"C1\")&\"-\"&A2"); //where A2 is defined above - assertEquals("MYFUNC2(\"C1\")&\"-\"&A2", cell3.getCellFormula()); - - assertEquals(2.0, evaluator.evaluate(cell1).getNumberValue(), 0); - assertEquals("B1abc", evaluator.evaluate(cell2).getStringValue()); - assertEquals("C1abc2-B1abc", evaluator.evaluate(cell3).getStringValue()); - } - } - - /** - * test invoking saved ATP functions - * - * @param testFile either atp.xls or atp.xlsx - */ - @Test - void baseTestInvokeATP() throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook(atpFile); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.getSheetAt(0); - // these two are not implemented in r - assertEquals("DELTA(1.3,1.5)", sh.getRow(0).getCell(1).getCellFormula()); - assertEquals("COMPLEX(2,4)", sh.getRow(1).getCell(1).getCellFormula()); - - Cell cell2 = sh.getRow(2).getCell(1); - assertEquals("ISODD(2)", cell2.getCellFormula()); - assertFalse(evaluator.evaluate(cell2).getBooleanValue()); - assertEquals(CellType.BOOLEAN, evaluator.evaluateFormulaCell(cell2)); - - Cell cell3 = sh.getRow(3).getCell(1); - assertEquals("ISEVEN(2)", cell3.getCellFormula()); - assertTrue(evaluator.evaluate(cell3).getBooleanValue()); - assertEquals(CellType.BOOLEAN, evaluator.evaluateFormulaCell(cell3)); - - wb.close(); - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/BaseTestMissingWorkbook.java b/src/testcases/org/apache/poi/ss/formula/BaseTestMissingWorkbook.java deleted file mode 100644 index 2e05261cf3..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/BaseTestMissingWorkbook.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public abstract class BaseTestMissingWorkbook { - protected Workbook mainWorkbook; - protected Workbook sourceWorkbook; - - protected final String MAIN_WORKBOOK_FILENAME; - protected final String SOURCE_DUMMY_WORKBOOK_FILENAME; - protected final String SOURCE_WORKBOOK_FILENAME; - - protected BaseTestMissingWorkbook(String MAIN_WORKBOOK_FILENAME, - String SOURCE_DUMMY_WORKBOOK_FILENAME, String SOURCE_WORKBOOK_FILENAME) { - this.MAIN_WORKBOOK_FILENAME = MAIN_WORKBOOK_FILENAME; - this.SOURCE_DUMMY_WORKBOOK_FILENAME = SOURCE_DUMMY_WORKBOOK_FILENAME; - this.SOURCE_WORKBOOK_FILENAME = SOURCE_WORKBOOK_FILENAME; - } - - @BeforeEach - protected void setUp() throws Exception { - mainWorkbook = HSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME); - sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME); - - assertNotNull(mainWorkbook); - assertNotNull(sourceWorkbook); - } - - @AfterEach - void tearDown() throws Exception { - if(mainWorkbook != null) { - mainWorkbook.close(); - } - - if(sourceWorkbook != null) { - sourceWorkbook.close(); - } - } - - @Test - void testMissingWorkbookMissing() { - FormulaEvaluator evaluator = mainWorkbook.getCreationHelper().createFormulaEvaluator(); - - Sheet lSheet = mainWorkbook.getSheetAt(0); - Row lARow = lSheet.getRow(0); - Cell lA1Cell = lARow.getCell(0); - - assertEquals(CellType.FORMULA, lA1Cell.getCellType()); - RuntimeException re = assertThrows(RuntimeException.class, () -> evaluator.evaluateFormulaCell(lA1Cell), - "Missing external workbook reference exception expected!"); - assertTrue(re.getMessage().contains(SOURCE_DUMMY_WORKBOOK_FILENAME)); - } - - @Test - void testMissingWorkbookMissingOverride() { - Sheet lSheet = mainWorkbook.getSheetAt(0); - Cell lA1Cell = lSheet.getRow(0).getCell(0); - Cell lB1Cell = lSheet.getRow(1).getCell(0); - Cell lC1Cell = lSheet.getRow(2).getCell(0); - - assertEquals(CellType.FORMULA, lA1Cell.getCellType()); - assertEquals(CellType.FORMULA, lB1Cell.getCellType()); - assertEquals(CellType.FORMULA, lC1Cell.getCellType()); - - // Check cached values - assertEquals(10.0d, lA1Cell.getNumericCellValue(), 0.00001d); - assertEquals("POI rocks!", lB1Cell.getStringCellValue()); - assertTrue(lC1Cell.getBooleanCellValue()); - - // Evaluate - FormulaEvaluator evaluator = mainWorkbook.getCreationHelper().createFormulaEvaluator(); - evaluator.setIgnoreMissingWorkbooks(true); - - assertEquals(CellType.NUMERIC, evaluator.evaluateFormulaCell(lA1Cell)); - assertEquals(CellType.STRING, evaluator.evaluateFormulaCell(lB1Cell)); - assertEquals(CellType.BOOLEAN, evaluator.evaluateFormulaCell(lC1Cell)); - - assertEquals(10.0d, lA1Cell.getNumericCellValue(), 0.00001d); - assertEquals("POI rocks!", lB1Cell.getStringCellValue()); - assertTrue(lC1Cell.getBooleanCellValue()); - } - - @Test - void testExistingWorkbook() { - Sheet lSheet = mainWorkbook.getSheetAt(0); - Cell lA1Cell = lSheet.getRow(0).getCell(0); - Cell lB1Cell = lSheet.getRow(1).getCell(0); - Cell lC1Cell = lSheet.getRow(2).getCell(0); - - assertEquals(CellType.FORMULA, lA1Cell.getCellType()); - assertEquals(CellType.FORMULA, lB1Cell.getCellType()); - assertEquals(CellType.FORMULA, lC1Cell.getCellType()); - - FormulaEvaluator lMainWorkbookEvaluator = mainWorkbook.getCreationHelper().createFormulaEvaluator(); - FormulaEvaluator lSourceEvaluator = sourceWorkbook.getCreationHelper().createFormulaEvaluator(); - Map workbooks = new HashMap<>(); - workbooks.put(MAIN_WORKBOOK_FILENAME, lMainWorkbookEvaluator); - workbooks.put(SOURCE_DUMMY_WORKBOOK_FILENAME, lSourceEvaluator); - lMainWorkbookEvaluator.setupReferencedWorkbooks(workbooks); - - assertEquals(CellType.NUMERIC, lMainWorkbookEvaluator.evaluateFormulaCell(lA1Cell)); - assertEquals(CellType.STRING, lMainWorkbookEvaluator.evaluateFormulaCell(lB1Cell)); - assertEquals(CellType.BOOLEAN, lMainWorkbookEvaluator.evaluateFormulaCell(lC1Cell)); - - assertEquals(20.0d, lA1Cell.getNumericCellValue(), 0.00001d); - assertEquals("Apache rocks!", lB1Cell.getStringCellValue()); - assertFalse(lC1Cell.getBooleanCellValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/EvaluationListener.java b/src/testcases/org/apache/poi/ss/formula/EvaluationListener.java deleted file mode 100644 index 3524c3f7d0..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/EvaluationListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests should extend this class if they need to track the internal working of the {@link WorkbookEvaluator}.
- * - * Default method implementations all do nothing - * - * @author Josh Micich - */ -public abstract class EvaluationListener implements IEvaluationListener { - @Override - public void onCacheHit(int sheetIndex, int rowIndex, int columnIndex, ValueEval result) { - // do nothing - } - @Override - public void onReadPlainValue(int sheetIndex, int rowIndex, int columnIndex, ICacheEntry entry) { - // do nothing - } - @Override - public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) { - // do nothing - } - @Override - public void onEndEvaluate(ICacheEntry entry, ValueEval result) { - // do nothing - } - @Override - public void onClearWholeCache() { - // do nothing - } - @Override - public void onClearCachedValue(ICacheEntry entry) { - // do nothing - } - @Override - public void onChangeFromBlankValue(int sheetIndex, int rowIndex, int columnIndex, - EvaluationCell cell, ICacheEntry entry) { - // do nothing - } - @Override - public void sortDependentCachedValues(ICacheEntry[] entries) { - // do nothing - } - @Override - public void onClearDependentCachedValue(ICacheEntry entry, int depth) { - // do nothing - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/SheetRangeAndWorkbookIndexFormatterTest.java b/src/testcases/org/apache/poi/ss/formula/SheetRangeAndWorkbookIndexFormatterTest.java deleted file mode 100644 index 507cbc854c..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/SheetRangeAndWorkbookIndexFormatterTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -public class SheetRangeAndWorkbookIndexFormatterTest { - @Test - void noDelimiting_ifASingleSheetNameDoesntNeedDelimiting() { - StringBuilder sb = new StringBuilder(); - String result = SheetRangeAndWorkbookIndexFormatter.format(sb, 0, "noDelimiting", null); - assertEquals("[0]noDelimiting", result); - } - - @Test - void everythingIsScreened_ifASingleSheetNameNeedsDelimiting() { - StringBuilder sb = new StringBuilder(); - String result = SheetRangeAndWorkbookIndexFormatter.format(sb, 0, "1delimiting", null); - assertEquals("'[0]1delimiting'", result); - } - - @Test - void noDelimiting_ifBothSheetNamesDontNeedDelimiting() { - StringBuilder sb = new StringBuilder(); - String result = SheetRangeAndWorkbookIndexFormatter.format(sb, 0, "noDelimiting1", "noDelimiting2"); - assertEquals("[0]noDelimiting1:noDelimiting2", result); - } - - @Test - void everythingIsScreened_ifFirstSheetNamesNeedsDelimiting() { - StringBuilder sb = new StringBuilder(); - String result = SheetRangeAndWorkbookIndexFormatter.format(sb, 0, "1delimiting", "noDelimiting"); - assertEquals("'[0]1delimiting:noDelimiting'", result); - } - - @Test - void everythingIsScreened_ifLastSheetNamesNeedsDelimiting() { - StringBuilder sb = new StringBuilder(); - String result = SheetRangeAndWorkbookIndexFormatter.format(sb, 0, "noDelimiting", "1delimiting"); - assertEquals("'[0]noDelimiting:1delimiting'", result); - } - - @Test - void everythingIsScreened_ifBothSheetNamesNeedDelimiting() { - StringBuilder sb = new StringBuilder(); - String result = SheetRangeAndWorkbookIndexFormatter.format(sb, 0, "1delimiting", "2delimiting"); - assertEquals("'[0]1delimiting:2delimiting'", result); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestCellCacheEntry.java b/src/testcases/org/apache/poi/ss/formula/TestCellCacheEntry.java deleted file mode 100644 index 11b08fade6..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestCellCacheEntry.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link org.apache.poi.ss.formula.CellCacheEntry}. - */ -class TestCellCacheEntry { - - @Test - void testBasic() { - CellCacheEntry pcce = new PlainValueCellCacheEntry(new NumberEval(42.0)); - ValueEval ve = pcce.getValue(); - assertEquals(42, ((NumberEval)ve).getNumberValue(), 0.0); - - FormulaCellCacheEntry fcce = new FormulaCellCacheEntry(); - fcce.updateFormulaResult(new NumberEval(10.0), CellCacheEntry.EMPTY_ARRAY, null); - - ve = fcce.getValue(); - assertEquals(10, ((NumberEval)ve).getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestEvaluationCache.java b/src/testcases/org/apache/poi/ss/formula/TestEvaluationCache.java deleted file mode 100644 index 5f7c6a76d2..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestEvaluationCache.java +++ /dev/null @@ -1,712 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.usermodel.FormulaExtractor; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFEvaluationTestHelper; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.IEvaluationListener.ICacheEntry; -import org.apache.poi.ss.formula.PlainCellCache.Loc; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link org.apache.poi.ss.formula.EvaluationCache}. Makes sure that where possible (previously calculated) cached - * values are used. Also checks that changing cell values causes the correct (minimal) set of - * dependent cached values to be cleared. - */ -class TestEvaluationCache { - - private static final class FormulaCellCacheEntryComparer implements Comparator { - - private final Map _formulaCellsByCacheEntry; - - public FormulaCellCacheEntryComparer(Map formulaCellsByCacheEntry) { - _formulaCellsByCacheEntry = formulaCellsByCacheEntry; - } - private EvaluationCell getCell(ICacheEntry a) { - return _formulaCellsByCacheEntry.get(a); - } - @Override - public int compare(ICacheEntry oa, ICacheEntry ob) { - EvaluationCell a = getCell(oa); - EvaluationCell b = getCell(ob); - int cmp; - cmp = a.getRowIndex() - b.getRowIndex(); - if (cmp != 0) { - return cmp; - } - cmp = a.getColumnIndex() - b.getColumnIndex(); - if (cmp != 0) { - return cmp; - } - if (a.getSheet() == b.getSheet()) { - return 0; - } - throw new RuntimeException("Incomplete code - don't know how to order sheets"); - } - } - - private static final class EvalListener extends EvaluationListener { - - private final List _logList; - private final HSSFWorkbook _book; - private final Map _formulaCellsByCacheEntry; - private final Map _plainCellLocsByCacheEntry; - - public EvalListener(HSSFWorkbook wb) { - _book = wb; - _logList = new ArrayList<>(); - _formulaCellsByCacheEntry = new HashMap<>(); - _plainCellLocsByCacheEntry = new HashMap<>(); - } - @Override - public void onCacheHit(int sheetIndex, int rowIndex, int columnIndex, ValueEval result) { - log("hit", rowIndex, columnIndex, result); - } - @Override - public void onReadPlainValue(int sheetIndex, int rowIndex, int columnIndex, ICacheEntry entry) { - Loc loc = new Loc(0, sheetIndex, rowIndex, columnIndex); - _plainCellLocsByCacheEntry.put(entry, loc); - log("value", rowIndex, columnIndex, entry.getValue()); - } - @Override - public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) { - _formulaCellsByCacheEntry.put(entry, cell); - HSSFCell hc = _book.getSheetAt(0).getRow(cell.getRowIndex()).getCell(cell.getColumnIndex()); - log("start", cell.getRowIndex(), cell.getColumnIndex(), FormulaExtractor.getPtgs(hc)); - } - @Override - public void onEndEvaluate(ICacheEntry entry, ValueEval result) { - EvaluationCell cell = _formulaCellsByCacheEntry.get(entry); - log("end", cell.getRowIndex(), cell.getColumnIndex(), result); - } - @Override - public void onClearCachedValue(ICacheEntry entry) { - int rowIndex; - int columnIndex; - EvaluationCell cell = _formulaCellsByCacheEntry.get(entry); - if (cell == null) { - Loc loc = _plainCellLocsByCacheEntry.get(entry); - if (loc == null) { - throw new IllegalStateException("can't find cell or location"); - } - rowIndex = loc.getRowIndex(); - columnIndex = loc.getColumnIndex(); - } else { - rowIndex = cell.getRowIndex(); - columnIndex = cell.getColumnIndex(); - } - log("clear", rowIndex, columnIndex, entry.getValue()); - } - @Override - public void sortDependentCachedValues(ICacheEntry[] entries) { - Arrays.sort(entries, new FormulaCellCacheEntryComparer(_formulaCellsByCacheEntry)); - } - @Override - public void onClearDependentCachedValue(ICacheEntry entry, int depth) { - EvaluationCell cell = _formulaCellsByCacheEntry.get(entry); - log("clear" + depth, cell.getRowIndex(), cell.getColumnIndex(), entry.getValue()); - } - - @Override - public void onChangeFromBlankValue(int sheetIndex, int rowIndex, int columnIndex, - EvaluationCell cell, ICacheEntry entry) { - log("changeFromBlank", rowIndex, columnIndex, entry.getValue()); - if (entry.getValue() == null) { // hack to tell the difference between formula and plain value - // perhaps the API could be improved: onChangeFromBlankToValue, onChangeFromBlankToFormula - _formulaCellsByCacheEntry.put(entry, cell); - } else { - Loc loc = new Loc(0, sheetIndex, rowIndex, columnIndex); - _plainCellLocsByCacheEntry.put(entry, loc); - } - } - private void log(String tag, int rowIndex, int columnIndex, Object value) { - StringBuilder sb = new StringBuilder(64); - sb.append(tag).append(' '); - sb.append(new CellReference(rowIndex, columnIndex, false, false).formatAsString()); - if (value != null) { - sb.append(' ').append(formatValue(value)); - } - _logList.add(sb.toString()); - } - private String formatValue(Object value) { - if (value instanceof Ptg[]) { - Ptg[] ptgs = (Ptg[]) value; - return HSSFFormulaParser.toFormulaString(_book, ptgs); - } - if (value instanceof NumberEval) { - NumberEval ne = (NumberEval) value; - return ne.getStringValue(); - } - if (value instanceof StringEval) { - StringEval se = (StringEval) value; - return "'" + se.getStringValue() + "'"; - } - if (value instanceof BoolEval) { - BoolEval be = (BoolEval) value; - return be.getStringValue(); - } - if (value == BlankEval.instance) { - return "#BLANK#"; - } - if (value instanceof ErrorEval) { - ErrorEval ee = (ErrorEval) value; - return ErrorEval.getText(ee.getErrorCode()); - } - throw new IllegalArgumentException("Unexpected value class (" - + value.getClass().getName() + ")"); - } - public String[] getAndClearLog() { - String[] result = new String[_logList.size()]; - _logList.toArray(result); - _logList.clear(); - return result; - } - } - /** - * Wrapper class to manage repetitive tasks from this test, - * - * Note - this class does a little bit more than just plain set-up of data. The method - * {@link WorkbookEvaluator#notifyUpdateCell(EvaluationCell)} is called whenever a - * cell value is changed. - */ - private static final class MySheet { - - private final HSSFSheet _sheet; - private final WorkbookEvaluator _evaluator; - private final EvalListener _evalListener; - - public MySheet() { - HSSFWorkbook _wb = new HSSFWorkbook(); - _evalListener = new EvalListener(_wb); - _evaluator = WorkbookEvaluatorTestHelper.createEvaluator(_wb, _evalListener); - _sheet = _wb.createSheet("Sheet1"); - } - - private static EvaluationCell wrapCell(HSSFCell cell) { - return HSSFEvaluationTestHelper.wrapCell(cell); - } - - public void setCellValue(String cellRefText, double value) { - HSSFCell cell = getOrCreateCell(cellRefText); - // be sure to blank cell, in case it is currently a formula - cell.setBlank(); - // otherwise this line will only set the formula cached result; - cell.setCellValue(value); - _evaluator.notifyUpdateCell(wrapCell(cell)); - } - public void clearCell(String cellRefText) { - HSSFCell cell = getOrCreateCell(cellRefText); - cell.setBlank(); - _evaluator.notifyUpdateCell(wrapCell(cell)); - } - - public void setCellFormula(String cellRefText, String formulaText) { - HSSFCell cell = getOrCreateCell(cellRefText); - cell.setCellFormula(formulaText); - _evaluator.notifyUpdateCell(wrapCell(cell)); - } - - private HSSFCell getOrCreateCell(String cellRefText) { - CellReference cr = new CellReference(cellRefText); - int rowIndex = cr.getRow(); - HSSFRow row = _sheet.getRow(rowIndex); - if (row == null) { - row = _sheet.createRow(rowIndex); - } - int cellIndex = cr.getCol(); - HSSFCell cell = row.getCell(cellIndex); - if (cell == null) { - cell = row.createCell(cellIndex); - } - return cell; - } - - public ValueEval evaluateCell(String cellRefText) { - return _evaluator.evaluate(wrapCell(getOrCreateCell(cellRefText))); - } - - public String[] getAndClearLog() { - return _evalListener.getAndClearLog(); - } - - public void clearAllCachedResultValues() { - _evaluator.clearAllCachedResultValues(); - } - } - - private static MySheet createMediumComplex() { - MySheet ms = new MySheet(); - - // plain data in D1:F3 - ms.setCellValue("D1", 12); - ms.setCellValue("E1", 13); - ms.setCellValue("D2", 14); - ms.setCellValue("E2", 15); - ms.setCellValue("D3", 16); - ms.setCellValue("E3", 17); - - - ms.setCellFormula("C1", "SUM(D1:E2)"); - ms.setCellFormula("C2", "SUM(D2:E3)"); - ms.setCellFormula("C3", "SUM(D3:E4)"); - - ms.setCellFormula("B1", "C2-C1"); - ms.setCellFormula("B2", "B3*C1-C2"); - ms.setCellValue("B3", 2); - - ms.setCellFormula("A1", "MAX(B1:B2)"); - ms.setCellFormula("A2", "MIN(B3,D2:F2)"); - ms.setCellFormula("A3", "B3*C3"); - - // clear all the logging from the above initialisation - ms.getAndClearLog(); - ms.clearAllCachedResultValues(); - return ms; - } - - @Test - void testMediumComplex() { - MySheet ms = createMediumComplex(); - // completely fresh evaluation - confirmEvaluate(ms, "A1", 46); - confirmLog(ms, new String[] { - "start A1 MAX(B1:B2)", - "start B1 C2-C1", - "start C2 SUM(D2:E3)", - "value D2 14", "value E2 15", "value D3 16", "value E3 17", - "end C2 62", - "start C1 SUM(D1:E2)", - "value D1 12", "value E1 13", "hit D2 14", "hit E2 15", - "end C1 54", - "end B1 8", - "start B2 B3*C1-C2", - "value B3 2", - "hit C1 54", - "hit C2 62", - "end B2 46", - "end A1 46", - }); - - - // simple cache hit - immediate re-evaluation with no changes - confirmEvaluate(ms, "A1", 46); - confirmLog(ms, new String[] { "hit A1 46", }); - - // change a low level cell - ms.setCellValue("D1", 10); - confirmLog(ms, new String[] { - "clear D1 10", - "clear1 C1 54", - "clear2 B1 8", - "clear3 A1 46", - "clear2 B2 46", - }); - confirmEvaluate(ms, "A1", 42); - confirmLog(ms, new String[] { - "start A1 MAX(B1:B2)", - "start B1 C2-C1", - "hit C2 62", - "start C1 SUM(D1:E2)", - "hit D1 10", "hit E1 13", "hit D2 14", "hit E2 15", - "end C1 52", - "end B1 10", - "start B2 B3*C1-C2", - "hit B3 2", - "hit C1 52", - "hit C2 62", - "end B2 42", - "end A1 42", - }); - - // Reset and try changing an intermediate value - ms = createMediumComplex(); - confirmEvaluate(ms, "A1", 46); - ms.getAndClearLog(); - - ms.setCellValue("B3", 3); // B3 is in the middle of the dependency tree - confirmLog(ms, new String[] { - "clear B3 3", - "clear1 B2 46", - "clear2 A1 46", - }); - confirmEvaluate(ms, "A1", 100); - confirmLog(ms, new String[] { - "start A1 MAX(B1:B2)", - "hit B1 8", - "start B2 B3*C1-C2", - "hit B3 3", - "hit C1 54", - "hit C2 62", - "end B2 100", - "end A1 100", - }); - } - - @Test - void testMediumComplexWithDependencyChange() { - // Changing an intermediate formula - MySheet ms = createMediumComplex(); - confirmEvaluate(ms, "A1", 46); - ms.getAndClearLog(); - ms.setCellFormula("B2", "B3*C2-C3"); // used to be "B3*C1-C2" - confirmLog(ms, new String[] { - "clear B2 46", - "clear1 A1 46", - }); - - confirmEvaluate(ms, "A1", 91); - confirmLog(ms, new String[] { - "start A1 MAX(B1:B2)", - "hit B1 8", - "start B2 B3*C2-C3", - "hit B3 2", - "hit C2 62", - "start C3 SUM(D3:E4)", - "hit D3 16", "hit E3 17", -// "value D4 #BLANK#", "value E4 #BLANK#", - "end C3 33", - "end B2 91", - "end A1 91", - }); - - //---------------- - // Note - From now on the demonstrated POI behaviour is not optimal - //---------------- - - // Now change a value that should no longer affect B2 - ms.setCellValue("D1", 11); - confirmLog(ms, new String[] { - "clear D1 11", - "clear1 C1 54", - // note there is no "clear2 B2 91" here because B2 doesn't depend on C1 anymore - "clear2 B1 8", - "clear3 A1 91", - }); - - confirmEvaluate(ms, "B2", 91); - confirmLog(ms, new String[] { - "hit B2 91", // further confirmation that B2 was not cleared due to changing D1 above - }); - - // things should be back to normal now - ms.setCellValue("D1", 11); - confirmLog(ms, new String[] { }); - confirmEvaluate(ms, "B2", 91); - confirmLog(ms, new String[] { - "hit B2 91", - }); - } - - /** - * verifies that when updating a plain cell, depending (formula) cell cached values are cleared - * only when the plain cell's value actually changes - */ - @Test - void testRedundantUpdate() { - MySheet ms = new MySheet(); - - ms.setCellValue("B1", 12); - ms.setCellValue("C1", 13); - ms.setCellFormula("A1", "B1+C1"); - - // evaluate twice to confirm caching looks OK - ms.evaluateCell("A1"); - ms.getAndClearLog(); - confirmEvaluate(ms, "A1", 25); - confirmLog(ms, new String[] { - "hit A1 25", - }); - - // Make redundant update, and check re-evaluation - ms.setCellValue("B1", 12); // value didn't change - confirmLog(ms, new String[] {}); - confirmEvaluate(ms, "A1", 25); - confirmLog(ms, new String[] { - "hit A1 25", - }); - - ms.setCellValue("B1", 11); // value changing - confirmLog(ms, new String[] { - "clear B1 11", - "clear1 A1 25", // expect consuming formula cached result to get cleared - }); - confirmEvaluate(ms, "A1", 24); - confirmLog(ms, new String[] { - "start A1 B1+C1", - "hit B1 11", - "hit C1 13", - "end A1 24", - }); - } - - /** - * Changing any input to a formula may cause the formula to 'use' a different set of cells. - * Functions like INDEX and OFFSET make this effect obvious, with functions like MATCH - * and VLOOKUP the effect can be subtle. The presence of error values can also produce this - * effect in almost every function and operator. - */ - @Test - void testSimpleWithDependencyChange() { - MySheet ms = new MySheet(); - - ms.setCellFormula("A1", "INDEX(C1:E1,1,B1)"); - ms.setCellValue("B1", 1); - ms.setCellValue("C1", 17); - ms.setCellValue("D1", 18); - ms.setCellValue("E1", 19); - ms.clearAllCachedResultValues(); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 17); - confirmLog(ms, new String[] { - "start A1 INDEX(C1:E1,1,B1)", - "value B1 1", - "value C1 17", - "end A1 17", - }); - ms.setCellValue("B1", 2); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 18); - confirmLog(ms, new String[] { - "start A1 INDEX(C1:E1,1,B1)", - "hit B1 2", - "value D1 18", - "end A1 18", - }); - - // change C1. Note - last time A1 evaluated C1 was not used - ms.setCellValue("C1", 15); - ms.getAndClearLog(); - confirmEvaluate(ms, "A1", 18); - confirmLog(ms, new String[] { - "hit A1 18", - }); - - // but A1 still uses D1, so if it changes... - ms.setCellValue("D1", 25); - ms.getAndClearLog(); - confirmEvaluate(ms, "A1", 25); - confirmLog(ms, new String[] { - "start A1 INDEX(C1:E1,1,B1)", - "hit B1 2", - "hit D1 25", - "end A1 25", - }); - } - - @Test - void testBlankCells() { - MySheet ms = new MySheet(); - - ms.setCellFormula("A1", "sum(B1:D4,B5:E6)"); - ms.setCellValue("B1", 12); - ms.clearAllCachedResultValues(); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 12); - confirmLog(ms, new String[] { - "start A1 SUM(B1:D4,B5:E6)", - "value B1 12", - "end A1 12", - }); - ms.setCellValue("B6", 2); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 14); - confirmLog(ms, new String[] { - "start A1 SUM(B1:D4,B5:E6)", - "hit B1 12", - "hit B6 2", - "end A1 14", - }); - ms.setCellValue("E4", 2); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 14); - confirmLog(ms, new String[] { - "hit A1 14", - }); - - ms.setCellValue("D1", 1); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 15); - confirmLog(ms, new String[] { - "start A1 SUM(B1:D4,B5:E6)", - "hit B1 12", - "hit D1 1", - "hit B6 2", - "end A1 15", - }); - } - - /** - * Make sure that when blank cells are changed to value/formula cells, any dependent formulas - * have their cached results cleared. - */ - @Test - void testBlankCellChangedToValueCell_bug46053() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cellA1 = row.createCell(0); - HSSFCell cellB1 = row.createCell(1); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - cellA1.setCellFormula("B1+2.2"); - cellB1.setCellValue(1.5); - - fe.notifyUpdateCell(cellA1); - fe.notifyUpdateCell(cellB1); - - CellValue cv; - cv = fe.evaluate(cellA1); - assertEquals(3.7, cv.getNumberValue(), 0.0); - - cellB1.setBlank(); - fe.notifyUpdateCell(cellB1); - cv = fe.evaluate(cellA1); // B1 was used to evaluate A1 - assertEquals(2.2, cv.getNumberValue(), 0.0); - - cellB1.setCellValue(0.4); // changing B1, so A1 cached result should be cleared - fe.notifyUpdateCell(cellB1); - cv = fe.evaluate(cellA1); - - // looks like left-over cached result from before change to B1 - assertNotEquals(2.2, cv.getNumberValue(), "Identified bug 46053"); - assertEquals(2.6, cv.getNumberValue(), 0.0); - } - - /** - * same use-case as the test for bug 46053, but checking trace values too - */ - @Test - void testBlankCellChangedToValueCell() { - - MySheet ms = new MySheet(); - - ms.setCellFormula("A1", "B1+2.2"); - ms.setCellValue("B1", 1.5); - ms.clearAllCachedResultValues(); - ms.clearCell("B1"); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 2.2); - confirmLog(ms, new String[] { - "start A1 B1+2.2", - "end A1 2.2", - }); - ms.setCellValue("B1", 0.4); - confirmLog(ms, new String[] { - "changeFromBlank B1 0.4", - "clear A1", - }); - - confirmEvaluate(ms, "A1", 2.6); - confirmLog(ms, new String[] { - "start A1 B1+2.2", - "hit B1 0.4", - "end A1 2.6", - }); - } - - private static void confirmEvaluate(MySheet ms, String cellRefText, double expectedValue) { - ValueEval v = ms.evaluateCell(cellRefText); - assertEquals(NumberEval.class, v.getClass()); - assertEquals(expectedValue, ((NumberEval)v).getNumberValue(), 0.0); - } - - private static void confirmLog(MySheet ms, String[] expectedLog) { - String[] actualLog = ms.getAndClearLog(); - assertArrayEquals(expectedLog, actualLog, "Log entry mismatch"); - } - - @Test - void testPlainValueCache() { - - Workbook wb = new HSSFWorkbook(); - int numberOfSheets = 4098; // Bug 51448 reported that Evaluation Cache got messed up after 256 sheets - - Row row; - Cell cell; - - //create summary sheet - Sheet summary = wb.createSheet("summary"); - wb.setActiveSheet(wb.getSheetIndex(summary)); - - //formula referring all sheets created below - row = summary.createRow(0); - Cell summaryCell = row.createCell(0); - summaryCell.setCellFormula("SUM(A2:A" + (numberOfSheets + 2) + ")"); - - - //create sheets with cells having (different) numbers - // and add a row to summary - for (int i = 1; i < numberOfSheets; i++) { - Sheet sheet = wb.createSheet("new" + i); - - row = sheet.createRow(0); - cell = row.createCell(0); - cell.setCellValue(i); - - row = summary.createRow(i); - cell = row.createCell(0); - cell.setCellFormula("new" + i + "!A1"); - - } - - - //calculate - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - evaluator.evaluateFormulaCell(summaryCell); - assertEquals(8394753.0, summaryCell.getNumericCellValue(), 0); - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestFormulaShifter.java b/src/testcases/org/apache/poi/ss/formula/TestFormulaShifter.java deleted file mode 100644 index 37e2131ee0..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestFormulaShifter.java +++ /dev/null @@ -1,455 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.ptg.AreaErrPtg; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.Ref3DPtg; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link FormulaShifter}. - */ -final class TestFormulaShifter { - // Note - the expected result row coordinates here were determined/verified - // in Excel 2007 by manually testing. - - /** - * Tests what happens to area refs when a range of rows from inside, or overlapping are - * moved - */ - @Test - void testShiftAreasSourceRows() { - - // all these operations are on an area ref spanning rows 10 to 20 - AreaPtg aptg = createAreaPtgRow(10, 20); - - confirmAreaRowShift(aptg, 9, 21, 20, 30, 40); - confirmAreaRowShift(aptg, 10, 21, 20, 30, 40); - confirmAreaRowShift(aptg, 9, 20, 20, 30, 40); - - confirmAreaRowShift(aptg, 8, 11, -3, 7, 20); // simple expansion of top - // rows containing area top being shifted down: - confirmAreaRowShift(aptg, 8, 11, 3, 13, 20); - confirmAreaRowShift(aptg, 8, 11, 7, 17, 20); - confirmAreaRowShift(aptg, 8, 11, 8, 18, 20); - confirmAreaRowShift(aptg, 8, 11, 9, 12, 20); // note behaviour changes here - confirmAreaRowShift(aptg, 8, 11, 10, 12, 21); - confirmAreaRowShift(aptg, 8, 11, 12, 12, 23); - confirmAreaRowShift(aptg, 8, 11, 13, 10, 20); // ignored - - // rows from within being moved: - confirmAreaRowShift(aptg, 12, 16, 3, 10, 20); // stay within - no change - confirmAreaRowShift(aptg, 11, 19, 20, 10, 20); // move completely out - no change - confirmAreaRowShift(aptg, 16, 17, -6, 10, 20); // moved exactly to top - no change - confirmAreaRowShift(aptg, 16, 17, -7, 11, 20); // truncation at top - confirmAreaRowShift(aptg, 12, 16, 4, 10, 20); // moved exactly to bottom - no change - confirmAreaRowShift(aptg, 12, 16, 6, 10, 17); // truncation at bottom - - // rows containing area bottom being shifted up: - confirmAreaRowShift(aptg, 18, 22, -1, 10, 19); // simple contraction at bottom - confirmAreaRowShift(aptg, 18, 22, -7, 10, 13); // simple contraction at bottom - confirmAreaRowShift(aptg, 18, 22, -8, 10, 17); // top calculated differently here - confirmAreaRowShift(aptg, 18, 22, -9, 9, 17); - confirmAreaRowShift(aptg, 18, 22,-15, 10, 20); // no change because range would be turned inside out - confirmAreaRowShift(aptg, 15, 19, -7, 13, 20); // dest truncates top (even though src is from inside range) - confirmAreaRowShift(aptg, 19, 23,-12, 7, 18); // complex: src encloses bottom, dest encloses top - - confirmAreaRowShift(aptg, 18, 22, 5, 10, 25); // simple expansion at bottom - } - - @Test - void testShiftAreasSourceColumns() { - - // all these operations are on an area ref spanning columns 10 to 20 - AreaPtg aptg = createAreaPtgColumn(10, 20); - - confirmAreaColumnShift(aptg, 9, 21, 20, 30, 40); - confirmAreaColumnShift(aptg, 10, 21, 20, 30, 40); - confirmAreaColumnShift(aptg, 9, 20, 20, 30, 40); - - confirmAreaColumnShift(aptg, 8, 11, -3, 7, 20); // simple expansion of top - // columns containing area top being shifted down: - confirmAreaColumnShift(aptg, 8, 11, 3, 13, 20); - confirmAreaColumnShift(aptg, 8, 11, 7, 17, 20); - confirmAreaColumnShift(aptg, 8, 11, 8, 18, 20); - confirmAreaColumnShift(aptg, 8, 11, 9, 12, 20); // note behaviour changes here - confirmAreaColumnShift(aptg, 8, 11, 10, 12, 21); - confirmAreaColumnShift(aptg, 8, 11, 12, 12, 23); - confirmAreaColumnShift(aptg, 8, 11, 13, 10, 20); // ignored - - // columns from within being moved: - confirmAreaColumnShift(aptg, 12, 16, 3, 10, 20); // stay within - no change - confirmAreaColumnShift(aptg, 11, 19, 20, 10, 20); // move completely out - no change - confirmAreaColumnShift(aptg, 16, 17, -6, 10, 20); // moved exactly to top - no change - confirmAreaColumnShift(aptg, 16, 17, -7, 11, 20); // truncation at top - confirmAreaColumnShift(aptg, 12, 16, 4, 10, 20); // moved exactly to bottom - no change - confirmAreaColumnShift(aptg, 12, 16, 6, 10, 17); // truncation at bottom - - // columns containing area bottom being shifted up: - confirmAreaColumnShift(aptg, 18, 22, -1, 10, 19); // simple contraction at bottom - confirmAreaColumnShift(aptg, 18, 22, -7, 10, 13); // simple contraction at bottom - confirmAreaColumnShift(aptg, 18, 22, -8, 10, 17); // top calculated differently here - confirmAreaColumnShift(aptg, 18, 22, -9, 9, 17); - confirmAreaColumnShift(aptg, 18, 22,-15, 10, 20); // no change because range would be turned inside out - confirmAreaColumnShift(aptg, 15, 19, -7, 13, 20); // dest truncates top (even though src is from inside range) - confirmAreaColumnShift(aptg, 19, 23,-12, 7, 18); // complex: src encloses bottom, dest encloses top - - confirmAreaColumnShift(aptg, 18, 22, 5, 10, 25); // simple expansion at bottom - } - - @Test - void testCopyAreasSourceRowsRelRel() { - - // all these operations are on an area ref spanning rows 10 to 20 - final AreaPtg aptg = createAreaPtgRow(10, 20, true, true); - - confirmAreaRowCopy(aptg, 0, 30, 20, 30, 40, true); - confirmAreaRowCopy(aptg, 15, 25, -15, -1, -1, true); //DeletedRef - } - - @Test - void testCopyAreasSourceRowsRelAbs() { - - // all these operations are on an area ref spanning rows 10 to 20 - final AreaPtg aptg = createAreaPtgRow(10, 20, true, false); - - // Only first row should move - confirmAreaRowCopy(aptg, 0, 30, 20, 20, 30, true); - confirmAreaRowCopy(aptg, 15, 25, -15, -1, -1, true); //DeletedRef - } - - @Test - void testCopyAreasSourceRowsAbsRel() { - // aptg is part of a formula in a cell that was just copied to another row - // aptg row references should be updated by the difference in rows that the cell was copied - // No other references besides the cells that were involved in the copy need to be updated - // this makes the row copy significantly different from the row shift, where all references - // in the workbook need to track the row shift - - // all these operations are on an area ref spanning rows 10 to 20 - final AreaPtg aptg = createAreaPtgRow(10, 20, false, true); - - // Only last row should move - confirmAreaRowCopy(aptg, 0, 30, 20, 10, 40, true); - confirmAreaRowCopy(aptg, 15, 25, -15, 5, 10, true); //sortTopLeftToBottomRight swapped firstRow and lastRow because firstRow is absolute - } - - @Test - void testCopyAreasSourceRowsAbsAbs() { - // aptg is part of a formula in a cell that was just copied to another row - // aptg row references should be updated by the difference in rows that the cell was copied - // No other references besides the cells that were involved in the copy need to be updated - // this makes the row copy significantly different from the row shift, where all references - // in the workbook need to track the row shift - - // all these operations are on an area ref spanning rows 10 to 20 - final AreaPtg aptg = createAreaPtgRow(10, 20, false, false); - - //AbsFirstRow AbsLastRow references should't change when copied to a different row - confirmAreaRowCopy(aptg, 0, 30, 20, 10, 20, false); - confirmAreaRowCopy(aptg, 15, 25, -15, 10, 20, false); - } - - @Test - void testCopyAreasSourceColumnsRelRel() { - - // all these operations are on an area ref spanning columns 10 to 20 - final AreaPtg aptg = createAreaPtgColumn(10, 20, true, true); - - confirmAreaColumnCopy(aptg, 0, 30, 20, 30, 40, true); - confirmAreaColumnCopy(aptg, 15, 25, -15, -1, -1, true); //DeletedRef - } - - @Test - void testCopyAreasSourceColumnsRelAbs() { - - // all these operations are on an area ref spanning columns 10 to 20 - final AreaPtg aptg = createAreaPtgColumn(10, 20, true, false); - - // Only first column should move - confirmAreaColumnCopy(aptg, 0, 30, 20, 20, 30, true); - confirmAreaColumnCopy(aptg, 15, 25, -15, -1, -1, true); //DeletedRef - } - - @Test - void testCopyAreasSourceColumnsAbsRel() { - // aptg is part of a formula in a cell that was just copied to another column - // aptg column references should be updated by the difference in columns that the cell was copied - // No other references besides the cells that were involved in the copy need to be updated - // this makes the column copy significantly different from the column shift, where all references - // in the workbook need to track the column shift - - // all these operations are on an area ref spanning columns 10 to 20 - final AreaPtg aptg = createAreaPtgColumn(10, 20, false, true); - - // Only last column should move - confirmAreaColumnCopy(aptg, 0, 30, 20, 10, 40, true); - confirmAreaColumnCopy(aptg, 15, 25, -15, 5, 10, true); //sortTopLeftToBottomRight swapped firstColumn and lastColumn because firstColumn is absolute - } - - @Test - void testCopyAreasSourceColumnsAbsAbs() { - // aptg is part of a formula in a cell that was just copied to another column - // aptg column references should be updated by the difference in columns that the cell was copied - // No other references besides the cells that were involved in the copy need to be updated - // this makes the column copy significantly different from the column shift, where all references - // in the workbook need to track the column shift - - // all these operations are on an area ref spanning columns 10 to 20 - final AreaPtg aptg = createAreaPtgColumn(10, 20, false, false); - - //AbsFirstColumn AbsLastColumn references should't change when copied to a different column - confirmAreaColumnCopy(aptg, 0, 30, 20, 10, 20, false); - confirmAreaColumnCopy(aptg, 15, 25, -15, 10, 20, false); - } - - - - /** - * Tests what happens to an area ref when some outside rows are moved to overlap - * that area ref - */ - @Test - void testShiftAreasDestRows() { - // all these operations are on an area ref spanning rows 20 to 25 - AreaPtg aptg = createAreaPtgRow(20, 25); - - // no change because no overlap: - confirmAreaRowShift(aptg, 5, 10, 9, 20, 25); - confirmAreaRowShift(aptg, 5, 10, 21, 20, 25); - - confirmAreaRowShift(aptg, 11, 14, 10, 20, 25); - - confirmAreaRowShift(aptg, 7, 17, 10, -1, -1); // converted to DeletedAreaRef - confirmAreaRowShift(aptg, 5, 15, 7, 23, 25); // truncation at top - confirmAreaRowShift(aptg, 13, 16, 10, 20, 22); // truncation at bottom - } - - /** - * Tests what happens to an area ref when some outside columns are moved to overlap - * that area ref - */ - @Test - void testShiftAreasDestColumns() { - // all these operations are on an area ref spanning columns 20 to 25 - AreaPtg aptg = createAreaPtgColumn(20, 25); - - // no change because no overlap: - confirmAreaColumnShift(aptg, 5, 10, 9, 20, 25); - confirmAreaColumnShift(aptg, 5, 10, 21, 20, 25); - - confirmAreaColumnShift(aptg, 11, 14, 10, 20, 25); - - confirmAreaColumnShift(aptg, 7, 17, 10, -1, -1); // converted to DeletedAreaRef - confirmAreaColumnShift(aptg, 5, 15, 7, 23, 25); // truncation at top - confirmAreaColumnShift(aptg, 13, 16, 10, 20, 22); // truncation at bottom - } - - private static void confirmAreaRowShift( - AreaPtg aptg, - int firstRowMoved, int lastRowMoved, int numberRowsMoved, - int expectedAreaFirstRow, int expectedAreaLastRow) { - - FormulaShifter fs = FormulaShifter.createForRowShift(0, "", firstRowMoved, lastRowMoved, numberRowsMoved, SpreadsheetVersion.EXCEL2007); - boolean expectedChanged = aptg.getFirstRow() != expectedAreaFirstRow || aptg.getLastRow() != expectedAreaLastRow; - - // clone so we can re-use aptg in calling method - AreaPtg copyPtg = aptg.copy(); - Ptg[] ptgs = { copyPtg, }; - boolean actualChanged = fs.adjustFormula(ptgs, 0); - if (expectedAreaFirstRow < 0) { - assertEquals(AreaErrPtg.class, ptgs[0].getClass()); - return; - } - assertEquals(expectedChanged, actualChanged); - // expected to change in place (although this is not a strict requirement) - assertEquals(copyPtg, ptgs[0]); - assertEquals(expectedAreaFirstRow, copyPtg.getFirstRow()); - assertEquals(expectedAreaLastRow, copyPtg.getLastRow()); - - } - - private static void confirmAreaColumnShift( - AreaPtg aptg, - int firstColumnMoved, int lastColumnMoved, int numberColumnsMoved, - int expectedAreaFirstColumn, int expectedAreaLastColumn) { - - FormulaShifter fs = FormulaShifter.createForColumnShift(0, "", firstColumnMoved, lastColumnMoved, numberColumnsMoved, SpreadsheetVersion.EXCEL2007); - boolean expectedChanged = aptg.getFirstColumn() != expectedAreaFirstColumn || aptg.getLastColumn() != expectedAreaLastColumn; - - // clone so we can re-use aptg in calling method - AreaPtg copyPtg = aptg.copy(); - Ptg[] ptgs = { copyPtg, }; - boolean actualChanged = fs.adjustFormula(ptgs, 0); - if (expectedAreaFirstColumn < 0) { - assertEquals(AreaErrPtg.class, ptgs[0].getClass()); - return; - } - assertEquals(expectedChanged, actualChanged); - // expected to change in place (although this is not a strict requirement) - assertEquals(copyPtg, ptgs[0]); - assertEquals(expectedAreaFirstColumn, copyPtg.getFirstColumn()); - assertEquals(expectedAreaLastColumn, copyPtg.getLastColumn()); - - } - - - private static void confirmAreaRowCopy(AreaPtg aptg, - int firstRowCopied, int lastRowCopied, int rowOffset, - int expectedFirstRow, int expectedLastRow, boolean expectedChanged) { - // clone so we can re-use aptg in calling method - final AreaPtg copyPtg = aptg.copy(); - final Ptg[] ptgs = { copyPtg, }; - final FormulaShifter fs = FormulaShifter.createForRowCopy(0, null, firstRowCopied, lastRowCopied, rowOffset, SpreadsheetVersion.EXCEL2007); - final boolean actualChanged = fs.adjustFormula(ptgs, 0); - - // DeletedAreaRef - if (expectedFirstRow < 0 || expectedLastRow < 0) { - assertEquals(AreaErrPtg.class, ptgs[0].getClass(), "Reference should have shifted off worksheet, producing #REF! error: " + ptgs[0]); - return; - } - - assertEquals(expectedChanged, actualChanged, "Should this AreaPtg change due to row copy?"); - // expected to change in place (although this is not a strict requirement) - assertEquals(copyPtg, ptgs[0], "AreaPtgs should be modified in-place when a row containing the AreaPtg is copied"); - assertEquals(expectedFirstRow, copyPtg.getFirstRow(), "AreaPtg first row"); - assertEquals(expectedLastRow, copyPtg.getLastRow(), "AreaPtg last row"); - - } - - private static void confirmAreaColumnCopy(AreaPtg aptg, - int firstColumnCopied, int lastColumnCopied, int columnOffset, - int expectedFirstColumn, int expectedLastColumn, boolean expectedChanged) { - // clone so we can re-use aptg in calling method - final AreaPtg copyPtg = aptg.copy(); - final Ptg[] ptgs = { copyPtg, }; - final FormulaShifter fs = FormulaShifter.createForColumnCopy(0, null, firstColumnCopied, lastColumnCopied, columnOffset, SpreadsheetVersion.EXCEL2007); - final boolean actualChanged = fs.adjustFormula(ptgs, 0); - - // DeletedAreaRef - if (expectedFirstColumn < 0 || expectedLastColumn < 0) { - assertEquals(AreaErrPtg.class, ptgs[0].getClass(), - "Reference should have shifted off worksheet, producing #REF! error: " + ptgs[0]); - return; - } - - assertEquals(expectedChanged, actualChanged, "Should this AreaPtg change due to column copy?"); - // expected to change in place (although this is not a strict requirement) - assertEquals(copyPtg, ptgs[0], "AreaPtgs should be modified in-place when a column containing the AreaPtg is copied"); - assertEquals(expectedFirstColumn, copyPtg.getFirstColumn(), "AreaPtg first column"); - assertEquals(expectedLastColumn, copyPtg.getLastColumn(), "AreaPtg last column"); - - } - - private static AreaPtg createAreaPtgRow(int initialAreaFirstRow, int initialAreaLastRow) { - return createAreaPtgRow(initialAreaFirstRow, initialAreaLastRow, false, false); - } - - private static AreaPtg createAreaPtgColumn(int initialAreaFirstColumn, int initialAreaLastColumn) { - return createAreaPtgColumn(initialAreaFirstColumn, initialAreaLastColumn, false, false); - } - - private static AreaPtg createAreaPtgRow(int initialAreaFirstRow, int initialAreaLastRow, boolean firstRowRelative, boolean lastRowRelative) { - return new AreaPtg(initialAreaFirstRow, initialAreaLastRow, 2, 5, firstRowRelative, lastRowRelative, false, false); - } - - private static AreaPtg createAreaPtgColumn(int initialAreaFirstColumn, int initialAreaLastColumn, boolean firstColumnRelative, boolean lastColumnRelative) { - return new AreaPtg(2, 5, initialAreaFirstColumn, initialAreaLastColumn, false, false, firstColumnRelative, lastColumnRelative); - } - - @Test - void testShiftSheet() { - // 4 sheets, move a sheet from pos 2 to pos 0, i.e. current 0 becomes 1, current 1 becomes pos 2 - FormulaShifter shifter = FormulaShifter.createForSheetShift(2, 0); - - Ptg[] ptgs = new Ptg[] { - new Ref3DPtg(new CellReference("first", 0, 0, true, true), 0), - new Ref3DPtg(new CellReference("second", 0, 0, true, true), 1), - new Ref3DPtg(new CellReference("third", 0, 0, true, true), 2), - new Ref3DPtg(new CellReference("fourth", 0, 0, true, true), 3), - }; - - shifter.adjustFormula(ptgs, -1); - - assertEquals(1, ((Ref3DPtg)ptgs[0]).getExternSheetIndex(), - "formula previously pointing to sheet 0 should now point to sheet 1"); - assertEquals(2, ((Ref3DPtg)ptgs[1]).getExternSheetIndex(), - "formula previously pointing to sheet 1 should now point to sheet 2"); - assertEquals(0, ((Ref3DPtg)ptgs[2]).getExternSheetIndex(), - "formula previously pointing to sheet 2 should now point to sheet 0"); - assertEquals(3, ((Ref3DPtg)ptgs[3]).getExternSheetIndex(), - "formula previously pointing to sheet 3 should be unchanged"); - } - - @Test - void testShiftSheet2() { - // 4 sheets, move a sheet from pos 1 to pos 2, i.e. current 2 becomes 1, current 1 becomes pos 2 - FormulaShifter shifter = FormulaShifter.createForSheetShift(1, 2); - - Ptg[] ptgs = new Ptg[] { - new Ref3DPtg(new CellReference("first", 0, 0, true, true), 0), - new Ref3DPtg(new CellReference("second", 0, 0, true, true), 1), - new Ref3DPtg(new CellReference("third", 0, 0, true, true), 2), - new Ref3DPtg(new CellReference("fourth", 0, 0, true, true), 3), - }; - - shifter.adjustFormula(ptgs, -1); - - assertEquals(0, ((Ref3DPtg)ptgs[0]).getExternSheetIndex(), - "formula previously pointing to sheet 0 should be unchanged"); - assertEquals(2, ((Ref3DPtg)ptgs[1]).getExternSheetIndex(), - "formula previously pointing to sheet 1 should now point to sheet 2"); - assertEquals(1, ((Ref3DPtg)ptgs[2]).getExternSheetIndex(), - "formula previously pointing to sheet 2 should now point to sheet 1"); - assertEquals(3, ((Ref3DPtg)ptgs[3]).getExternSheetIndex(), - "formula previously pointing to sheet 3 should be unchanged"); - } - - @Test - void testInvalidArgument() { - assertThrows(IllegalArgumentException.class, () -> - FormulaShifter.createForRowShift(1, "name", 1, 2, 0, SpreadsheetVersion.EXCEL97)); - assertThrows(IllegalArgumentException.class, () -> - FormulaShifter.createForRowShift(1, "name", 2, 1, 2, SpreadsheetVersion.EXCEL97)); - } - - @Test - void testConstructor() { - assertNotNull(FormulaShifter.createForRowShift(1, "name", 1, 2, 2, SpreadsheetVersion.EXCEL97)); - } - - @Test - void testToString() { - FormulaShifter shifter = FormulaShifter.createForRowShift(0, "sheet", 123, 456, 789, - SpreadsheetVersion.EXCEL2007); - assertNotNull(shifter); - assertNotNull(shifter.toString()); - assertTrue(shifter.toString().contains("123")); - assertTrue(shifter.toString().contains("456")); - assertTrue(shifter.toString().contains("789")); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java b/src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java deleted file mode 100644 index 5bb859ce34..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.atp.AnalysisToolPak; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.FunctionEval; -import org.apache.poi.ss.formula.eval.NotImplementedException; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -@TestMethodOrder(MethodOrderer.MethodName.class) -class TestFunctionRegistry { - - HSSFWorkbook wb; - HSSFSheet sheet; - HSSFRow row; - HSSFFormulaEvaluator fe; - - @BeforeEach - void setup() { - wb = new HSSFWorkbook(); - sheet = wb.createSheet("Sheet1"); - row = sheet.createRow(0); - fe = new HSSFFormulaEvaluator(wb); - } - - @AfterEach - void teardown() throws IOException { - wb.close(); - wb = null; - sheet = null; - row = null; - fe = null; - } - - @Test - void testRegisterInRuntimeA() { - HSSFCell cellA = row.createCell(0); - cellA.setCellFormula("FISHER(A5)"); - assertThrows(NotImplementedException.class, () -> fe.evaluate(cellA)); - } - - @Test - void testRegisterInRuntimeB() { - HSSFCell cellA = row.createCell(0); - cellA.setCellFormula("FISHER(A5)"); - FunctionEval.registerFunction("FISHER", (args, srcRowIndex, srcColumnIndex) -> ErrorEval.NA); - CellValue cv = fe.evaluate(cellA); - assertEquals(ErrorEval.NA.getErrorCode(), cv.getErrorValue()); - } - - @Test - void testRegisterInRuntimeC() { - HSSFCell cellB = row.createCell(1); - cellB.setCellFormula("CUBEMEMBERPROPERTY(A5)"); - assertThrows(NotImplementedException.class, () -> fe.evaluate(cellB)); - } - - @Test - void testRegisterInRuntimeD() { - HSSFCell cellB = row.createCell(1); - cellB.setCellFormula("CUBEMEMBERPROPERTY(A5)"); - - AnalysisToolPak.registerFunction("CUBEMEMBERPROPERTY", (args, ec) -> ErrorEval.NUM_ERROR); - - CellValue cv = fe.evaluate(cellB); - assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), cv.getErrorValue()); - } - - private static ValueEval na(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { - return ErrorEval.NA; - } - - @Test - void testExceptionsA() { - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> FunctionEval.registerFunction("SUM", TestFunctionRegistry::na) - ); - assertEquals("POI already implements SUM. You cannot override POI's implementations of Excel functions", ex.getMessage()); - } - - @Test - void testExceptionsB() { - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> FunctionEval.registerFunction("SUMXXX", TestFunctionRegistry::na) - ); - assertTrue(ex.getMessage().contains("Unknown function: SUMXXX")); - } - - @Test - void testExceptionsC() { - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> FunctionEval.registerFunction("ISODD", TestFunctionRegistry::na) - ); - assertEquals("ISODD is a function from the Excel Analysis Toolpack. " + - "Use AnalysisToolpack.registerFunction(String name, FreeRefFunction func) instead.", - ex.getMessage()); - } - - private static ValueEval atpFunc(ValueEval[] args, OperationEvaluationContext ec) { - return ErrorEval.NUM_ERROR; - } - - @Test - void testExceptionsD() { - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> AnalysisToolPak.registerFunction("ISODD", TestFunctionRegistry::atpFunc) - ); - assertEquals("POI already implements ISODD. You cannot override POI's implementations of Excel functions", ex.getMessage()); - } - - @Test - void testExceptionsE() { - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> AnalysisToolPak.registerFunction("ISODDXXX", TestFunctionRegistry::atpFunc) - ); - assertEquals("ISODDXXX is not a function from the Excel Analysis Toolpack.", ex.getMessage()); - } - - @Test - void testExceptionsF() { - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> AnalysisToolPak.registerFunction("SUM", TestFunctionRegistry::atpFunc) - ); - assertEquals("SUM is a built-in Excel function. " + - "Use FunctoinEval.registerFunction(String name, Function func) instead.", - ex.getMessage()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestPlainCellCache.java b/src/testcases/org/apache/poi/ss/formula/TestPlainCellCache.java deleted file mode 100644 index dc05d792f4..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestPlainCellCache.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -import org.apache.poi.ss.formula.PlainCellCache.Loc; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.junit.jupiter.api.Test; - -class TestPlainCellCache { - - @Test - void testLoc(){ - PlainCellCache cache = new PlainCellCache(); - for (int bookIndex = 0; bookIndex < 0x1000; bookIndex += 0x100) { - for (int sheetIndex = 0; sheetIndex < 0x1000; sheetIndex += 0x100) { - for (int rowIndex = 0; rowIndex < 0x100000; rowIndex += 0x1000) { - for (int columnIndex = 0; columnIndex < 0x4000; columnIndex += 0x100) { - Loc loc = new Loc(bookIndex, sheetIndex, rowIndex, columnIndex); - assertEquals(bookIndex, loc.getBookIndex()); - assertEquals(sheetIndex, loc.getSheetIndex()); - assertEquals(rowIndex, loc.getRowIndex()); - assertEquals(columnIndex, loc.getColumnIndex()); - - Loc sameLoc = new Loc(bookIndex, sheetIndex, rowIndex, columnIndex); - assertEquals(loc.hashCode(), sameLoc.hashCode()); - assertEquals(loc, sameLoc); - - assertNull(cache.get(loc)); - PlainValueCellCacheEntry entry = new PlainValueCellCacheEntry(new NumberEval(0)); - cache.put(loc, entry); - assertSame(entry, cache.get(loc)); - cache.remove(loc); - assertNull(cache.get(loc)); - - cache.put(loc, entry); - } - cache.clear(); - } - } - - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestSheetNameFormatter.java b/src/testcases/org/apache/poi/ss/formula/TestSheetNameFormatter.java deleted file mode 100644 index 484e5597cb..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestSheetNameFormatter.java +++ /dev/null @@ -1,193 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link SheetNameFormatter} - * - * @author Josh Micich - */ -final class TestSheetNameFormatter { - /** - * Tests main public method 'format' - */ - @Test - void testFormat() { - - confirmFormat("abc", "abc"); - confirmFormat("123", "'123'"); - - confirmFormat("my sheet", "'my sheet'"); // space - confirmFormat("A:MEM", "'A:MEM'"); // colon - - confirmFormat("O'Brian", "'O''Brian'"); // single quote gets doubled - - confirmFormat("3rdTimeLucky", "'3rdTimeLucky'"); // digit in first pos - confirmFormat("_", "_"); // plain underscore OK - confirmFormat("my_3rd_sheet", "my_3rd_sheet"); // underscores and digits OK - confirmFormat("A12220", "'A12220'"); - confirmFormat("TAXRETURN19980415", "TAXRETURN19980415"); - - confirmFormat(null, "#REF"); - } - - private static void confirmFormat(String rawSheetName, String expectedSheetNameEncoding) { - // test all variants - - assertEquals(expectedSheetNameEncoding, SheetNameFormatter.format(rawSheetName)); - - StringBuilder sb = new StringBuilder(); - SheetNameFormatter.appendFormat(sb, rawSheetName); - assertEquals(expectedSheetNameEncoding, sb.toString()); - - sb = new StringBuilder(); - SheetNameFormatter.appendFormat((Appendable)sb, rawSheetName); - assertEquals(expectedSheetNameEncoding, sb.toString()); - - StringBuffer sbf = new StringBuffer(); - //noinspection deprecation - SheetNameFormatter.appendFormat(sbf, rawSheetName); - assertEquals(expectedSheetNameEncoding, sbf.toString()); - } - - @Test - void testFormatWithWorkbookName() { - - confirmFormat("abc", "abc", "[abc]abc"); - confirmFormat("abc", "123", "'[abc]123'"); - - confirmFormat("abc", "my sheet", "'[abc]my sheet'"); // space - confirmFormat("abc", "A:MEM", "'[abc]A:MEM'"); // colon - - confirmFormat("abc", "O'Brian", "'[abc]O''Brian'"); // single quote gets doubled - - confirmFormat("abc", "3rdTimeLucky", "'[abc]3rdTimeLucky'"); // digit in first pos - confirmFormat("abc", "_", "[abc]_"); // plain underscore OK - confirmFormat("abc", "my_3rd_sheet", "[abc]my_3rd_sheet"); // underscores and digits OK - confirmFormat("abc", "A12220", "'[abc]A12220'"); - confirmFormat("abc", "TAXRETURN19980415", "[abc]TAXRETURN19980415"); - - confirmFormat("abc", null, "[abc]#REF"); - confirmFormat(null, "abc", "[#REF]abc"); - confirmFormat(null, null, "[#REF]#REF"); - } - - private static void confirmFormat(String workbookName, String rawSheetName, String expectedSheetNameEncoding) { - // test all variants - - StringBuilder sb = new StringBuilder(); - SheetNameFormatter.appendFormat(sb, workbookName, rawSheetName); - assertEquals(expectedSheetNameEncoding, sb.toString()); - - sb = new StringBuilder(); - SheetNameFormatter.appendFormat((Appendable)sb, workbookName, rawSheetName); - assertEquals(expectedSheetNameEncoding, sb.toString()); - - StringBuffer sbf = new StringBuffer(); - //noinspection deprecation - SheetNameFormatter.appendFormat(sbf, workbookName, rawSheetName); - assertEquals(expectedSheetNameEncoding, sbf.toString()); - } - - @Test - void testFormatException() { - Appendable mock = new Appendable() { - @Override - public Appendable append(CharSequence csq) throws IOException { - throw new IOException("Test exception"); - } - - @Override - public Appendable append(CharSequence csq, int start, int end) throws IOException { - throw new IOException("Test exception"); - } - - @Override - public Appendable append(char c) throws IOException { - throw new IOException("Test exception"); - } - }; - - assertThrows(RuntimeException.class, () -> SheetNameFormatter.appendFormat(mock, null, null)); - assertThrows(RuntimeException.class, () -> SheetNameFormatter.appendFormat(mock, null)); - } - - @Test - void testBooleanLiterals() { - confirmFormat("TRUE", "'TRUE'"); - confirmFormat("FALSE", "'FALSE'"); - confirmFormat("True", "'True'"); - confirmFormat("fAlse", "'fAlse'"); - - confirmFormat("Yes", "Yes"); - confirmFormat("No", "No"); - } - - private static void confirmCellNameMatch(String rawSheetName, boolean expected) { - assertEquals(expected, SheetNameFormatter.nameLooksLikePlainCellReference(rawSheetName)); - } - - /** - * Tests functionality to determine whether a sheet name containing only letters and digits - * would look (to Excel) like a cell name. - */ - @Test - void testLooksLikePlainCellReference() { - - confirmCellNameMatch("A1", true); - confirmCellNameMatch("a111", true); - confirmCellNameMatch("AA", false); - confirmCellNameMatch("aa1", true); - confirmCellNameMatch("A1A", false); - confirmCellNameMatch("A1A1", false); - confirmCellNameMatch("Sh3", false); - confirmCellNameMatch("SALES20080101", false); // out of range - } - - private static void confirmCellRange(String text, int numberOfPrefixLetters, boolean expected) { - String prefix = text.substring(0, numberOfPrefixLetters); - String suffix = text.substring(numberOfPrefixLetters); - assertEquals(expected, SheetNameFormatter.cellReferenceIsWithinRange(prefix, suffix)); - } - - /** - * Tests exact boundaries for names that look very close to cell names (i.e. contain 1 or more - * letters followed by one or more digits). - */ - @Test - void testCellRange() { - confirmCellRange("A1", 1, true); - confirmCellRange("a111", 1, true); - confirmCellRange("A65536", 1, true); - confirmCellRange("A65537", 1, false); - confirmCellRange("iv1", 2, true); - confirmCellRange("IW1", 2, false); - confirmCellRange("AAA1", 3, false); - confirmCellRange("a111", 1, true); - confirmCellRange("Sheet1", 6, false); - confirmCellRange("iV65536", 2, true); // max cell in Excel 97-2003 - confirmCellRange("IW65537", 2, false); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java b/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java deleted file mode 100644 index 39eafbe65f..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java +++ /dev/null @@ -1,646 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.MissingArgEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.ptg.*; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link WorkbookEvaluator}. - * - * @author Josh Micich - */ -class TestWorkbookEvaluator { - - private static final double EPSILON = 0.0000001; - - private static ValueEval evaluateFormula(Ptg[] ptgs) { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet().createRow(0).createCell(0); - EvaluationWorkbook ewb = HSSFEvaluationWorkbook.create(wb); - OperationEvaluationContext ec = new OperationEvaluationContext(null, ewb, 0, 0, 0, null); - return new WorkbookEvaluator(null, null, null).evaluateFormula(ec, ptgs); - } - - /** - * Make sure that the evaluator can directly handle tAttrSum (instead of relying on re-parsing - * the whole formula which converts tAttrSum to tFuncVar("SUM") ) - */ - @Test - void testAttrSum() { - - Ptg[] ptgs = { - new IntPtg(42), - AttrPtg.SUM, - }; - - ValueEval result = evaluateFormula(ptgs); - assertEquals(42, ((NumberEval)result).getNumberValue(), 0.0); - } - - /** - * Make sure that the evaluator can directly handle (deleted) ref error tokens - * (instead of relying on re-parsing the whole formula which converts these - * to the error constant #REF! ) - */ - @Test - void testRefErr() { - - confirmRefErr(new RefErrorPtg()); - confirmRefErr(new AreaErrPtg()); - confirmRefErr(new DeletedRef3DPtg(0)); - confirmRefErr(new DeletedArea3DPtg(0)); - } - private static void confirmRefErr(Ptg ptg) { - Ptg[] ptgs = { - ptg, - }; - - ValueEval result = evaluateFormula(ptgs); - assertEquals(ErrorEval.REF_INVALID, result); - } - - /** - * Make sure that the evaluator can directly handle tAttrSum (instead of relying on re-parsing - * the whole formula which converts tAttrSum to tFuncVar("SUM") ) - */ - @Test - void testMemFunc() { - Ptg[] ptgs = { - new IntPtg(42), - AttrPtg.SUM, - }; - - ValueEval result = evaluateFormula(ptgs); - assertEquals(42, ((NumberEval)result).getNumberValue(), 0.0); - } - - @Test - void testEvaluateMultipleWorkbooks() { - HSSFWorkbook wbA = HSSFTestDataSamples.openSampleWorkbook("multibookFormulaA.xls"); - HSSFWorkbook wbB = HSSFTestDataSamples.openSampleWorkbook("multibookFormulaB.xls"); - - HSSFFormulaEvaluator evaluatorA = new HSSFFormulaEvaluator(wbA); - HSSFFormulaEvaluator evaluatorB = new HSSFFormulaEvaluator(wbB); - - // Hook up the workbook evaluators to enable evaluation of formulas across books - String[] bookNames = { "multibookFormulaA.xls", "multibookFormulaB.xls", }; - HSSFFormulaEvaluator[] evaluators = { evaluatorA, evaluatorB, }; - HSSFFormulaEvaluator.setupEnvironment(bookNames, evaluators); - - HSSFCell cell; - - HSSFSheet aSheet1 = wbA.getSheetAt(0); - HSSFSheet bSheet1 = wbB.getSheetAt(0); - - // Simple case - single link from wbA to wbB - confirmFormula(wbA, 0, 0, 0, "[multibookFormulaB.xls]BSheet1!B1"); - cell = aSheet1.getRow(0).getCell(0); - confirmEvaluation(35, evaluatorA, cell); - - - // more complex case - back link into wbA - // [wbA]ASheet1!A2 references (among other things) [wbB]BSheet1!B2 - confirmFormula(wbA, 0, 1, 0, "[multibookFormulaB.xls]BSheet1!$B$2+2*A3"); - // [wbB]BSheet1!B2 references (among other things) [wbA]AnotherSheet!A1:B2 - confirmFormula(wbB, 0, 1, 1, "SUM([multibookFormulaA.xls]AnotherSheet!$A$1:$B$2)+B3"); - - cell = aSheet1.getRow(1).getCell(0); - confirmEvaluation(264, evaluatorA, cell); - - // change [wbB]BSheet1!B3 (from 50 to 60) - HSSFCell cellB3 = bSheet1.getRow(2).getCell(1); - cellB3.setCellValue(60); - evaluatorB.notifyUpdateCell(cellB3); - confirmEvaluation(274, evaluatorA, cell); - - // change [wbA]ASheet1!A3 (from 100 to 80) - HSSFCell cellA3 = aSheet1.getRow(2).getCell(0); - cellA3.setCellValue(80); - evaluatorA.notifyUpdateCell(cellA3); - confirmEvaluation(234, evaluatorA, cell); - - // change [wbA]AnotherSheet!A1 (from 2 to 3) - HSSFCell cellA1 = wbA.getSheetAt(1).getRow(0).getCell(0); - cellA1.setCellValue(3); - evaluatorA.notifyUpdateCell(cellA1); - confirmEvaluation(235, evaluatorA, cell); - } - - private static void confirmEvaluation(double expectedValue, HSSFFormulaEvaluator fe, HSSFCell cell) { - assertEquals(expectedValue, fe.evaluate(cell).getNumberValue(), 0.0); - } - - private static void confirmFormula(HSSFWorkbook wb, int sheetIndex, int rowIndex, int columnIndex, - String expectedFormula) { - HSSFCell cell = wb.getSheetAt(sheetIndex).getRow(rowIndex).getCell(columnIndex); - assertEquals(expectedFormula, cell.getCellFormula()); - } - - /** - * This test makes sure that any {@link MissingArgEval} that propagates to - * the result of a function gets translated to {@link BlankEval}. - */ - @Test - void testMissingArg() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("1+IF(1,,)"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - assertDoesNotThrow(() -> fe.evaluate(cell), "Missing arg result not being handled correctly."); - - CellValue cv = fe.evaluate(cell); - assertEquals(CellType.NUMERIC, cv.getCellType()); - // adding blank to 1.0 gives 1.0 - assertEquals(1.0, cv.getNumberValue(), 0.0); - - // check with string operand - cell.setCellFormula("\"abc\"&IF(1,,)"); - fe.notifySetFormula(cell); - cv = fe.evaluate(cell); - assertEquals(CellType.STRING, cv.getCellType()); - // adding blank to "abc" gives "abc" - assertEquals("abc", cv.getStringValue()); - - // check CHOOSE() - cell.setCellFormula("\"abc\"&CHOOSE(2,5,,9)"); - fe.notifySetFormula(cell); - cv = fe.evaluate(cell); - assertEquals(CellType.STRING, cv.getCellType()); - // adding blank to "abc" gives "abc" - assertEquals("abc", cv.getStringValue()); - } - - /** - * Functions like IF, INDIRECT, INDEX, OFFSET etc can return AreaEvals which - * should be dereferenced by the evaluator - */ - @Test - void testResultOutsideRange() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Cell cell = wb.createSheet("Sheet1").createRow(0).createCell(0); - cell.setCellFormula("D2:D5"); // IF(TRUE,D2:D5,D2) or OFFSET(D2:D5,0,0) would work too - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cv; - try { - cv = fe.evaluate(cell); - } catch (IllegalArgumentException e) { - if ("Specified row index (0) is outside the allowed range (1..4)".equals(e.getMessage())) { - fail("Identified bug in result dereferencing"); - } - throw new RuntimeException(e); - } - assertEquals(CellType.ERROR, cv.getCellType()); - assertEquals(ErrorEval.VALUE_INVALID.getErrorCode(), cv.getErrorValue()); - - // verify circular refs are still detected properly - fe.clearAllCachedResultValues(); - cell.setCellFormula("OFFSET(A1,0,0)"); - cv = fe.evaluate(cell); - assertEquals(CellType.ERROR, cv.getCellType()); - assertEquals(ErrorEval.CIRCULAR_REF_ERROR.getErrorCode(), cv.getErrorValue()); - } - } - - - /** - * formulas with defined names. - */ - @Test - void testNamesInFormulas() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - - Name name1 = wb.createName(); - name1.setNameName("aConstant"); - name1.setRefersToFormula("3.14"); - - Name name2 = wb.createName(); - name2.setNameName("aFormula"); - name2.setRefersToFormula("SUM(Sheet1!$A$1:$A$3)"); - - Name name3 = wb.createName(); - name3.setNameName("aSet"); - name3.setRefersToFormula("Sheet1!$A$2:$A$4"); - - Name name4 = wb.createName(); - name4.setNameName("offsetFormula"); - name4.setRefersToFormula("OFFSET(Sheet1!$A$1:$A$4,2,0,2,1)"); - - Name name5 = wb.createName(); - name5.setNameName("rowFormula"); - name5.setRefersToFormula("ROW()"); - - Row row0 = sheet.createRow(0); - Row row1 = sheet.createRow(1); - Row row2 = sheet.createRow(2); - Row row3 = sheet.createRow(3); - Row row4 = sheet.createRow(4); - Row row5 = sheet.createRow(5); - - row0.createCell(0).setCellValue(2); - row1.createCell(0).setCellValue(5); - row2.createCell(0).setCellValue(3); - row3.createCell(0).setCellValue(7); - - row0.createCell(2).setCellFormula("aConstant"); - row1.createCell(2).setCellFormula("aFormula"); - row2.createCell(2).setCellFormula("SUM(aSet)"); - row3.createCell(2).setCellFormula("aConstant+aFormula+SUM(aSet)"); - row4.createCell(2).setCellFormula("SUM(offsetFormula)"); - row5.createCell(2).setCellFormula("rowFormula"); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals(3.14, fe.evaluate(row0.getCell(2)).getNumberValue(), EPSILON); - assertEquals(10.0, fe.evaluate(row1.getCell(2)).getNumberValue(), EPSILON); - assertEquals(15.0, fe.evaluate(row2.getCell(2)).getNumberValue(), EPSILON); - assertEquals(28.14, fe.evaluate(row3.getCell(2)).getNumberValue(), EPSILON); - assertEquals(10.0, fe.evaluate(row4.getCell(2)).getNumberValue(), EPSILON); - assertEquals(6.0, fe.evaluate(row5.getCell(2)).getNumberValue(), EPSILON); - - wb.close(); - } - - @Test - void testIgnoreMissingWorkbooks() { - // TODO: update this test for meaningful functional behavior - WorkbookEvaluator evaluator = new WorkbookEvaluator(null, null, null); - assertFalse(evaluator.isIgnoreMissingWorkbooks()); - - evaluator.setIgnoreMissingWorkbooks(true); - assertTrue(evaluator.isIgnoreMissingWorkbooks()); - - evaluator.setIgnoreMissingWorkbooks(false); - assertFalse(evaluator.isIgnoreMissingWorkbooks()); - } - - @Test - void testDebugEvaluationOutputForNextEval() { - // TODO: update this test for meaningful functional behavior - WorkbookEvaluator evaluator = new WorkbookEvaluator(null, null, null); - assertFalse(evaluator.isDebugEvaluationOutputForNextEval()); - - evaluator.setDebugEvaluationOutputForNextEval(true); - assertTrue(evaluator.isDebugEvaluationOutputForNextEval()); - - evaluator.setDebugEvaluationOutputForNextEval(false); - assertFalse(evaluator.isDebugEvaluationOutputForNextEval()); - } - -// Test IF-Equals Formula Evaluation (bug 58591) - - private Workbook testIFEqualsFormulaEvaluation_setup(String formula, CellType a1CellType) { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("IFEquals"); - Row row = sheet.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - Cell C1 = row.createCell(2); - Cell D1 = row.createCell(3); - - switch (a1CellType) { - case NUMERIC: - A1.setCellValue(1.0); - // "A1=1" should return true - break; - case STRING: - A1.setCellValue("1"); - // "A1=1" should return false - // "A1=\"1\"" should return true - break; - case BOOLEAN: - A1.setCellValue(true); - // "A1=1" should return true - break; - case FORMULA: - A1.setCellFormula("1"); - // "A1=1" should return true - break; - case BLANK: - A1.setCellValue((String) null); - // "A1=1" should return false - break; - default: - throw new IllegalArgumentException("unexpected cell type: " + a1CellType); - } - B1.setCellValue(2.0); - C1.setCellValue(3.0); - D1.setCellFormula(formula); - - return wb; - } - - private void testIFEqualsFormulaEvaluation_teardown(Workbook wb) { - assertDoesNotThrow(wb::close, "Unable to close workbook"); - } - - - - private void testIFEqualsFormulaEvaluation_evaluate( - String formula, CellType cellType, String expectedFormula, double expectedResult) { - Workbook wb = testIFEqualsFormulaEvaluation_setup(formula, cellType); - Cell D1 = wb.getSheet("IFEquals").getRow(0).getCell(3); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - CellValue result = eval.evaluate(D1); - - // Call should not modify the contents - assertEquals(CellType.FORMULA, D1.getCellType()); - assertEquals(expectedFormula, D1.getCellFormula()); - - assertEquals(CellType.NUMERIC, result.getCellType()); - assertEquals(expectedResult, result.getNumberValue(), EPSILON); - - testIFEqualsFormulaEvaluation_teardown(wb); - } - - private void testIFEqualsFormulaEvaluation_eval( - final String formula, final CellType cellType, final String expectedFormula, final double expectedValue) { - testIFEqualsFormulaEvaluation_evaluate(formula, cellType, expectedFormula, expectedValue); - testIFEqualsFormulaEvaluation_evaluateFormulaCell(formula, cellType, expectedFormula, expectedValue); - testIFEqualsFormulaEvaluation_evaluateInCell(formula, cellType, expectedValue); - testIFEqualsFormulaEvaluation_evaluateAll(formula, cellType, expectedFormula, expectedValue); - testIFEqualsFormulaEvaluation_evaluateAllFormulaCells(formula, cellType, expectedFormula, expectedValue); - } - - @Test - void testIFEqualsFormulaEvaluation_NumericLiteral() { - final String formula = "IF(A1=1, 2, 3)"; - final CellType cellType = CellType.NUMERIC; - final String expectedFormula = "IF(A1=1,2,3)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - void testIFEqualsFormulaEvaluation_Numeric() { - final String formula = "IF(A1=1, B1, C1)"; - final CellType cellType = CellType.NUMERIC; - final String expectedFormula = "IF(A1=1,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - void testIFEqualsFormulaEvaluation_NumericCoerceToString() { - final String formula = "IF(A1&\"\"=\"1\", B1, C1)"; - final CellType cellType = CellType.NUMERIC; - final String expectedFormula = "IF(A1&\"\"=\"1\",B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - void testIFEqualsFormulaEvaluation_String() { - final String formula = "IF(A1=1, B1, C1)"; - final CellType cellType = CellType.STRING; - final String expectedFormula = "IF(A1=1,B1,C1)"; - final double expectedValue = 3.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - void testIFEqualsFormulaEvaluation_StringCompareToString() { - final String formula = "IF(A1=\"1\", B1, C1)"; - final CellType cellType = CellType.STRING; - final String expectedFormula = "IF(A1=\"1\",B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - void testIFEqualsFormulaEvaluation_StringCoerceToNumeric() { - final String formula = "IF(A1+0=1, B1, C1)"; - final CellType cellType = CellType.STRING; - final String expectedFormula = "IF(A1+0=1,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Disabled("Bug 58591: this test currently fails") - @Test - void testIFEqualsFormulaEvaluation_Boolean() { - final String formula = "IF(A1=1, B1, C1)"; - final CellType cellType = CellType.BOOLEAN; - final String expectedFormula = "IF(A1=1,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Disabled("Bug 58591: this test currently fails") - @Test - void testIFEqualsFormulaEvaluation_BooleanSimple() { - final String formula = "3-(A1=1)"; - final CellType cellType = CellType.BOOLEAN; - final String expectedFormula = "3-(A1=1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - void testIFEqualsFormulaEvaluation_Formula() { - final String formula = "IF(A1=1, B1, C1)"; - final CellType cellType = CellType.FORMULA; - final String expectedFormula = "IF(A1=1,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - void testIFEqualsFormulaEvaluation_Blank() { - final String formula = "IF(A1=1, B1, C1)"; - final CellType cellType = CellType.BLANK; - final String expectedFormula = "IF(A1=1,B1,C1)"; - final double expectedValue = 3.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - void testIFEqualsFormulaEvaluation_BlankCompareToZero() { - final String formula = "IF(A1=0, B1, C1)"; - final CellType cellType = CellType.BLANK; - final String expectedFormula = "IF(A1=0,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Disabled("Bug 58591: this test currently fails") - @Test - void testIFEqualsFormulaEvaluation_BlankInverted() { - final String formula = "IF(NOT(A1)=1, B1, C1)"; - final CellType cellType = CellType.BLANK; - final String expectedFormula = "IF(NOT(A1)=1,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Disabled("Bug 58591: this test currently fails") - @Test - void testIFEqualsFormulaEvaluation_BlankInvertedSimple() { - final String formula = "3-(NOT(A1)=1)"; - final CellType cellType = CellType.BLANK; - final String expectedFormula = "3-(NOT(A1)=1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - - private void testIFEqualsFormulaEvaluation_evaluateFormulaCell( - String formula, CellType cellType, String expectedFormula, double expectedResult) { - Workbook wb = testIFEqualsFormulaEvaluation_setup(formula, cellType); - Cell D1 = wb.getSheet("IFEquals").getRow(0).getCell(3); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - CellType resultCellType = eval.evaluateFormulaCell(D1); - - // Call should modify the contents, but leave the formula intact - assertEquals(CellType.FORMULA, D1.getCellType()); - assertEquals(expectedFormula, D1.getCellFormula()); - assertEquals(CellType.NUMERIC, resultCellType); - assertEquals(CellType.NUMERIC, D1.getCachedFormulaResultType()); - assertEquals(expectedResult, D1.getNumericCellValue(), EPSILON); - - testIFEqualsFormulaEvaluation_teardown(wb); - } - - private void testIFEqualsFormulaEvaluation_evaluateInCell( - String formula, CellType cellType, double expectedResult) { - Workbook wb = testIFEqualsFormulaEvaluation_setup(formula, cellType); - Cell D1 = wb.getSheet("IFEquals").getRow(0).getCell(3); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - Cell result = eval.evaluateInCell(D1); - - // Call should modify the contents and replace the formula with the result - // returns the same cell that was provided as an argument so that calls can be chained. - assertSame(D1, result); - assertThrows(IllegalStateException.class, D1::getCellFormula, "cell formula should be overwritten with formula result"); - assertEquals(CellType.NUMERIC, D1.getCellType()); - assertEquals(expectedResult, D1.getNumericCellValue(), EPSILON); - - testIFEqualsFormulaEvaluation_teardown(wb); - } - - private void testIFEqualsFormulaEvaluation_evaluateAll( - String formula, CellType cellType, String expectedFormula, double expectedResult) { - Workbook wb = testIFEqualsFormulaEvaluation_setup(formula, cellType); - Cell D1 = wb.getSheet("IFEquals").getRow(0).getCell(3); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - eval.evaluateAll(); - - // Call should modify the contents - assertEquals(CellType.FORMULA, D1.getCellType()); - assertEquals(expectedFormula, D1.getCellFormula()); - - assertEquals(CellType.NUMERIC, D1.getCachedFormulaResultType()); - assertEquals(expectedResult, D1.getNumericCellValue(), EPSILON); - - testIFEqualsFormulaEvaluation_teardown(wb); - } - - private void testIFEqualsFormulaEvaluation_evaluateAllFormulaCells( - String formula, CellType cellType, String expectedFormula, double expectedResult) { - Workbook wb = testIFEqualsFormulaEvaluation_setup(formula, cellType); - Cell D1 = wb.getSheet("IFEquals").getRow(0).getCell(3); - - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - - // Call should modify the contents - assertEquals(CellType.FORMULA, D1.getCellType()); - // whitespace gets deleted because formula is parsed and re-rendered - assertEquals(expectedFormula, D1.getCellFormula()); - - assertEquals(CellType.NUMERIC, D1.getCachedFormulaResultType()); - assertEquals(expectedResult, D1.getNumericCellValue(), EPSILON); - - testIFEqualsFormulaEvaluation_teardown(wb); - } - - @Test - void testRefToBlankCellInArrayFormula() { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cellA1 = row.createCell(0); - Cell cellB1 = row.createCell(1); - Cell cellC1 = row.createCell(2); - Row row2 = sheet.createRow(1); - Cell cellA2 = row2.createCell(0); - Cell cellB2 = row2.createCell(1); - Cell cellC2 = row2.createCell(2); - Row row3 = sheet.createRow(2); - Cell cellA3 = row3.createCell(0); - Cell cellB3 = row3.createCell(1); - Cell cellC3 = row3.createCell(2); - - cellA1.setCellValue("1"); - // cell B1 intentionally left blank - cellC1.setCellValue("3"); - - cellA2.setCellFormula("A1"); - cellB2.setCellFormula("B1"); - cellC2.setCellFormula("C1"); - - sheet.setArrayFormula("A1:C1", CellRangeAddress.valueOf("A3:C3")); - - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - assertEquals(cellA2.getStringCellValue(), "1"); - assertEquals(cellB2.getNumericCellValue(),0, 0.00001); - assertEquals(cellC2.getStringCellValue(),"3"); - - assertEquals(cellA3.getStringCellValue(), "1"); - assertEquals(cellB3.getNumericCellValue(),0, 0.00001); - assertEquals(cellC3.getStringCellValue(),"3"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/WorkbookEvaluatorTestHelper.java b/src/testcases/org/apache/poi/ss/formula/WorkbookEvaluatorTestHelper.java deleted file mode 100644 index 673cb9500c..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/WorkbookEvaluatorTestHelper.java +++ /dev/null @@ -1,37 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Allows tests to execute {@link WorkbookEvaluator}s and track the internal workings. - * - * @author Josh Micich - */ -public final class WorkbookEvaluatorTestHelper { - - private WorkbookEvaluatorTestHelper() { - // no instances of this class - } - - public static WorkbookEvaluator createEvaluator(HSSFWorkbook wb, EvaluationListener listener) { - return new WorkbookEvaluator(HSSFEvaluationWorkbook.create(wb), listener, null, null); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestIfError.java b/src/testcases/org/apache/poi/ss/formula/atp/TestIfError.java deleted file mode 100644 index 8214390798..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestIfError.java +++ /dev/null @@ -1,98 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.atp; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; - -/** - * Testcase for 'Analysis Toolpak' function IFERROR() - */ -class TestIfError { - - /** - * =IFERROR(210/35,\"Error in calculation\")" Divides 210 by 35 and returns 6.0 - * =IFERROR(55/0,\"Error in calculation\")" Divides 55 by 0 and returns the error text - * =IFERROR(C1,\"Error in calculation\")" References the result of dividing 55 by 0 and returns the error text - */ - @Test - void testEvaluate() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sh = wb.createSheet(); - Row row1 = sh.createRow(0); - Row row2 = sh.createRow(1); - - // Create cells - row1.createCell(0, CellType.NUMERIC); - row1.createCell(1, CellType.NUMERIC); - row1.createCell(2, CellType.NUMERIC); - row2.createCell(0, CellType.NUMERIC); - row2.createCell(1, CellType.NUMERIC); - - // Create references - CellReference a1 = new CellReference("A1"); - CellReference a2 = new CellReference("A2"); - CellReference b1 = new CellReference("B1"); - CellReference b2 = new CellReference("B2"); - CellReference c1 = new CellReference("C1"); - - // Set values - sh.getRow(a1.getRow()).getCell(a1.getCol()).setCellValue(210); - sh.getRow(a2.getRow()).getCell(a2.getCol()).setCellValue(55); - sh.getRow(b1.getRow()).getCell(b1.getCol()).setCellValue(35); - sh.getRow(b2.getRow()).getCell(b2.getCol()).setCellValue(0); - sh.getRow(c1.getRow()).getCell(c1.getCol()).setCellFormula("A1/B2"); - - Cell cell1 = sh.createRow(3).createCell(0); - cell1.setCellFormula("IFERROR(A1/B1,\"Error in calculation\")"); - Cell cell2 = sh.createRow(3).createCell(0); - cell2.setCellFormula("IFERROR(A2/B2,\"Error in calculation\")"); - Cell cell3 = sh.createRow(3).createCell(0); - cell3.setCellFormula("IFERROR(C1,\"error\")"); - - double accuracy = 1E-9; - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - assertEquals(CellType.NUMERIC, evaluator.evaluate(cell1).getCellType(), - "Checks that the cell is numeric"); - assertEquals(6.0, evaluator.evaluate(cell1).getNumberValue(), accuracy, - "Divides 210 by 35 and returns 6.0"); - - assertEquals(CellType.STRING, evaluator.evaluate(cell2).getCellType(), - "Checks that the cell is numeric"); - assertEquals("Error in calculation", evaluator.evaluate(cell2).getStringValue(), - "Rounds -10 to a nearest multiple of -3 (-9)"); - - assertEquals(CellType.STRING, evaluator.evaluate(cell3).getCellType(), - "Check that C1 returns string"); - assertEquals("error", evaluator.evaluate(cell3).getStringValue(), - "Check that C1 returns string \"error\""); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestMRound.java b/src/testcases/org/apache/poi/ss/formula/atp/TestMRound.java deleted file mode 100644 index 2e99276f7f..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestMRound.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.atp; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Testcase for 'Analysis Toolpak' function MROUND() - */ -class TestMRound { - - /** - =MROUND(10, 3) Rounds 10 to a nearest multiple of 3 (9) - =MROUND(-10, -3) Rounds -10 to a nearest multiple of -3 (-9) - =MROUND(1.3, 0.2) Rounds 1.3 to a nearest multiple of 0.2 (1.4) - =MROUND(5, -2) Returns an error, because -2 and 5 have different signs (#NUM!) * - */ - @Test - void testEvaluate(){ - Workbook wb = new HSSFWorkbook(); - Sheet sh = wb.createSheet(); - Cell cell1 = sh.createRow(0).createCell(0); - cell1.setCellFormula("MROUND(10, 3)"); - Cell cell2 = sh.createRow(0).createCell(0); - cell2.setCellFormula("MROUND(-10, -3)"); - Cell cell3 = sh.createRow(0).createCell(0); - cell3.setCellFormula("MROUND(1.3, 0.2)"); - Cell cell4 = sh.createRow(0).createCell(0); - cell4.setCellFormula("MROUND(5, -2)"); - Cell cell5 = sh.createRow(0).createCell(0); - cell5.setCellFormula("MROUND(5, 0)"); - - double accuracy = 1E-9; - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - assertEquals(9.0, evaluator.evaluate(cell1).getNumberValue(), accuracy, - "Rounds 10 to a nearest multiple of 3 (9)"); - - assertEquals(-9.0, evaluator.evaluate(cell2).getNumberValue(), accuracy, - "Rounds -10 to a nearest multiple of -3 (-9)"); - - assertEquals(1.4, evaluator.evaluate(cell3).getNumberValue(), accuracy, - "Rounds 1.3 to a nearest multiple of 0.2 (1.4)"); - - assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), evaluator.evaluate(cell4).getErrorValue(), - "Returns an error, because -2 and 5 have different signs (#NUM!)"); - - assertEquals(0.0, evaluator.evaluate(cell5).getNumberValue(), 0, - "Returns 0 because the multiple is 0"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java b/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java deleted file mode 100644 index 7ee0476b3c..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java +++ /dev/null @@ -1,134 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.atp; - -import static org.apache.poi.ss.formula.eval.ErrorEval.NAME_INVALID; -import static org.apache.poi.ss.formula.eval.ErrorEval.VALUE_INVALID; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.TwoDEval; -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.AreaEvalBase; -import org.apache.poi.ss.formula.eval.NumericValueEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -class TestNetworkdaysFunction { - - private static final String STARTING_DATE = "2008/10/01"; - private static final String END_DATE = "2009/03/01"; - private static final String FIRST_HOLIDAY = "2008/11/26"; - private static final String SECOND_HOLIDAY = "2008/12/04"; - private static final String THIRD_HOLIDAY = "2009/01/21"; - - private static final OperationEvaluationContext EC = new OperationEvaluationContext(null, null, 1, 1, 1, null); - - @Test - void testFailWhenNoArguments() { - assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[0], null)); - } - - @Test - void testFailWhenLessThan2Arguments() { - assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[1], null)); - } - - @Test - void testFailWhenMoreThan3Arguments() { - assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[4], null)); - } - - @Test - void testFailWhenArgumentsAreNotDates() { - assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[]{ new StringEval("Potato"), - new StringEval("Cucumber") }, EC)); - } - - @Test - void testFailWhenStartDateAfterEndDate() { - assertEquals(NAME_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[]{ new StringEval(END_DATE), - new StringEval(STARTING_DATE) }, EC)); - } - - @Test - void testReturnNetworkdays() { - assertEquals(108, (int) ((NumericValueEval) NetworkdaysFunction.instance.evaluate(new ValueEval[]{ - new StringEval(STARTING_DATE), new StringEval(END_DATE) }, EC)).getNumberValue()); - } - - @Test - void testReturnNetworkdaysWithAHoliday() { - assertEquals(107, (int) ((NumericValueEval) NetworkdaysFunction.instance.evaluate(new ValueEval[]{ - new StringEval(STARTING_DATE), new StringEval(END_DATE), new StringEval(FIRST_HOLIDAY) }, - EC)).getNumberValue()); - } - - @Test - void testReturnNetworkdaysWithManyHolidays() { - assertEquals(105, (int) ((NumericValueEval) NetworkdaysFunction.instance.evaluate(new ValueEval[]{ - new StringEval(STARTING_DATE), new StringEval(END_DATE), - new MockAreaEval(FIRST_HOLIDAY, SECOND_HOLIDAY, THIRD_HOLIDAY)}, EC)).getNumberValue()); - } - - private static class MockAreaEval extends AreaEvalBase { - - private List holidays; - - public MockAreaEval(String... holidays) { - this(0, 0, 0, holidays.length - 1); - this.holidays = new ArrayList<>(); - for (String holiday : holidays) { - this.holidays.add(new StringEval(holiday)); - } - } - - protected MockAreaEval(int firstRow, int firstColumn, int lastRow, int lastColumn) { - super(firstRow, firstColumn, lastRow, lastColumn); - } - - @Override - public ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex) { - return this.holidays.get(relativeColumnIndex); - } - @Override - public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) { - return getRelativeValue(-1, relativeRowIndex, relativeColumnIndex); - } - - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { - return null; - } - - @Override - public TwoDEval getColumn(int columnIndex) { - return null; - } - - @Override - public TwoDEval getRow(int rowIndex) { - return null; - } - - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java b/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java deleted file mode 100644 index 9af99fb0ee..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.atp; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.AggregateFunction; -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.junit.jupiter.api.Test; - -/** - * Testcase for Excel function PERCENTILE() - */ -class TestPercentile { - - private static ValueEval invokePercentile(ValueEval[] args, ValueEval percentile) { - AreaEval aeA = EvalFactory.createAreaEval("A1:A" + args.length, args); - ValueEval[] args2 = { aeA, percentile }; - return AggregateFunction.PERCENTILE.evaluate(args2, -1, -1); - } - - private void confirmPercentile(ValueEval percentile, ValueEval[] args, double expected) { - ValueEval result = invokePercentile(args, percentile); - assertEquals(NumberEval.class, result.getClass()); - double delta = 0.00000001; - assertEquals(expected, ((NumberEval) result).getNumberValue(), delta); - } - - private void confirmPercentile(ValueEval percentile, ValueEval[] args, ErrorEval expectedError) { - ValueEval result = invokePercentile(args, percentile); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval) result).getErrorCode()); - } - - @Test - void testBasic() { - ValueEval[] values = { new NumberEval(210.128), new NumberEval(65.2182), new NumberEval(32.231), - new NumberEval(12.123), new NumberEval(45.32) }; - ValueEval percentile = new NumberEval(0.95); - confirmPercentile(percentile, values, 181.14604); - } - - @Test - void testBlanks() { - ValueEval[] values = { new NumberEval(210.128), new NumberEval(65.2182), new NumberEval(32.231), - BlankEval.instance, new NumberEval(45.32) }; - ValueEval percentile = new NumberEval(0.95); - confirmPercentile(percentile, values, 188.39153); - } - - @Test - void testUnusualArgs() { - ValueEval[] values = { new NumberEval(1), new NumberEval(2), BoolEval.TRUE, BoolEval.FALSE }; - ValueEval percentile = new NumberEval(0.95); - confirmPercentile(percentile, values, 1.95); - } - - //percentile has to be between 0 and 1 - here we test less than zero - @Test - void testUnusualArgs2() { - ValueEval[] values = { new NumberEval(1), new NumberEval(2), }; - ValueEval percentile = new NumberEval(-0.1); - confirmPercentile(percentile, values, ErrorEval.NUM_ERROR); - } - - //percentile has to be between 0 and 1 - here we test more than 1 - @Test - void testUnusualArgs3() { - ValueEval[] values = { new NumberEval(1), new NumberEval(2) }; - ValueEval percentile = new NumberEval(1.1); - confirmPercentile(percentile, values, ErrorEval.NUM_ERROR); - } - - //here we test where there are errors as part of inputs - @Test - void testErrors() { - ValueEval[] values = { new NumberEval(1), ErrorEval.NAME_INVALID, new NumberEval(3), ErrorEval.DIV_ZERO, }; - ValueEval percentile = new NumberEval(0.95); - confirmPercentile(percentile, values, ErrorEval.NAME_INVALID); - } - - //here we test where there are errors as part of inputs - @Test - void testErrors2() { - ValueEval[] values = { new NumberEval(1), new NumberEval(2), new NumberEval(3), ErrorEval.DIV_ZERO, }; - ValueEval percentile = new NumberEval(0.95); - confirmPercentile(percentile, values, ErrorEval.DIV_ZERO); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java b/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java deleted file mode 100644 index 83d54ef446..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java +++ /dev/null @@ -1,196 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.atp; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Testcase for 'Analysis Toolpak' function RANDBETWEEN() - */ -class TestRandBetween { - - private FormulaEvaluator evaluator; - private Cell bottomValueCell; - private Cell topValueCell; - private Cell formulaCell; - - @BeforeEach - void setUp() { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("TestRandBetween.xls"); - evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sheet = wb.createSheet("RandBetweenSheet"); - Row row = sheet.createRow(0); - bottomValueCell = row.createCell(0); - topValueCell = row.createCell(1); - formulaCell = row.createCell(2, CellType.FORMULA); - } - - /** - * Check where values are the same - */ - @Test - void testRandBetweenSameValues() { - evaluator.clearAllCachedResultValues(); - formulaCell.setCellFormula("RANDBETWEEN(1,1)"); - evaluator.evaluateFormulaCell(formulaCell); - assertEquals(1, formulaCell.getNumericCellValue(), 0); - evaluator.clearAllCachedResultValues(); - formulaCell.setCellFormula("RANDBETWEEN(-1,-1)"); - evaluator.evaluateFormulaCell(formulaCell); - assertEquals(-1, formulaCell.getNumericCellValue(), 0); - - } - - @Test - void testRandBetweenLargeLongs() { - for (int i = 0; i < 100; i++) { - evaluator.clearAllCachedResultValues(); - formulaCell.setCellFormula("RANDBETWEEN(0,9999999999)"); - evaluator.evaluateFormulaCell(formulaCell); - double value = formulaCell.getNumericCellValue(); - assertTrue(value >= 0.0, "rand is greater than or equal to lowerbound"); - assertTrue(value <= 9999999999.0, "rand is less than or equal to upperbound"); - } - } - - /** - * Check special case where rounded up bottom value is greater than - * top value. - */ - @Test - void testRandBetweenSpecialCase() { - bottomValueCell.setCellValue(0.05); - topValueCell.setCellValue(0.1); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCell(formulaCell); - assertEquals(1, formulaCell.getNumericCellValue(), 0); - bottomValueCell.setCellValue(-0.1); - topValueCell.setCellValue(-0.05); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCell(formulaCell); - assertEquals(0, formulaCell.getNumericCellValue(), 0); - bottomValueCell.setCellValue(-1.1); - topValueCell.setCellValue(-1.05); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCell(formulaCell); - assertEquals(-1, formulaCell.getNumericCellValue(), 0); - bottomValueCell.setCellValue(-1.1); - topValueCell.setCellValue(-1.1); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCell(formulaCell); - assertEquals(-1, formulaCell.getNumericCellValue(), 0); - } - - /** - * Check top value of BLANK which Excel will evaluate as 0 - */ - @Test - void testRandBetweenTopBlank() { - bottomValueCell.setCellValue(-1); - topValueCell.setBlank(); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCell(formulaCell); - assertTrue(formulaCell.getNumericCellValue() == 0 || formulaCell.getNumericCellValue() == -1); - - } - /** - * Check where input values are of wrong type - */ - @Test - void testRandBetweenWrongInputTypes() { - // Check case where bottom input is of the wrong type - bottomValueCell.setCellValue("STRING"); - topValueCell.setCellValue(1); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCell(formulaCell); - assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultType()); - assertEquals(ErrorEval.VALUE_INVALID.getErrorCode(), formulaCell.getErrorCellValue()); - - - // Check case where top input is of the wrong type - bottomValueCell.setCellValue(1); - topValueCell.setCellValue("STRING"); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCell(formulaCell); - assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultType()); - assertEquals(ErrorEval.VALUE_INVALID.getErrorCode(), formulaCell.getErrorCellValue()); - - // Check case where both inputs are of wrong type - bottomValueCell.setCellValue("STRING"); - topValueCell.setCellValue("STRING"); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCell(formulaCell); - assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultType()); - assertEquals(ErrorEval.VALUE_INVALID.getErrorCode(), formulaCell.getErrorCellValue()); - } - - /** - * Check case where bottom is greater than top - */ - @Test - void testRandBetweenBottomGreaterThanTop() { - // Check case where bottom is greater than top - bottomValueCell.setCellValue(1); - topValueCell.setCellValue(0); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCell(formulaCell); - assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultType()); - assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), formulaCell.getErrorCellValue()); - bottomValueCell.setCellValue(1); - topValueCell.setBlank(); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCell(formulaCell); - assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultType()); - assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), formulaCell.getErrorCellValue()); - } - - /** - * Boundary check of Double MIN and MAX values - */ - @Test - void testRandBetweenBoundaryCheck() { - bottomValueCell.setCellValue(Double.MIN_VALUE); - topValueCell.setCellValue(Double.MAX_VALUE); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCell(formulaCell); - assertTrue(formulaCell.getNumericCellValue() >= Double.MIN_VALUE && formulaCell.getNumericCellValue() <= Double.MAX_VALUE); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java b/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java deleted file mode 100644 index 598b3119b7..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java +++ /dev/null @@ -1,154 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.atp; - -import static java.util.Calendar.SATURDAY; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -class TestWorkdayCalculator { - - @Test - void testCalculateWorkdaysShouldReturnJustWeekdaysWhenNoWeekend() { - final double A_MONDAY = DateUtil.getExcelDate(d(2011, 12, 12)); - final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 16)); - assertEquals(5, WorkdayCalculator.instance.calculateWorkdays(A_MONDAY, A_FRIDAY, new double[0])); - } - - @Test - void testCalculateWorkdaysShouldReturnAllDaysButNoSaturdays() { - final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 14)); - final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 18)); - assertEquals(3, WorkdayCalculator.instance.calculateWorkdays(A_WEDNESDAY, A_SATURDAY, new double[0])); - } - - @Test - void testCalculateWorkdaysShouldReturnAllDaysButNoSundays() { - final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 11)); - final double A_THURSDAY = DateUtil.getExcelDate(d(2011, 12, 15)); - assertEquals(4, WorkdayCalculator.instance.calculateWorkdays(A_SUNDAY, A_THURSDAY, new double[0])); - } - - @Test - void testCalculateWorkdaysShouldReturnAllDaysButNoHolidays() { - final double A_MONDAY = DateUtil.getExcelDate(d(2011, 12, 12)); - final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 16)); - final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 14)); - assertEquals(4, WorkdayCalculator.instance.calculateWorkdays(A_MONDAY, A_FRIDAY, new double[]{ A_WEDNESDAY })); - } - - @Test - void testCalculateWorkdaysShouldIgnoreWeekendHolidays() { - final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 16)); - final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 17)); - final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 18)); - final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 21)); - assertEquals(4, WorkdayCalculator.instance.calculateWorkdays(A_FRIDAY, A_WEDNESDAY, new double[]{ A_SATURDAY, A_SUNDAY })); - } - - @Test - void testCalculateWorkdaysOnSameDayShouldReturn1ForWeekdays() { - final double A_MONDAY = DateUtil.getExcelDate(d(2017, 1, 2)); - assertEquals(1, WorkdayCalculator.instance.calculateWorkdays(A_MONDAY, A_MONDAY, new double[0])); - } - - @Test - void testCalculateWorkdaysOnSameDayShouldReturn0ForHolidays() { - final double A_MONDAY = DateUtil.getExcelDate(d(2017, 1, 2)); - assertEquals(0, WorkdayCalculator.instance.calculateWorkdays(A_MONDAY, A_MONDAY, new double[]{ A_MONDAY })); - } - - @Test - void testCalculateWorkdaysOnSameDayShouldReturn0ForWeekends() { - final double A_SUNDAY = DateUtil.getExcelDate(d(2017, 1, 1)); - assertEquals(0, WorkdayCalculator.instance.calculateWorkdays(A_SUNDAY, A_SUNDAY, new double[0])); - } - - @Test - void testCalculateWorkdaysNumberOfDays() { - double start = 41553.0; - int days = 1; - assertEquals(d(2013, 10, 7), WorkdayCalculator.instance.calculateWorkdays(start, days, new double[0])); - } - - @Test - void testPastDaysOfWeekShouldReturn0Past0Saturdays() { - final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 7)); - final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 9)); - assertEquals(0, WorkdayCalculator.instance.pastDaysOfWeek(A_WEDNESDAY, A_FRIDAY, SATURDAY)); - } - - @Test - void testPastDaysOfWeekShouldReturn1Past1Saturdays() { - final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 7)); - final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 11)); - assertEquals(1, WorkdayCalculator.instance.pastDaysOfWeek(A_WEDNESDAY, A_SUNDAY, SATURDAY)); - } - - @Test - void testPastDaysOfWeekShouldReturn2Past2Saturdays() { - final double A_THURSDAY = DateUtil.getExcelDate(d(2011, 12, 8)); - final double A_MONDAY = DateUtil.getExcelDate(d(2011, 12, 19)); - assertEquals(2, WorkdayCalculator.instance.pastDaysOfWeek(A_THURSDAY, A_MONDAY, SATURDAY)); - } - - @Test - void testPastDaysOfWeekShouldReturn1BeginningFromASaturday() { - final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 10)); - final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 11)); - assertEquals(1, WorkdayCalculator.instance.pastDaysOfWeek(A_SATURDAY, A_SUNDAY, SATURDAY)); - } - - @Test - void testPastDaysOfWeekShouldReturn1EndingAtASaturday() { - final double A_THURSDAY = DateUtil.getExcelDate(d(2011, 12, 8)); - final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 10)); - assertEquals(1, WorkdayCalculator.instance.pastDaysOfWeek(A_THURSDAY, A_SATURDAY, SATURDAY)); - } - - private static Date d(int year, int month, int day) { - Calendar cal = LocaleUtil.getLocaleCalendar(year, month-1, day, 0, 0, 0); - return cal.getTime(); - } - - @Test - void testCalculateNonWeekendHolidays() { - final double start = DateUtil.getExcelDate(d(2016, 12, 24)); - final double end = DateUtil.getExcelDate(d(2016, 12, 31)); - final double holiday1 = DateUtil.getExcelDate(d(2016, 12, 25)); - final double holiday2 = DateUtil.getExcelDate(d(2016, 12, 26)); - int count = WorkdayCalculator.instance.calculateNonWeekendHolidays(start, end, new double[]{holiday1, holiday2}); - assertEquals(1, count, "Expected 1 non-weekend-holiday for " + start + " to " + end + " and " + holiday1 + " and " + holiday2); - } - - @Test - void testCalculateNonWeekendHolidaysOneDay() { - final double start = DateUtil.getExcelDate(d(2016, 12, 26)); - final double end = DateUtil.getExcelDate(d(2016, 12, 26)); - final double holiday1 = DateUtil.getExcelDate(d(2016, 12, 25)); - final double holiday2 = DateUtil.getExcelDate(d(2016, 12, 26)); - int count = WorkdayCalculator.instance.calculateNonWeekendHolidays(start, end, new double[]{holiday1, holiday2}); - assertEquals(1, count, "Expected 1 non-weekend-holiday for " + start + " to " + end + " and " + holiday1 + " and " + holiday2); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java b/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java deleted file mode 100644 index e2e73bad04..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java +++ /dev/null @@ -1,215 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.ss.formula.atp; - - -import static org.apache.poi.ss.formula.eval.ErrorEval.VALUE_INVALID; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.TwoDEval; -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.AreaEvalBase; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -class TestWorkdayFunction { - - private static final String STARTING_DATE = "2008/10/01"; - private static final String FIRST_HOLIDAY = "2008/11/26"; - private static final String SECOND_HOLIDAY = "2008/12/04"; - private static final String THIRD_HOLIDAY = "2009/01/21"; - private static final String RETROATIVE_HOLIDAY = "2008/09/29"; - - private static final OperationEvaluationContext EC = new OperationEvaluationContext(null, null, 1, 1, 1, null); - - @Test - void testFailWhenNoArguments() { - ValueEval[] ve = new ValueEval[0]; - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, null)); - } - - @Test - void testFailWhenLessThan2Arguments() { - ValueEval[] ve = new ValueEval[1]; - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, null)); - } - - @Test - void testFailWhenMoreThan3Arguments() { - ValueEval[] ve = new ValueEval[4]; - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, null)); - } - - @Test - void testFailWhenArgumentsAreNotDatesNorNumbers() { - ValueEval[] ve = {new StringEval("Potato"), new StringEval("Cucumber")}; - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, EC)); - } - - @Test - void testReturnWorkdays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2009, 3, 30); - Date expDate = expCal.getTime(); - ValueEval[] ve = {new StringEval(STARTING_DATE), new NumberEval(151)}; - Date actDate = DateUtil.getJavaDate(((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue()); - assertEquals(expDate, actDate); - } - - @Test - void testReturnWorkdaysSpanningAWeekendSubtractingDays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 8, 27); - Date expDate = expCal.getTime(); - - ValueEval[] ve = {new StringEval("2013/09/30"), new NumberEval(-1)}; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - assertEquals(41544.0, numberValue, 0); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - void testReturnWorkdaysSpanningAWeekendAddingDays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 8, 30); - Date expDate = expCal.getTime(); - - ValueEval[] ve = {new StringEval("2013/09/27"), new NumberEval(1)}; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - assertEquals(41547.0, numberValue, 0); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - void testReturnWorkdaysWhenStartIsWeekendAddingDays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 9, 7); - Date expDate = expCal.getTime(); - - ValueEval[] ve = {new StringEval("2013/10/06"), new NumberEval(1)}; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - assertEquals(41554.0, numberValue, 0); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - void testReturnWorkdaysWhenStartIsWeekendSubtractingDays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 9, 4); - Date expDate = expCal.getTime(); - - ValueEval[] ve = {new StringEval("2013/10/06"), new NumberEval(-1)}; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - assertEquals(41551.0, numberValue, 0); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - void testReturnWorkdaysWithDaysTruncated() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2009, 3, 30); - Date expDate = expCal.getTime(); - - ValueEval[] ve = {new StringEval(STARTING_DATE), new NumberEval(151.99999)}; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - void testReturnRetroativeWorkday() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2008, 8, 23); - Date expDate = expCal.getTime(); - - ValueEval[] ve = {new StringEval(STARTING_DATE), new NumberEval(-5), new StringEval(RETROATIVE_HOLIDAY)}; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - void testReturnNetworkdaysWithManyHolidays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2009, 4, 5); - Date expDate = expCal.getTime(); - - ValueEval[] ve = { - new StringEval(STARTING_DATE), new NumberEval(151), - new MockAreaEval(FIRST_HOLIDAY, SECOND_HOLIDAY, THIRD_HOLIDAY)}; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - private class MockAreaEval extends AreaEvalBase { - - private List holidays; - - public MockAreaEval(String... holidays) { - this(0, 0, 0, holidays.length - 1); - this.holidays = new ArrayList<>(); - for (String holiday : holidays) { - this.holidays.add(new StringEval(holiday)); - } - } - - protected MockAreaEval(int firstRow, int firstColumn, int lastRow, int lastColumn) { - super(firstRow, firstColumn, lastRow, lastColumn); - } - - @Override - public ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex) { - return this.holidays.get(relativeColumnIndex); - } - @Override - public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) { - return getRelativeValue(-1, relativeRowIndex, relativeColumnIndex); - } - - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { - return null; - } - - @Override - public TwoDEval getColumn(int columnIndex) { - return null; - } - - @Override - public TwoDEval getRow(int rowIndex) { - return null; - } - - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java deleted file mode 100644 index 57875af9cd..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.atp; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Calendar; - -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * Specific test cases for YearFracCalculator - */ -final class TestYearFracCalculator { - - @Test - void testBasis1() { - confirm(md(1999, 1, 1), md(1999, 4, 5), 1, 0.257534247); - confirm(md(1999, 4, 1), md(1999, 4, 5), 1, 0.010958904); - confirm(md(1999, 4, 1), md(1999, 4, 4), 1, 0.008219178); - confirm(md(1999, 4, 2), md(1999, 4, 5), 1, 0.008219178); - confirm(md(1999, 3, 31), md(1999, 4, 3), 1, 0.008219178); - confirm(md(1999, 4, 5), md(1999, 4, 8), 1, 0.008219178); - confirm(md(1999, 4, 4), md(1999, 4, 7), 1, 0.008219178); - confirm(md(2000, 2, 5), md(2000, 6, 1), 0, 0.322222222); - } - - private void confirm(double startDate, double endDate, int basis, double expectedValue) { - double actualValue; - try { - actualValue = YearFracCalculator.calculate(startDate, endDate, basis); - } catch (EvaluationException e) { - throw new RuntimeException(e); - } - double diff = actualValue - expectedValue; - if (Math.abs(diff) > 0.000000001) { - double hours = diff * 365 * 24; - System.out.println(startDate + " " + endDate + " off by " + hours + " hours"); - assertEquals(expectedValue, actualValue, 0.000000001); - } - - } - - private static double md(int year, int month, int day) { - Calendar c = LocaleUtil.getLocaleCalendar(year, month-1, day); - return DateUtil.getExcelDate(c.getTime()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java deleted file mode 100644 index 1ac4f2576b..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java +++ /dev/null @@ -1,115 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.atp; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Calendar; -import java.util.Iterator; - -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; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * Tests YearFracCalculator using test-cases listed in a sample spreadsheet - */ -final class TestYearFracCalculatorFromSpreadsheet { - - private static final class SS { - - public static final int BASIS_COLUMN = 1; // "B" - public static final int START_YEAR_COLUMN = 2; // "C" - public static final int END_YEAR_COLUMN = 5; // "F" - public static final int YEARFRAC_FORMULA_COLUMN = 11; // "L" - public static final int EXPECTED_RESULT_COLUMN = 13; // "N" - } - - @Test - void testAll() throws Exception { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("yearfracExamples.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFFormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator(wb); - int nSuccess = 0; - Iterator rowIterator = sheet.rowIterator(); - while(rowIterator.hasNext()) { - HSSFRow row = (HSSFRow) rowIterator.next(); - - HSSFCell cell = row.getCell(SS.YEARFRAC_FORMULA_COLUMN); - if (cell == null || cell.getCellType() != CellType.FORMULA) { - continue; - } - processRow(row, cell, formulaEvaluator); - nSuccess++; - } - - assertTrue(nSuccess > 0, "No test sample cases found"); - wb.close(); - } - - private void processRow(HSSFRow row, HSSFCell cell, HSSFFormulaEvaluator formulaEvaluator) - throws EvaluationException { - - double startDate = makeDate(row, SS.START_YEAR_COLUMN); - double endDate = makeDate(row, SS.END_YEAR_COLUMN); - - int basis = getIntCell(row, SS.BASIS_COLUMN); - - double expectedValue = getDoubleCell(row, SS.EXPECTED_RESULT_COLUMN); - - double actualValue = YearFracCalculator.calculate(startDate, endDate, basis); - - String loc = " - row " + (row.getRowNum()+1); - assertEquals(expectedValue, actualValue, 0, "Direct calculate failed"+loc); - actualValue = formulaEvaluator.evaluate(cell).getNumberValue(); - assertEquals(expectedValue, actualValue, 0, "Formula evaluate failed"+loc); - } - - private static double makeDate(HSSFRow row, int yearColumn) { - int year = getIntCell(row, yearColumn + 0); - int month = getIntCell(row, yearColumn + 1); - int day = getIntCell(row, yearColumn + 2); - Calendar c = LocaleUtil.getLocaleCalendar(year, month-1, day); - return DateUtil.getExcelDate(c.getTime()); - } - - private static int getIntCell(HSSFRow row, int colIx) { - double dVal = getDoubleCell(row, colIx); - String msg = "Non integer value (" + dVal + ") cell found at column " + (char)('A' + colIx); - assertEquals(Math.floor(dVal), dVal, 0, msg); - return (int)dVal; - } - - private static double getDoubleCell(HSSFRow row, int colIx) { - HSSFCell cell = row.getCell(colIx); - assertNotNull(cell, "No cell found at column " + colIx); - return cell.getNumericCellValue(); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java b/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java deleted file mode 100644 index 0f9c0ee60a..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.constant; - - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; -import org.apache.poi.util.LittleEndianInput; -import org.junit.jupiter.api.Test; - -final class TestConstantValueParser { - private static final Object[] SAMPLE_VALUES = { - Boolean.TRUE, - null, - 1.1, - "Sample text", - ErrorConstant.valueOf(FormulaError.DIV0.getCode()), - }; - private static final byte[] SAMPLE_ENCODING = HexRead.readFromString( - "04 01 00 00 00 00 00 00 00 " + - "00 00 00 00 00 00 00 00 00 " + - "01 9A 99 99 99 99 99 F1 3F " + - "02 0B 00 00 53 61 6D 70 6C 65 20 74 65 78 74 " + - "10 07 00 00 00 00 00 00 00"); - - @Test - void testGetEncodedSize() { - int actual = ConstantValueParser.getEncodedSize(SAMPLE_VALUES); - assertEquals(51, actual); - } - - @Test - void testEncode() { - int size = ConstantValueParser.getEncodedSize(SAMPLE_VALUES); - byte[] data = new byte[size]; - - ConstantValueParser.encode(new LittleEndianByteArrayOutputStream(data, 0), SAMPLE_VALUES); - - assertArrayEquals(SAMPLE_ENCODING, data, "Encoding differs"); - } - - @Test - void testDecode() { - LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(SAMPLE_ENCODING); - - Object[] values = ConstantValueParser.parse(in, 4); - for (int i = 0; i < values.length; i++) { - assertTrue(isEqual(SAMPLE_VALUES[i], values[i]), "Decoded result differs"); - } - } - private static boolean isEqual(Object a, Object b) { - if (a == null) { - return b == null; - } - return a.equals(b); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java b/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java deleted file mode 100644 index 74de1ca32c..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java +++ /dev/null @@ -1,189 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Common superclass for testing cases of circular references - * both for HSSF and XSSF - */ -public abstract class BaseTestCircularReferences { - - protected final ITestDataProvider _testDataProvider; - - /** - * @param testDataProvider an object that provides test data in HSSF / XSSF specific way - */ - protected BaseTestCircularReferences(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - - /** - * Translates StackOverflowError into AssertionFailedError - */ - private CellValue evaluateWithCycles(Workbook wb, Cell testCell) { - FormulaEvaluator evaluator = _testDataProvider.createFormulaEvaluator(wb); - try { - return evaluator.evaluate(testCell); - } catch (StackOverflowError e) { - fail( "circular reference caused stack overflow error"); - return null; - } - } - /** - * Makes sure that the specified evaluated cell value represents a circular reference error. - */ - private static void confirmCycleErrorCode(CellValue cellValue) { - assertSame(cellValue.getCellType(), CellType.ERROR); - assertEquals(ErrorEval.CIRCULAR_REF_ERROR.getErrorCode(), cellValue.getErrorValue()); - } - - - /** - * ASF Bugzilla Bug 44413 - * "INDEX() formula cannot contain its own location in the data array range" - */ - @Test - void testIndexFormula() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("Sheet1"); - - int colB = 1; - sheet.createRow(0).createCell(colB).setCellValue(1); - sheet.createRow(1).createCell(colB).setCellValue(2); - sheet.createRow(2).createCell(colB).setCellValue(3); - Row row4 = sheet.createRow(3); - Cell testCell = row4.createCell(0); - // This formula should evaluate to the contents of B2, - testCell.setCellFormula("INDEX(A1:B4,2,2)"); - // However the range A1:B4 also includes the current cell A4. If the other parameters - // were 4 and 1, this would represent a circular reference. Prior to v3.2 POI would - // 'fully' evaluate ref arguments before invoking operators, which raised the possibility of - // cycles / StackOverflowErrors. - - - CellValue cellValue = evaluateWithCycles(wb, testCell); - assertNotNull(cellValue); - assertSame(cellValue.getCellType(), CellType.NUMERIC); - assertEquals(2, cellValue.getNumberValue(), 0); - } - } - - /** - * Cell A1 has formula "=A1" - */ - @Test - void testSimpleCircularReference() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("Sheet1"); - - Row row = sheet.createRow(0); - Cell testCell = row.createCell(0); - testCell.setCellFormula("A1"); - - CellValue cellValue = evaluateWithCycles(wb, testCell); - assertNotNull(cellValue); - confirmCycleErrorCode(cellValue); - - } - } - - /** - * A1=B1, B1=C1, C1=D1, D1=A1 - */ - @Test - void testMultiLevelCircularReference() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("Sheet1"); - - Row row = sheet.createRow(0); - row.createCell(0).setCellFormula("B1"); - row.createCell(1).setCellFormula("C1"); - row.createCell(2).setCellFormula("D1"); - Cell testCell = row.createCell(3); - testCell.setCellFormula("A1"); - - CellValue cellValue = evaluateWithCycles(wb, testCell); - assertNotNull(cellValue); - confirmCycleErrorCode(cellValue); - } - } - - @Test - void testIntermediateCircularReferenceResults_bug46898() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("Sheet1"); - - Row row = sheet.createRow(0); - - Cell cellA1 = row.createCell(0); - Cell cellB1 = row.createCell(1); - Cell cellC1 = row.createCell(2); - Cell cellD1 = row.createCell(3); - Cell cellE1 = row.createCell(4); - - cellA1.setCellFormula("IF(FALSE, 1+B1, 42)"); - cellB1.setCellFormula("1+C1"); - cellC1.setCellFormula("1+D1"); - cellD1.setCellFormula("1+E1"); - cellE1.setCellFormula("1+A1"); - - FormulaEvaluator fe = _testDataProvider.createFormulaEvaluator(wb); - CellValue cv; - - // Happy day flow - evaluate A1 first - cv = fe.evaluate(cellA1); - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(42.0, cv.getNumberValue(), 0.0); - cv = fe.evaluate(cellB1); // no circ-ref-error because A1 result is cached - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(46.0, cv.getNumberValue(), 0.0); - - // Show the bug - evaluate another cell from the loop first - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cellB1); - // Identified bug 46898 - assertNotEquals(cv.getErrorValue(), ErrorEval.CIRCULAR_REF_ERROR.getErrorCode()); - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(46.0, cv.getNumberValue(), 0.0); - - // start evaluation on another cell - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cellE1); - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(43.0, cv.getNumberValue(), 0.0); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/EvalInstances.java b/src/testcases/org/apache/poi/ss/formula/eval/EvalInstances.java deleted file mode 100644 index 4a15444773..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/EvalInstances.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import org.apache.poi.ss.formula.functions.Function; - -/** - * Collects eval instances for easy access by tests in this package - * - * @author Josh Micich - */ -final class EvalInstances { - private EvalInstances() { - // no instances of this class - } - - public static final Function Add = TwoOperandNumericOperation.AddEval; - public static final Function Subtract = TwoOperandNumericOperation.SubtractEval; - public static final Function Multiply = TwoOperandNumericOperation.MultiplyEval; - public static final Function Divide = TwoOperandNumericOperation.DivideEval; - - public static final Function Power = TwoOperandNumericOperation.PowerEval; - - public static final Function Percent = PercentEval.instance; - - public static final Function UnaryMinus = UnaryMinusEval.instance; - public static final Function UnaryPlus = UnaryPlusEval.instance; - - public static final Function Equal = RelationalOperationEval.EqualEval; - public static final Function LessThan = RelationalOperationEval.LessThanEval; - public static final Function LessEqual = RelationalOperationEval.LessEqualEval; - public static final Function GreaterThan = RelationalOperationEval.GreaterThanEval; - public static final Function GreaterEqual = RelationalOperationEval.GreaterEqualEval; - public static final Function NotEqual = RelationalOperationEval.NotEqualEval; - - public static final Function Range = RangeEval.instance; - public static final Function Concat = ConcatEval.instance; -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java deleted file mode 100644 index 40b9a09715..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.util.AreaReference; -import org.junit.jupiter.api.Test; - -/** - * Tests for AreaEval - */ -final class TestAreaEval { - - @Test - void testGetValue_bug44950() { - // TODO - this test probably isn't testing much anymore - AreaPtg ptg = new AreaPtg(new AreaReference("B2:D3", SpreadsheetVersion.EXCEL97)); - NumberEval one = new NumberEval(1); - ValueEval[] values = { - one, - new NumberEval(2), - new NumberEval(3), - new NumberEval(4), - new NumberEval(5), - new NumberEval(6), - }; - AreaEval ae = EvalFactory.createAreaEval(ptg, values); - assertNotEquals(one, ae.getAbsoluteValue(1, 2), "Identified bug 44950 a"); - confirm(1, ae, 1, 1); - confirm(2, ae, 1, 2); - confirm(3, ae, 1, 3); - confirm(4, ae, 2, 1); - confirm(5, ae, 2, 2); - confirm(6, ae, 2, 3); - - } - - private static void confirm(int expectedValue, AreaEval ae, int row, int col) { - NumberEval v = (NumberEval) ae.getAbsoluteValue(row, col); - assertEquals(expectedValue, v.getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java deleted file mode 100644 index 3155ba5b37..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.apache.poi.ss.formula.functions.NumericFunctionInvoker; -import org.junit.jupiter.api.Test; - -/** - * Test for divide operator evaluator. - */ -final class TestDivideEval { - - private static void confirm(ValueEval arg0, ValueEval arg1, double expectedResult) { - ValueEval[] args = { - arg0, arg1, - }; - - double result = NumericFunctionInvoker.invoke(EvalInstances.Divide, args, 0, 0); - - assertEquals(expectedResult, result, 0); - } - - @Test - void testBasic() { - confirm(new NumberEval(5), new NumberEval(2), 2.5); - confirm(new NumberEval(3), new NumberEval(16), 0.1875); - confirm(new NumberEval(-150), new NumberEval(-15), 10.0); - confirm(new StringEval("0.2"), new NumberEval(0.05), 4.0); - confirm(BoolEval.TRUE, new StringEval("-0.2"), -5.0); - } - - @Test - void test1x1Area() { - AreaEval ae0 = EvalFactory.createAreaEval("B2:B2", new ValueEval[] { new NumberEval(50), }); - AreaEval ae1 = EvalFactory.createAreaEval("C2:C2", new ValueEval[] { new NumberEval(10), }); - confirm(ae0, ae1, 5); - } - - @Test - void testDivZero() { - ValueEval[] args = { - new NumberEval(5), NumberEval.ZERO, - }; - ValueEval result = EvalInstances.Divide.evaluate(args, 0, (short) 0); - assertEquals(ErrorEval.DIV_ZERO, result); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java deleted file mode 100644 index 8d8e29f2f0..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java +++ /dev/null @@ -1,160 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.apache.poi.ss.formula.functions.Function; -import org.junit.jupiter.api.Test; - -/** - * Test for EqualEval - */ -final class TestEqualEval { - /** - * Test for bug observable at svn revision 692218 (Sep 2008)
- * The value from a 1x1 area should be taken immediately, regardless of srcRow and srcCol - */ - @Test - void test1x1AreaOperand() { - - ValueEval[] values = { BoolEval.FALSE, }; - ValueEval[] args = { - EvalFactory.createAreaEval("B1:B1", values), - BoolEval.FALSE, - }; - ValueEval result = evaluate(EvalInstances.Equal, args, 10, 10); - assertNotEquals(ErrorEval.VALUE_INVALID, result, "Identified bug in evaluation of 1x1 area"); - assertTrue(result instanceof BoolEval); - assertTrue(((BoolEval)result).getBooleanValue()); - } - - /** - * Empty string is equal to blank - */ - @Test - void testBlankEqualToEmptyString() { - - ValueEval[] args = { - new StringEval(""), - BlankEval.instance, - }; - ValueEval result = evaluate(EvalInstances.Equal, args, 10, 10); - assertEquals(BoolEval.class, result.getClass()); - BoolEval be = (BoolEval) result; - assertTrue(be.getBooleanValue(), "Identified bug blank/empty string equality"); - } - - /** - * Test for bug 46613 (observable at svn r737248) - */ - @Test - void testStringInsensitive_bug46613() { - assertTrue(evalStringCmp("abc", "aBc", EvalInstances.Equal)); - assertTrue(evalStringCmp("ABC", "azz", EvalInstances.LessThan)); - assertTrue(evalStringCmp("abc", "AZZ", EvalInstances.LessThan)); - assertTrue(evalStringCmp("ABC", "aaa", EvalInstances.GreaterThan)); - assertTrue(evalStringCmp("abc", "AAA", EvalInstances.GreaterThan)); - } - - private static boolean evalStringCmp(String a, String b, Function cmpOp) { - ValueEval[] args = { - new StringEval(a), - new StringEval(b), - }; - ValueEval result = evaluate(cmpOp, args, 10, 20); - assertEquals(BoolEval.class, result.getClass()); - BoolEval be = (BoolEval) result; - return be.getBooleanValue(); - } - - @Test - void testBooleanCompares() { - confirmCompares(BoolEval.TRUE, new StringEval("TRUE"), +1); - confirmCompares(BoolEval.TRUE, new NumberEval(1.0), +1); - confirmCompares(BoolEval.TRUE, BoolEval.TRUE, 0); - confirmCompares(BoolEval.TRUE, BoolEval.FALSE, +1); - - confirmCompares(BoolEval.FALSE, new StringEval("TRUE"), +1); - confirmCompares(BoolEval.FALSE, new StringEval("FALSE"), +1); - confirmCompares(BoolEval.FALSE, new NumberEval(0.0), +1); - confirmCompares(BoolEval.FALSE, BoolEval.FALSE, 0); - } - - private static void confirmCompares(ValueEval a, ValueEval b, int expRes) { - confirm(a, b, expRes>0, EvalInstances.GreaterThan); - confirm(a, b, expRes>=0, EvalInstances.GreaterEqual); - confirm(a, b, expRes==0, EvalInstances.Equal); - confirm(a, b, expRes<=0, EvalInstances.LessEqual); - confirm(a, b, expRes<0, EvalInstances.LessThan); - - confirm(b, a, expRes<0, EvalInstances.GreaterThan); - confirm(b, a, expRes<=0, EvalInstances.GreaterEqual); - confirm(b, a, expRes==0, EvalInstances.Equal); - confirm(b, a, expRes>=0, EvalInstances.LessEqual); - confirm(b, a, expRes>0, EvalInstances.LessThan); - } - - private static void confirm(ValueEval a, ValueEval b, boolean expectedResult, Function cmpOp) { - ValueEval[] args = { a, b, }; - ValueEval result = evaluate(cmpOp, args, 10, 20); - assertEquals(BoolEval.class, result.getClass()); - assertEquals(expectedResult, ((BoolEval) result).getBooleanValue()); - } - - /** - * Bug 47198 involved a formula "-A1=0" where cell A1 was 0.0. - * Excel evaluates "-A1=0" to TRUE, not because it thinks -0.0==0.0 - * but because "-A1" evaluated to +0.0 - *

- * Note - the original diagnosis of bug 47198 was that - * "Excel considers -0.0 to be equal to 0.0" which is NQR - * See {@link TestMinusZeroResult} for more specific tests regarding -0.0. - */ - @Test - void testZeroEquality_bug47198() { - NumberEval zero = new NumberEval(0.0); - NumberEval mZero = (NumberEval) evaluate(UnaryMinusEval.instance, new ValueEval[] { zero, }, 0, 0); - assertNotEquals(0x8000000000000000L, Double.doubleToLongBits(mZero.getNumberValue()), - "Identified bug 47198: unary minus should convert -0.0 to 0.0"); - ValueEval[] args = { zero, mZero, }; - BoolEval result = (BoolEval) evaluate(EvalInstances.Equal, args, 0, 0); - assertTrue(result.getBooleanValue(), "Identified bug 47198: -0.0 != 0.0"); - } - - @Test - void testRounding_bug47598() { - double x = 1+1.0028-0.9973; // should be 1.0055, but has IEEE rounding - assertNotEquals(1.0055, x, 0.0); - - NumberEval a = new NumberEval(x); - NumberEval b = new NumberEval(1.0055); - assertEquals("1.0055", b.getStringValue()); - - ValueEval[] args = { a, b, }; - BoolEval result = (BoolEval) evaluate(EvalInstances.Equal, args, 0, 0); - assertTrue(result.getBooleanValue(), "Identified bug 47598: 1+1.0028-0.9973 != 1.0055"); - } - - private static ValueEval evaluate(Function oper, ValueEval[] args, int srcRowIx, int srcColIx) { - return oper.evaluate(args, srcRowIx, (short) srcColIx); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java b/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java deleted file mode 100644 index e4eba2c296..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -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; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; -import org.apache.poi.ss.formula.udf.DefaultUDFFinder; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.junit.jupiter.api.Test; - -final class TestExternalFunction { - - private static ValueEval myFunc1(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 1 || !(args[0] instanceof StringEval)) { - return ErrorEval.VALUE_INVALID; - } - StringEval input = (StringEval) args[0]; - return new StringEval(input.getStringValue() + "abc"); - } - - private static ValueEval myFunc2(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 1 || !(args[0] instanceof StringEval)) { - return ErrorEval.VALUE_INVALID; - } - StringEval input = (StringEval) args[0]; - return new StringEval(input.getStringValue() + "abc2"); - } - - /** - * Checks that an external function can get invoked from the formula evaluator. - */ - @Test - void testInvoke() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testNames.xls")) { - HSSFSheet sheet = wb.getSheetAt(0); - - /* - * register the two test UDFs in a UDF finder, to be passed to the evaluator - */ - UDFFinder udff1 = new DefaultUDFFinder(new String[]{"myFunc",}, - new FreeRefFunction[]{TestExternalFunction::myFunc1}); - UDFFinder udff2 = new DefaultUDFFinder(new String[]{"myFunc2",}, - new FreeRefFunction[]{TestExternalFunction::myFunc2,}); - UDFFinder udff = new AggregatingUDFFinder(udff1, udff2); - - - HSSFRow row = sheet.getRow(0); - HSSFCell myFuncCell = row.getCell(1); // =myFunc("_") - - HSSFCell myFunc2Cell = row.getCell(2); // =myFunc2("_") - - HSSFFormulaEvaluator fe = HSSFFormulaEvaluator.create(wb, null, udff); - assertEquals("_abc", fe.evaluate(myFuncCell).getStringValue()); - assertEquals("_abc2", fe.evaluate(myFunc2Cell).getStringValue()); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulaBugs.java b/src/testcases/org/apache/poi/ss/formula/eval/TestFormulaBugs.java deleted file mode 100644 index b82532592d..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulaBugs.java +++ /dev/null @@ -1,261 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Miscellaneous tests for bugzilla entries.

The test name contains the - * bugzilla bug id. - */ -final class TestFormulaBugs { - - /** - * Bug 27349 - VLOOKUP with reference to another sheet.

This test was - * added long after the relevant functionality was fixed. - */ - @Test - void test27349() throws Exception { - // 27349-vlookupAcrossSheets.xls is bugzilla/attachment.cgi?id=10622 - InputStream is = HSSFTestDataSamples.openSampleFileStream("27349-vlookupAcrossSheets.xls"); - // original bug may have thrown exception here, - // or output warning to stderr - Workbook wb = new HSSFWorkbook(is); - - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(1); - Cell cell = row.getCell(0); - - // this definitely would have failed due to 27349 - assertEquals("VLOOKUP(1,'DATA TABLE'!$A$8:'DATA TABLE'!$B$10,2)", cell - .getCellFormula()); - - // We might as well evaluate the formula - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cv = fe.evaluate(cell); - - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(3.0, cv.getNumberValue(), 0.0); - - wb.close(); - is.close(); - } - - /** - * Bug 27405 - isnumber() formula always evaluates to false in if statement

- * - * seems to be a duplicate of 24925 - */ - @Test - void test27405() throws Exception { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("input"); - // input row 0 - Row row = sheet.createRow(0); - /*Cell cell =*/ row.createCell(0); - Cell cell = row.createCell(1); - cell.setCellValue(1); // B1 - // input row 1 - row = sheet.createRow(1); - cell = row.createCell(1); - cell.setCellValue(999); // B2 - - int rno = 4; - row = sheet.createRow(rno); - cell = row.createCell(1); // B5 - cell.setCellFormula("isnumber(b1)"); - cell = row.createCell(3); // D5 - cell.setCellFormula("IF(ISNUMBER(b1),b1,b2)"); - -// if (false) { // set true to check excel file manually -// // bug report mentions 'Editing the formula in excel "fixes" the problem.' -// try { -// FileOutputStream fileOut = new FileOutputStream("27405output.xls"); -// wb.write(fileOut); -// fileOut.close(); -// } catch (IOException e) { -// throw new RuntimeException(e); -// } -// } - - // use POI's evaluator as an extra sanity check - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cv; - cv = fe.evaluate(cell); - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(1.0, cv.getNumberValue(), 0.0); - - cv = fe.evaluate(row.getCell(1)); - assertEquals(CellType.BOOLEAN, cv.getCellType()); - assertTrue(cv.getBooleanValue()); - - wb.close(); - } - - /** - * Bug 42448 - Can't parse SUMPRODUCT(A!C7:A!C67, B8:B68) / B69

- */ - @Test - void test42448() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet1 = wb.createSheet("Sheet1"); - - Row row = sheet1.createRow(0); - Cell cell = row.createCell(0); - - // it's important to create the referenced sheet first - Sheet sheet2 = wb.createSheet("A"); // note name 'A' - // TODO - POI crashes if the formula is added before this sheet - // RuntimeException("Zero length string is an invalid sheet name") - // Excel doesn't crash but the formula doesn't work until it is - // re-entered - - String inputFormula = "SUMPRODUCT(A!C7:A!C67, B8:B68) / B69"; // as per bug report - try { - cell.setCellFormula(inputFormula); - } catch (StringIndexOutOfBoundsException e) { - fail("Identified bug 42448"); - } - - assertEquals("SUMPRODUCT(A!C7:A!C67,B8:B68)/B69", cell.getCellFormula()); - - // might as well evaluate the sucker... - - addCell(sheet2, 5, 2, 3.0); // A!C6 - addCell(sheet2, 6, 2, 4.0); // A!C7 - addCell(sheet2, 66, 2, 5.0); // A!C67 - addCell(sheet2, 67, 2, 6.0); // A!C68 - - addCell(sheet1, 6, 1, 7.0); // B7 - addCell(sheet1, 7, 1, 8.0); // B8 - addCell(sheet1, 67, 1, 9.0); // B68 - addCell(sheet1, 68, 1, 10.0); // B69 - - double expectedResult = (4.0 * 8.0 + 5.0 * 9.0) / 10.0; - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cv = fe.evaluate(cell); - - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(expectedResult, cv.getNumberValue(), 0.0); - } - } - - private static void addCell(Sheet sheet, int rowIx, int colIx, - double value) { - sheet.createRow(rowIx).createCell(colIx).setCellValue(value); - } - - @Test - void test55032() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("input"); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(1); - - checkFormulaValue(wb, cell, "PV(0.08/12, 20*12, 500, ,0)", -59777.14585); - checkFormulaValue(wb, cell, "PV(0.08/12, 20*12, 500, ,)", -59777.14585); - checkFormulaValue(wb, cell, "PV(0.08/12, 20*12, 500, 500,)", -59878.6315455); - - checkFormulaValue(wb, cell, "FV(0.08/12, 20*12, 500, ,)", -294510.2078107270); - checkFormulaValue(wb, cell, "PMT(0.08/12, 20*12, 500, ,)", -4.1822003450); - checkFormulaValue(wb, cell, "NPER(0.08/12, 20*12, 500, ,)", -2.0758873434); - - wb.close(); - } - - // bug 52063: LOOKUP(2-arg) and LOOKUP(3-arg) - // FIXME: This could be moved into LookupFunctionsTestCaseData.xls, which is tested by TestLookupFunctionsFromSpreadsheet.java - @Test - void testLookupFormula() throws Exception { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("52063"); - - // Note: Values in arrays are in ascending order since LOOKUP expects that in order to work properly - // column - // A B C - // +------- - // row 1 | P Q R - // row 2 | X Y Z - Row row = sheet.createRow(0); - row.createCell(0).setCellValue("P"); - row.createCell(1).setCellValue("Q"); - row.createCell(2).setCellValue("R"); - row = sheet.createRow(1); - row.createCell(0).setCellValue("X"); - row.createCell(1).setCellValue("Y"); - row.createCell(2).setCellValue("Z"); - - Cell evalcell = sheet.createRow(2).createCell(0); - - //// ROW VECTORS - // lookup and result row are the same - checkFormulaValue(wb, evalcell, "LOOKUP(\"Q\", A1:C1)", "Q"); - checkFormulaValue(wb, evalcell, "LOOKUP(\"R\", A1:C1)", "R"); - checkFormulaValue(wb, evalcell, "LOOKUP(\"Q\", A1:C1, A1:C1)", "Q"); - checkFormulaValue(wb, evalcell, "LOOKUP(\"R\", A1:C1, A1:C1)", "R"); - - // lookup and result row are different - checkFormulaValue(wb, evalcell, "LOOKUP(\"Q\", A1:C2)", "Y"); - checkFormulaValue(wb, evalcell, "LOOKUP(\"R\", A1:C2)", "Z"); - checkFormulaValue(wb, evalcell, "LOOKUP(\"Q\", A1:C1, A2:C2)", "Y"); - checkFormulaValue(wb, evalcell, "LOOKUP(\"R\", A1:C1, A2:C2)", "Z"); - - //// COLUMN VECTORS - // lookup and result column are different - checkFormulaValue(wb, evalcell, "LOOKUP(\"P\", A1:B2)", "Q"); - checkFormulaValue(wb, evalcell, "LOOKUP(\"X\", A1:A2, C1:C2)", "Z"); - - wb.close(); - } - - private CellValue evaluateFormulaInCell(Workbook wb, Cell cell, String formula) { - cell.setCellFormula(formula); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - return evaluator.evaluate(cell); - } - - private void checkFormulaValue(Workbook wb, Cell cell, String formula, double expectedValue) { - CellValue value = evaluateFormulaInCell(wb, cell, formula); - assertEquals(expectedValue, value.getNumberValue(), 0.0001); - } - - private void checkFormulaValue(Workbook wb, Cell cell, String formula, String expectedValue) { - CellValue value = evaluateFormulaInCell(wb, cell, formula); - assertEquals(expectedValue, value.getStringValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java deleted file mode 100644 index 80ddc6d988..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java +++ /dev/null @@ -1,224 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.stream.Stream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.functions.TestMathX; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Tests formulas and operators as loaded from a test data spreadsheet.

- * This class does not test implementors of Function and OperationEval in - * isolation. Much of the evaluation engine (i.e. HSSFFormulaEvaluator, ...) gets - * exercised as well. Tests for bug fixes and specific/tricky behaviour can be found in the - * corresponding test class (TestXxxx) of the target (Xxxx) implementor, - * where execution can be observed more easily. - */ -public final class TestFormulasFromSpreadsheet { - - private static HSSFWorkbook workbook; - private static Sheet sheet; - private static HSSFFormulaEvaluator evaluator; - private static Locale userLocale; - - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - private interface SS { - - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - String FILENAME = "FormulaEvalTestData.xls"; - /** - * Row (zero-based) in the test spreadsheet where the operator examples start. - */ - int START_OPERATORS_ROW_INDEX = 22; // Row '23' - /** - * Row (zero-based) in the test spreadsheet where the function examples start. - */ - int START_FUNCTIONS_ROW_INDEX = 95; // Row '96' - /** - * Index of the column that contains the function names - */ - int COLUMN_INDEX_FUNCTION_NAME = 1; // Column 'B' - - /** - * Used to indicate when there are no more functions left - */ - String FUNCTION_NAMES_END_SENTINEL = ""; - - /** - * Index of the column where the test values start (for each function) - */ - short COLUMN_INDEX_FIRST_TEST_VALUE = 3; // Column 'D' - - /** - * Each function takes 4 rows in the test spreadsheet - */ - int NUMBER_OF_ROWS_PER_FUNCTION = 4; - } - - @AfterAll - public static void closeResource() throws Exception { - LocaleUtil.setUserLocale(userLocale); - workbook.close(); - } - - public static Stream data() { - // Function "Text" uses custom-formats which are locale specific - // can't set the locale on a per-testrun execution, as some settings have been - // already set, when we would try to change the locale by then - userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.ROOT); - - workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME); - sheet = workbook.getSheetAt( 0 ); - evaluator = new HSSFFormulaEvaluator(workbook); - - List data = new ArrayList<>(); - - processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX); - processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX); - // example for debugging individual functions/operators: - // processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, "ConcatEval"); - // processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, "Text"); - - return data.stream(); - } - - /** - * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * Typically pass null to test all functions - */ - private static void processFunctionGroup(List data, int startRowIndex) { - for (int rowIndex = startRowIndex; true; rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION) { - Row r = sheet.getRow(rowIndex); - String targetFunctionName = getTargetFunctionName(r); - assertNotNull(targetFunctionName, "Test spreadsheet cell empty on row (" - + (rowIndex+1) + "). Expected function name or '" - + SS.FUNCTION_NAMES_END_SENTINEL + "'"); - if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { - // found end of functions list - break; - } - - // expected results are on the row below - Row expectedValuesRow = sheet.getRow(rowIndex + 1); - int missingRowNum = rowIndex + 2; //+1 for 1-based, +1 for next row - assertNotNull(expectedValuesRow, "Missing expected values row for function '" - + targetFunctionName + " (row " + missingRowNum + ")"); - - data.add(Arguments.of(targetFunctionName, rowIndex, rowIndex + 1)); - } - } - - @ParameterizedTest - @MethodSource("data") - void processFunctionRow(String targetFunctionName, int formulasRowIdx, int expectedValuesRowIdx) { - Row formulasRow = sheet.getRow(formulasRowIdx); - Row expectedValuesRow = sheet.getRow(expectedValuesRowIdx); - - short endcolnum = formulasRow.getLastCellNum(); - - // iterate across the row for all the evaluation cases - for (int colnum=SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++) { - Cell c = formulasRow.getCell(colnum); - if (c == null || c.getCellType() != CellType.FORMULA) { - continue; - } - - CellValue actValue = evaluator.evaluate(c); - Cell expValue = (expectedValuesRow == null) ? null : expectedValuesRow.getCell(colnum); - - String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" - , targetFunctionName, c.getCellFormula(), formulasRow.getRowNum(), colnum); - - assertNotNull(expValue, msg + " - Bad setup data expected value is null"); - assertNotNull(actValue, msg + " - actual value was null"); - - final CellType cellType = expValue.getCellType(); - switch (cellType) { - case BLANK: - assertEquals(CellType.BLANK, actValue.getCellType(), msg); - break; - case BOOLEAN: - assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); - assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); - break; - case ERROR: - assertEquals(CellType.ERROR, actValue.getCellType(), msg); - assertEquals(ErrorEval.getText(expValue.getErrorCellValue()), ErrorEval.getText(actValue.getErrorValue()), msg); - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - fail("Cannot expect formula as result of formula evaluation: " + msg); - case NUMERIC: - assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); - TestMathX.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); - break; - case STRING: - assertEquals(CellType.STRING, actValue.getCellType(), msg); - assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); - break; - default: - fail("Unexpected cell type: " + cellType); - } - } - } - /** - * @return null if cell is missing, empty or blank - */ - private static String getTargetFunctionName(Row r) { - if(r == null) { - System.err.println("Warning - given null row, can't figure out function name"); - return null; - } - Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME); - if(cell == null) { - System.err.println("Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name"); - return null; - } - - CellType ct = cell.getCellType(); - assertTrue(ct == CellType.BLANK || ct == CellType.STRING, - "Bad cell type for 'function name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - - return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null; - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestHSSFCircularReferences.java b/src/testcases/org/apache/poi/ss/formula/eval/TestHSSFCircularReferences.java deleted file mode 100644 index 90d9739efb..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestHSSFCircularReferences.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import org.apache.poi.hssf.HSSFITestDataProvider; - -/** - * Tests HSSFFormulaEvaluator for its handling of cell formula circular references. - * - * @author Josh Micich - */ -final class TestHSSFCircularReferences extends BaseTestCircularReferences { - public TestHSSFCircularReferences() { - super(HSSFITestDataProvider.instance); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java b/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java deleted file mode 100644 index f5a73d186d..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java +++ /dev/null @@ -1,150 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.formula.functions.Function; -import org.junit.jupiter.api.Test; - -/** - * IEEE 754 defines a quantity '-0.0' which is distinct from '0.0'. - * Negative zero is not easy to observe in Excel, since it is usually converted to 0.0. - * (Note - the results of XLL add-in functions don't seem to be converted, so they are one - * reliable avenue to observe Excel's treatment of '-0.0' as an operand.) - *

- * POI attempts to emulate Excel faithfully, so this class tests - * two aspects of '-0.0' in formula evaluation: - *

    - *
  1. For most operation results '-0.0' is converted to '0.0'.
  2. - *
  3. Comparison operators have slightly different rules regarding '-0.0'.
  4. - *
- */ -final class TestMinusZeroResult { - private static final double MINUS_ZERO = -0.0; - - @Test - void testSimpleOperators() { - - // unary plus is a no-op - checkEval(MINUS_ZERO, UnaryPlusEval.instance, MINUS_ZERO); - - // most simple operators convert -0.0 to +0.0 - checkEval(0.0, EvalInstances.UnaryMinus, 0.0); - checkEval(0.0, EvalInstances.Percent, MINUS_ZERO); - checkEval(0.0, EvalInstances.Multiply, MINUS_ZERO, 1.0); - checkEval(0.0, EvalInstances.Divide, MINUS_ZERO, 1.0); - checkEval(0.0, EvalInstances.Power, MINUS_ZERO, 1.0); - - // but SubtractEval does not convert -0.0, so '-' and '+' work like java - checkEval(MINUS_ZERO, EvalInstances.Subtract, MINUS_ZERO, 0.0); // this is the main point of bug 47198 - checkEval(0.0, EvalInstances.Add, MINUS_ZERO, 0.0); - } - - /** - * These results are hard to see in Excel (since -0.0 is usually converted to +0.0 before it - * gets to the comparison operator) - */ - @Test - void testComparisonOperators() { - checkEval(false, EvalInstances.Equal, 0.0, MINUS_ZERO); - checkEval(true, EvalInstances.GreaterThan, 0.0, MINUS_ZERO); - checkEval(true, EvalInstances.LessThan, MINUS_ZERO, 0.0); - } - - @Test - void testTextRendering() { - confirmTextRendering(MINUS_ZERO); - // sub-normal negative numbers also display as '-0' - confirmTextRendering(Double.longBitsToDouble(0x8000100020003000L)); - } - - /** - * Uses {@link ConcatEval} to force number-to-text conversion - */ - private static void confirmTextRendering(double d) { - ValueEval[] args = { StringEval.EMPTY_INSTANCE, new NumberEval(d), }; - StringEval se = (StringEval) EvalInstances.Concat.evaluate(args, -1, (short)-1); - String result = se.getStringValue(); - assertEquals("-0", result); - } - - private static void checkEval(double expectedResult, Function instance, double... dArgs) { - NumberEval result = (NumberEval) evaluate(instance, dArgs); - assertDouble(expectedResult, result.getNumberValue()); - } - private static void checkEval(boolean expectedResult, Function instance, double... dArgs) { - BoolEval result = (BoolEval) evaluate(instance, dArgs); - assertEquals(expectedResult, result.getBooleanValue()); - } - private static ValueEval evaluate(Function instance, double... dArgs) { - ValueEval[] evalArgs; - evalArgs = new ValueEval[dArgs.length]; - for (int i = 0; i < evalArgs.length; i++) { - evalArgs[i] = new NumberEval(dArgs[i]); - } - return instance.evaluate(evalArgs, -1, (short)-1); - } - - /** - * Not really a POI test - just shows similar behaviour of '-0.0' in Java. - */ - @Test - void testJava() { - assertEquals(0x8000000000000000L, Double.doubleToLongBits(MINUS_ZERO)); - - // The simple operators consider all zeros to be the same - //noinspection SimplifiableJUnitAssertion,ConstantConditions - assertTrue(MINUS_ZERO == MINUS_ZERO); - //noinspection SimplifiableJUnitAssertion,ConstantConditions - assertTrue(MINUS_ZERO == +0.0); - //noinspection ConstantConditions - assertFalse(MINUS_ZERO < +0.0); - - // Double.compare() considers them different - assertTrue(Double.compare(MINUS_ZERO, +0.0) < 0); - - // multiplying zero by any negative quantity yields minus zero - assertDouble(MINUS_ZERO, 0.0*-1); - assertDouble(MINUS_ZERO, 0.0*-1e300); - assertDouble(MINUS_ZERO, 0.0*-1e-300); - - // minus zero can be produced as a result of underflow - assertDouble(MINUS_ZERO, -1e-300 / 1e100); - - // multiplying or dividing minus zero by a positive quantity yields minus zero - assertDouble(MINUS_ZERO, MINUS_ZERO * 1.0); - assertDouble(MINUS_ZERO, MINUS_ZERO / 1.0); - - // subtracting positive zero gives minus zero - assertDouble(MINUS_ZERO, MINUS_ZERO - 0.0); - // BUT adding positive zero gives positive zero - assertDouble(0.0, MINUS_ZERO + 0.0); // <<---- - } - - /** - * Just so there is no ambiguity. The two double values have to be exactly equal - */ - private static void assertDouble(double a, double b) { - long bitsA = Double.doubleToLongBits(a); - long bitsB = Double.doubleToLongBits(b); - assertEquals(bitsA, bitsB); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java deleted file mode 100644 index a89db5837f..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java +++ /dev/null @@ -1,134 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link MissingArgEval} - */ -final class TestMissingArgEval { - - @Test - void testEvaluateMissingArgs() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFCell cell = sheet.createRow(0).createCell(0); - - cell.setCellFormula("if(true,)"); - fe.clearAllCachedResultValues(); - // EmptyStackException -> Missing args evaluation not implemented (bug 43354) - CellValue cv = fe.evaluate(cell); - // MissingArg -> BlankEval -> zero (as formula result) - assertEquals(0.0, cv.getNumberValue(), 0.0); - - // MissingArg -> BlankEval -> empty string (in concatenation) - cell.setCellFormula("\"abc\"&if(true,)"); - fe.clearAllCachedResultValues(); - assertEquals("abc", fe.evaluate(cell).getStringValue()); - } - } - - @Test - void testCompareMissingArgs() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFCell cell = sheet.createRow(0).createCell(0); - - cell.setCellFormula("iferror(0/0,)<0"); - fe.clearAllCachedResultValues(); - CellValue cv = fe.evaluate(cell); - assertFalse(cv.getBooleanValue()); - - cell.setCellFormula("iferror(0/0,)<=0"); - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cell); - assertTrue(cv.getBooleanValue()); - - cell.setCellFormula("iferror(0/0,)=0"); - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cell); - assertTrue(cv.getBooleanValue()); - - cell.setCellFormula("iferror(0/0,)>=0"); - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cell); - assertTrue(cv.getBooleanValue()); - - cell.setCellFormula("iferror(0/0,)>0"); - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cell); - assertFalse(cv.getBooleanValue()); - - // invert above for code coverage - cell.setCellFormula("0=iferror(0/0,)"); - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cell); - assertTrue(cv.getBooleanValue()); - - cell.setCellFormula("0>iferror(0/0,)"); - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cell); - assertFalse(cv.getBooleanValue()); - } - } - - @Test - void testCountFuncs() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFCell cell = sheet.createRow(0).createCell(0); - - cell.setCellFormula("COUNT(C5,,,,)"); // 4 missing args, C5 is blank - assertEquals(4.0, fe.evaluate(cell).getNumberValue(), 0.0); - - cell.setCellFormula("COUNTA(C5,,)"); // 2 missing args, C5 is blank - fe.clearAllCachedResultValues(); - assertEquals(2.0, fe.evaluate(cell).getNumberValue(), 0.0); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java deleted file mode 100644 index 68e634f1cd..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java +++ /dev/null @@ -1,188 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Locale; -import java.util.stream.Stream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.functions.TestMathX; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Tests formulas for multi sheet reference (i.e. SUM(Sheet1:Sheet5!A1)) - */ -final class TestMultiSheetEval { - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - private static final class SS { - - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - public static final String FILENAME = "FormulaSheetRange.xls"; - /** - * Row (zero-based) in the test spreadsheet where the function examples start. - */ - public static final int START_FUNCTIONS_ROW_INDEX = 10; // Row '11' - /** - * Index of the column that contains the function names - */ - public static final int COLUMN_INDEX_FUNCTION_NAME = 0; // Column 'A' - /** - * Index of the column that contains the test names - */ - public static final int COLUMN_INDEX_TEST_NAME = 1; // Column 'B' - /** - * Used to indicate when there are no more functions left - */ - public static final String FUNCTION_NAMES_END_SENTINEL = ""; - - /** - * Index of the column where the test expected value is present - */ - public static final short COLUMN_INDEX_EXPECTED_VALUE = 2; // Column 'C' - /** - * Index of the column where the test actual value is present - */ - public static final short COLUMN_INDEX_ACTUAL_VALUE = 3; // Column 'D' - /** - * Test sheet name (sheet with all test formulae) - */ - public static final String TEST_SHEET_NAME = "test"; - } - - private static HSSFFormulaEvaluator evaluator; - private static Collection funcs; - - - public static Stream data() { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME); - Sheet sheet = workbook.getSheet(SS.TEST_SHEET_NAME); - evaluator = new HSSFFormulaEvaluator(workbook); - funcs = FunctionEval.getSupportedFunctionNames(); - - List data = new ArrayList<>(); - for (int rowIndex = SS.START_FUNCTIONS_ROW_INDEX;true;rowIndex++) { - Row r = sheet.getRow(rowIndex); - - // only evaluate non empty row - if (r == null) { - continue; - } - - String targetFunctionName = getTargetFunctionName(r); - assertNotNull(targetFunctionName, "Expected function name or '" + SS.FUNCTION_NAMES_END_SENTINEL + "'"); - if (targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { - // found end of functions list - break; - } - String targetTestName = getTargetTestName(r); - - // expected results are on the row below - Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); - assertNotNull(expectedValueCell, "Missing expected values cell for function '" + targetFunctionName); - - data.add(Arguments.of( targetTestName, targetFunctionName, expectedValueCell, r )); - } - - return data.stream(); - } - - @ParameterizedTest - @MethodSource("data") - void testFunction(String testName, String functionName, Cell expected, Row testRow) { - - Cell c = testRow.getCell(SS.COLUMN_INDEX_ACTUAL_VALUE); - if (c == null || c.getCellType() != CellType.FORMULA) { - // missing test data - assertTrue(testRow.getRowNum() >= SS.START_FUNCTIONS_ROW_INDEX); - assertTrue(funcs.contains(functionName.toUpperCase(Locale.ROOT)), "unsupported function"); - return; - } - - CellValue actual = evaluator.evaluate(c); - - assertNotNull(expected, "Bad setup data expected value is null"); - assertNotNull(actual, "actual value was null"); - - final CellType cellType = expected.getCellType(); - - switch (cellType) { - case BLANK: - assertEquals(CellType.BLANK, actual.getCellType()); - break; - case BOOLEAN: - assertEquals(CellType.BOOLEAN, actual.getCellType()); - assertEquals(expected.getBooleanCellValue(), actual.getBooleanValue()); - break; - case ERROR: - assertEquals(CellType.ERROR, actual.getCellType()); - assertEquals(ErrorEval.getText(expected.getErrorCellValue()), ErrorEval.getText(actual.getErrorValue())); - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - fail("Cannot expect formula as result of formula evaluation."); - break; - case NUMERIC: - assertEquals(CellType.NUMERIC, actual.getCellType()); - TestMathX.assertDouble("", expected.getNumericCellValue(), actual.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); - break; - case STRING: - assertEquals(CellType.STRING, actual.getCellType()); - assertEquals(expected.getRichStringCellValue().getString(), actual.getStringValue()); - break; - default: - fail("Unexpected cell type: " + cellType); - break; - } - } - - private static String getTargetFunctionName(Row r) { - assertNotNull(r, "given null row, can't figure out function name"); - Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME); - assertNotNull(cell, "Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name"); - assertEquals(CellType.STRING, cell.getCellType()); - return cell.getRichStringCellValue().getString(); - } - - private static String getTargetTestName(Row r) { - assertNotNull(r, "Given null row, can't figure out test name"); - Cell cell = r.getCell(SS.COLUMN_INDEX_TEST_NAME); - assertNotNull(cell, "Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_TEST_NAME + ", can't figure out test name"); - assertEquals(CellType.STRING, cell.getCellType()); - return cell.getRichStringCellValue().getString(); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java b/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java deleted file mode 100644 index f37b818142..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java +++ /dev/null @@ -1,101 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.util.LinkedHashMap; -import java.util.Map; - -import org.junit.jupiter.api.Test; - -/** - * Tests for OperandResolver - */ -final class TestOperandResolver { - @Test - void testParseDouble_bug48472() { - // bug 48472 - StringIndexOutOfBoundsException - Double resolvedValue = OperandResolver.parseDouble("-"); - assertNull(resolvedValue); - } - - @Test - void testParseDouble_bug49723() { - String value = ".1"; - Double resolvedValue = OperandResolver.parseDouble(value); - - assertNotNull(resolvedValue, "Identified bug 49723"); - } - - /** - * Tests that a list of valid strings all return a non null value from {@link OperandResolver#parseDouble(String)} - */ - @Test - void testParseDoubleValidStrings() { - String[] values = new String[]{".19", "0.19", "1.9", "1E4", "-.19", "-0.19", - "8.5","-1E4", ".5E6","+1.5","+1E5", " +1E5 ", " 123 ", "1E4", "-123" }; - - for (String value : values) { - Double act = OperandResolver.parseDouble(value); - assertNotNull(act); - assertEquals(act, Double.parseDouble(value), 0); - } - } - - /** - * Tests that a list of invalid strings all return null from {@link OperandResolver#parseDouble(String)} - */ - @Test - void testParseDoubleInvalidStrings() { - String[] values = new String[]{"-", "ABC", "-X", "1E5a", "Infinity", "NaN", ".5F", "1,000"}; - - for (String value : values) { - assertNull(OperandResolver.parseDouble(value)); - } - } - - @Test - void testCoerceDateStringToNumber() throws EvaluationException { - Map values = new LinkedHashMap<>(); - values.put("2019/1/18", 43483.); - values.put("01/18/2019", 43483.); - values.put("18 Jan 2019", 43483.); - values.put("18-Jan-2019", 43483.); - - for (String str : values.keySet()) { - assertEquals(OperandResolver.coerceValueToDouble(new StringEval(str)), values.get(str), 0.00001); - } - } - - @Test - void testCoerceTimeStringToNumber() throws EvaluationException { - Map values = new LinkedHashMap<>(); - values.put("00:00", 0.0); - values.put("12:00", 0.5); - values.put("15:43:09", 0.654965278); - values.put("15:43", 0.654861111); - values.put("3:43 PM", 0.654861111); - - for (String str : values.keySet()) { - assertEquals(OperandResolver.coerceValueToDouble(new StringEval(str)), values.get(str), 0.00001); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java deleted file mode 100644 index 3727cc1c71..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.apache.poi.ss.formula.functions.NumericFunctionInvoker; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -/** - * Test for percent operator evaluator. - */ -final class TestPercentEval { - - private static void confirm(ValueEval arg, double expectedResult) { - ValueEval[] args = { - arg, - }; - - double result = NumericFunctionInvoker.invoke(PercentEval.instance, args, 0, 0); - - assertEquals(expectedResult, result, 0); - } - - @Test - void testBasic() { - confirm(new NumberEval(5), 0.05); - confirm(new NumberEval(3000), 30.0); - confirm(new NumberEval(-150), -1.5); - confirm(new StringEval("0.2"), 0.002); - confirm(BoolEval.TRUE, 0.01); - } - - @Test - void test1x1Area() { - AreaEval ae = EvalFactory.createAreaEval("B2:B2", new ValueEval[] { new NumberEval(50), }); - confirm(ae, 0.5); - } - - @Test - void testInSpreadSheet() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("B1%"); - row.createCell(1).setCellValue(50.0); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - // bug 44608 - NullPointerException - CellValue cv = fe.evaluate(cell); - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(0.5, cv.getNumberValue(), 0.0); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java deleted file mode 100644 index 78b0d49ac8..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -/** - * Tests for power operator evaluator. - */ -final class TestPowerEval { - @Test - void testPositiveValues() { - confirm(0, 0, 1); - confirm(1, 1, 0); - confirm(9, 3, 2); - } - - @Test - void testNegativeValues() { - confirm(-1, -1, 1); - confirm(1, 1, -1); - confirm(1, -10, 0); - confirm((1.0/3), 3, -1); - } - - @Test - void testPositiveDecimalValues() { - confirm(3, 27, (1/3.0)); - } - - @Test - void testNegativeDecimalValues() { - confirm(-3, -27, (1/3.0)); - } - - @Test - void testErrorValues() { - confirmError(-1.00001, 1.1); - } - - @Test - void testInSpreadSheet() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("B1^C1"); - row.createCell(1).setCellValue(-27); - row.createCell(2).setCellValue((1/3.0)); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue cv = fe.evaluate(cell); - - assertEquals(CellType.NUMERIC, cv.getCellType()); - assertEquals(-3.0, cv.getNumberValue(), 0); - } - - private void confirm(double expected, double a, double b) { - NumberEval result = (NumberEval) evaluate(a, b); - - assertEquals(expected, result.getNumberValue(), 0); - } - - private void confirmError(double a, double b) { - ErrorEval result = (ErrorEval) evaluate(a, b); - - assertEquals("#NUM!", result.getErrorString()); - } - - private static ValueEval evaluate(double... dArgs) { - ValueEval[] evalArgs; - evalArgs = new ValueEval[dArgs.length]; - for (int i = 0; i < evalArgs.length; i++) { - evalArgs[i] = new NumberEval(dArgs[i]); - } - return EvalInstances.Power.evaluate(evalArgs, -1, (short) -1); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java deleted file mode 100644 index f67d8a92ff..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.TwoDEval; -import org.apache.poi.ss.formula.ptg.AreaI; -import org.apache.poi.ss.formula.ptg.AreaI.OffsetArea; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; - -/** - * Test for unary plus operator evaluator. - */ -final class TestRangeEval { - @Test - void testPermutations() { - - confirm("B3", "D7", "B3:D7"); - confirm("B1", "B1", "B1:B1"); - - confirm("B7", "D3", "B3:D7"); - confirm("D3", "B7", "B3:D7"); - confirm("D7", "B3", "B3:D7"); - } - - private static void confirm(String refA, String refB, String expectedAreaRef) { - - ValueEval[] args = { - createRefEval(refA), - createRefEval(refB), - }; - List versions = Arrays.asList(SpreadsheetVersion.EXCEL97, SpreadsheetVersion.EXCEL2007); - for(SpreadsheetVersion version : versions) { - AreaReference ar = new AreaReference(expectedAreaRef, version); - ValueEval result = EvalInstances.Range.evaluate(args, 0, (short)0); - assertTrue(result instanceof AreaEval); - AreaEval ae = (AreaEval) result; - assertEquals(ar.getFirstCell().getRow(), ae.getFirstRow()); - assertEquals(ar.getLastCell().getRow(), ae.getLastRow()); - assertEquals(ar.getFirstCell().getCol(), ae.getFirstColumn()); - assertEquals(ar.getLastCell().getCol(), ae.getLastColumn()); - } - } - - private static ValueEval createRefEval(String refStr) { - CellReference cr = new CellReference(refStr); - return new MockRefEval(cr.getRow(), cr.getCol()); - - } - - private static final class MockRefEval extends RefEvalBase { - public MockRefEval(int rowIndex, int columnIndex) { - super(-1, -1, rowIndex, columnIndex); - } - @Override - public ValueEval getInnerValueEval(int sheetIndex) { - throw new RuntimeException("not expected to be called during this test"); - } - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, - int relLastColIx) { - AreaI area = new OffsetArea(getRow(), getColumn(), - relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); - return new MockAreaEval(area); - } - } - - private static final class MockAreaEval extends AreaEvalBase { - - public MockAreaEval(AreaI ptg) { - super(ptg); - } - private MockAreaEval(int firstRow, int firstColumn, int lastRow, int lastColumn) { - super(firstRow, firstColumn, lastRow, lastColumn); - } - @Override - public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) { - throw new RuntimeException("not expected to be called during this test"); - } - @Override - public ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex) { - throw new RuntimeException("not expected to be called during this test"); - } - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, - int relLastColIx) { - AreaI area = new OffsetArea(getFirstRow(), getFirstColumn(), - relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); - - return new MockAreaEval(area); - } - @Override - public TwoDEval getRow(int rowIndex) { - if (rowIndex >= getHeight()) { - throw new IllegalArgumentException("Invalid rowIndex " + rowIndex - + ". Allowable range is (0.." + getHeight() + ")."); - } - return new MockAreaEval(rowIndex, getFirstColumn(), rowIndex, getLastColumn()); - } - @Override - public TwoDEval getColumn(int columnIndex) { - if (columnIndex >= getWidth()) { - throw new IllegalArgumentException("Invalid columnIndex " + columnIndex - + ". Allowable range is (0.." + getWidth() + ")."); - } - return new MockAreaEval(getFirstRow(), columnIndex, getLastRow(), columnIndex); - } - } - - @Test - void testRangeUsingOffsetFunc_bug46948() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFRow row = wb.createSheet("Sheet1").createRow(0); - HSSFCell cellA1 = row.createCell(0); - HSSFCell cellB1 = row.createCell(1); - row.createCell(2).setCellValue(5.0); // C1 - row.createCell(3).setCellValue(7.0); // D1 - row.createCell(4).setCellValue(9.0); // E1 - - - cellA1.setCellFormula("SUM(C1:OFFSET(C1,0,B1))"); - - cellB1.setCellValue(1.0); // range will be C1:D1 - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - // bug 46948 - Unexpected ref arg class (org.apache.poi.ss.formula.LazyAreaEval) - CellValue cv = fe.evaluate(cellA1); - - assertEquals(12.0, cv.getNumberValue(), 0.0); - - cellB1.setCellValue(2.0); // range will be C1:E1 - fe.notifyUpdateCell(cellB1); - cv = fe.evaluate(cellA1); - assertEquals(21.0, cv.getNumberValue(), 0.0); - - cellB1.setCellValue(0.0); // range will be C1:C1 - fe.notifyUpdateCell(cellB1); - cv = fe.evaluate(cellA1); - assertEquals(5.0, cv.getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java deleted file mode 100644 index febecbe359..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.apache.poi.ss.formula.functions.NumericFunctionInvoker; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.junit.jupiter.api.Test; - -/** - * Test for unary plus operator evaluator. - */ -final class TestUnaryPlusEval { - - /** - * Test for bug observable at svn revision 618865 (5-Feb-2008)
- * The code for handling column operands had been copy-pasted from the row handling code. - */ - @Test - void testColumnOperand() { - - short firstRow = (short)8; - short lastRow = (short)12; - short colNum = (short)5; - AreaPtg areaPtg = new AreaPtg(firstRow, lastRow, colNum, colNum, false, false, false, false); - ValueEval[] values = { - new NumberEval(27), - new NumberEval(29), - new NumberEval(35), // value in row 10 - new NumberEval(37), - new NumberEval(38), - }; - ValueEval[] args = { - EvalFactory.createAreaEval(areaPtg, values), - }; - - double result = NumericFunctionInvoker.invoke(EvalInstances.UnaryPlus, args, 10, (short)20); - - assertEquals(35, result, 0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/forked/BaseTestForkedEvaluator.java b/src/testcases/org/apache/poi/ss/formula/eval/forked/BaseTestForkedEvaluator.java deleted file mode 100644 index 5c3dcb9875..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/forked/BaseTestForkedEvaluator.java +++ /dev/null @@ -1,117 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval.forked; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.IStabilityClassifier; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -public class BaseTestForkedEvaluator { - - protected Workbook newWorkbook() { - return new HSSFWorkbook(); - } - - /** - * set up a calculation workbook with input cells nicely segregated on a - * sheet called "Inputs" - */ - protected Workbook createWorkbook() { - Workbook wb = newWorkbook(); - Sheet sheet1 = wb.createSheet("Inputs"); - Sheet sheet2 = wb.createSheet("Calculations"); - Row row; - row = sheet2.createRow(0); - row.createCell(0).setCellFormula("B1*Inputs!A1-Inputs!B1"); - row.createCell(1).setCellValue(5.0); // Calculations!B1 - - // some default input values - row = sheet1.createRow(0); - row.createCell(0).setCellValue(2.0); // Inputs!A1 - row.createCell(1).setCellValue(3.0); // Inputs!B1 - return wb; - } - - /** - * Shows a basic use-case for {@link ForkedEvaluator} - */ - @Test - void testBasic() throws IOException { - try (Workbook wb = createWorkbook()) { - - // The stability classifier is useful to reduce memory consumption of caching logic - IStabilityClassifier stabilityClassifier = (sheetIndex, rowIndex, columnIndex) -> sheetIndex == 1; - - ForkedEvaluator fe1 = ForkedEvaluator.create(wb, stabilityClassifier, null); - ForkedEvaluator fe2 = ForkedEvaluator.create(wb, stabilityClassifier, null); - - // fe1 and fe2 can be used concurrently on separate threads - - fe1.updateCell("Inputs", 0, 0, new NumberEval(4.0)); - fe1.updateCell("Inputs", 0, 1, new NumberEval(1.1)); - - fe2.updateCell("Inputs", 0, 0, new NumberEval(1.2)); - fe2.updateCell("Inputs", 0, 1, new NumberEval(2.0)); - - NumberEval eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0); - assertNotNull(eval1); - assertEquals(18.9, eval1.getNumberValue(), 0.0); - NumberEval eval2 = (NumberEval) fe2.evaluate("Calculations", 0, 0); - assertNotNull(eval2); - assertEquals(4.0, eval2.getNumberValue(), 0.0); - fe1.updateCell("Inputs", 0, 0, new NumberEval(3.0)); - eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0); - assertNotNull(eval1); - assertEquals(13.9, eval1.getNumberValue(), 0.0); - } - } - - /** - * As of Sep 2009, the Forked evaluator can update values from existing cells (this is because - * the underlying 'master' cell is used as a key into the calculation cache. Prior to the fix - * for this bug, an attempt to update a missing cell would result in NPE. This junit tests for - * a more meaningful error message.
- * - * An alternate solution might involve allowing empty cells to be created as necessary. That - * was considered less desirable because so far, the underlying 'master' workbook is strictly - * read-only with respect to the ForkedEvaluator. - */ - @Test - void testMissingInputCellH() throws IOException { - - try (Workbook wb = createWorkbook()) { - ForkedEvaluator fe = ForkedEvaluator.create(wb, null, null); - // attempt update input at cell A2 (which is missing) - UnsupportedOperationException ex = assertThrows( - UnsupportedOperationException.class, - () -> fe.updateCell("Inputs", 1, 0, new NumberEval(4.0)) - ); - assertEquals("Underlying cell 'A2' is missing in master sheet.", ex.getMessage()); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/function/ExcelCetabFunctionExtractor.java b/src/testcases/org/apache/poi/ss/formula/function/ExcelCetabFunctionExtractor.java deleted file mode 100644 index db87e07377..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/function/ExcelCetabFunctionExtractor.java +++ /dev/null @@ -1,378 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.function; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintStream; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * This class is not used during normal POI run-time but is used at development time to generate - * the file 'functionMetadataCetab.txt'. There are more than 300 built-in functions in Excel in - * the Cetab and the intention of this class is to make it easier to maintain the metadata, by extracting - * it from a reliable source. - */ -public final class ExcelCetabFunctionExtractor { - - private static final String SOURCE_DOC_FILE_NAME = "functionMetadataCetab-PDF.txt"; - - /** - * For simplicity, the output file is strictly simple ASCII. - * This method detects any unexpected characters. - */ - /* package */ static boolean isSimpleAscii(char c) { - - if (c>=0x21 && c<=0x7E) { - // everything from '!' to '~' (includes letters, digits, punctuation - return true; - } - // some specific whitespace chars below 0x21: - switch(c) { - case ' ': - case '\t': - case '\r': - case '\n': - return true; - } - return false; - } - - - private static final class FunctionData { - // special characters from the ooo document - private static final int CHAR_ELLIPSIS_8230 = 8230; - private static final int CHAR_NDASH_8211 = 8211; - - private final int _index; - private final boolean _hasFootnote; - private final String _name; - private final int _minParams; - private final int _maxParams; - private final String _returnClass; - private final String _paramClasses; - private final boolean _isVolatile; - - public FunctionData(int funcIx, boolean hasFootnote, String funcName, int minParams, int maxParams, - String returnClass, String paramClasses, boolean isVolatile) { - _index = funcIx; - _hasFootnote = hasFootnote; - _name = funcName; - _minParams = minParams; - _maxParams = maxParams; - _returnClass = convertSpecialChars(returnClass); - _paramClasses = convertSpecialChars(paramClasses); - _isVolatile = isVolatile; - } - private static String convertSpecialChars(String ss) { - StringBuilder sb = new StringBuilder(ss.length() + 4); - for(int i=0; i _allFunctionsByIndex; - private final Map _allFunctionsByName; - private final Set _groupFunctionIndexes; - private final Set _groupFunctionNames; - private final PrintStream _ps; - - public FunctionDataCollector(PrintStream ps) { - _ps = ps; - _allFunctionsByIndex = new HashMap<>(); - _allFunctionsByName = new HashMap<>(); - _groupFunctionIndexes = new HashSet<>(); - _groupFunctionNames = new HashSet<>(); - } - - public void addFunction(int funcIx, boolean hasFootnote, String funcName, int minParams, int maxParams, - String returnClass, String paramClasses, String volatileFlagStr) { - boolean isVolatile = volatileFlagStr.length() > 0; - - Integer funcIxKey = Integer.valueOf(funcIx); - if(!_groupFunctionIndexes.add(funcIxKey)) { - throw new RuntimeException("Duplicate function index (" + funcIx + ")"); - } - if(!_groupFunctionNames.add(funcName)) { - throw new RuntimeException("Duplicate function name '" + funcName + "'"); - } - - checkRedefinedFunction(hasFootnote, funcName, funcIxKey); - FunctionData fd = new FunctionData(funcIx, hasFootnote, funcName, - minParams, maxParams, returnClass, paramClasses, isVolatile); - - _allFunctionsByIndex.put(funcIxKey, fd); - _allFunctionsByName.put(funcName, fd); - } - - /** - * Some extra validation here. - * Any function which changes definition will have a footnote in the source document - */ - private void checkRedefinedFunction(boolean hasNote, String funcName, Integer funcIxKey) { - FunctionData fdPrev; - // check by index - fdPrev = _allFunctionsByIndex.get(funcIxKey); - if(fdPrev != null) { - if(!fdPrev.hasFootnote() || !hasNote) { - throw new RuntimeException("changing function [" - + funcIxKey + "] definition without foot-note"); - } - _allFunctionsByName.remove(fdPrev.getName()); - } - // check by name - fdPrev = _allFunctionsByName.get(funcName); - if(fdPrev != null) { - if(!fdPrev.hasFootnote() || !hasNote) { - throw new RuntimeException("changing function '" - + funcName + "' definition without foot-note"); - } - _allFunctionsByIndex.remove(Integer.valueOf(fdPrev.getIndex())); - } - } - - public void endTableGroup(String headingText) { - Integer[] keys = new Integer[_groupFunctionIndexes.size()]; - _groupFunctionIndexes.toArray(keys); - _groupFunctionIndexes.clear(); - _groupFunctionNames.clear(); - Arrays.sort(keys); - - _ps.println("# " + headingText); - for (Integer key : keys) { - FunctionData fd = _allFunctionsByIndex.get(key); - _ps.println(fd.formatAsDataLine()); - } - } - } - - private static final Pattern ID_MATCH = Pattern.compile("0x([\\dA-F]+)"); - private static final Pattern NAME_MATCH = Pattern.compile("([0-9A-Z.]+)"); - private static final Pattern ID_NAME_MATCH = Pattern.compile("0x([\\dA-F]+)\\s+([0-9A-Z.]+)"); - - private static final Set IGNORED_LINES = new HashSet<>(); - static { - IGNORED_LINES.add("[MS-XLS] — v20141018"); - IGNORED_LINES.add("Excel Binary File Format (.xls) Structure"); - IGNORED_LINES.add("Copyright © 2014 Microsoft Corporation."); - IGNORED_LINES.add("Release: October 30, 2014Value Meaning"); - IGNORED_LINES.add("Release: October 30, 2014Value"); - IGNORED_LINES.add("Meaning"); - } - - private static void extractFunctionData(FunctionDataCollector fdc, InputStream is) throws IOException { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { - - String id = null; - String name = null; - while (true) { - String line = reader.readLine(); - if(line == null) { - break; - } - - if(IGNORED_LINES.contains(line) || line.matches("\\d+ / \\d+")) { - continue; - } - - Matcher idMatcher = ID_MATCH.matcher(line); - boolean foundID = idMatcher.matches(); - Matcher nameMatcher = NAME_MATCH.matcher(line); - boolean foundName = nameMatcher.matches(); - Matcher idAndNameMatcher = ID_NAME_MATCH.matcher(line); - boolean foundIDandName = idAndNameMatcher.matches(); - if(foundID && foundName || - foundName && foundIDandName || - foundID && foundIDandName) { - throw new IllegalStateException("Should not find id and name: " + - foundID + "/" + foundName + "/" + foundIDandName + - ", line: " + line); - } - - if(foundID && id != null) { - throw new IllegalStateException("Found ID, but already had one: " + id + ", line: " + line); - } - if(foundName && name != null) { - throw new IllegalStateException("Found name, but already had one: " + name + ", line: " + line); - } - if(foundIDandName && (name != null || id != null)) { - throw new IllegalStateException("Found name and id, but already had one: id: " + id + ", name: " + name + ", line: " + line); - } - - if(foundID) { - id = idMatcher.group(1); - } else if (foundName) { - name = nameMatcher.group(1); - } else if (foundIDandName) { - id = idAndNameMatcher.group(1); - name = idAndNameMatcher.group(2); - // manual override for one function name which contains lowercase characters - } else if(line.equals("VBAActivate")) { - name = line; - } else if (id == null || name == null) { - throw new IllegalStateException("Found params, but had empty id or name, id: " + id + - ", name: " + name + ", line: " + line); - } else { - System.out.println("Found function " + id + " " + name + " " + line); - fdc.addFunction(Integer.parseInt(id, 16), false, name, 0, 0, - "", "", ""); - - id = null; - name = null; - } - } - } - - fdc.endTableGroup(""); - } - /** - * To be sure that no tricky unicode chars make it through to the output file. - */ - private static final class SimpleAsciiOutputStream extends OutputStream { - - private final OutputStream _os; - - public SimpleAsciiOutputStream(OutputStream os) { - _os = os; - } - - @Override - public void write(int b) throws IOException { - checkByte(b); - _os.write(b); - } - - private static void checkByte(int b) { - if (!isSimpleAscii((char)b)) { - throw new RuntimeException("Encountered char (" + b + ") which was not simple ascii as expected"); - } - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - for (int i = 0; i < len; i++) { - checkByte(b[i + off]); - - } - _os.write(b, off, len); - } - } - - private static void processFile(InputStream input, File outFile) throws IOException { - try (OutputStream os = new SimpleAsciiOutputStream(new FileOutputStream(outFile)); - PrintStream ps = new PrintStream(os, true, "UTF-8")) { - - outputLicenseHeader(ps); - Class genClass = ExcelCetabFunctionExtractor.class; - ps.println("# Created by (" + genClass.getName() + ")"); - // identify the source file - ps.println("# from source file '" + SOURCE_DOC_FILE_NAME + "'"); - ps.println("#"); - ps.println("#Columns: (index, name, minParams, maxParams, returnClass, paramClasses, isVolatile, hasFootnote )"); - ps.println(); - extractFunctionData(new FunctionDataCollector(ps), input); - ps.close(); - - String canonicalOutputFileName = outFile.getCanonicalPath(); - System.out.println("Successfully output to '" + canonicalOutputFileName + "'"); - } - } - - private static void outputLicenseHeader(PrintStream ps) { - String[] lines= { - "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.", - }; - for (String line : lines) { - ps.print("# "); - ps.println(line); - } - ps.println(); - } - - public static void main(String[] args) throws IOException { - if(!new File(SOURCE_DOC_FILE_NAME).exists()) { - throw new IllegalStateException("Did not find file " + SOURCE_DOC_FILE_NAME + " in the resources"); - } - - try (InputStream stream = new FileInputStream(SOURCE_DOC_FILE_NAME)) { - File outFile = new File("functionMetadataCetab.txt"); - - processFile(stream, outFile); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java b/src/testcases/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java deleted file mode 100644 index c408dd527b..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java +++ /dev/null @@ -1,623 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.function; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.math.BigInteger; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; -import java.util.zip.ZipFile; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.util.TempFile; -import org.apache.poi.util.XMLHelper; -import org.xml.sax.Attributes; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * This class is not used during normal POI run-time but is used at development time to generate - * the file 'functionMetadata.txt'. There are more than 300 built-in functions in Excel and the - * intention of this class is to make it easier to maintain the metadata, by extracting it from - * a reliable source. - */ -public final class ExcelFileFormatDocFunctionExtractor { - - private static final String SOURCE_DOC_FILE_NAME = "excelfileformat.odt"; - - /** - * For simplicity, the output file is strictly simple ASCII. - * This method detects any unexpected characters. - */ - /* package */ static boolean isSimpleAscii(char c) { - - if (c>=0x21 && c<=0x7E) { - // everything from '!' to '~' (includes letters, digits, punctuation - return true; - } - // some specific whitespace chars below 0x21: - switch(c) { - case ' ': - case '\t': - case '\r': - case '\n': - return true; - } - return false; - } - - - private static final class FunctionData { - // special characters from the ooo document - private static final int CHAR_ELLIPSIS_8230 = 8230; - private static final int CHAR_NDASH_8211 = 8211; - - private final int _index; - private final boolean _hasFootnote; - private final String _name; - private final int _minParams; - private final int _maxParams; - private final String _returnClass; - private final String _paramClasses; - private final boolean _isVolatile; - - public FunctionData(int funcIx, boolean hasFootnote, String funcName, int minParams, int maxParams, - String returnClass, String paramClasses, boolean isVolatile) { - _index = funcIx; - _hasFootnote = hasFootnote; - _name = funcName; - _minParams = minParams; - _maxParams = maxParams; - _returnClass = convertSpecialChars(returnClass); - _paramClasses = convertSpecialChars(paramClasses); - _isVolatile = isVolatile; - } - private static String convertSpecialChars(String ss) { - StringBuilder sb = new StringBuilder(ss.length() + 4); - for(int i=0; i _allFunctionsByIndex; - private final Map _allFunctionsByName; - private final Set _groupFunctionIndexes; - private final Set _groupFunctionNames; - private final PrintStream _ps; - - public FunctionDataCollector(PrintStream ps) { - _ps = ps; - _allFunctionsByIndex = new HashMap<>(); - _allFunctionsByName = new HashMap<>(); - _groupFunctionIndexes = new HashSet<>(); - _groupFunctionNames = new HashSet<>(); - } - - public void addFuntion(int funcIx, boolean hasFootnote, String funcName, int minParams, int maxParams, - String returnClass, String paramClasses, String volatileFlagStr) { - boolean isVolatile = volatileFlagStr.length() > 0; - - Integer funcIxKey = Integer.valueOf(funcIx); - if(!_groupFunctionIndexes.add(funcIxKey)) { - throw new RuntimeException("Duplicate function index (" + funcIx + ")"); - } - if(!_groupFunctionNames.add(funcName)) { - throw new RuntimeException("Duplicate function name '" + funcName + "'"); - } - - checkRedefinedFunction(hasFootnote, funcName, funcIxKey); - FunctionData fd = new FunctionData(funcIx, hasFootnote, funcName, - minParams, maxParams, returnClass, paramClasses, isVolatile); - - _allFunctionsByIndex.put(funcIxKey, fd); - _allFunctionsByName.put(funcName, fd); - } - - /** - * Some extra validation here. - * Any function which changes definition will have a footnote in the source document - */ - private void checkRedefinedFunction(boolean hasNote, String funcName, Integer funcIxKey) { - FunctionData fdPrev; - // check by index - fdPrev = _allFunctionsByIndex.get(funcIxKey); - if(fdPrev != null) { - if(!fdPrev.hasFootnote() || !hasNote) { - throw new RuntimeException("changing function [" - + funcIxKey + "] definition without foot-note"); - } - _allFunctionsByName.remove(fdPrev.getName()); - } - // check by name - fdPrev = _allFunctionsByName.get(funcName); - if(fdPrev != null) { - if(!fdPrev.hasFootnote() || !hasNote) { - throw new RuntimeException("changing function '" - + funcName + "' definition without foot-note"); - } - _allFunctionsByIndex.remove(Integer.valueOf(fdPrev.getIndex())); - } - } - - public void endTableGroup(String headingText) { - Integer[] keys = new Integer[_groupFunctionIndexes.size()]; - _groupFunctionIndexes.toArray(keys); - _groupFunctionIndexes.clear(); - _groupFunctionNames.clear(); - Arrays.sort(keys); - - _ps.println("# " + headingText); - for (Integer key : keys) { - FunctionData fd = _allFunctionsByIndex.get(key); - _ps.println(fd.formatAsDataLine()); - } - } - } - - /** - * To avoid drag-in - parse XML using only JDK. - */ - private static class EFFDocHandler extends DefaultHandler { - private static final String[] HEADING_PATH_NAMES = { - "office:document-content", "office:body", "office:text", "text:h", - }; - private static final String[] TABLE_BASE_PATH_NAMES = { - "office:document-content", "office:body", "office:text", "table:table", - }; - private static final String[] TABLE_ROW_RELPATH_NAMES = { - "table:table-row", - }; - private static final String[] TABLE_CELL_RELPATH_NAMES = { - "table:table-row", "table:table-cell", "text:p", - }; - // after May 2008 there was one more style applied to the footnotes - private static final String[] NOTE_REF_RELPATH_NAMES_OLD = { - "table:table-row", "table:table-cell", "text:p", "text:span", "text:note-ref", - }; - private static final String[] NOTE_REF_RELPATH_NAMES = { - "table:table-row", "table:table-cell", "text:p", "text:span", "text:span", "text:note-ref", - }; - - - private final Stack _elemNameStack; - /** true only when parsing the target tables */ - private boolean _isInsideTable; - - private final List _rowData; - private final StringBuilder _textNodeBuffer; - private final List _rowNoteFlags; - private boolean _cellHasNote; - - private final FunctionDataCollector _fdc; - private String _lastHeadingText; - - public EFFDocHandler(FunctionDataCollector fdc) { - _fdc = fdc; - _elemNameStack = new Stack<>(); - _isInsideTable = false; - _rowData = new ArrayList<>(); - _textNodeBuffer = new StringBuilder(); - _rowNoteFlags = new ArrayList<>(); - } - - private boolean matchesTargetPath() { - return matchesPath(0, TABLE_BASE_PATH_NAMES); - } - - private boolean matchesRelPath(String[] pathNames) { - return matchesPath(TABLE_BASE_PATH_NAMES.length, pathNames); - } - - private boolean matchesPath(int baseStackIndex, String[] pathNames) { - if(_elemNameStack.size() != baseStackIndex + pathNames.length) { - return false; - } - for (int i = 0; i < pathNames.length; i++) { - if(!_elemNameStack.get(baseStackIndex + i).equals(pathNames[i])) { - return false; - } - } - return true; - } - - @Override - public void characters(char[] ch, int start, int length) { - // only 2 text nodes where text is collected: - if(matchesRelPath(TABLE_CELL_RELPATH_NAMES) || matchesPath(0, HEADING_PATH_NAMES)) { - _textNodeBuffer.append(ch, start, length); - } - } - - @Override - public void endElement(String namespaceURI, String localName, String name) { - String expectedName = _elemNameStack.peek(); - if(expectedName != name) { - throw new RuntimeException("close tag mismatch"); - } - if(matchesPath(0, HEADING_PATH_NAMES)) { - _lastHeadingText = _textNodeBuffer.toString().trim(); - _textNodeBuffer.setLength(0); - } - if(_isInsideTable) { - if(matchesTargetPath()) { - _fdc.endTableGroup(_lastHeadingText); - _isInsideTable = false; - } else if(matchesRelPath(TABLE_ROW_RELPATH_NAMES)) { - String[] cellData = new String[_rowData.size()]; - _rowData.toArray(cellData); - _rowData.clear(); - Boolean[] noteFlags = new Boolean[_rowNoteFlags.size()]; - _rowNoteFlags.toArray(noteFlags); - _rowNoteFlags.clear(); - processTableRow(cellData, noteFlags); - } else if(matchesRelPath(TABLE_CELL_RELPATH_NAMES)) { - _rowData.add(_textNodeBuffer.toString().trim()); - _rowNoteFlags.add(Boolean.valueOf(_cellHasNote)); - _textNodeBuffer.setLength(0); - } - } - _elemNameStack.pop(); - } - - private void processTableRow(String[] cellData, Boolean[] noteFlags) { - // each table row of the document contains data for two functions - if(cellData.length != 15) { - throw new RuntimeException("Bad table row size"); - } - processFunction(cellData, noteFlags, 0); - processFunction(cellData, noteFlags, 8); - } - - public void processFunction(String[] cellData, Boolean[] noteFlags, int i) { - String funcIxStr = cellData[i + 0]; - if (funcIxStr.length() < 1) { - // empty (happens on the right hand side when there is an odd number of functions) - return; - } - int funcIx = parseInt(funcIxStr); - - boolean hasFootnote = noteFlags[i + 1].booleanValue(); - String funcName = cellData[i + 1]; - int minParams = parseInt(cellData[i + 2]); - int maxParams = parseInt(cellData[i + 3]); - - String returnClass = cellData[i + 4]; - String paramClasses = cellData[i + 5]; - String volatileFlagStr = cellData[i + 6]; - - _fdc.addFuntion(funcIx, hasFootnote, funcName, minParams, maxParams, returnClass, paramClasses, volatileFlagStr); - } - - private static int parseInt(String valStr) { - try { - return Integer.parseInt(valStr); - } catch (NumberFormatException e) { - throw new RuntimeException("Value '" + valStr + "' could not be parsed as an integer"); - } - } - - @Override - public void startElement(String namespaceURI, String localName, String name, Attributes atts) { - _elemNameStack.add(name); - if(matchesTargetPath()) { - String tableName = atts.getValue("table:name"); - if(tableName.startsWith("tab_fml_func") && !tableName.equals("tab_fml_func0")) { - _isInsideTable = true; - } - return; - } - if(matchesPath(0, HEADING_PATH_NAMES)) { - _textNodeBuffer.setLength(0); - } else if(matchesRelPath(TABLE_ROW_RELPATH_NAMES)) { - _rowData.clear(); - _rowNoteFlags.clear(); - } else if(matchesRelPath(TABLE_CELL_RELPATH_NAMES)) { - _textNodeBuffer.setLength(0); - _cellHasNote = false; - } else if(matchesRelPath(NOTE_REF_RELPATH_NAMES_OLD)) { - _cellHasNote = true; - } else if(matchesRelPath(NOTE_REF_RELPATH_NAMES)) { - _cellHasNote = true; - } - } - - @Override - public void endDocument() { - // do nothing - } - @Override - public void endPrefixMapping(String prefix) { - // do nothing - } - @Override - public void ignorableWhitespace(char[] ch, int start, int length) { - // do nothing - } - @Override - public void processingInstruction(String target, String data) { - // do nothing - } - @Override - public void setDocumentLocator(Locator locator) { - // do nothing - } - @Override - public void skippedEntity(String name) { - // do nothing - } - @Override - public void startDocument() { - // do nothing - } - @Override - public void startPrefixMapping(String prefix, String uri) { - // do nothing - } - } - - private static void extractFunctionData(FunctionDataCollector fdc, InputStream is) { - SAXParserFactory sf = XMLHelper.getSaxParserFactory(); - SAXParser xr; - - try { - // First up, try the default one - xr = sf.newSAXParser(); - } catch (SAXException | ParserConfigurationException e) { - throw new RuntimeException(e); - } - - try (InputStream is2 = is) { - xr.parse(is2, new EFFDocHandler(fdc)); - } catch (IOException | SAXException e) { - throw new RuntimeException(e); - } - } - /** - * To be sure that no tricky unicode chars make it through to the output file. - */ - private static final class SimpleAsciiOutputStream extends OutputStream { - - private final OutputStream _os; - - public SimpleAsciiOutputStream(OutputStream os) { - _os = os; - } - - @Override - public void write(int b) throws IOException { - checkByte(b); - _os.write(b); - } - - private static void checkByte(int b) { - if (!isSimpleAscii((char)b)) { - throw new RuntimeException("Encountered char (" + b + ") which was not simple ascii as expected"); - } - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - for (int i = 0; i < len; i++) { - checkByte(b[i + off]); - - } - _os.write(b, off, len); - } - } - - private static void processFile(File effDocFile, File outFile) { - if(!effDocFile.exists()) { - throw new RuntimeException("file '" + effDocFile.getAbsolutePath() + "' does not exist"); - } - OutputStream os; - try { - os = new FileOutputStream(outFile); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - os = new SimpleAsciiOutputStream(os); - PrintStream ps; - try { - ps = new PrintStream(os, true, "UTF-8"); - } catch(UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - - outputLicenseHeader(ps); - Class genClass = ExcelFileFormatDocFunctionExtractor.class; - ps.println("# Created by (" + genClass.getName() + ")"); - // identify the source file - ps.print("# from source file '" + SOURCE_DOC_FILE_NAME + "'"); - ps.println(" (size=" + effDocFile.length() + ", md5=" + getFileMD5(effDocFile) + ")"); - ps.println("#"); - ps.println("#Columns: (index, name, minParams, maxParams, returnClass, paramClasses, isVolatile, hasFootnote )"); - ps.println(); - try { - // can't use ZipHelper here, because its in a different module - ZipFile zf = new ZipFile(effDocFile); - InputStream is = zf.getInputStream(zf.getEntry("content.xml")); - extractFunctionData(new FunctionDataCollector(ps), is); - zf.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - ps.close(); - - String canonicalOutputFileName; - try { - canonicalOutputFileName = outFile.getCanonicalPath(); - } catch (IOException e) { - throw new RuntimeException(e); - } - System.out.println("Successfully output to '" + canonicalOutputFileName + "'"); - } - - private static void outputLicenseHeader(PrintStream ps) { - String[] lines= { - "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.", - }; - for (String line : lines) { - ps.print("# "); - ps.println(line); - } - ps.println(); - } - - /** - * Helps identify the source file - */ - private static String getFileMD5(File f) { - MessageDigest m = CryptoFunctions.getMessageDigest(HashAlgorithm.md5); - - byte[]buf = new byte[2048]; - try { - InputStream is = new FileInputStream(f); - while(true) { - int bytesRead = is.read(buf); - if(bytesRead<1) { - break; - } - m.update(buf, 0, bytesRead); - } - is.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - - return "0x" + new BigInteger(1, m.digest()).toString(16); - } - - private static File downloadSourceFile() { - URL url; - try { - url = new URL("http://sc.openoffice.org/" + SOURCE_DOC_FILE_NAME); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - - File result; - byte[]buf = new byte[2048]; - try { - URLConnection conn = url.openConnection(); - InputStream is = conn.getInputStream(); - System.out.println("downloading " + url.toExternalForm()); - result = TempFile.createTempFile("excelfileformat", ".odt"); - OutputStream os = new FileOutputStream(result); - while(true) { - int bytesRead = is.read(buf); - if(bytesRead<1) { - break; - } - os.write(buf, 0, bytesRead); - } - is.close(); - os.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - System.out.println("file downloaded ok"); - return result; - } - - public static void main(String[] args) { - - File outFile = new File("functionMetadata-asGenerated.txt"); - -// if (false) { // set true to use local file -// File dir = new File("c:/temp"); -// File effDocFile = new File(dir, SOURCE_DOC_FILE_NAME); -// processFile(effDocFile, outFile); -// return; -// } - - File tempEFFDocFile = downloadSourceFile(); - processFile(tempEFFDocFile, outFile); - tempEFFDocFile.delete(); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java b/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java deleted file mode 100644 index 29853a410d..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.function; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.junit.jupiter.api.Test; - -final class TestFunctionMetadataRegistry { - @Test - void testWellKnownFunctions() { - confirmFunction(0, "COUNT"); - confirmFunction(1, "IF"); - - } - - private static void confirmFunction(int index, String funcName) { - FunctionMetadata fm; - fm = FunctionMetadataRegistry.getFunctionByIndex(index); - assertNotNull(fm); - assertEquals(funcName, fm.getName()); - - fm = FunctionMetadataRegistry.getFunctionByName(funcName); - assertNotNull(fm); - assertEquals(index, fm.getIndex()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java b/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java deleted file mode 100644 index c95eae8871..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java +++ /dev/null @@ -1,104 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.function; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.ptg.AbstractFunctionPtg; -import org.apache.poi.ss.formula.ptg.FuncPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.junit.jupiter.api.Test; - -/** - * Tests parsing of some built-in functions that were not properly - * registered in POI as of bug #44675, #44733 (March/April 2008). - */ -final class TestParseMissingBuiltInFuncs { - - private static Ptg[] parse(String formula) throws IOException { - HSSFWorkbook book = new HSSFWorkbook(); - Ptg[] ptgs = HSSFFormulaParser.parse(formula, book); - book.close(); - return ptgs; - } - - private static void confirmFunc(String formula, int expPtgArraySize, boolean isVarArgFunc, int funcIx) - throws IOException { - Ptg[] ptgs = parse(formula); - Ptg ptgF = ptgs[ptgs.length-1]; // func is last RPN token in all these formulas - - // Check critical things in the Ptg array encoding. - if(!(ptgF instanceof AbstractFunctionPtg)) { - throw new RuntimeException("function token missing"); - } - AbstractFunctionPtg func = (AbstractFunctionPtg) ptgF; - assertNotEquals(255, func.getFunctionIndex(), "Failed to recognise built-in function in formula"); - assertEquals(expPtgArraySize, ptgs.length); - assertEquals(funcIx, func.getFunctionIndex()); - Class expCls = isVarArgFunc ? FuncVarPtg.class : FuncPtg.class; - assertEquals(expCls, ptgF.getClass()); - - // check that parsed Ptg array converts back to formula text OK - HSSFWorkbook book = new HSSFWorkbook(); - String reRenderedFormula = HSSFFormulaParser.toFormulaString(book, ptgs); - assertEquals(formula, reRenderedFormula); - book.close(); - } - - @Test - void testDatedif() throws IOException { - int expSize = 4; // NB would be 5 if POI added tAttrVolatile properly - confirmFunc("DATEDIF(NOW(),NOW(),\"d\")", expSize, false, 351); - } - - @Test - void testDdb() throws IOException { - confirmFunc("DDB(1,1,1,1,1)", 6, true, 144); - } - - @Test - void testAtan() throws IOException { - confirmFunc("ATAN(1)", 2, false, 18); - } - - @Test - void testUsdollar() throws IOException { - confirmFunc("USDOLLAR(1)", 2, true, 204); - } - - @Test - void testDBCS() throws IOException { - confirmFunc("DBCS(\"abc\")", 2, false, 215); - } - - @Test - void testIsnontext() throws IOException { - confirmFunc("ISNONTEXT(\"abc\")", 2, false, 190); - } - - @Test - void testDproduct() throws IOException { - confirmFunc("DPRODUCT(C1:E5,\"HarvestYield\",G1:H2)", 4, false, 189); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java b/src/testcases/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java deleted file mode 100644 index c26220dbd8..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java +++ /dev/null @@ -1,155 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.function; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.fail; - -import java.lang.reflect.InvocationTargetException; - -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.RecordFormatException; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Tests reading from a sample spreadsheet some built-in functions that were not properly - * registered in POI as of bug #44675, #44733 (March/April 2008). - */ -final class TestReadMissingBuiltInFuncs { - - /** - * This spreadsheet has examples of calls to the interesting built-in functions in cells A1:A7 - */ - private static final String SAMPLE_SPREADSHEET_FILE_NAME = "missingFuncs44675.xls"; - - private static HSSFWorkbook wb; - private static HSSFSheet _sheet; - - @BeforeAll - public static void initSheet() { - wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_SPREADSHEET_FILE_NAME); - try { - _sheet = wb.getSheetAt(0); - } catch (RecordFormatException e) { - if(e.getCause() instanceof InvocationTargetException) { - InvocationTargetException ite = (InvocationTargetException) e.getCause(); - if(ite.getTargetException() instanceof RuntimeException) { - RuntimeException re = (RuntimeException) ite.getTargetException(); - assertNotEquals("Invalid built-in function index (189)", re.getMessage(), - "DPRODUCT() registered with wrong index"); - } - } - // some other unexpected error - throw e; - } - } - - @AfterAll - public static void closeResources() throws Exception { - wb.close(); - } - - @Test - void testDatedif() { - String formula; - try { - formula = getCellFormula(0); - } catch (IllegalStateException e) { - if(e.getMessage().startsWith("Too few arguments")) { - assertFalse(e.getMessage().contains("AttrPtg"), - "tAttrVolatile not supported in FormulaParser.toFormulaString"); - fail("NOW() registered with 1 arg instead of 0"); - } - if(e.getMessage().startsWith("too much stuff")) { - fail("DATEDIF() not registered"); - } - // some other unexpected error - throw e; - } - assertEquals("DATEDIF(NOW(),NOW(),\"d\")", formula); - } - - @Test - void testDdb() { - String formula = getCellFormula(1); - assertNotEquals("externalflag(1,1,1,1,1)", formula, "DDB() not registered"); - assertEquals("DDB(1,1,1,1,1)", formula); - } - - @Test - void testAtan() { - String formula = getCellFormula(2); - assertNotEquals("ARCTAN(1)", formula, "func ix 18 registered as ARCTAN() instead of ATAN()"); - assertEquals("ATAN(1)", formula); - } - - @Test - void testUsdollar() { - String formula = getCellFormula(3); - assertNotEquals("YEN(1)", formula, "func ix 204 registered as YEN() instead of USDOLLAR()"); - assertEquals("USDOLLAR(1)", formula); - } - - @Test - void testDBCS() { - String formula = ""; - try { - formula = getCellFormula(4); - } catch (IllegalStateException e) { - assertFalse(e.getMessage().startsWith("too much stuff"), "DBCS() not registered"); - // some other unexpected error - throw e; - } catch (NegativeArraySizeException e) { - fail("found err- DBCS() registered with -1 args"); - } - assertNotEquals("JIS(\"abc\")", formula, "func ix 215 registered as JIS() instead of DBCS()"); - assertEquals("DBCS(\"abc\")", formula); - } - - @Test - void testIsnontext() { - String formula; - try { - formula = getCellFormula(5); - } catch (IllegalStateException e) { - assertFalse(e.getMessage().startsWith("too much stuff"), "ISNONTEXT() registered with wrong index"); - // some other unexpected error - throw e; - } - assertEquals("ISNONTEXT(\"abc\")", formula); - } - - @Test - void testDproduct() { - String formula = getCellFormula(6); - assertEquals("DPRODUCT(C1:E5,\"HarvestYield\",G1:H2)", formula); - } - - private String getCellFormula(int rowIx) { - // if (false) { -// System.err.println(result); -// } - return _sheet.getRow(rowIx).getCell(0).getCellFormula(); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/BaseTestFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/BaseTestFunctionsFromSpreadsheet.java deleted file mode 100644 index a39599c526..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/BaseTestFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,244 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.stream.Stream; - -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; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -public abstract class BaseTestFunctionsFromSpreadsheet { - - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - interface SS { - /** Name of the first sheet in the spreadsheet (contains comments) */ - String README_SHEET_NAME = "Read Me"; - - /** Row (zero-based) in each sheet where the evaluation cases start. */ - int START_TEST_CASES_ROW_INDEX = 4; // Row '5' - /** Index of the column that contains the function names */ - int COLUMN_INDEX_MARKER = 0; // Column 'A' - int COLUMN_INDEX_EVALUATION = 1; // Column 'B' - int COLUMN_INDEX_EXPECTED_RESULT = 2; // Column 'C' - int COLUMN_ROW_COMMENT = 3; // Column 'D' - - /** Used to indicate when there are no more test cases on the current sheet */ - String TEST_CASES_END_MARKER = ""; - /** Used to indicate that the test on the current row should be ignored */ - String SKIP_CURRENT_TEST_CASE_MARKER = ""; - - } - - - - protected static Stream data(Class clazz, String filename) throws Exception { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook(filename); - confirmReadMeSheet(workbook, clazz); - - List data = new ArrayList<>(); - - int nSheets = workbook.getNumberOfSheets(); - for(int sheetIdx=1; sheetIdx< nSheets; sheetIdx++) { - HSSFSheet sheet = workbook.getSheetAt(sheetIdx); - processFunctionGroup(data, sheet, SS.START_TEST_CASES_ROW_INDEX, filename); - } - - workbook.close(); - - return data.stream(); - } - - private static void processFunctionGroup(List data, HSSFSheet sheet, final int startRowIndex, String filename) { - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet.getWorkbook()); - - int precisionColumnIndex = -1; - HSSFRow precisionRow = sheet.getWorkbook().getSheetAt(0).getRow(11); - HSSFCell precisionCell = precisionRow == null ? null : precisionRow.getCell(0); - if(precisionCell != null && precisionCell.getCellType() == CellType.NUMERIC){ - precisionColumnIndex = (int)precisionCell.getNumericCellValue(); - } - - - String currentGroupComment = ""; - final int maxRows = sheet.getLastRowNum()+1; - for(int rowIndex=startRowIndex; rowIndex clazz) { - String firstSheetName = workbook.getSheetName(0); - assertTrue(firstSheetName.equalsIgnoreCase(SS.README_SHEET_NAME), - "First sheet's name was '" + firstSheetName + "' but expected '" + SS.README_SHEET_NAME + "'"); - HSSFSheet sheet = workbook.getSheetAt(0); - String specifiedClassName = sheet.getRow(2).getCell(0).getRichStringCellValue().getString(); - assertEquals(clazz.getName(), specifiedClassName, "Test class name in spreadsheet comment"); - - HSSFRow precisionRow = sheet.getRow(11); - HSSFCell precisionCell = precisionRow == null ? null : precisionRow.getCell(0); - if(precisionCell != null && precisionCell.getCellType() == CellType.NUMERIC){ - - } - } - - /** - * @return null if cell is missing, empty or blank - */ - private static String getCellTextValue(HSSFRow r, int colIndex, String columnName) { - if(r == null) { - return null; - } - HSSFCell cell = r.getCell(colIndex); - if(cell == null) { - return null; - } - if(cell.getCellType() == CellType.BLANK) { - return null; - } - if(cell.getCellType() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - - fail("Bad cell type for '" + columnName + "' column: (" - + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - return ""; - } - - private static String formatValue(HSSFCell expectedCell) { - switch (expectedCell.getCellType()) { - case BLANK: return ""; - case BOOLEAN: return Boolean.toString(expectedCell.getBooleanCellValue()); - case NUMERIC: return Double.toString(expectedCell.getNumericCellValue()); - case STRING: return expectedCell.getRichStringCellValue().getString(); - default: fail("Unexpected cell type of expected value (" + expectedCell.getCellType() + ")"); - } - return ""; - } - - -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/BaseTestNumeric.java b/src/testcases/org/apache/poi/ss/formula/functions/BaseTestNumeric.java deleted file mode 100644 index d5e02e0de8..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/BaseTestNumeric.java +++ /dev/null @@ -1,66 +0,0 @@ -/* -* 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. -*/ -/* - * Created on May 29, 2005 - * - */ -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * @author Amol S. Deshmukh < amolweb at ya hoo dot com > - * - */ -public abstract class BaseTestNumeric { - - public static final double POS_ZERO = 1E-4; - public static final double DIFF_TOLERANCE_FACTOR = 1E-8; - - /** - * Why doesnt JUnit have a method like this for doubles? - * The current impl (3.8.1) of Junit has a retar*** method - * for comparing doubles. DO NOT use that. - * TODO: This class should really be in an abstract super class - * to avoid code duplication across this project. - */ - public static void assertDouble(String message, double baseval, double checkval, double almostZero, double diffToleranceFactor) { - double posZero = Math.abs(almostZero); - double negZero = -1 * posZero; - if (Double.isNaN(baseval)) { - assertTrue(Double.isNaN(baseval), message+": Expected " + baseval + " but was " + checkval); - } - else if (Double.isInfinite(baseval)) { - assertTrue(Double.isInfinite(baseval) && ((baseval<0) == (checkval<0)), message+": Expected " + baseval + " but was " + checkval); - } - else { - assertTrue(baseval != 0 - ? Math.abs(baseval - checkval) <= Math.abs(diffToleranceFactor * baseval) - : checkval < posZero && checkval > negZero, - message+": Expected " + baseval + " but was " + checkval); - } - } - - public static void assertDouble(String msg, double baseval, double checkval) { - assertDouble(msg, baseval, checkval, POS_ZERO, DIFF_TOLERANCE_FACTOR); - } - - - public static void assertDouble(double baseval, double checkval) { - assertDouble("", baseval, checkval, POS_ZERO, DIFF_TOLERANCE_FACTOR); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/EvalFactory.java b/src/testcases/org/apache/poi/ss/formula/functions/EvalFactory.java deleted file mode 100644 index 345b4fb80c..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/EvalFactory.java +++ /dev/null @@ -1,186 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.TwoDEval; -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.AreaEvalBase; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.RefEval; -import org.apache.poi.ss.formula.eval.RefEvalBase; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.ptg.AreaI; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.ptg.Ref3DPtg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.util.AreaReference; - -/** - * Test helper class for creating mock Eval objects - * - * @author Josh Micich - */ -public final class EvalFactory { - - private EvalFactory() { - // no instances of this class - } - - /** - * Creates a dummy AreaEval - * @param values empty (null) entries in this array will be converted to NumberEval.ZERO - */ - public static AreaEval createAreaEval(String areaRefStr, ValueEval[] values) { - AreaPtg areaPtg = new AreaPtg(new AreaReference(areaRefStr, SpreadsheetVersion.EXCEL2007)); - return createAreaEval(areaPtg, values); - } - - /** - * Creates a dummy AreaEval - * @param values empty (null) entries in this array will be converted to NumberEval.ZERO - */ - public static AreaEval createAreaEval(AreaPtg areaPtg, ValueEval[] values) { - int nCols = areaPtg.getLastColumn() - areaPtg.getFirstColumn() + 1; - int nRows = areaPtg.getLastRow() - areaPtg.getFirstRow() + 1; - int nExpected = nRows * nCols; - if (values.length != nExpected) { - throw new RuntimeException("Expected " + nExpected + " values but got " + values.length); - } - for (int i = 0; i < nExpected; i++) { - if (values[i] == null) { - values[i] = NumberEval.ZERO; - } - } - return new MockAreaEval(areaPtg, values); - } - - /** - * Creates a single RefEval (with value zero) - */ - public static RefEval createRefEval(String refStr) { - return createRefEval(refStr, NumberEval.ZERO); - } - public static RefEval createRefEval(String refStr, ValueEval value) { - return new MockRefEval(new RefPtg(refStr), value); - } - - private static final class MockAreaEval extends AreaEvalBase { - private final ValueEval[] _values; - public MockAreaEval(AreaI areaPtg, ValueEval[] values) { - super(areaPtg); - _values = values; - } - private MockAreaEval(int firstRow, int firstColumn, int lastRow, int lastColumn, ValueEval[] values) { - super(firstRow, firstColumn, lastRow, lastColumn); - _values = values; - } - @Override - public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) { - return getRelativeValue(-1, relativeRowIndex, relativeColumnIndex); - } - @Override - public ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex) { - if (relativeRowIndex < 0 || relativeRowIndex >=getHeight()) { - throw new IllegalArgumentException("row index out of range"); - } - int width = getWidth(); - if (relativeColumnIndex < 0 || relativeColumnIndex >=width) { - throw new IllegalArgumentException("column index out of range"); - } - int oneDimensionalIndex = relativeRowIndex * width + relativeColumnIndex; - return _values[oneDimensionalIndex]; - } - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { - if (relFirstRowIx < 0 || relFirstColIx < 0 - || relLastRowIx >= getHeight() || relLastColIx >= getWidth()) { - throw new RuntimeException("Operation not implemented on this mock object"); - } - - if (relFirstRowIx == 0 && relFirstColIx == 0 - && relLastRowIx == getHeight()-1 && relLastColIx == getWidth()-1) { - return this; - } - ValueEval[] values = transpose(_values, getWidth(), relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); - return new MockAreaEval(getFirstRow() + relFirstRowIx, getFirstColumn() + relFirstColIx, - getFirstRow() + relLastRowIx, getFirstColumn() + relLastColIx, values); - } - private static ValueEval[] transpose(ValueEval[] srcValues, int srcWidth, - int relFirstRowIx, int relLastRowIx, - int relFirstColIx, int relLastColIx) { - int height = relLastRowIx - relFirstRowIx + 1; - int width = relLastColIx - relFirstColIx + 1; - ValueEval[] result = new ValueEval[height * width]; - for (int r=0; r= getHeight()) { - throw new IllegalArgumentException("Invalid rowIndex " + rowIndex - + ". Allowable range is (0.." + getHeight() + ")."); - } - ValueEval[] values = new ValueEval[getWidth()]; - for (int i = 0; i < values.length; i++) { - values[i] = getRelativeValue(rowIndex, i); - } - return new MockAreaEval(rowIndex, getFirstColumn(), rowIndex, getLastColumn(), values); - } - @Override - public TwoDEval getColumn(int columnIndex) { - if (columnIndex >= getWidth()) { - throw new IllegalArgumentException("Invalid columnIndex " + columnIndex - + ". Allowable range is (0.." + getWidth() + ")."); - } - ValueEval[] values = new ValueEval[getHeight()]; - for (int i = 0; i < values.length; i++) { - values[i] = getRelativeValue(i, columnIndex); - } - return new MockAreaEval(getFirstRow(), columnIndex, getLastRow(), columnIndex, values); - } - } - - private static final class MockRefEval extends RefEvalBase { - private final ValueEval _value; - public MockRefEval(RefPtg ptg, ValueEval value) { - super(-1, -1, ptg.getRow(), ptg.getColumn()); - _value = value; - } - public MockRefEval(Ref3DPtg ptg, ValueEval value) { - super(-1, -1, ptg.getRow(), ptg.getColumn()); - _value = value; - } - @Override - public ValueEval getInnerValueEval(int sheetIndex) { - return _value; - } - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { - throw new RuntimeException("Operation not implemented on this mock object"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java b/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java deleted file mode 100644 index bf49dad45d..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.fail; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NotImplementedException; -import org.apache.poi.ss.formula.eval.NumericValueEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Test helper class for invoking functions with numeric results. - */ -public final class NumericFunctionInvoker { - - private NumericFunctionInvoker() { - // no instances of this class - } - - private static final class NumericEvalEx extends Exception { - public NumericEvalEx(String msg) { - super(msg); - } - } - - /** - * Invokes the specified function with the arguments. - *

- * Assumes that the cell coordinate parameters of - * Function.evaluate(args, srcCellRow, srcCellCol) - * are not required. - *

- * This method cannot be used for confirming error return codes. Any non-numeric evaluation - * result causes the current junit test to fail. - */ - public static double invoke(Function f, ValueEval[] args) { - return invoke(f, args, -1, -1); - } - /** - * Invokes the specified operator with the arguments. - *

- * This method cannot be used for confirming error return codes. Any non-numeric evaluation - * result causes the current junit test to fail. - */ - public static double invoke(Function f, ValueEval[] args, int srcCellRow, int srcCellCol) { - try { - return invokeInternal(f, args, srcCellRow, srcCellCol); - } catch (NumericEvalEx e) { - fail("Evaluation of function (" + f.getClass().getName() + ") failed: " + e.getMessage()); - return -1; - } - } - /** - * Formats nicer error messages for the junit output - */ - private static double invokeInternal(Function target, ValueEval[] args, int srcCellRow, int srcCellCol) - throws NumericEvalEx { - ValueEval evalResult; - try { - evalResult = target.evaluate(args, srcCellRow, (short)srcCellCol); - } catch (NotImplementedException e) { - throw new NumericEvalEx("Not implemented:" + e.getMessage()); - } - - if(evalResult == null) { - throw new NumericEvalEx("Result object was null"); - } - if(evalResult instanceof ErrorEval) { - ErrorEval ee = (ErrorEval) evalResult; - throw new NumericEvalEx(formatErrorMessage(ee)); - } - if(!(evalResult instanceof NumericValueEval)) { - throw new NumericEvalEx("Result object type (" + evalResult.getClass().getName() - + ") is invalid. Expected implementor of (" - + NumericValueEval.class.getName() + ")"); - } - - NumericValueEval result = (NumericValueEval) evalResult; - return result.getNumberValue(); - } - - private static String formatErrorMessage(ErrorEval ee) { - boolean b = (ee == ErrorEval.VALUE_INVALID || ee.getErrorCode() == ErrorEval.VALUE_INVALID.getErrorCode()); - return b ? "Error code: #VALUE! (invalid value)" : "Error code=" + ee.getErrorCode(); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/RefEvalImplementation.java b/src/testcases/org/apache/poi/ss/formula/functions/RefEvalImplementation.java deleted file mode 100644 index 05cfdfc8a2..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/RefEvalImplementation.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.RefEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -final class RefEvalImplementation implements RefEval { - - private final ValueEval value; - - public RefEvalImplementation(ValueEval value) { - this.value = value; - } - - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, - int relFirstColIx, int relLastColIx) { - throw new UnsupportedOperationException(); - } - - @Override - public ValueEval getInnerValueEval(int sheetIndex) { - return value; - } - - @Override - public int getNumberOfSheets() { - return 1; - } - - @Override - public int getFirstSheetIndex() { - return 0; - } - - @Override - public int getLastSheetIndex() { - return 0; - } - - @Override - public int getRow() { - throw new UnsupportedOperationException(); - } - - @Override - public int getColumn() { - throw new UnsupportedOperationException(); - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestAddress.java b/src/testcases/org/apache/poi/ss/formula/functions/TestAddress.java deleted file mode 100644 index 766ccc303e..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestAddress.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -final class TestAddress { - - @Test - void testAddress() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFCell cell = wb.createSheet().createRow(0).createCell(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - String formulaText = "ADDRESS(1,2)"; - confirmResult(fe, cell, formulaText, "$B$1"); - - formulaText = "ADDRESS(1,2,)"; // with explicitly empty third parameter - confirmResult(fe, cell, formulaText, "$B$1"); - - formulaText = "ADDRESS(22,44)"; - confirmResult(fe, cell, formulaText, "$AR$22"); - - formulaText = "ADDRESS(1,1)"; - confirmResult(fe, cell, formulaText, "$A$1"); - - formulaText = "ADDRESS(1,128)"; - confirmResult(fe, cell, formulaText, "$DX$1"); - - formulaText = "ADDRESS(1,512)"; - confirmResult(fe, cell, formulaText, "$SR$1"); - - formulaText = "ADDRESS(1,1000)"; - confirmResult(fe, cell, formulaText, "$ALL$1"); - - formulaText = "ADDRESS(1,10000)"; - confirmResult(fe, cell, formulaText, "$NTP$1"); - - formulaText = "ADDRESS(2,3)"; - confirmResult(fe, cell, formulaText, "$C$2"); - - formulaText = "ADDRESS(2,3,2)"; - confirmResult(fe, cell, formulaText, "C$2"); - - formulaText = "ADDRESS(2,3,2,,\"EXCEL SHEET\")"; - confirmResult(fe, cell, formulaText, "'EXCEL SHEET'!C$2"); - - formulaText = "ADDRESS(2,3,3,TRUE,\"[Book1]Sheet1\")"; - confirmResult(fe, cell, formulaText, "'[Book1]Sheet1'!$C2"); - } - - private static void confirmResult(HSSFFormulaEvaluator fe, HSSFCell cell, String formulaText, - String expectedResult) { - cell.setCellFormula(formulaText); - fe.notifyUpdateCell(cell); - CellValue result = fe.evaluate(cell); - assertEquals(result.getCellType(), CellType.STRING); - assertEquals(expectedResult, result.getStringValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestAreas.java b/src/testcases/org/apache/poi/ss/formula/functions/TestAreas.java deleted file mode 100644 index 3137614d3a..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestAreas.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -final class TestAreas { - - @Test - void testAreas() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFCell cell = wb.createSheet().createRow(0).createCell(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - String formulaText = "AREAS(B1)"; - confirmResult(fe, cell, formulaText,1.0); - - formulaText = "AREAS(B2:D4)"; - confirmResult(fe, cell, formulaText,1.0); - - formulaText = "AREAS((B2:D4,E5,F6:I9))"; - confirmResult(fe, cell, formulaText,3.0); - - formulaText = "AREAS((B2:D4,E5,C3,E4))"; - confirmResult(fe, cell, formulaText,4.0); - - formulaText = "AREAS((I9))"; - confirmResult(fe, cell, formulaText,1.0); - } - - private static void confirmResult(HSSFFormulaEvaluator fe, HSSFCell cell, String formulaText,Double expectedResult) { - cell.setCellFormula(formulaText); - fe.notifyUpdateCell(cell); - CellValue result = fe.evaluate(cell); - assertEquals(result.getCellType(), CellType.NUMERIC); - assertEquals(expectedResult, result.getNumberValue(), 0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestAverage.java b/src/testcases/org/apache/poi/ss/formula/functions/TestAverage.java deleted file mode 100644 index bfee8f6ad6..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestAverage.java +++ /dev/null @@ -1,101 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for Excel function AVERAGE() - */ -final class TestAverage { - - private static ValueEval invokeAverage(ValueEval[] args) { - return AggregateFunction.AVERAGE.evaluate(args, -1, (short)-1); - } - - private void confirmAverage(ValueEval[] args, double expected) { - ValueEval result = invokeAverage(args); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval)result).getNumberValue(), 0); - } - - private void confirmAverage(ValueEval[] args, ErrorEval expectedError) { - ValueEval result = invokeAverage(args); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - @Test - void testBasic() { - - ValueEval[] values = { - new NumberEval(1), - new NumberEval(2), - new NumberEval(3), - new NumberEval(4), - }; - - confirmAverage(values, 2.5); - - values = new ValueEval[] { - new NumberEval(1), - new NumberEval(2), - BlankEval.instance, - new NumberEval(3), - BlankEval.instance, - new NumberEval(4), - BlankEval.instance, - }; - - confirmAverage(values, 2.5); - } - - /** - * Valid cases where values are not pure numbers - */ - @Test - void testUnusualArgs() { - ValueEval[] values = { - new NumberEval(1), - new NumberEval(2), - BoolEval.TRUE, - BoolEval.FALSE, - }; - - confirmAverage(values, 1.0); - - } - - @Test - void testErrors() { - ValueEval[] values = { - new NumberEval(1), - ErrorEval.NAME_INVALID, - new NumberEval(3), - ErrorEval.DIV_ZERO, - }; - confirmAverage(values, ErrorEval.NAME_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestBin2Dec.java b/src/testcases/org/apache/poi/ss/formula/functions/TestBin2Dec.java deleted file mode 100644 index e873ba227c..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestBin2Dec.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Bin2Dec} - * - * @author cedric dot walter @ gmail dot com - */ -final class TestBin2Dec { - - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Bin2Dec().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals(NumberEval.class, result.getClass(), "Had: " + result); - assertEquals(expected, ((NumberEval) result).getStringValue(), msg); - } - - private static void confirmValueError(String msg, String number1, ErrorEval numError) { - ValueEval result = invokeValue(number1); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(numError, result, msg); - } - - @Test - void testBasic() { - confirmValue("Converts binary '00101' to decimal (5)", "00101", "5"); - confirmValue("Converts binary '1111111111' to decimal (-1)", "1111111111", "-1"); - confirmValue("Converts binary '1111111110' to decimal (-2)", "1111111110", "-2"); - confirmValue("Converts binary '0111111111' to decimal (511)", "0111111111", "511"); - } - - @Test - void testErrors() { - confirmValueError("does not support more than 10 digits","01010101010", ErrorEval.NUM_ERROR); - confirmValueError("not a valid binary number","GGGGGGG", ErrorEval.NUM_ERROR); - confirmValueError("not a valid binary number","3.14159", ErrorEval.NUM_ERROR); - } - - @Test - void testEvalOperationEvaluationContext() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Bin2Dec().evaluate(args, ctx); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals("0", ((NumberEval) result).getStringValue()); - } - - @Test - void testEvalOperationEvaluationContextFails() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 0) }; - ValueEval result = new Bin2Dec().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - private OperationEvaluationContext createContext() { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet(); - HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, (sheetIndex, rowIndex, columnIndex) -> true, null); - return new OperationEvaluationContext(workbookEvaluator, workbook, 0, 0, 0, null); - } - - @Test - void testRefs() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Bin2Dec().evaluate(args, -1, -1); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals("0", ((NumberEval) result).getStringValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestBooleanFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestBooleanFunctionsFromSpreadsheet.java deleted file mode 100644 index bb9a238eaa..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestBooleanFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests boolean functions as loaded from a test data spreadsheet.

- */ -class TestBooleanFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestBooleanFunctionsFromSpreadsheet.class, "BooleanFunctionsTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java b/src/testcases/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java deleted file mode 100644 index b59eb221a4..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java +++ /dev/null @@ -1,115 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Test for YEAR / MONTH / DAY / HOUR / MINUTE / SECOND - */ -final class TestCalendarFieldFunction { - - private HSSFCell cell11; - private HSSFFormulaEvaluator evaluator; - - @BeforeEach - void setUp() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - cell11 = sheet.createRow(0).createCell(0); - evaluator = new HSSFFormulaEvaluator(wb); - } - - @Test - void testValid() { - confirm("YEAR(2.26)", 1900); - confirm("MONTH(2.26)", 1); - confirm("DAY(2.26)", 2); - confirm("HOUR(2.26)", 6); - confirm("MINUTE(2.26)", 14); - confirm("SECOND(2.26)", 24); - - confirm("YEAR(40627.4860417)", 2011); - confirm("MONTH(40627.4860417)", 3); - confirm("DAY(40627.4860417)", 25); - confirm("HOUR(40627.4860417)", 11); - confirm("MINUTE(40627.4860417)", 39); - confirm("SECOND(40627.4860417)", 54); - } - - @Test - void testRounding() { - // 41484.999994200 = 23:59:59,499 - // 41484.9999942129 = 23:59:59,500 (but sub-milliseconds are below 0.5 (0.49999453965575), XLS-second results in 59) - // 41484.9999942130 = 23:59:59,500 (sub-milliseconds are 0.50000334065408, XLS-second results in 00) - - confirm("DAY(41484.999994200)", 29); - confirm("SECOND(41484.999994200)", 59); - - confirm("DAY(41484.9999942129)", 29); - confirm("HOUR(41484.9999942129)", 23); - confirm("MINUTE(41484.9999942129)", 59); - confirm("SECOND(41484.9999942129)", 59); - - confirm("DAY(41484.9999942130)", 30); - confirm("HOUR(41484.9999942130)", 0); - confirm("MINUTE(41484.9999942130)", 0); - confirm("SECOND(41484.9999942130)", 0); - } - - @Test - void testDaylightSaving() { - confirm("HOUR(41364.08263888890000)", 1); // 31.03.2013 01:59:00,000 - confirm("HOUR(41364.08333333330000)", 2); // 31.03.2013 02:00:00,000 (this time does not exist in TZ CET, but EXCEL does not care) - confirm("HOUR(41364.08402777780000)", 2); // 31.03.2013 02:01:00,000 - confirm("HOUR(41364.12430555560000)", 2); // 31.03.2013 02:59:00,000 - confirm("HOUR(41364.12500000000000)", 3); // 31.03.2013 03:00:00,000 - } - - @Test - void testBugDate() { - confirm("YEAR(0.0)", 1900); - confirm("MONTH(0.0)", 1); - confirm("DAY(0.0)", 0); - - confirm("YEAR(0.26)", 1900); - confirm("MONTH(0.26)", 1); - confirm("DAY(0.26)", 0); - confirm("HOUR(0.26)", 6); - confirm("MINUTE(0.26)", 14); - confirm("SECOND(0.26)", 24); - } - - private void confirm(String formulaText, double expectedResult) { - cell11.setCellFormula(formulaText); - evaluator.clearAllCachedResultValues(); - CellValue cv = evaluator.evaluate(cell11); - assertEquals(CellType.NUMERIC, cv.getCellType(), "Wrong result type"); - double actualValue = cv.getNumberValue(); - assertEquals(expectedResult, actualValue, 0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestClean.java b/src/testcases/org/apache/poi/ss/formula/functions/TestClean.java deleted file mode 100644 index 1ab4f90ea0..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestClean.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -final class TestClean { - - @Test - void testClean() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFCell cell = wb.createSheet().createRow(0).createCell(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - String[] asserts = { - "aniket\u0007\u0017\u0019", "aniket", - "\u0011aniket\u0007\u0017\u0010", "aniket", - "\u0011aniket\u0007\u0017\u007F", "aniket\u007F", - "\u2116aniket\u2211\uFB5E\u2039", "\u2116aniket\u2211\uFB5E\u2039", - }; - - for(int i = 0; i < asserts.length; i+= 2){ - String formulaText = "CLEAN(\"" + asserts[i] + "\")"; - confirmResult(fe, cell, formulaText, asserts[i + 1]); - } - - asserts = new String[] { - "CHAR(7)&\"text\"&CHAR(7)", "text", - "CHAR(7)&\"text\"&CHAR(17)", "text", - "CHAR(181)&\"text\"&CHAR(190)", "\u00B5text\u00BE", - "\"text\"&CHAR(160)&\"'\"", "text\u00A0'", - }; - for(int i = 0; i < asserts.length; i+= 2){ - String formulaText = "CLEAN(" + asserts[i] + ")"; - confirmResult(fe, cell, formulaText, asserts[i + 1]); - } - } - - private static void confirmResult(HSSFFormulaEvaluator fe, HSSFCell cell, String formulaText, - String expectedResult) { - cell.setCellFormula(formulaText); - fe.notifyUpdateCell(cell); - CellValue result = fe.evaluate(cell); - assertEquals(result.getCellType(), CellType.STRING); - assertEquals(expectedResult, result.getStringValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestCode.java b/src/testcases/org/apache/poi/ss/formula/functions/TestCode.java deleted file mode 100644 index 32dd466ba8..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCode.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Code} - * - * @author cedric dot walter @ gmail dot com - */ -class TestCode { - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[]{new StringEval(number1),}; - return new Code().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals(StringEval.class, result.getClass()); - assertEquals(expected, ((StringEval) result).getStringValue(), msg); - } - - private static void confirmValueError(String msg, String number1, ErrorEval numError) { - ValueEval result = invokeValue(number1); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(numError, result, msg); - } - - @Test - void testBasic() { - confirmValue("Displays the numeric code for A (65)", "A", "65"); - confirmValue("Displays the numeric code for the first character in text ABCDEFGHI (65)", "ABCDEFGHI", "65"); - - confirmValue("Displays the numeric code for ! (33)", "!", "33"); - } - - @Test - void testErrors() { - confirmValueError("Empty text", "", ErrorEval.VALUE_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestCodeFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestCodeFunctionsFromSpreadsheet.java deleted file mode 100644 index 213aeca067..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCodeFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests CODE() as loaded from a test data spreadsheet.

- */ -class TestCodeFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestCodeFunctionsFromSpreadsheet.class, "CodeFunctionTestCaseData.xls"); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestComplex.java b/src/testcases/org/apache/poi/ss/formula/functions/TestComplex.java deleted file mode 100644 index 018e2222f3..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestComplex.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Complex} - * - * @author cedric dot walter @ gmail dot com - */ -class TestComplex { - private static ValueEval invokeValue(String real_num, String i_num, String suffix) { - ValueEval[] args = new ValueEval[]{new StringEval(real_num), new StringEval(i_num), new StringEval(suffix)}; - return new Complex().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String real_num, String i_num, String suffix, String expected) { - ValueEval result = invokeValue(real_num, i_num, suffix); - assertEquals(StringEval.class, result.getClass()); - assertEquals(expected, ((StringEval) result).getStringValue(), msg); - } - - private static void confirmValueError(String msg, String real_num, String i_num, String suffix, ErrorEval numError) { - ValueEval result = invokeValue(real_num, i_num, suffix); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(numError, result, msg); - } - - @Test - void testBasic() { - confirmValue("Complex number with 3 and 4 as the real and imaginary coefficients (3 + 4i)", "3","4", "", "3+4i"); - confirmValue("Complex number with 3 and 4 as the real and imaginary coefficients, and j as the suffix (3 + 4j)", "3","4", "j", "3+4j"); - - confirmValue("Complex number with 0 and 1 as the real and imaginary coefficients (i)", "0","1", "", "i"); - confirmValue("Complex number with 1 and 0 as the real and imaginary coefficients (1)", "1","0", "", "1"); - - confirmValue("Complex number with 2 and 3 as the real and imaginary coefficients (2 + 3i)", "2","3", "", "2+3i"); - confirmValue("Complex number with -2 and -3 as the real and imaginary coefficients (-2-3i)", "-2","-3", "", "-2-3i"); - - confirmValue("Complex number with -2 and -3 as the real and imaginary coefficients (-0.5-3.2i)", "-0.5","-3.2", "", "-0.5-3.2i"); - } - - @Test - void testErrors() { - confirmValueError("argument is nonnumeric", "ABCD", "","", ErrorEval.VALUE_INVALID); - confirmValueError("argument is nonnumeric", "1", "ABCD","", ErrorEval.VALUE_INVALID); - confirmValueError("f suffix is neither \"i\" nor \"j\"", "1", "1","k", ErrorEval.VALUE_INVALID); - - confirmValueError("never use \"I\" ", "1", "1","I", ErrorEval.VALUE_INVALID); - confirmValueError("never use \"J\" ", "1", "1","J", ErrorEval.VALUE_INVALID); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestComplexFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestComplexFunctionsFromSpreadsheet.java deleted file mode 100644 index 3318832fc1..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestComplexFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests COMPLEX() as loaded from a test data spreadsheet.

- */ -class TestComplexFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestComplexFunctionsFromSpreadsheet.class, "ComplexFunctionTestCaseData.xls"); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestCountFuncs.java b/src/testcases/org/apache/poi/ss/formula/functions/TestCountFuncs.java deleted file mode 100644 index 6b351fbe0d..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCountFuncs.java +++ /dev/null @@ -1,584 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -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; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.OperandResolver; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.CountUtils.I_MatchPredicate; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; - -/** - * Test cases for COUNT(), COUNTA() COUNTIF(), COUNTBLANK() - */ -final class TestCountFuncs { - - private static final String NULL = null; - - @Test - void testCountBlank() { - AreaEval range; - ValueEval[] values; - - values = new ValueEval[] { - new NumberEval(0), - new StringEval(""), // note - does match blank - BoolEval.TRUE, - BoolEval.FALSE, - ErrorEval.DIV_ZERO, - BlankEval.instance, - }; - range = EvalFactory.createAreaEval("A1:B3", values); - confirmCountBlank(2, range); - - values = new ValueEval[] { - new NumberEval(0), - new StringEval(""), // does match blank - BlankEval.instance, - BoolEval.FALSE, - BoolEval.TRUE, - BlankEval.instance, - }; - range = EvalFactory.createAreaEval("A1:B3", values); - confirmCountBlank(3, range); - } - - @Test - void testCountA() { - ValueEval[] args; - - args = new ValueEval[] { - new NumberEval(0), - }; - confirmCountA(1, args); - - args = new ValueEval[] { - new NumberEval(0), - new NumberEval(0), - new StringEval(""), - }; - confirmCountA(3, args); - - args = new ValueEval[] { - EvalFactory.createAreaEval("D2:F5", new ValueEval[12]), - }; - confirmCountA(12, args); - - args = new ValueEval[] { - EvalFactory.createAreaEval("D1:F5", new ValueEval[15]), - EvalFactory.createRefEval("A1"), - EvalFactory.createAreaEval("A1:G6", new ValueEval[42]), - new NumberEval(0), - }; - confirmCountA(59, args); - } - - @Test - void testCountIf() { - AreaEval range; - ValueEval[] values; - - // when criteria is a boolean value - values = new ValueEval[] { - new NumberEval(0), - new StringEval("TRUE"), // note - does not match boolean TRUE - BoolEval.TRUE, - BoolEval.FALSE, - BoolEval.TRUE, - BlankEval.instance, - }; - range = EvalFactory.createAreaEval("A1:B3", values); - confirmCountIf(2, range, BoolEval.TRUE); - - // when criteria is numeric - values = new ValueEval[] { - new NumberEval(0), - new StringEval("2"), - new StringEval("2.001"), - new NumberEval(2), - new NumberEval(2), - BoolEval.TRUE, - }; - range = EvalFactory.createAreaEval("A1:B3", values); - confirmCountIf(3, range, new NumberEval(2)); - // note - same results when criteria is a string that parses as the number with the same value - confirmCountIf(3, range, new StringEval("2.00")); - - // when criteria is an expression (starting with a comparison operator) - confirmCountIf(2, range, new StringEval(">1")); - // when criteria is an expression (starting with a comparison operator) - confirmCountIf(2, range, new StringEval(">0.5")); - } - - @Test - void testCriteriaPredicateNe_Bug46647() { - I_MatchPredicate mp = Countif.createCriteriaPredicate(new StringEval("<>aa"), 0, 0); - assertNotNull(mp); - StringEval seA = new StringEval("aa"); // this should not match the criteria '<>aa' - StringEval seB = new StringEval("bb"); // this should match - assertFalse(mp.matches(seA) && !mp.matches(seB), "Identified bug 46647"); - assertFalse(mp.matches(seA)); - assertTrue(mp.matches(seB)); - - // general tests for not-equal (<>) operator - AreaEval range; - ValueEval[] values; - - values = new ValueEval[] { - new StringEval("aa"), - new StringEval("def"), - new StringEval("aa"), - new StringEval("ghi"), - new StringEval("aa"), - new StringEval("aa"), - }; - - range = EvalFactory.createAreaEval("A1:A6", values); - confirmCountIf(2, range, new StringEval("<>aa")); - - values = new ValueEval[] { - new StringEval("ab"), - new StringEval("aabb"), - new StringEval("aa"), // match - new StringEval("abb"), - new StringEval("aab"), - new StringEval("ba"), // match - }; - - range = EvalFactory.createAreaEval("A1:A6", values); - confirmCountIf(2, range, new StringEval("<>a*b")); - - - values = new ValueEval[] { - new NumberEval(222), - new NumberEval(222), - new NumberEval(111), - new StringEval("aa"), - new StringEval("111"), - }; - - range = EvalFactory.createAreaEval("A1:A5", values); - confirmCountIf(4, range, new StringEval("<>111")); - } - - /** - * String criteria in COUNTIF are case insensitive; - * for example, the string "apples" and the string "APPLES" will match the same cells. - */ - @Test - void testCaseInsensitiveStringComparison() { - AreaEval range; - ValueEval[] values; - - values = new ValueEval[] { - new StringEval("no"), - new StringEval("NO"), - new StringEval("No"), - new StringEval("Yes") - }; - - range = EvalFactory.createAreaEval("A1:A4", values); - confirmCountIf(3, range, new StringEval("no")); - confirmCountIf(3, range, new StringEval("NO")); - confirmCountIf(3, range, new StringEval("No")); - } - - /** - * special case where the criteria argument is a cell reference - */ - @Test - void testCountIfWithCriteriaReference() { - - ValueEval[] values = { - new NumberEval(22), - new NumberEval(25), - new NumberEval(21), - new NumberEval(25), - new NumberEval(25), - new NumberEval(25), - }; - AreaEval arg0 = EvalFactory.createAreaEval("C1:C6", values); - - ValueEval criteriaArg = EvalFactory.createRefEval("A1", new NumberEval(25)); - ValueEval[] args= { arg0, criteriaArg, }; - - double actual = NumericFunctionInvoker.invoke(new Countif(), args); - assertEquals(4, actual, 0D); - } - - private static void confirmCountA(int expected, ValueEval[] args) { - double result = NumericFunctionInvoker.invoke(new Counta(), args); - assertEquals(expected, result, 0); - } - private static void confirmCountIf(int expected, AreaEval range, ValueEval criteria) { - - ValueEval[] args = { range, criteria, }; - double result = NumericFunctionInvoker.invoke(new Countif(), args); - assertEquals(expected, result, 0); - } - private static void confirmCountBlank(int expected, AreaEval range) { - - ValueEval[] args = { range }; - double result = NumericFunctionInvoker.invoke(new Countblank(), args); - assertEquals(expected, result, 0); - } - - private static I_MatchPredicate createCriteriaPredicate(ValueEval ev) { - return Countif.createCriteriaPredicate(ev, 0, 0); - } - - /** - * the criteria arg is mostly handled by {@link OperandResolver#getSingleValue(org.apache.poi.ss.formula.eval.ValueEval, int, int)}} - */ - @Test - void testCountifAreaCriteria() { - int srcColIx = 2; // anything but column A - - ValueEval v0 = new NumberEval(2.0); - ValueEval v1 = new StringEval("abc"); - ValueEval v2 = ErrorEval.DIV_ZERO; - - AreaEval ev = EvalFactory.createAreaEval("A10:A12", new ValueEval[] { v0, v1, v2, }); - - I_MatchPredicate mp; - mp = Countif.createCriteriaPredicate(ev, 9, srcColIx); - assertNotNull(mp); - confirmPredicate(true, mp, srcColIx); - confirmPredicate(false, mp, "abc"); - confirmPredicate(false, mp, ErrorEval.DIV_ZERO); - - mp = Countif.createCriteriaPredicate(ev, 10, srcColIx); - assertNotNull(mp); - confirmPredicate(false, mp, srcColIx); - confirmPredicate(true, mp, "abc"); - confirmPredicate(false, mp, ErrorEval.DIV_ZERO); - - mp = Countif.createCriteriaPredicate(ev, 11, srcColIx); - assertNotNull(mp); - confirmPredicate(false, mp, srcColIx); - confirmPredicate(false, mp, "abc"); - confirmPredicate(true, mp, ErrorEval.DIV_ZERO); - confirmPredicate(false, mp, ErrorEval.VALUE_INVALID); - - // tricky: indexing outside of A10:A12 - // even this #VALUE! error gets used by COUNTIF as valid criteria - mp = Countif.createCriteriaPredicate(ev, 12, srcColIx); - assertNotNull(mp); - confirmPredicate(false, mp, srcColIx); - confirmPredicate(false, mp, "abc"); - confirmPredicate(false, mp, ErrorEval.DIV_ZERO); - confirmPredicate(true, mp, ErrorEval.VALUE_INVALID); - } - - @Test - void testCountifEmptyStringCriteria() { - I_MatchPredicate mp; - - // pred '=' matches blank cell but not empty string - mp = createCriteriaPredicate(new StringEval("=")); - confirmPredicate(false, mp, ""); - confirmPredicate(true, mp, NULL); - - // pred '' matches both blank cell but not empty string - mp = createCriteriaPredicate(new StringEval("")); - confirmPredicate(true, mp, ""); - confirmPredicate(true, mp, NULL); - - // pred '<>' matches empty string but not blank cell - mp = createCriteriaPredicate(new StringEval("<>")); - confirmPredicate(false, mp, NULL); - confirmPredicate(true, mp, ""); - } - - @Test - void testCountifComparisons() { - I_MatchPredicate mp; - - mp = createCriteriaPredicate(new StringEval(">5")); - confirmPredicate(false, mp, 4); - confirmPredicate(false, mp, 5); - confirmPredicate(true, mp, 6); - - mp = createCriteriaPredicate(new StringEval("<=5")); - confirmPredicate(true, mp, 4); - confirmPredicate(true, mp, 5); - confirmPredicate(false, mp, 6); - confirmPredicate(false, mp, "4.9"); - confirmPredicate(false, mp, "4.9t"); - confirmPredicate(false, mp, "5.1"); - confirmPredicate(false, mp, NULL); - - mp = createCriteriaPredicate(new StringEval("=abc")); - confirmPredicate(true, mp, "abc"); - - mp = createCriteriaPredicate(new StringEval("=42")); - confirmPredicate(false, mp, 41); - confirmPredicate(true, mp, 42); - confirmPredicate(true, mp, "42"); - - mp = createCriteriaPredicate(new StringEval(">abc")); - confirmPredicate(false, mp, 4); - confirmPredicate(false, mp, "abc"); - confirmPredicate(true, mp, "abd"); - - mp = createCriteriaPredicate(new StringEval(">4t3")); - confirmPredicate(false, mp, 4); - confirmPredicate(false, mp, 500); - confirmPredicate(true, mp, "500"); - confirmPredicate(true, mp, "4t4"); - } - - /** - * the criteria arg value can be an error code (the error does not - * propagate to the COUNTIF result). - */ - @Test - void testCountifErrorCriteria() { - I_MatchPredicate mp; - - mp = createCriteriaPredicate(new StringEval("#REF!")); - confirmPredicate(false, mp, 4); - confirmPredicate(false, mp, "#REF!"); - confirmPredicate(true, mp, ErrorEval.REF_INVALID); - - mp = createCriteriaPredicate(new StringEval("<#VALUE!")); - confirmPredicate(false, mp, 4); - confirmPredicate(false, mp, "#DIV/0!"); - confirmPredicate(false, mp, "#REF!"); - confirmPredicate(true, mp, ErrorEval.DIV_ZERO); - confirmPredicate(false, mp, ErrorEval.REF_INVALID); - - // not quite an error literal, should be treated as plain text - mp = createCriteriaPredicate(new StringEval("<=#REF!a")); - confirmPredicate(false, mp, 4); - confirmPredicate(true, mp, "#DIV/0!"); - confirmPredicate(true, mp, "#REF!"); - confirmPredicate(false, mp, ErrorEval.DIV_ZERO); - confirmPredicate(false, mp, ErrorEval.REF_INVALID); - } - - /** - * Bug #51498 - Check that CountIf behaves correctly for GTE, LTE - * and NEQ cases - */ - @Test - void testCountifBug51498() { - final int REF_COL = 4; - final int EVAL_COL = 3; - - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("51498.xls"); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - HSSFSheet sheet = workbook.getSheetAt(0); - - // numeric criteria - for (int i = 0; i < 8; i++) { - CellValue expected = evaluator.evaluate(sheet.getRow(i).getCell(REF_COL)); - CellValue actual = evaluator.evaluate(sheet.getRow(i).getCell(EVAL_COL)); - assertEquals(expected.formatAsString(), actual.formatAsString()); - } - - // boolean criteria - for (int i = 0; i < 8; i++) { - HSSFCell cellFmla = sheet.getRow(i).getCell(8); - HSSFCell cellRef = sheet.getRow(i).getCell(9); - - double expectedValue = cellRef.getNumericCellValue(); - double actualValue = evaluator.evaluate(cellFmla).getNumberValue(); - - assertEquals(expectedValue, actualValue, 0.0001, - "Problem with a formula at " + new CellReference(cellFmla).formatAsString() + "[" + cellFmla.getCellFormula()+"] "); - } - - // string criteria - for (int i = 1; i < 9; i++) { - HSSFCell cellFmla = sheet.getRow(i).getCell(13); - HSSFCell cellRef = sheet.getRow(i).getCell(14); - - double expectedValue = cellRef.getNumericCellValue(); - double actualValue = evaluator.evaluate(cellFmla).getNumberValue(); - - assertEquals(expectedValue, actualValue, 0.0001, - "Problem with a formula at " + new CellReference(cellFmla).formatAsString() + "[" + cellFmla.getCellFormula()+"] "); - } - } - - @Test - void testWildCards() { - I_MatchPredicate mp; - - mp = createCriteriaPredicate(new StringEval("a*b")); - confirmPredicate(false, mp, "abc"); - confirmPredicate(true, mp, "ab"); - confirmPredicate(true, mp, "axxb"); - confirmPredicate(false, mp, "xab"); - - mp = createCriteriaPredicate(new StringEval("a?b")); - confirmPredicate(false, mp, "abc"); - confirmPredicate(false, mp, "ab"); - confirmPredicate(false, mp, "axxb"); - confirmPredicate(false, mp, "xab"); - confirmPredicate(true, mp, "axb"); - - mp = createCriteriaPredicate(new StringEval("a~?")); - confirmPredicate(false, mp, "a~a"); - confirmPredicate(false, mp, "a~?"); - confirmPredicate(true, mp, "a?"); - - mp = createCriteriaPredicate(new StringEval("~*a")); - confirmPredicate(false, mp, "~aa"); - confirmPredicate(false, mp, "~*a"); - confirmPredicate(true, mp, "*a"); - - mp = createCriteriaPredicate(new StringEval("12?12")); - confirmPredicate(false, mp, 12812); - confirmPredicate(true, mp, "12812"); - confirmPredicate(false, mp, "128812"); - } - - @Test - void testNotQuiteWildCards() { - I_MatchPredicate mp; - - // make sure special reg-ex chars are treated like normal chars - mp = createCriteriaPredicate(new StringEval("a.b")); - confirmPredicate(false, mp, "aab"); - confirmPredicate(true, mp, "a.b"); - - - mp = createCriteriaPredicate(new StringEval("a~b")); - confirmPredicate(false, mp, "ab"); - confirmPredicate(false, mp, "axb"); - confirmPredicate(false, mp, "a~~b"); - confirmPredicate(true, mp, "a~b"); - - mp = createCriteriaPredicate(new StringEval(">a*b")); - confirmPredicate(false, mp, "a(b"); - confirmPredicate(true, mp, "aab"); - confirmPredicate(false, mp, "a*a"); - confirmPredicate(true, mp, "a*c"); - } - - private static void confirmPredicate(boolean expectedResult, I_MatchPredicate matchPredicate, int value) { - assertEquals(expectedResult, matchPredicate.matches(new NumberEval(value))); - } - private static void confirmPredicate(boolean expectedResult, I_MatchPredicate matchPredicate, String value) { - ValueEval ev = value == null ? BlankEval.instance : new StringEval(value); - assertEquals(expectedResult, matchPredicate.matches(ev)); - } - private static void confirmPredicate(boolean expectedResult, I_MatchPredicate matchPredicate, ErrorEval value) { - assertEquals(expectedResult, matchPredicate.matches(value)); - } - - @Test - void testCountifFromSpreadsheet() { - testCountFunctionFromSpreadsheet("countifExamples.xls", 1, 2, 3, "countif"); - } - - /** - * Two COUNTIF examples taken from - * http://office.microsoft.com/en-us/excel-help/countif-function-HP010069840.aspx?CTT=5&origin=HA010277524 - */ - @Test - void testCountifExamples() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("countifExamples.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet sheet1 = wb.getSheet("MSDN Example 1"); - for (int rowIx=7; rowIx<=12; rowIx++) { - HSSFRow row = sheet1.getRow(rowIx-1); - HSSFCell cellA = row.getCell(0); // cell containing a formula with COUNTIF - assertEquals(CellType.FORMULA, cellA.getCellType()); - HSSFCell cellC = row.getCell(2); // cell with a reference value - assertEquals(CellType.NUMERIC, cellC.getCellType()); - - CellValue cv = fe.evaluate(cellA); - double actualValue = cv.getNumberValue(); - double expectedValue = cellC.getNumericCellValue(); - assertEquals(expectedValue, actualValue, 0.0001, - "Problem with a formula at " + new CellReference(cellA).formatAsString() + ": " + cellA.getCellFormula() + " :Expected = (" + expectedValue + ") Actual=(" + actualValue + ") "); - } - - HSSFSheet sheet2 = wb.getSheet("MSDN Example 2"); - for (int rowIx=9; rowIx<=14; rowIx++) { - HSSFRow row = sheet2.getRow(rowIx-1); - HSSFCell cellA = row.getCell(0); // cell containing a formula with COUNTIF - assertEquals(CellType.FORMULA, cellA.getCellType()); - HSSFCell cellC = row.getCell(2); // cell with a reference value - assertEquals(CellType.NUMERIC, cellC.getCellType()); - - CellValue cv = fe.evaluate(cellA); - double actualValue = cv.getNumberValue(); - double expectedValue = cellC.getNumericCellValue(); - - assertEquals(expectedValue, actualValue, 0.0001, - "Problem with a formula at " + new CellReference(cellA).formatAsString() + "[" + - cellA.getCellFormula()+"]: Expected = (" + expectedValue + ") Actual=(" + actualValue + ") "); - } - } - - @Test - void testCountBlankFromSpreadsheet() { - testCountFunctionFromSpreadsheet("countblankExamples.xls", 1, 3, 4, "countblank"); - } - - private static void testCountFunctionFromSpreadsheet(String FILE_NAME, int START_ROW_IX, int COL_IX_ACTUAL, int COL_IX_EXPECTED, String functionName) { - - int failureCount = 0; - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(FILE_NAME); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - int maxRow = sheet.getLastRowNum(); - for (int rowIx=START_ROW_IX; rowIx data() throws Exception { - return data(TestDGetFunctionsFromSpreadsheet.class, "DGet.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDStarFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDStarFunctionsFromSpreadsheet.java deleted file mode 100644 index f7d20532c6..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDStarFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** -* Tests D*() functions as loaded from a test data spreadsheet. -*/ -class TestDStarFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestDStarFunctionsFromSpreadsheet.class, "DStar.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDate.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDate.java deleted file mode 100644 index 82d0e82742..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDate.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * @author Pavel Krupets (pkrupets at palmtreebusiness dot com) - */ -final class TestDate { - - private HSSFCell cell11; - private HSSFFormulaEvaluator evaluator; - - @BeforeEach - void setUp() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - cell11 = sheet.createRow(0).createCell(0); - evaluator = new HSSFFormulaEvaluator(wb); - } - - /** - * Test disabled pending a fix in the formula evaluator - * TODO - create MissingArgEval and modify the formula evaluator to handle this - */ - @Test - @Disabled - void testSomeArgumentsMissing() { - confirm("DATE(, 1, 0)", 0.0); - confirm("DATE(, 1, 1)", 1.0); - } - - @Test - void testValid() { - confirm("DATE(1900, 1, 1)", 1); - confirm("DATE(1900, 1, 32)", 32); - confirm("DATE(1900, 222, 1)", 6727); - confirm("DATE(1900, 2, 0)", 31); - confirm("DATE(2000, 1, 222)", 36747.00); - confirm("DATE(2007, 1, 1)", 39083); - } - - @Test - void testBugDate() { - confirm("DATE(1900, 2, 29)", 60); - confirm("DATE(1900, 2, 30)", 61); - confirm("DATE(1900, 1, 222)", 222); - confirm("DATE(1900, 1, 2222)", 2222); - confirm("DATE(1900, 1, 22222)", 22222); - } - - @Test - void testPartYears() { - confirm("DATE(4, 1, 1)", 1462.00); - confirm("DATE(14, 1, 1)", 5115.00); - confirm("DATE(104, 1, 1)", 37987.00); - confirm("DATE(1004, 1, 1)", 366705.00); - } - - private void confirm(String formulaText, double expectedResult) { - cell11.setCellFormula(formulaText); - evaluator.clearAllCachedResultValues(); - CellValue cv = evaluator.evaluate(cell11); - assertEquals(CellType.NUMERIC, cv.getCellType(), "Wrong result type"); - double actualValue = cv.getNumberValue(); - assertEquals(expectedResult, actualValue, 0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDateTimeToNumberFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDateTimeToNumberFromSpreadsheet.java deleted file mode 100644 index 4f0e9ee7ba..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDateTimeToNumberFromSpreadsheet.java +++ /dev/null @@ -1,28 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -class TestDateTimeToNumberFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestDateTimeToNumberFromSpreadsheet.class, "DateTimeToNumberTestCases.xls"); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDateValue.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDateValue.java deleted file mode 100644 index fe487b6815..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDateValue.java +++ /dev/null @@ -1,113 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.time.LocalDate; -import java.time.Month; -import java.time.Year; -import java.time.temporal.ChronoUnit; -import java.util.Locale; - -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Tests for Excel function DATEVALUE() - * - * @author Milosz Rembisz - */ -final class TestDateValue { - - @BeforeAll - public static void init() { - LocaleUtil.setUserLocale(Locale.US); - } - - @AfterAll - public static void clear() { - LocaleUtil.setUserLocale(null); - } - - @Test - void testDateValue() { - LocaleUtil.setUserLocale(Locale.ENGLISH); - try { - int days1900 = (int)ChronoUnit.DAYS.between( - LocalDate.of(1899, Month.DECEMBER, 31), - LocalDate.of(Year.now(LocaleUtil.getUserTimeZone().toZoneId()).getValue(), Month.FEBRUARY, 1) - )+1; - confirmDateValue(new StringEval("2020-02-01"), 43862); - confirmDateValue(new StringEval("01-02-2020"), 43862); - confirmDateValue(new StringEval("2020-FEB-01"), 43862); - confirmDateValue(new StringEval("2020-Feb-01"), 43862); - confirmDateValue(new StringEval("2020-FEBRUARY-01"), 43862); - confirmDateValue(new StringEval("FEB-01"), days1900); - confirmDateValue(new StringEval("2/1/2020"), 43862); - confirmDateValue(new StringEval("2/1"), days1900); - confirmDateValue(new StringEval("2020/2/1"), 43862); - confirmDateValue(new StringEval("2020/FEB/1"), 43862); - confirmDateValue(new StringEval("FEB/1/2020"), 43862); - confirmDateValue(new StringEval("2020/02/01"), 43862); - - confirmDateValue(new StringEval("")); - confirmDateValue(BlankEval.instance); - - confirmDateValueError(new StringEval("non-date text")); - - // // EXCEL - confirmDateValue(new StringEval("8/22/2011"), 40777); // Serial number of a date entered as text. - confirmDateValue(new StringEval("22-MAY-2011"), 40685); // Serial number of a date entered as text. - confirmDateValue(new StringEval("2011/02/23"), 40597); // Serial number of a date entered as text. - - // LibreOffice compatibility - confirmDateValue(new StringEval("1954-07-20"), 19925); - } finally { - LocaleUtil.setUserLocale(null); - } - } - - private ValueEval invokeDateValue(ValueEval text) { - return new DateValue().evaluate(0, 0, text); - } - - private void confirmDateValue(ValueEval text, double expected) { - ValueEval result = invokeDateValue(text); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval) result).getNumberValue(), 0.0001); - } - - private void confirmDateValue(ValueEval text) { - ValueEval result = invokeDateValue(text); - assertEquals(BlankEval.class, result.getClass()); - } - - private void confirmDateValueError(ValueEval text) { - ValueEval result = invokeDateValue(text); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID.getErrorCode(), ((ErrorEval) result).getErrorCode()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java deleted file mode 100644 index b796a4d5b9..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java +++ /dev/null @@ -1,165 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -final class TestDays360 { - - /** - * @param month 1-based - */ - private static Date makeDate(int year, int month, int day) { - Calendar cal = LocaleUtil.getLocaleCalendar(year, month-1, day); - return cal.getTime(); - } - - private static Date decrementDay(Date d) { - Calendar c = LocaleUtil.getLocaleCalendar(); - c.setTime(d); - c.add(Calendar.DAY_OF_MONTH, -1); - return c.getTime(); - } - - @Test - void testBasic() { - confirm(120, 2009, 1, 15, 2009, 5, 15); - confirm(158, 2009, 1, 26, 2009, 7, 4); - - // same results in leap years - confirm(120, 2008, 1, 15, 2008, 5, 15); - confirm(158, 2008, 1, 26, 2008, 7, 4); - - // longer time spans - confirm(562, 2008, 8, 11, 2010, 3, 3); - confirm(916, 2007, 2, 23, 2009, 9, 9); - - // other tests - confirm(1, makeDate(1993, 2, 28), makeDate(1993, 3, 1), false); - confirm(1, makeDate(1996, 2, 29), makeDate(1996, 3, 1), false); - confirm(-2, makeDate(1993, 2, 28), makeDate(1993, 2, 28), false); - confirm(3, makeDate(1993, 2, 28), makeDate(1993, 3, 1), true); - confirm(2, makeDate(1996, 2, 29), makeDate(1996, 3, 1), true); - - // from https://support.office.com/en-us/article/DAYS360-function-B9A509FD-49EF-407E-94DF-0CBDA5718C2A - confirm(1, makeDate(2011, 1, 30), makeDate(2011, 2, 1), false); - confirm(360, makeDate(2011, 1, 1), makeDate(2011, 12, 31), false); - confirm(30, makeDate(2011, 1, 1), makeDate(2011, 2, 1), false); - } - - private static void confirm(int expResult, int y1, int m1, int d1, int y2, int m2, int d2) { - confirm(expResult, makeDate(y1, m1, d1), makeDate(y2, m2, d2), false); - confirm(-expResult, makeDate(y2, m2, d2), makeDate(y1, m1, d1), false); - } - - /** - * The method parameter only makes a difference when the second parameter - * is the last day of the month that does not have 30 days. - */ - @Test - void testMonthBoundaries() { - // jan - confirmMonthBoundary(false, 2001, 1, 0, 0, 2, 3, 4); - confirmMonthBoundary(true, 2001, 1, 0, 0, 1, 2, 3); - // feb - confirmMonthBoundary(false, 2001, 2,-2, 1, 2, 3, 4); - confirmMonthBoundary(true, 2001, 2, 0, 1, 2, 3, 4); - // mar - confirmMonthBoundary(false, 2001, 3, 0, 0, 2, 3, 4); - confirmMonthBoundary(true, 2001, 3, 0, 0, 1, 2, 3); - // apr - confirmMonthBoundary(false, 2001, 4, 0, 1, 2, 3, 4); - confirmMonthBoundary(true, 2001, 4, 0, 1, 2, 3, 4); - // may - confirmMonthBoundary(false, 2001, 5, 0, 0, 2, 3, 4); - confirmMonthBoundary(true, 2001, 5, 0, 0, 1, 2, 3); - // jun - confirmMonthBoundary(false, 2001, 6, 0, 1, 2, 3, 4); - confirmMonthBoundary(true, 2001, 6, 0, 1, 2, 3, 4); - // leap year - confirmMonthBoundary(false, 2012, 2, -1, 1, 2, 3, 4); - confirmMonthBoundary(true, 2012, 2, 0, 1, 2, 3, 4); - - // bug 60029 - Date start = makeDate(2018, 2, 28); - Date end = makeDate(2018, 3, 31); - confirm(30, start, end, false); - - // examples from https://support.office.com/en-us/article/DAYS360-function-B9A509FD-49EF-407E-94DF-0CBDA5718C2A - start = makeDate(2011, 1, 30); - end = makeDate(2011, 2, 1); - confirm(1, start, end, false); - - start = makeDate(2011, 1, 1); - end = makeDate(2011, 12, 31); - confirm(360, start, end, false); - - start = makeDate(2011, 1, 1); - end = makeDate(2011, 2, 1); - confirm(30, start, end, false); - } - - - /** - * @param monthNo 1-based - */ - private static void confirmMonthBoundary(boolean method, int year, int monthNo, int...diffs) { - Date firstDayOfNextMonth = makeDate(year, monthNo+1, 1); - Date secondArg = decrementDay(firstDayOfNextMonth); - Date firstArg = secondArg; - - for (int expResult : diffs) { - confirm(expResult, firstArg, secondArg, method); - firstArg = decrementDay(firstArg); - } - - } - private static void confirm(int expResult, Date firstArg, Date secondArg, boolean method) { - ValueEval ve; - if (method) { - ve = invokeDays360(convert(firstArg), convert(secondArg), BoolEval.TRUE); - } else { - ve = invokeDays360(convert(firstArg), convert(secondArg)); - } - assertTrue(ve instanceof NumberEval, "wrong return type (" + ve.getClass().getName() + ")"); - - NumberEval numberEval = (NumberEval) ve; - String err = String.format(Locale.ROOT, "days360(%tF,%tF,%b) wrong result", firstArg, secondArg, method); - assertEquals(expResult, numberEval.getNumberValue(), 0, err); - } - - private static ValueEval invokeDays360(ValueEval...args) { - return new Days360().evaluate(args, -1, -1); - } - - private static NumberEval convert(Date d) { - return new NumberEval(DateUtil.getExcelDate(d)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Bin.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Bin.java deleted file mode 100644 index d745603a5a..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Bin.java +++ /dev/null @@ -1,245 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Dec2Bin} - * - * @author cedric dot walter @ gmail dot com - */ -final class TestDec2Bin { - - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Dec2Bin().evaluate(args, -1, -1); - } - - private static ValueEval invokeBack(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Bin2Dec().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals(StringEval.class, result.getClass(), "Had: " + result); - assertEquals(expected, ((StringEval) result).getStringValue(), msg); - } - - private static void confirmValueError(String msg, String number1, ErrorEval numError) { - ValueEval result = invokeValue(number1); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(numError, result, msg); - } - - @Test - void testBasic() { - confirmValue("Converts binary '00101' from binary (5)", "5", "101"); - confirmValue("Converts binary '1111111111' from binary (-1)", "-1", "1111111111"); - confirmValue("Converts binary '1111111110' from binary (-2)", "-2", "1111111110"); - confirmValue("Converts binary '0111111111' from binary (511)", "511", "111111111"); - confirmValue("Converts binary '1000000000' from binary (511)", "-512", "1000000000"); - } - - @Test - void testErrors() { - confirmValueError("fails for >= 512 or < -512","512", ErrorEval.NUM_ERROR); - confirmValueError("fails for >= 512 or < -512","-513", ErrorEval.NUM_ERROR); - confirmValueError("not a valid decimal number","GGGGGGG", ErrorEval.VALUE_INVALID); - confirmValueError("not a valid decimal number","3.14159a", ErrorEval.VALUE_INVALID); - } - - @Test - void testEvalOperationEvaluationContext() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Dec2Bin().evaluate(args, ctx); - - assertEquals(StringEval.class, result.getClass()); - assertEquals("1101", ((StringEval) result).getStringValue()); - } - - @Test - void testEvalOperationEvaluationContextFails() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ErrorEval.VALUE_INVALID }; - ValueEval result = new Dec2Bin().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - private OperationEvaluationContext createContext() { - HSSFWorkbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue("13.43"); - cell = row.createCell(1); - cell.setCellValue("8"); - cell = row.createCell(2); - cell.setCellValue("-8"); - cell = row.createCell(3); - cell.setCellValue("1"); - - HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, (sheetIndex, rowIndex, columnIndex) -> true, null); - return new OperationEvaluationContext(workbookEvaluator, workbook, 0, 0, 0, null); - } - - @Test - void testRefs() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(StringEval.class, result.getClass(), "Had: " + result); - assertEquals("1101", ((StringEval) result).getStringValue()); - } - - @Test - void testWithPlacesIntInt() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(StringEval.class, result.getClass(), "Had: " + result); - // TODO: documentation and behavior do not match here! - assertEquals("1101", ((StringEval) result).getStringValue()); - } - - @Test - void testWithPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Bin().evaluate(args, ctx); - - assertEquals(StringEval.class, result.getClass(), "Had: " + result); - // TODO: documentation and behavior do not match here! - assertEquals("1101", ((StringEval) result).getStringValue()); - } - - @Test - void testWithToShortPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 3) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NUM_ERROR, result); - } - - @Test - void testWithTooManyParamsIntInt() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testWithTooManyParams() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Bin().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testWithErrorPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ErrorEval.NULL_INTERSECTION }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NULL_INTERSECTION, result); - } - - @Test - void testWithNegativePlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 2) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NUM_ERROR, result); - } - - @Test - void testWithZeroPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), new NumberEval(0.0) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NUM_ERROR, result); - } - - @Test - void testWithEmptyPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(1, 0) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testBackAndForth() { - for (int i = -512; i < 512; i++) { - ValueEval result = invokeValue(Integer.toString(i)); - assertEquals(StringEval.class, result.getClass(), "Had: " + result); - - ValueEval back = invokeBack(((StringEval) result).getStringValue()); - assertEquals(NumberEval.class, back.getClass(), "Had: " + back); - - assertEquals(Integer.toString(i), ((NumberEval) back).getStringValue()); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java deleted file mode 100644 index 125f9c4396..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java +++ /dev/null @@ -1,245 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Dec2Hex} - * - * @author cedric dot walter @ gmail dot com - */ -final class TestDec2Hex { - - private static ValueEval invokeValue(String number1, String number2) { - ValueEval[] args = new ValueEval[] { new StringEval(number1), new StringEval(number2), }; - return new Dec2Hex().evaluate(args, -1, -1); - } - - private static ValueEval invokeBack(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Hex2Dec().evaluate(args, -1, -1); - } - - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1), }; - return new Dec2Hex().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String number2, String expected) { - ValueEval result = invokeValue(number1, number2); - assertEquals(StringEval.class, result.getClass()); - assertEquals(expected, ((StringEval) result).getStringValue(), msg); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals(StringEval.class, result.getClass()); - assertEquals(expected, ((StringEval) result).getStringValue(), msg); - } - - private static void confirmValueError(String msg, String number1, String number2, ErrorEval numError) { - ValueEval result = invokeValue(number1, number2); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(numError, result, msg); - } - - @Test - void testBasic() { - confirmValue("Converts decimal 100 to hexadecimal with 0 characters (64)", "100","0", "64"); - confirmValue("Converts decimal 100 to hexadecimal with 4 characters (0064)", "100","4", "0064"); - confirmValue("Converts decimal 100 to hexadecimal with 5 characters (0064)", "100","5", "00064"); - confirmValue("Converts decimal 100 to hexadecimal with 10 (default) characters", "100","10", "0000000064"); - confirmValue("If argument places contains a decimal value, dec2hex ignores the numbers to the right side of the decimal point.", "100","10.0", "0000000064"); - - confirmValue("Converts decimal -54 to hexadecimal, 2 is ignored","-54", "2", "FFFFFFFFCA"); - confirmValue("places is optionnal","-54", "FFFFFFFFCA"); - - confirmValue("Converts normal decimal number to hexadecimal", "100", "64"); - - String maxInt = Integer.toString(Integer.MAX_VALUE); - assertEquals("2147483647", maxInt); - confirmValue("Converts INT_MAX to hexadecimal", maxInt, "7FFFFFFF"); - - String minInt = Integer.toString(Integer.MIN_VALUE); - assertEquals("-2147483648", minInt); - confirmValue("Converts INT_MIN to hexadecimal", minInt, "FF80000000"); - - String maxIntPlusOne = Long.toString(((long)Integer.MAX_VALUE)+1); - assertEquals("2147483648", maxIntPlusOne); - confirmValue("Converts INT_MAX + 1 to hexadecimal", maxIntPlusOne, "80000000"); - - String maxLong = Long.toString(549755813887L); - assertEquals("549755813887", maxLong); - confirmValue("Converts the max supported value to hexadecimal", maxLong, "7FFFFFFFFF"); - - String minLong = Long.toString(-549755813888L); - assertEquals("-549755813888", minLong); - confirmValue("Converts the min supported value to hexadecimal", minLong, "FF80000000"); - } - - @Test - void testErrors() { - confirmValueError("Out of range min number","-549755813889","0", ErrorEval.NUM_ERROR); - confirmValueError("Out of range max number","549755813888","0", ErrorEval.NUM_ERROR); - - confirmValueError("negative places not allowed","549755813888","-10", ErrorEval.NUM_ERROR); - confirmValueError("non number places not allowed","ABCDEF","0", ErrorEval.VALUE_INVALID); - } - - @Test - void testEvalOperationEvaluationContextFails() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ErrorEval.VALUE_INVALID }; - ValueEval result = new Dec2Hex().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - private OperationEvaluationContext createContext() { - HSSFWorkbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue("123.43"); - cell = row.createCell(1); - cell.setCellValue("8"); - cell = row.createCell(2); - cell.setCellValue("-8"); - - HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, (sheetIndex, rowIndex, columnIndex) -> true, null); - return new OperationEvaluationContext(workbookEvaluator, workbook, 0, 0, 0, null); - } - - @Test - void testRefs() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals(StringEval.class, result.getClass(), "Had: " + result); - assertEquals("7B", ((StringEval) result).getStringValue()); - } - - @Test - void testWithPlacesIntInt() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals(StringEval.class, result.getClass(), "Had: " + result); - assertEquals("0000007B", ((StringEval) result).getStringValue()); - } - - @Test - void testWithPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Hex().evaluate(args, ctx); - - assertEquals(StringEval.class, result.getClass(), "Had: " + result); - assertEquals("0000007B", ((StringEval) result).getStringValue()); - } - - @Test - void testWithTooManyParamsIntInt() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testWithTooManyParams() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Hex().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testWithErrorPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ErrorEval.NULL_INTERSECTION }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NULL_INTERSECTION, result); - } - - @Test - void testWithNegativePlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 2) }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NUM_ERROR, result); - } - - @Test - void testWithEmptyPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(1, 0) }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testBackAndForth() { - for (int i = -512; i < 512; i++) { - ValueEval result = invokeValue(Integer.toString(i)); - assertEquals(StringEval.class, result.getClass(), "Had: " + result); - - ValueEval back = invokeBack(((StringEval) result).getStringValue()); - assertEquals(NumberEval.class, back.getClass(), "Had: " + back); - - assertEquals(Integer.toString(i), ((NumberEval) back).getStringValue()); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDelta.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDelta.java deleted file mode 100644 index 83aee557f3..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDelta.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link org.apache.poi.ss.formula.functions.Delta} - * - * @author cedric dot walter @ gmail dot com - */ -final class TestDelta { - - private static ValueEval invokeValue(String number1, String number2) { - ValueEval[] args = new ValueEval[] { new StringEval(number1), new StringEval(number2), }; - return new Delta().evaluate(args, -1, -1); - } - - private static void confirmValue(String number1, String number2, double expected) { - ValueEval result = invokeValue(number1, number2); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval) result).getNumberValue(), 0.0); - } - - private static void confirmValueError(String number1, String number2) { - ValueEval result = invokeValue(number1, number2); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testBasic() { - confirmValue("5","4", 0); // Checks whether 5 equals 4 (0) - confirmValue("5","5", 1); // Checks whether 5 equals 5 (1) - - confirmValue("0.5","0", 0); // Checks whether 0.5 equals 0 (0) - confirmValue("0.50","0.5", 1); - confirmValue("0.5000000000","0.5", 1); - } - - @Test - void testErrors() { - confirmValueError("A1","B2"); - confirmValueError("AAAA","BBBB"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDeltaFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDeltaFunctionsFromSpreadsheet.java deleted file mode 100644 index aa1bf1f0c5..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDeltaFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests DELTA() as loaded from a test data spreadsheet.

- */ -class TestDeltaFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestDeltaFunctionsFromSpreadsheet.class, "DeltaFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java b/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java deleted file mode 100644 index d55fdcf5e8..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -class TestEDate { - - @Test - void testEDateProperValues() { - // verify some border-case combinations of startDate and month-increase - checkValue(1000, 0, 1000d); - checkValue(1, 0, 1d); - checkValue(0, 1, 31d); - checkValue(1, 1, 32d); - checkValue(0, 0, /* BAD_DATE! */ -1.0d); - checkValue(0, -2, /* BAD_DATE! */ -1.0d); - checkValue(0, -3, /* BAD_DATE! */ -1.0d); - checkValue(49104, 0, 49104d); - checkValue(49104, 1, 49134d); - } - - private void checkValue(int startDate, int monthInc, double expectedResult) { - EDate eDate = new EDate(); - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(startDate), new NumberEval(monthInc)}, null); - assertEquals(expectedResult, result.getNumberValue(), 0); - } - - @Test - void testEDateInvalidValues() { - EDate eDate = new EDate(); - ErrorEval result = (ErrorEval) eDate.evaluate(new ValueEval[]{new NumberEval(1000)}, null); - assertEquals(FormulaError.VALUE.getCode(), result.getErrorCode(), 0); - } - - @Test - void testEDateIncrease() { - EDate eDate = new EDate(); - Date startDate = new Date(); - int offset = 2; - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(DateUtil.getExcelDate(startDate)), new NumberEval(offset)}, null); - Date resultDate = DateUtil.getJavaDate(result.getNumberValue()); - Calendar instance = LocaleUtil.getLocaleCalendar(); - instance.setTime(startDate); - instance.add(Calendar.MONTH, offset); - assertEquals(resultDate, instance.getTime()); - - } - - @Test - void testEDateDecrease() { - EDate eDate = new EDate(); - Date startDate = new Date(); - int offset = -2; - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(DateUtil.getExcelDate(startDate)), new NumberEval(offset)}, null); - Date resultDate = DateUtil.getJavaDate(result.getNumberValue()); - Calendar instance = LocaleUtil.getLocaleCalendar(); - instance.setTime(startDate); - instance.add(Calendar.MONTH, offset); - assertEquals(resultDate, instance.getTime()); - } - - @Test - void testBug56688() { - EDate eDate = new EDate(); - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(1000), new RefEvalImplementation(new NumberEval(0))}, null); - assertEquals(1000d, result.getNumberValue(), 0); - } - - @Test - void testRefEvalStartDate() { - EDate eDate = new EDate(); - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new RefEvalImplementation(new NumberEval(1000)), new NumberEval(0)}, null); - assertEquals(1000d, result.getNumberValue(), 0); - } - - @Test - void testEDateInvalidValueEval() { - ValueEval evaluate = new EDate().evaluate(new ValueEval[]{new ValueEval() {}, new NumberEval(0)}, null); - assertTrue(evaluate instanceof ErrorEval); - assertEquals(ErrorEval.VALUE_INVALID, evaluate); - } - - @Test - void testEDateBlankValueEval() { - NumberEval evaluate = (NumberEval) new EDate().evaluate(new ValueEval[]{BlankEval.instance, new NumberEval(0)}, null); - assertEquals(-1.0d, evaluate.getNumberValue(), 0); - } - - @Test - void testEDateBlankRefValueEval() { - EDate eDate = new EDate(); - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new RefEvalImplementation(BlankEval.instance), new NumberEval(0)}, null); - assertEquals(-1.0d, result.getNumberValue(), 0, "0 startDate triggers BAD_DATE currently, thus -1.0!"); - - result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(1), new RefEvalImplementation(BlankEval.instance)}, null); - assertEquals(1.0d, result.getNumberValue(), 0, "Blank is handled as 0 otherwise"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java b/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java deleted file mode 100644 index c1e1349909..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -class TestEOMonth { - - private static final double BAD_DATE = -1.0; - - private static final double DATE_1900_01_01 = 1.0; - private static final double DATE_1900_01_31 = 31.0; - private static final double DATE_1900_02_28 = 59.0; - private static final double DATE_1902_09_26 = 1000.0; - private static final double DATE_1902_09_30 = 1004.0; - private static final double DATE_2034_06_09 = 49104.0; - private static final double DATE_2034_06_30 = 49125.0; - private static final double DATE_2034_07_31 = 49156.0; - - private final FreeRefFunction eOMonth = EOMonth.instance; - private final OperationEvaluationContext ec = new OperationEvaluationContext(null, null, 0, 0, 0, null); - - @Test - void testEOMonthProperValues() { - // verify some border-case combinations of startDate and month-increase - checkValue(DATE_1900_01_01, 0, DATE_1900_01_31); - checkValue(DATE_1900_01_01, 1, DATE_1900_02_28); - checkValue(DATE_1902_09_26, 0, DATE_1902_09_30); - checkValue(DATE_2034_06_09, 0, DATE_2034_06_30); - checkValue(DATE_2034_06_09, 1, DATE_2034_07_31); - } - - @Test - void testEOMonthBadDateValues() { - checkValue(0.0, -2, BAD_DATE); - checkValue(0.0, -3, BAD_DATE); - checkValue(DATE_1900_01_31, -1, BAD_DATE); - } - - private void checkValue(double startDate, int monthInc, double expectedResult) { - ValueEval[] ve = {new NumberEval(startDate), new NumberEval(monthInc)}; - NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec); - assertEquals(expectedResult, result.getNumberValue(), 0); - } - - @Test - void testEOMonthZeroDate() { - NumberEval result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new NumberEval(0), new NumberEval(0)}, ec); - assertEquals(DATE_1900_01_31, result.getNumberValue(), 0, "0 startDate is 1900-01-00"); - - result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new NumberEval(0), new NumberEval(1)}, ec); - assertEquals(DATE_1900_02_28, result.getNumberValue(), 0, "0 startDate is 1900-01-00"); - } - - @Test - void testEOMonthInvalidArguments() { - ValueEval result = eOMonth.evaluate(new ValueEval[] {new NumberEval(DATE_1902_09_26)}, ec); - assertTrue(result instanceof ErrorEval); - assertEquals(FormulaError.VALUE.getCode(), ((ErrorEval) result).getErrorCode(), 0); - - result = eOMonth.evaluate(new ValueEval[] {new StringEval("a"), new StringEval("b")}, ec); - assertTrue(result instanceof ErrorEval); - assertEquals(FormulaError.VALUE.getCode(), ((ErrorEval) result).getErrorCode(), 0); - } - - @Test - void checkOffset() { - for (int offset=-12; offset<=12; offset++) { - Calendar cal = LocaleUtil.getLocaleCalendar(); - Date startDate = cal.getTime(); - - cal.add(Calendar.MONTH, offset); - cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); - cal.clear(Calendar.HOUR); - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.clear(Calendar.MINUTE); - cal.clear(Calendar.SECOND); - cal.clear(Calendar.MILLISECOND); - Date expDate = cal.getTime(); - - ValueEval[] ve = { - new NumberEval(DateUtil.getExcelDate(startDate)), - new NumberEval(offset) - }; - NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec); - Date actDate = DateUtil.getJavaDate(result.getNumberValue()); - - assertEquals(expDate, actDate); - } - } - - @Test - void testBug56688() { - ValueEval[] ve = {new NumberEval(DATE_1902_09_26), new RefEvalImplementation(new NumberEval(0))}; - NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec); - assertEquals(DATE_1902_09_30, result.getNumberValue(), 0); - } - - @Test - void testRefEvalStartDate() { - ValueEval[] ve = {new RefEvalImplementation(new NumberEval(DATE_1902_09_26)), new NumberEval(0)}; - NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec); - assertEquals(DATE_1902_09_30, result.getNumberValue(), 0); - } - - @Test - void testEOMonthBlankValueEval() { - NumberEval evaluate = (NumberEval) eOMonth.evaluate(new ValueEval[] {BlankEval.instance, new NumberEval(0)}, ec); - assertEquals(DATE_1900_01_31, evaluate.getNumberValue(), 0, "Blank is handled as 0"); - } - - @Test - void testEOMonthBlankRefValueEval() { - ValueEval[] ve1 = {new RefEvalImplementation(BlankEval.instance), new NumberEval(1)}; - NumberEval result = (NumberEval) eOMonth.evaluate(ve1, ec); - assertEquals(DATE_1900_02_28, result.getNumberValue(), 0, "Blank is handled as 0"); - - ValueEval[] ve2 = {new NumberEval(1), new RefEvalImplementation(BlankEval.instance)}; - result = (NumberEval) eOMonth.evaluate(ve2, ec); - assertEquals(DATE_1900_01_31, result.getNumberValue(), 0, "Blank is handled as 0"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFactDoubleFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFactDoubleFunctionsFromSpreadsheet.java deleted file mode 100644 index 9e9394c791..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFactDoubleFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests FactDouble() as loaded from a test data spreadsheet.

- */ -class TestFactDoubleFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestFactDoubleFunctionsFromSpreadsheet.class, "FactDoubleFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFinanceLib.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFinanceLib.java deleted file mode 100644 index e0d2aca4c5..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFinanceLib.java +++ /dev/null @@ -1,229 +0,0 @@ -/* -* 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. -*/ -/* - * Created on May 23, 2005 - * - */ -package org.apache.poi.ss.formula.functions; - - -import org.junit.jupiter.api.Test; - -/** - * @author Amol S. Deshmukh < amolweb at ya hoo dot com > - * - */ -class TestFinanceLib extends BaseTestNumeric { - - @Test - void testFv() { - double f, r, y, p, x; - int n; - boolean t; - - r = 0; n = 1; y = 1; p = 1; t = true; - f = FinanceLib.fv(r, n, y, p, t); - x = -2; - assertDouble("fv ", x, f); - - r = 0.12/12; n = 12; y = -1000; p = 0; t = false; - f = FinanceLib.fv(r, n, y, p, t); - x = 12682.50301319; - assertDouble("fv ", x, f); - - r = 0.06/12; n = 10; y = -200; p = -500; t = true; - f = FinanceLib.fv(r, n, y, p, t); - x = 2581.4033740; - assertDouble("fv ", x, f); - - r = 0; n = 3; y = 2; p = 7; t = true; - f = FinanceLib.fv(r, n, y, p, t); - x = -13; - assertDouble("fv ", x, f); - - r = 1; n = 10; y = 100; p = 10000; t = false; - f = FinanceLib.fv(r, n, y, p, t); - x = -10342300; - assertDouble("fv ", x, f); - - r = 1; n = 10; y = 100; p = 10000; t = true; - f = FinanceLib.fv(r, n, y, p, t); - x = -10444600; - assertDouble("fv ", x, f); - - r = 2; n = 12; y = 120; p = 12000; t = false; - f = FinanceLib.fv(r, n, y, p, t); - x = -6409178400d; - assertDouble("fv ", x, f); - - r = 2; n = 12; y = 120; p = 12000; t = true; - f = FinanceLib.fv(r, n, y, p, t); - x = -6472951200d; - assertDouble("fv ", x, f); - - // cross tests with pv - r = 2.95; n = 13; y = 13000; p = -4406.78544294496; t = false; - f = FinanceLib.fv(r, n, y, p, t); - x = 333891.230010986; // as returned by excel - assertDouble("fv ", x, f); - - r = 2.95; n = 13; y = 13000; p = -17406.7852148156; t = true; - f = FinanceLib.fv(r, n, y, p, t); - x = 333891.230102539; // as returned by excel - assertDouble("fv ", x, f); - - } - - @Test - void testNpv() { - double r; - double[] v; - double npv; - double x; - - r = 1; v = new double[]{100, 200, 300, 400}; - npv = FinanceLib.npv(r, v); - x = 162.5; - assertDouble("npv ", x, npv); - - r = 2.5; v = new double[]{1000, 666.66666, 333.33, 12.2768416}; - npv = FinanceLib.npv(r, v); - x = 347.99232604144827; - assertDouble("npv ", x, npv); - - r = 12.33333; v = new double[]{1000, 0, -900, -7777.5765}; - npv = FinanceLib.npv(r, v); - x = 74.3742433377061; - assertDouble("npv ", x, npv); - - r = 0.05; v = new double[]{200000, 300000.55, 400000, 1000000, 6000000, 7000000, -300000}; - npv = FinanceLib.npv(r, v); - x = 11342283.4233124; - assertDouble("npv ", x, npv); - } - - @Test - void testPmt() { - double f, r, y, p, x; - int n; - boolean t; - - r = 0; n = 3; p = 2; f = 7; t = true; - y = FinanceLib.pmt(r, n, p, f, t); - x = -3; - assertDouble("pmt ", x, y); - - // cross check with pv - r = 1; n = 10; p = -109.66796875; f = 10000; t = false; - y = FinanceLib.pmt(r, n, p, f, t); - x = 100; - assertDouble("pmt ", x, y); - - r = 1; n = 10; p = -209.5703125; f = 10000; t = true; - y = FinanceLib.pmt(r, n, p, f, t); - x = 100; - assertDouble("pmt ", x, y); - - // cross check with fv - r = 2; n = 12; f = -6409178400d; p = 12000; t = false; - y = FinanceLib.pmt(r, n, p, f, t); - x = 120; - assertDouble("pmt ", x, y); - - r = 2; n = 12; f = -6472951200d; p = 12000; t = true; - y = FinanceLib.pmt(r, n, p, f, t); - x = 120; - assertDouble("pmt ", x, y); - } - - @Test - void testPv() { - double f, r, y, p, x; - int n; - boolean t; - - r = 0; n = 3; y = 2; f = 7; t = true; - f = FinanceLib.pv(r, n, y, f, t); - x = -13; - assertDouble("pv ", x, f); - - r = 1; n = 10; y = 100; f = 10000; t = false; - p = FinanceLib.pv(r, n, y, f, t); - x = -109.66796875; - assertDouble("pv ", x, p); - - r = 1; n = 10; y = 100; f = 10000; t = true; - p = FinanceLib.pv(r, n, y, f, t); - x = -209.5703125; - assertDouble("pv ", x, p); - - r = 2.95; n = 13; y = 13000; f = 333891.23; t = false; - p = FinanceLib.pv(r, n, y, f, t); - x = -4406.78544294496; - assertDouble("pv ", x, p); - - r = 2.95; n = 13; y = 13000; f = 333891.23; t = true; - p = FinanceLib.pv(r, n, y, f, t); - x = -17406.7852148156; - assertDouble("pv ", x, p); - - // cross tests with fv - r = 2; n = 12; y = 120; f = -6409178400d; t = false; - p = FinanceLib.pv(r, n, y, f, t); - x = 12000; - assertDouble("pv ", x, p); - - r = 2; n = 12; y = 120; f = -6472951200d; t = true; - p = FinanceLib.pv(r, n, y, f, t); - x = 12000; - assertDouble("pv ", x, p); - - } - - @Test - void testNper() { - double f, r, y, p, x, n; - boolean t; - - r = 0; y = 7; p = 2; f = 3; t = false; - n = FinanceLib.nper(r, y, p, f, t); - x = -0.71428571429; // can you believe it? excel returns nper as a fraction!?? - assertDouble("nper ", x, n); - - // cross check with pv - r = 1; y = 100; p = -109.66796875; f = 10000; t = false; - n = FinanceLib.nper(r, y, p, f, t); - x = 10; - assertDouble("nper ", x, n); - - r = 1; y = 100; p = -209.5703125; f = 10000; t = true; - n = FinanceLib.nper(r, y, p, f, t); - x = 10; - assertDouble("nper ", x, n); - - // cross check with fv - r = 2; y = 120; f = -6409178400d; p = 12000; t = false; - n = FinanceLib.nper(r, y, p, f, t); - x = 12; - assertDouble("nper ", x, n); - - r = 2; y = 120; f = -6472951200d; p = 12000; t = true; - n = FinanceLib.nper(r, y, p, f, t); - x = 12; - assertDouble("nper ", x, n); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFind.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFind.java deleted file mode 100644 index 31e50331d0..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFind.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaError; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Financed} - */ -final class TestFind { - - @Test - void testFind() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFCell cell = wb.createSheet().createRow(0).createCell(0); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - confirmResult(fe, cell, "find(\"h\", \"haystack\")", 1); - confirmResult(fe, cell, "find(\"a\", \"haystack\",2)", 2); - confirmResult(fe, cell, "find(\"a\", \"haystack\",3)", 6); - - // number args converted to text - confirmResult(fe, cell, "find(7, 32768)", 3); - confirmResult(fe, cell, "find(\"34\", 1341235233412, 3)", 10); - confirmResult(fe, cell, "find(5, 87654)", 4); - - // Errors - confirmError(fe, cell, "find(\"n\", \"haystack\")", FormulaError.VALUE); - confirmError(fe, cell, "find(\"k\", \"haystack\",9)", FormulaError.VALUE); - confirmError(fe, cell, "find(\"k\", \"haystack\",#REF!)", FormulaError.REF); - confirmError(fe, cell, "find(\"k\", \"haystack\",0)", FormulaError.VALUE); - confirmError(fe, cell, "find(#DIV/0!, #N/A, #REF!)", FormulaError.DIV0); - confirmError(fe, cell, "find(2, #N/A, #REF!)", FormulaError.NA); - - wb.close(); - } - - private static void confirmResult(HSSFFormulaEvaluator fe, HSSFCell cell, String formulaText, - int expectedResult) { - cell.setCellFormula(formulaText); - fe.notifyUpdateCell(cell); - CellValue result = fe.evaluate(cell); - assertEquals(result.getCellType(), CellType.NUMERIC); - assertEquals(expectedResult, result.getNumberValue(), 0.0); - } - - private static void confirmError(HSSFFormulaEvaluator fe, HSSFCell cell, String formulaText, - FormulaError expectedErrorCode) { - cell.setCellFormula(formulaText); - fe.notifyUpdateCell(cell); - CellValue result = fe.evaluate(cell); - assertEquals(result.getCellType(), CellType.ERROR); - assertEquals(expectedErrorCode.getCode(), result.getErrorValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java deleted file mode 100644 index 63f01cdbb6..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaError; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -final class TestFixed { - - private HSSFCell cell11; - private HSSFFormulaEvaluator evaluator; - - @BeforeEach - void setUp() throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - HSSFSheet sheet = wb.createSheet("new sheet"); - cell11 = sheet.createRow(0).createCell(0); - evaluator = new HSSFFormulaEvaluator(wb); - } - } - - @Test - void testValid() { - // thousands separator - confirm("FIXED(1234.56789,2,TRUE)", "1234.57"); - confirm("FIXED(1234.56789,2,FALSE)", "1,234.57"); - // rounding - confirm("FIXED(1.8,0,TRUE)", "2"); - confirm("FIXED(1.2,0,TRUE)", "1"); - confirm("FIXED(1.5,0,TRUE)", "2"); - confirm("FIXED(1,0,TRUE)", "1"); - // fractional digits - confirm("FIXED(1234.56789,7,TRUE)", "1234.5678900"); - confirm("FIXED(1234.56789,0,TRUE)", "1235"); - confirm("FIXED(1234.56789,-1,TRUE)", "1230"); - // less than three arguments - confirm("FIXED(1234.56789)", "1,234.57"); - confirm("FIXED(1234.56789,3)", "1,234.568"); - // invalid arguments - confirmValueError("FIXED(\"invalid\")"); - confirmValueError("FIXED(1,\"invalid\")"); - confirmValueError("FIXED(1,2,\"invalid\")"); - // strange arguments - confirm("FIXED(1000,2,8)", "1000.00"); - confirm("FIXED(1000,2,0)", "1,000.00"); - // corner cases - confirm("FIXED(1.23456789012345,15,TRUE)", "1.234567890123450"); - // Seems POI accepts longer numbers than Excel does, excel trims the - // number to 15 digits and removes the "9" in the formula itself. - // Not the fault of FIXED though. - // confirm("FIXED(1.234567890123459,15,TRUE)", "1.234567890123450"); - confirm("FIXED(60,-2,TRUE)", "100"); - confirm("FIXED(10,-2,TRUE)", "0"); - // rounding propagation - confirm("FIXED(99.9,0,TRUE)", "100"); - } - - @Test - void testOptionalParams() { - Fixed fixed = new Fixed(); - ValueEval evaluate = fixed.evaluate(0, 0, new NumberEval(1234.56789)); - assertTrue(evaluate instanceof StringEval); - assertEquals("1,234.57", ((StringEval)evaluate).getStringValue()); - - evaluate = fixed.evaluate(0, 0, new NumberEval(1234.56789), new NumberEval(1)); - assertTrue(evaluate instanceof StringEval); - assertEquals("1,234.6", ((StringEval)evaluate).getStringValue()); - - evaluate = fixed.evaluate(0, 0, new NumberEval(1234.56789), new NumberEval(1), BoolEval.TRUE); - assertTrue(evaluate instanceof StringEval); - assertEquals("1234.6", ((StringEval)evaluate).getStringValue()); - - evaluate = fixed.evaluate(new ValueEval[] {}, 1, 1); - assertTrue(evaluate instanceof ErrorEval); - - evaluate = fixed.evaluate(new ValueEval[] { new NumberEval(1), new NumberEval(1), new NumberEval(1), new NumberEval(1) }, 1, 1); - assertTrue(evaluate instanceof ErrorEval); - } - - private void confirm(String formulaText, String expectedResult) { - cell11.setCellFormula(formulaText); - evaluator.clearAllCachedResultValues(); - CellValue cv = evaluator.evaluate(cell11); - assertEquals(CellType.STRING, cv.getCellType(), "Wrong result type: " + cv.formatAsString()); - String actualValue = cv.getStringValue(); - assertEquals(expectedResult, actualValue); - } - - private void confirmValueError(String formulaText) { - cell11.setCellFormula(formulaText); - evaluator.clearAllCachedResultValues(); - CellValue cv = evaluator.evaluate(cell11); - assertTrue(cv.getCellType() == CellType.ERROR - && cv.getErrorValue() == FormulaError.VALUE.getCode(), - "Wrong result type: " + cv.formatAsString()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFixedFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFixedFunctionsFromSpreadsheet.java deleted file mode 100644 index 907ecf7cc1..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFixedFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests FIXED() as loaded from a test data spreadsheet. - */ -class TestFixedFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestFixedFunctionsFromSpreadsheet.class, "57003-FixedFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFrequency.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFrequency.java deleted file mode 100644 index 6dd04d13c1..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFrequency.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import static org.apache.poi.ss.formula.functions.Frequency.histogram; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellRange; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Test; - -/** - * Testcase for the function FREQUENCY(data, bins) - * - * @author Yegor Kozlov - */ -class TestFrequency { - - @Test - void testHistogram() { - assertArrayEquals(new int[]{3, 2, 2, 0, 1, 1}, - histogram( - new double[]{11, 12, 13, 21, 29, 36, 40, 58, 69}, - new double[]{20, 30, 40, 50, 60}) - ); - - assertArrayEquals(new int[]{1, 1, 1, 1, 1, 0}, - histogram( - new double[]{20, 30, 40, 50, 60}, - new double[]{20, 30, 40, 50, 60}) - - ); - - assertArrayEquals(new int[]{2, 3}, - histogram( - new double[]{20, 30, 40, 50, 60}, - new double[]{30}) - - ); - } - - @Test - void testEvaluate() { - Workbook wb = new HSSFWorkbook(); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - int[] data = {1, 1, 2, 3, 4, 4, 5, 7, 8, 9, 9, 11, 3, 5, 8}; - int[] bins = {3, 6, 9}; - Sheet sheet = wb.createSheet(); - Row dataRow = sheet.createRow(0); // A1:O1 - for (int i = 0; i < data.length; i++) { - dataRow.createCell(i).setCellValue(data[i]); - } - Row binsRow = sheet.createRow(1); - for (int i = 0; i < bins.length; i++) { // A2:C2 - binsRow.createCell(i).setCellValue(bins[i]); - } - Row fmlaRow = sheet.createRow(2); - CellRange arrayFmla = sheet.setArrayFormula("FREQUENCY(A1:O1,A2:C2)", CellRangeAddress.valueOf("A3:A6")); - Cell b3 = fmlaRow.createCell(1); // B3 - b3.setCellFormula("COUNT(FREQUENCY(A1:O1,A2:C2))"); // frequency returns a vertical array of bins+1 - - Cell c3 = fmlaRow.createCell(2); - c3.setCellFormula("SUM(FREQUENCY(A1:O1,A2:C2))"); // sum of the frequency bins should add up to the number of data values - - assertEquals(5, (int) evaluator.evaluate(arrayFmla.getFlattenedCells()[0]).getNumberValue()); - assertEquals(4, (int) evaluator.evaluate(arrayFmla.getFlattenedCells()[1]).getNumberValue()); - assertEquals(5, (int) evaluator.evaluate(arrayFmla.getFlattenedCells()[2]).getNumberValue()); - assertEquals(1, (int) evaluator.evaluate(arrayFmla.getFlattenedCells()[3]).getNumberValue()); - - assertEquals(4, (int) evaluator.evaluate(b3).getNumberValue()); - assertEquals(15, (int) evaluator.evaluate(c3).getNumberValue()); - - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestGeomean.java b/src/testcases/org/apache/poi/ss/formula/functions/TestGeomean.java deleted file mode 100644 index 681b9e00dc..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestGeomean.java +++ /dev/null @@ -1,134 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.MissingArgEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * From Excel documentation at https://support.office.com/en-us/article/geomean-function-db1ac48d-25a5-40a0-ab83-0b38980e40d5: - * 1. Arguments can either be numbers or names, arrays, or references that contain numbers. - * 2. Logical values and text representations of numbers that you type directly into the list of arguments are counted. - * 3. If an array or reference argument contains text, logical values, or empty cells, those values are ignored; however, cells with the value zero are included. - * 4. Arguments that are error values or text that cannot be translated into numbers cause errors. - * 5. If any data point ≤ 0, GEOMEAN returns the #NUM! error value. - * - * Remarks: - * Actually, 5. is not true. If an error is encountered before a 0 value, the error is returned. - */ -class TestGeomean { - @Test - void acceptanceTest() { - Function geomean = getInstance(); - - final ValueEval result = geomean.evaluate(new ValueEval[]{new NumberEval(2), new NumberEval(3)}, 0, 0); - verifyNumericResult(2.449489742783178, result); - } - - @Test - void booleansByValueAreCoerced() { - final ValueEval[] args = {BoolEval.TRUE}; - final ValueEval result = getInstance().evaluate(args, 0, 0); - verifyNumericResult(1.0, result); - } - - @Test - void stringsByValueAreCoerced() { - final ValueEval[] args = {new StringEval("2")}; - final ValueEval result = getInstance().evaluate(args, 0, 0); - verifyNumericResult(2.0, result); - } - - @Test - void nonCoerceableStringsByValueCauseValueInvalid() { - final ValueEval[] args = {new StringEval("foo")}; - final ValueEval result = getInstance().evaluate(args, 0, 0); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void booleansByReferenceAreSkipped() { - final ValueEval[] args = new ValueEval[]{new NumberEval(2.0), EvalFactory.createRefEval("A1", BoolEval.TRUE)}; - final ValueEval result = getInstance().evaluate(args, 0, 0); - verifyNumericResult(2.0, result); - } - - @Test - void booleansStringsAndBlanksByReferenceAreSkipped() { - ValueEval ref = EvalFactory.createAreaEval("A1:A3", new ValueEval[]{new StringEval("foo"), BoolEval.FALSE, BlankEval.instance}); - final ValueEval[] args = {ref, new NumberEval(2.0)}; - final ValueEval result = getInstance().evaluate(args, 0, 0); - verifyNumericResult(2.0, result); - } - - @Test - void stringsByValueAreCounted() { - final ValueEval[] args = {new StringEval("2.0")}; - final ValueEval result = getInstance().evaluate(args, 0, 0); - verifyNumericResult(2.0, result); - } - - @Test - void missingArgCountAsZero() { - // and, naturally, produces a NUM_ERROR - final ValueEval[] args = {new NumberEval(1.0), MissingArgEval.instance}; - final ValueEval result = getInstance().evaluate(args, 0, 0); - assertEquals(ErrorEval.NUM_ERROR, result); - } - - /** - * Implementation-specific: the math lib returns 0 for the input [1.0, 0.0], but a NUM_ERROR should be returned. - */ - @Test - void sequence_1_0_shouldReturnError() { - final ValueEval[] args = {new NumberEval(1.0), new NumberEval(0)}; - final ValueEval result = getInstance().evaluate(args, 0, 0); - assertEquals(ErrorEval.NUM_ERROR, result); - } - - @Test - void minusOneShouldReturnError() { - final ValueEval[] args = {new NumberEval(1.0), new NumberEval(-1.0)}; - final ValueEval result = getInstance().evaluate(args, 0, 0); - assertEquals(ErrorEval.NUM_ERROR, result); - } - - @Test - void firstErrorPropagates() { - final ValueEval[] args = {ErrorEval.DIV_ZERO, ErrorEval.NUM_ERROR}; - final ValueEval result = getInstance().evaluate(args, 0, 0); - assertEquals(ErrorEval.DIV_ZERO, result); - } - - private void verifyNumericResult(double expected, ValueEval result) { - assertTrue(result instanceof NumberEval); - assertEquals(expected, ((NumberEval) result).getNumberValue(), 1e-15); - } - - private Function getInstance() { - return AggregateFunction.GEOMEAN; - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestHex2Dec.java b/src/testcases/org/apache/poi/ss/formula/functions/TestHex2Dec.java deleted file mode 100644 index ba5bae0b1f..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestHex2Dec.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Hex2Dec} - * - * @author cedric dot walter @ gmail dot com - */ -final class TestHex2Dec { - - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Hex2Dec().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval) result).getStringValue(), msg); - } - - private static void confirmValueError(String msg, String number1, ErrorEval numError) { - ValueEval result = invokeValue(number1); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(numError, result, msg); - } - - @Test - void testBasic() { - confirmValue("Converts hex 'A5' to decimal (165)", "A5", "165"); - confirmValue("Converts hex FFFFFFFF5B to decimal (-165)", "FFFFFFFF5B", "-165"); - confirmValue("Converts hex 3DA408B9 to decimal (-165)", "3DA408B9", "1034160313"); - } - - @Test - void testErrors() { - confirmValueError("not a valid hex number","GGGGGGG", ErrorEval.NUM_ERROR); - confirmValueError("not a valid hex number","3.14159", ErrorEval.NUM_ERROR); - } - - @Test - void testEvalOperationEvaluationContext() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Hex2Dec().evaluate(args, ctx); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals("0", ((NumberEval) result).getStringValue()); - } - - @Test - void testEvalOperationEvaluationContextFails() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 0) }; - ValueEval result = new Hex2Dec().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - private OperationEvaluationContext createContext() { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet(); - HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, (sheetIndex, rowIndex, columnIndex) -> true, null); - return new OperationEvaluationContext(workbookEvaluator, workbook, 0, 0, 0, null); - } - - @Test - void testRefs() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Hex2Dec().evaluate(args, -1, -1); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals("0", ((NumberEval) result).getStringValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIFFunctionFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIFFunctionFromSpreadsheet.java deleted file mode 100644 index 3614200239..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIFFunctionFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests IF() as loaded from a test data spreadsheet.

- */ -class TestIFFunctionFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestIFFunctionFromSpreadsheet.class, "IfFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIPMT.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIPMT.java deleted file mode 100644 index e11a2b87c1..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIPMT.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -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.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Test cases for IPMT() - * - */ -final class TestIPMT { - - - /** - * from http://office.microsoft.com/en-001/excel-help/ipmt-HP005209145.aspx - */ - @Test - void testFromFile() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("finance.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet example1 = wb.getSheet("IPMT"); - HSSFCell ex1cell1 = example1.getRow(6).getCell(0); - fe.evaluate(ex1cell1); - assertEquals(-22.41, ex1cell1.getNumericCellValue(), 0.1); - - HSSFCell ex1cell2 = example1.getRow(7).getCell(0); - fe.evaluate(ex1cell2); - assertEquals(-292.45, ex1cell2.getNumericCellValue(), 0.1); - - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestImRealFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestImRealFunctionsFromSpreadsheet.java deleted file mode 100644 index 4d226fa26a..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestImRealFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests ImReal() as loaded from a test data spreadsheet.

- */ -class TestImRealFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestImRealFunctionsFromSpreadsheet.class, "ImRealFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestImaginaryFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestImaginaryFunctionsFromSpreadsheet.java deleted file mode 100644 index ea1fe44b1f..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestImaginaryFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests Imaginary() as loaded from a test data spreadsheet.

- */ -class TestImaginaryFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestImaginaryFunctionsFromSpreadsheet.class, "ImaginaryFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIndex.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIndex.java deleted file mode 100644 index b39e396c04..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndex.java +++ /dev/null @@ -1,320 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Arrays; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.MissingArgEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Test; - -/** - * Tests for the INDEX() function.

- * - * This class contains just a few specific cases that directly invoke {@link Index}, - * with minimum overhead.
- * Another test: {@link TestIndexFunctionFromSpreadsheet} operates from a higher level - * and has far greater coverage of input permutations.
- */ -final class TestIndex { - - private static final Index FUNC_INST = new Index(); - private static final double[] TEST_VALUES0 = { - 1, 2, - 3, 4, - 5, 6, - 7, 8, - 9, 10, - 11, 12, - }; - - /** - * For the case when the first argument to INDEX() is an area reference - */ - @Test - void testEvaluateAreaReference() { - - double[] values = TEST_VALUES0; - confirmAreaEval("C1:D6", values, 4, 1, 7); - confirmAreaEval("C1:D6", values, 6, 2, 12); - confirmAreaEval("C1:D6", values, 3, 1, 5); - - // now treat same data as 3 columns, 4 rows - confirmAreaEval("C10:E13", values, 2, 2, 5); - confirmAreaEval("C10:E13", values, 4, 1, 10); - } - - /** - * @param areaRefString in Excel notation e.g. 'D2:E97' - * @param dValues array of evaluated values for the area reference - * @param rowNum 1-based - * @param colNum 1-based, pass -1 to signify argument not present - */ - private static void confirmAreaEval(String areaRefString, double[] dValues, - int rowNum, int colNum, double expectedResult) { - ValueEval[] values = new ValueEval[dValues.length]; - for (int i = 0; i < values.length; i++) { - values[i] = new NumberEval(dValues[i]); - } - AreaEval arg0 = EvalFactory.createAreaEval(areaRefString, values); - - ValueEval[] args; - if (colNum > 0) { - args = new ValueEval[] { arg0, new NumberEval(rowNum), new NumberEval(colNum), }; - } else { - args = new ValueEval[] { arg0, new NumberEval(rowNum), }; - } - - double actual = invokeAndDereference(args); - assertEquals(expectedResult, actual, 0D); - } - - private static double invokeAndDereference(ValueEval[] args) { - ValueEval ve = FUNC_INST.evaluate(args, -1, -1); - ve = WorkbookEvaluator.dereferenceResult(ve, -1, -1); - assertEquals(NumberEval.class, ve.getClass()); - return ((NumberEval)ve).getNumberValue(); - } - - /** - * Tests expressions like "INDEX(A1:C1,,2)".
- * This problem was found while fixing bug 47048 and is observable up to svn r773441. - */ - @Test - void testMissingArg() { - ValueEval[] values = { - new NumberEval(25.0), - new NumberEval(26.0), - new NumberEval(28.0), - }; - AreaEval arg0 = EvalFactory.createAreaEval("A10:C10", values); - ValueEval[] args = new ValueEval[] { arg0, MissingArgEval.instance, new NumberEval(2), }; - // Identified bug 47048b - INDEX() should support missing-arg - ValueEval actualResult = FUNC_INST.evaluate(args, -1, -1); - // result should be an area eval "B10:B10" - AreaEval ae = confirmAreaEval("B10:B10", actualResult); - actualResult = ae.getValue(0, 0); - assertEquals(NumberEval.class, actualResult.getClass()); - assertEquals(26.0, ((NumberEval)actualResult).getNumberValue(), 0.0); - } - - /** - * When the argument to INDEX is a reference, the result should be a reference - * A formula like "OFFSET(INDEX(A1:B2,2,1),1,1,1,1)" should return the value of cell B3. - * This works because the INDEX() function returns a reference to A2 (not the value of A2) - */ - @Test - void testReferenceResult() { - ValueEval[] values = new ValueEval[4]; - Arrays.fill(values, NumberEval.ZERO); - AreaEval arg0 = EvalFactory.createAreaEval("A1:B2", values); - ValueEval[] args = new ValueEval[] { arg0, new NumberEval(2), new NumberEval(1), }; - ValueEval ve = FUNC_INST.evaluate(args, -1, -1); - confirmAreaEval("A2:A2", ve); - } - - /** - * Confirms that the result is an area ref with the specified coordinates - * @return ve cast to {@link AreaEval} if it is valid - */ - private static AreaEval confirmAreaEval(String refText, ValueEval ve) { - CellRangeAddress cra = CellRangeAddress.valueOf(refText); - assertTrue(ve instanceof AreaEval); - AreaEval ae = (AreaEval) ve; - assertEquals(cra.getFirstRow(), ae.getFirstRow()); - assertEquals(cra.getFirstColumn(), ae.getFirstColumn()); - assertEquals(cra.getLastRow(), ae.getLastRow()); - assertEquals(cra.getLastColumn(), ae.getLastColumn()); - return ae; - } - - @Test - void test61859(){ - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("maxindextest.xls"); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet example1 = wb.getSheetAt(0); - Cell ex1cell1 = example1.getRow(1).getCell(6); - assertEquals("MAX(INDEX(($B$2:$B$11=F2)*$A$2:$A$11,0))", ex1cell1.getCellFormula()); - fe.evaluate(ex1cell1); - assertEquals(4.0, ex1cell1.getNumericCellValue(), 0); - - Cell ex1cell2 = example1.getRow(2).getCell(6); - assertEquals("MAX(INDEX(($B$2:$B$11=F3)*$A$2:$A$11,0))", ex1cell2.getCellFormula()); - fe.evaluate(ex1cell2); - assertEquals(10.0, ex1cell2.getNumericCellValue(), 0); - - Cell ex1cell3 = example1.getRow(3).getCell(6); - assertEquals("MAX(INDEX(($B$2:$B$11=F4)*$A$2:$A$11,0))", ex1cell3.getCellFormula()); - fe.evaluate(ex1cell3); - assertEquals(20.0, ex1cell3.getNumericCellValue(), 0); - } - - @Test - void test61116(){ - Workbook workbook = HSSFTestDataSamples.openSampleWorkbook("61116.xls"); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - Sheet sheet = workbook.getSheet("sample2"); - - Row row = sheet.getRow(1); - assertEquals(3.0, evaluator.evaluate(row.getCell(1)).getNumberValue(), 0); - assertEquals(3.0, evaluator.evaluate(row.getCell(2)).getNumberValue(), 0); - - row = sheet.getRow(2); - assertEquals(5.0, evaluator.evaluate(row.getCell(1)).getNumberValue(), 0); - assertEquals(5.0, evaluator.evaluate(row.getCell(2)).getNumberValue(), 0); - } - - /** - * If both the Row_num and Column_num arguments are used, - * INDEX returns the value in the cell at the intersection of Row_num and Column_num - */ - @Test - void testReference2DArea(){ - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - /* - * 1 2 3 - * 4 5 6 - * 7 8 9 - */ - int val = 0; - for(int i = 0; i < 3; i++){ - Row row = sheet.createRow(i); - for(int j = 0; j < 3; j++){ - row.createCell(j).setCellValue(++val); - } - } - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Cell c1 = sheet.getRow(0).createCell(5); - c1.setCellFormula("INDEX(A1:C3,2,2)"); - Cell c2 = sheet.getRow(0).createCell(6); - c2.setCellFormula("INDEX(A1:C3,3,2)"); - - assertEquals(5.0, fe.evaluate(c1).getNumberValue(), 0); - assertEquals(8.0, fe.evaluate(c2).getNumberValue(), 0); - } - - /** - * If Column_num is 0 (zero), INDEX returns the array of values for the entire row. - */ - @Test - void testArrayArgument_RowLookup(){ - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - /* - * 1 2 3 - * 4 5 6 - * 7 8 9 - */ - int val = 0; - for(int i = 0; i < 3; i++){ - Row row = sheet.createRow(i); - for(int j = 0; j < 3; j++){ - row.createCell(j).setCellValue(++val); - } - } - Cell c1 = sheet.getRow(0).createCell(5); - c1.setCellFormula("SUM(INDEX(A1:C3,1,0))"); // sum of all values in the 1st row: 1 + 2 + 3 = 6 - - Cell c2 = sheet.getRow(0).createCell(6); - c2.setCellFormula("SUM(INDEX(A1:C3,2,0))"); // sum of all values in the 2nd row: 4 + 5 + 6 = 15 - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - assertEquals(6.0, fe.evaluate(c1).getNumberValue(), 0); - assertEquals(15.0, fe.evaluate(c2).getNumberValue(), 0); - - } - - /** - * If Row_num is 0 (zero), INDEX returns the array of values for the entire column. - */ - @Test - void testArrayArgument_ColumnLookup(){ - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - /* - * 1 2 3 - * 4 5 6 - * 7 8 9 - */ - int val = 0; - for(int i = 0; i < 3; i++){ - Row row = sheet.createRow(i); - for(int j = 0; j < 3; j++){ - row.createCell(j).setCellValue(++val); - } - } - Cell c1 = sheet.getRow(0).createCell(5); - c1.setCellFormula("SUM(INDEX(A1:C3,0,1))"); // sum of all values in the 1st column: 1 + 4 + 7 = 12 - - Cell c2 = sheet.getRow(0).createCell(6); - c2.setCellFormula("SUM(INDEX(A1:C3,0,3))"); // sum of all values in the 3rd column: 3 + 6 + 9 = 18 - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - assertEquals(12.0, fe.evaluate(c1).getNumberValue(), 0); - assertEquals(18.0, fe.evaluate(c2).getNumberValue(), 0); - } - - /** - * =SUM(B1:INDEX(B1:B3,2)) - * - * The sum of the range starting at B1, and ending at the intersection of the 2nd row of the range B1:B3, - * which is the sum of B1:B2. - */ - @Test - void testDynamicReference(){ - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - /* - * 1 2 3 - * 4 5 6 - * 7 8 9 - */ - int val = 0; - for(int i = 0; i < 3; i++){ - Row row = sheet.createRow(i); - for(int j = 0; j < 3; j++){ - row.createCell(j).setCellValue(++val); - } - } - Cell c1 = sheet.getRow(0).createCell(5); - c1.setCellFormula("SUM(B1:INDEX(B1:B3,2))"); // B1:INDEX(B1:B3,2) evaluates to B1:B2 - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - assertEquals(7.0, fe.evaluate(c1).getNumberValue(), 0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIndexFunctionFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIndexFunctionFromSpreadsheet.java deleted file mode 100644 index 8bf6ffc1a9..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndexFunctionFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests INDEX() as loaded from a test data spreadsheet.

- */ -final class TestIndexFunctionFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestIndexFunctionFromSpreadsheet.class, "IndexFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIndirect.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIndirect.java deleted file mode 100644 index 45422e19e7..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndirect.java +++ /dev/null @@ -1,203 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.junit.jupiter.api.Test; - -/** - * Tests for the INDIRECT() function.

- */ -final class TestIndirect { - // convenient access to namespace - // private static final ErrorEval EE = null; - - private static void createDataRow(HSSFSheet sheet, int rowIndex, double... vals) { - HSSFRow row = sheet.createRow(rowIndex); - for (int i = 0; i < vals.length; i++) { - row.createCell(i).setCellValue(vals[i]); - } - } - - private static HSSFWorkbook createWBA() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("John's sales"); - - createDataRow(sheet1, 0, 11, 12, 13, 14); - createDataRow(sheet1, 1, 21, 22, 23, 24); - createDataRow(sheet1, 2, 31, 32, 33, 34); - - createDataRow(sheet2, 0, 50, 55, 60, 65); - createDataRow(sheet2, 1, 51, 56, 61, 66); - createDataRow(sheet2, 2, 52, 57, 62, 67); - - createDataRow(sheet3, 0, 30, 31, 32); - createDataRow(sheet3, 1, 33, 34, 35); - - HSSFName name1 = wb.createName(); - name1.setNameName("sales1"); - name1.setRefersToFormula("Sheet1!A1:D1"); - - HSSFName name2 = wb.createName(); - name2.setNameName("sales2"); - name2.setRefersToFormula("Sheet2!B1:C3"); - - HSSFRow row = sheet1.createRow(3); - row.createCell(0).setCellValue("sales1"); //A4 - row.createCell(1).setCellValue("sales2"); //B4 - - return wb; - } - - private static HSSFWorkbook createWBB() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("## Look here!"); - - createDataRow(sheet1, 0, 400, 440, 480, 520); - createDataRow(sheet1, 1, 420, 460, 500, 540); - - createDataRow(sheet2, 0, 50, 55, 60, 65); - createDataRow(sheet2, 1, 51, 56, 61, 66); - - createDataRow(sheet3, 0, 42); - - return wb; - } - - @Test - void testBasic() throws Exception { - - HSSFWorkbook wbA = createWBA(); - HSSFCell c = wbA.getSheetAt(0).createRow(5).createCell(2); - HSSFFormulaEvaluator feA = new HSSFFormulaEvaluator(wbA); - - // non-error cases - confirm(feA, c, "INDIRECT(\"C2\")", 23); - confirm(feA, c, "INDIRECT(\"C2\", TRUE)", 23); - confirm(feA, c, "INDIRECT(\"$C2\")", 23); - confirm(feA, c, "INDIRECT(\"C$2\")", 23); - confirm(feA, c, "SUM(INDIRECT(\"Sheet2!B1:C3\"))", 351); // area ref - confirm(feA, c, "SUM(INDIRECT(\"Sheet2! B1 : C3 \"))", 351); // spaces in area ref - confirm(feA, c, "SUM(INDIRECT(\"'John''s sales'!A1:C1\"))", 93); // special chars in sheet name - confirm(feA, c, "INDIRECT(\"'Sheet1'!B3\")", 32); // redundant sheet name quotes - confirm(feA, c, "INDIRECT(\"sHeet1!B3\")", 32); // case-insensitive sheet name - confirm(feA, c, "INDIRECT(\" D3 \")", 34); // spaces around cell ref - confirm(feA, c, "INDIRECT(\"Sheet1! D3 \")", 34); // spaces around cell ref - confirm(feA, c, "INDIRECT(\"A1\", TRUE)", 11); // explicit arg1. only TRUE supported so far - - confirm(feA, c, "INDIRECT(\"A1:G1\")", 13); // de-reference area ref (note formula is in C4) - - confirm(feA, c, "SUM(INDIRECT(A4))", 50); // indirect defined name - confirm(feA, c, "SUM(INDIRECT(B4))", 351); // indirect defined name pointinh to other sheet - - // simple error propagation: - - // arg0 is evaluated to text first - confirm(feA, c, "INDIRECT(#DIV/0!)", ErrorEval.DIV_ZERO); - confirm(feA, c, "INDIRECT(#DIV/0!)", ErrorEval.DIV_ZERO); - confirm(feA, c, "INDIRECT(#NAME?, \"x\")", ErrorEval.NAME_INVALID); - confirm(feA, c, "INDIRECT(#NUM!, #N/A)", ErrorEval.NUM_ERROR); - - // arg1 is evaluated to boolean before arg0 is decoded - confirm(feA, c, "INDIRECT(\"garbage\", #N/A)", ErrorEval.NA); - confirm(feA, c, "INDIRECT(\"garbage\", \"\")", ErrorEval.VALUE_INVALID); // empty string is not valid boolean - confirm(feA, c, "INDIRECT(\"garbage\", \"flase\")", ErrorEval.VALUE_INVALID); // must be "TRUE" or "FALSE" - - - // spaces around sheet name (with or without quotes makes no difference) - confirm(feA, c, "INDIRECT(\"'Sheet1 '!D3\")", ErrorEval.REF_INVALID); - confirm(feA, c, "INDIRECT(\" Sheet1!D3\")", ErrorEval.REF_INVALID); - confirm(feA, c, "INDIRECT(\"'Sheet1' !D3\")", ErrorEval.REF_INVALID); - - - confirm(feA, c, "SUM(INDIRECT(\"'John's sales'!A1:C1\"))", ErrorEval.REF_INVALID); // bad quote escaping - confirm(feA, c, "INDIRECT(\"[Book1]Sheet1!A1\")", ErrorEval.REF_INVALID); // unknown external workbook - confirm(feA, c, "INDIRECT(\"Sheet3!A1\")", ErrorEval.REF_INVALID); // unknown sheet -// if (false) { // TODO - support evaluation of defined names -// confirm(feA, c, "INDIRECT(\"Sheet1!IW1\")", ErrorEval.REF_INVALID); // bad column -// confirm(feA, c, "INDIRECT(\"Sheet1!A65537\")", ErrorEval.REF_INVALID); // bad row -// } - confirm(feA, c, "INDIRECT(\"Sheet1!A 1\")", ErrorEval.REF_INVALID); // space in cell ref - - wbA.close(); - } - - @Test - void testMultipleWorkbooks() throws Exception { - HSSFWorkbook wbA = createWBA(); - HSSFCell cellA = wbA.getSheetAt(0).createRow(10).createCell(0); - HSSFFormulaEvaluator feA = new HSSFFormulaEvaluator(wbA); - - HSSFWorkbook wbB = createWBB(); - HSSFCell cellB = wbB.getSheetAt(0).createRow(10).createCell(0); - HSSFFormulaEvaluator feB = new HSSFFormulaEvaluator(wbB); - - String[] workbookNames = { "MyBook", "Figures for January", }; - HSSFFormulaEvaluator[] evaluators = { feA, feB, }; - HSSFFormulaEvaluator.setupEnvironment(workbookNames, evaluators); - - confirm(feB, cellB, "INDIRECT(\"'[Figures for January]## Look here!'!A1\")", 42); // same wb - confirm(feA, cellA, "INDIRECT(\"'[Figures for January]## Look here!'!A1\")", 42); // across workbooks - - // 2 level recursion - confirm(feB, cellB, "INDIRECT(\"[MyBook]Sheet2!A1\")", 50); // set up (and check) first level - confirm(feA, cellA, "INDIRECT(\"'[Figures for January]Sheet1'!A11\")", 50); // points to cellB - - wbB.close(); - wbA.close(); - } - - private static void confirm(FormulaEvaluator fe, Cell cell, String formula, double expectedResult) { - fe.clearAllCachedResultValues(); - cell.setCellFormula(formula); - CellValue cv = fe.evaluate(cell); - assertEquals(CellType.NUMERIC, cv.getCellType(), "expected numeric cell type but got " + cv.formatAsString()); - assertEquals(expectedResult, cv.getNumberValue(), 0.0); - } - - private static void confirm(FormulaEvaluator fe, Cell cell, String formula, ErrorEval expectedResult) { - fe.clearAllCachedResultValues(); - cell.setCellFormula(formula); - CellValue cv = fe.evaluate(cell); - assertEquals(CellType.ERROR, cv.getCellType(), "expected error cell type but got " + cv.formatAsString()); - int expCode = expectedResult.getErrorCode(); - assertEquals(expCode, cv.getErrorValue(), "Expected error '" + ErrorEval.getText(expCode) + "' but got '" + cv.formatAsString() + "'."); - } - - @Test - void testInvalidInput() { - assertEquals(ErrorEval.VALUE_INVALID, Indirect.instance.evaluate(new ValueEval[] {}, null)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIndirectFunctionFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIndirectFunctionFromSpreadsheet.java deleted file mode 100644 index f3a8cccb4f..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndirectFunctionFromSpreadsheet.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests INDIRECT() as loaded from a test data spreadsheet.

- * - * Tests for bug fixes and specific/tricky behaviour can be found in the corresponding test class - * (TestXxxx) of the target (Xxxx) implementor, where execution can be observed - * more easily. - */ -final class TestIndirectFunctionFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestIndirectFunctionFromSpreadsheet.class, "IndirectFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIntercept.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIntercept.java deleted file mode 100644 index 03dac3cef2..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIntercept.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -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.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Test for Excel function INTERCEPT() - * - * @author Johan Karlsteen - */ -final class TestIntercept { - private static final Function INTERCEPT = new Intercept(); - - private static ValueEval invoke(Function function, ValueEval xArray, ValueEval yArray) { - ValueEval[] args = new ValueEval[] { xArray, yArray, }; - return function.evaluate(args, -1, (short)-1); - } - - private void confirm(Function function, ValueEval xArray, ValueEval yArray, double expected) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval)result).getNumberValue(), 0); - } - private void confirmError(Function function, ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - private void confirmError(ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - confirmError(INTERCEPT, xArray, yArray, expectedError); - } - - @Test - void testBasic() { - Double exp = Math.pow(10, 7.5); - ValueEval[] yValues = { - new NumberEval(3+exp), - new NumberEval(4+exp), - new NumberEval(2+exp), - new NumberEval(5+exp), - new NumberEval(4+exp), - new NumberEval(7+exp), - }; - ValueEval areaEvalY = createAreaEval(yValues); - - ValueEval[] xValues = { - new NumberEval(1), - new NumberEval(2), - new NumberEval(3), - new NumberEval(4), - new NumberEval(5), - new NumberEval(6), - }; - ValueEval areaEvalX = createAreaEval(xValues); - confirm(INTERCEPT, areaEvalX, areaEvalY, -24516534.39905822); - // Excel 2010 gives -24516534.3990583 - } - - /** - * number of items in array is not limited to 30 - */ - @Test - void testLargeArrays() { - ValueEval[] yValues = createMockNumberArray(100, 3); // [1,2,0,1,2,0,...,0,1] - yValues[0] = new NumberEval(2.0); // Changes first element to 2 - ValueEval[] xValues = createMockNumberArray(100, 101); // [1,2,3,4,...,99,100] - - confirm(INTERCEPT, createAreaEval(xValues), createAreaEval(yValues), 51.74384236453202); - // Excel 2010 gives 51.74384236453200 - } - - private ValueEval[] createMockNumberArray(int size, double value) { - ValueEval[] result = new ValueEval[size]; - for (int i = 0; i < result.length; i++) { - result[i] = new NumberEval((i+1)%value); - } - return result; - } - - private static ValueEval createAreaEval(ValueEval[] values) { - String refStr = "A1:A" + values.length; - return EvalFactory.createAreaEval(refStr, values); - } - - @Test - void testErrors() { - ValueEval[] xValues = { - ErrorEval.REF_INVALID, - new NumberEval(2), - }; - ValueEval areaEvalX = createAreaEval(xValues); - ValueEval[] yValues = { - new NumberEval(2), - ErrorEval.NULL_INTERSECTION, - }; - ValueEval areaEvalY = createAreaEval(yValues); - ValueEval[] zValues = { // wrong size - new NumberEval(2), - }; - ValueEval areaEvalZ = createAreaEval(zValues); - - // if either arg is an error, that error propagates - confirmError(ErrorEval.REF_INVALID, ErrorEval.NAME_INVALID, ErrorEval.REF_INVALID); - confirmError(areaEvalX, ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - confirmError(ErrorEval.NAME_INVALID, areaEvalX, ErrorEval.NAME_INVALID); - - // array sizes must match - confirmError(areaEvalX, areaEvalZ, ErrorEval.NA); - confirmError(areaEvalZ, areaEvalY, ErrorEval.NA); - - // any error in an array item propagates up - confirmError(areaEvalX, areaEvalX, ErrorEval.REF_INVALID); - - // search for errors array by array, not pair by pair - confirmError(areaEvalX, areaEvalY, ErrorEval.NULL_INTERSECTION); - confirmError(areaEvalY, areaEvalX, ErrorEval.REF_INVALID); - } - - /** - * Example from - * http://office.microsoft.com/en-us/excel-help/intercept-function-HP010062512.aspx?CTT=5&origin=HA010277524 - */ - @Test - void testFromFile() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("intercept.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet example1 = wb.getSheet("Example 1"); - HSSFCell a8 = example1.getRow(7).getCell(0); - assertEquals("INTERCEPT(A2:A6,B2:B6)", a8.getCellFormula()); - fe.evaluate(a8); - assertEquals(0.048387097, a8.getNumericCellValue(), 0.000000001); - - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIrr.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIrr.java deleted file mode 100644 index 6764ebdc2b..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIrr.java +++ /dev/null @@ -1,128 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -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; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Irr} - */ -final class TestIrr { - - @Test - void testIrr() { - // http://en.wikipedia.org/wiki/Internal_rate_of_return#Example - double[] incomes = {-4000d, 1200d, 1410d, 1875d, 1050d}; - double irr = Irr.irr(incomes); - double irrRounded = Math.round(irr * 1000d) / 1000d; - assertEquals(0.143d, irrRounded, 0); - - // http://www.techonthenet.com/excel/formulas/irr.php - incomes = new double[]{-7500d, 3000d, 5000d, 1200d, 4000d}; - irr = Irr.irr(incomes); - irrRounded = Math.round(irr * 100d) / 100d; - assertEquals(0.28d, irrRounded, 0); - - incomes = new double[]{-10000d, 3400d, 6500d, 1000d}; - irr = Irr.irr(incomes); - irrRounded = Math.round(irr * 100d) / 100d; - assertEquals(0.05, irrRounded, 0); - - incomes = new double[]{100d, -10d, -110d}; - irr = Irr.irr(incomes); - irrRounded = Math.round(irr * 100d) / 100d; - assertEquals(0.1, irrRounded, 0); - - incomes = new double[]{-70000d, 12000, 15000}; - irr = Irr.irr(incomes, -0.1); - irrRounded = Math.round(irr * 100d) / 100d; - assertEquals(-0.44, irrRounded, 0); - } - - @Test - void testEvaluateInSheet() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - - row.createCell(0).setCellValue(-4000d); - row.createCell(1).setCellValue(1200d); - row.createCell(2).setCellValue(1410d); - row.createCell(3).setCellValue(1875d); - row.createCell(4).setCellValue(1050d); - - HSSFCell cell = row.createCell(5); - cell.setCellFormula("IRR(A1:E1)"); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCell(cell); - double res = cell.getNumericCellValue(); - assertEquals(0.143d, Math.round(res * 1000d) / 1000d, 0); - } - - @Test - void testIrrFromSpreadsheet(){ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("IrrNpvTestCaseData.xls"); - HSSFSheet sheet = wb.getSheet("IRR-NPV"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - StringBuilder failures = new StringBuilder(); - // TODO YK: Formulas in rows 16 and 17 operate with ArrayPtg which isn't yet supported - // FormulaEvaluator as of r1041407 throws "Unexpected ptg class (org.apache.poi.ss.formula.ptg.ArrayPtg)" - for(int rownum = 9; rownum <= 15; rownum++){ - HSSFRow row = sheet.getRow(rownum); - HSSFCell cellA = row.getCell(0); - try { - CellValue cv = fe.evaluate(cellA); - assertFormulaResult(cv, cellA); - } catch (Throwable e){ - if(failures.length() > 0) failures.append('\n'); - failures.append("Row[" + (cellA.getRowIndex() + 1)+ "]: " + cellA.getCellFormula() + " "); - failures.append(e.getMessage()); - } - - HSSFCell cellC = row.getCell(2); //IRR-NPV relationship: NPV(IRR(values), values) = 0 - try { - CellValue cv = fe.evaluate(cellC); - assertEquals(0, cv.getNumberValue(), 0.0001); // should agree within 0.01% - } catch (Throwable e){ - if(failures.length() > 0) failures.append('\n'); - failures.append("Row[" + (cellC.getRowIndex() + 1)+ "]: " + cellC.getCellFormula() + " "); - failures.append(e.getMessage()); - } - } - assertEquals(0, failures.length(), "IRR assertions failed"); - } - - private static void assertFormulaResult(CellValue cv, HSSFCell cell){ - double actualValue = cv.getNumberValue(); - double expectedValue = cell.getNumericCellValue(); // cached formula result calculated by Excel - assertEquals(CellType.NUMERIC, cv.getCellType(), "Invalid formula result: " + cv); - assertEquals(expectedValue, actualValue, 1E-4); // should agree within 0.01% - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIsBlank.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIsBlank.java deleted file mode 100644 index 9f6ece060c..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIsBlank.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -/** - * Tests for Excel function ISBLANK() - * - * @author Josh Micich - */ -final class TestIsBlank { - - @Test - void test3DArea() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet(); - wb.setSheetName(0, "Sheet1"); - wb.createSheet(); - wb.setSheetName(1, "Sheet2"); - HSSFRow row = sheet1.createRow(0); - HSSFCell cell = row.createCell(0); - - - cell.setCellFormula("isblank(Sheet2!A1:A1)"); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue result = fe.evaluate(cell); - assertEquals(CellType.BOOLEAN, result.getCellType()); - assertTrue(result.getBooleanValue()); - - cell.setCellFormula("isblank(D7:D7)"); - - result = fe.evaluate(cell); - assertEquals(CellType.BOOLEAN, result.getCellType()); - assertTrue(result.getBooleanValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLeftRight.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLeftRight.java deleted file mode 100644 index 4bf92c7196..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLeftRight.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * - * Test cases for {@link TextFunction#LEFT} and {@link TextFunction#RIGHT} - * - * @author Brendan Nolan - * - */ -class TestLeftRight { - - private static final NumberEval NEGATIVE_OPERAND = new NumberEval(-1.0); - private static final StringEval ANY_STRING_VALUE = new StringEval("ANYSTRINGVALUE"); - - - private static ValueEval invokeLeft(ValueEval text, ValueEval operand) { - ValueEval[] args = new ValueEval[] { text, operand }; - return TextFunction.LEFT.evaluate(args, -1, (short)-1); - } - - private static ValueEval invokeRight(ValueEval text, ValueEval operand) { - ValueEval[] args = new ValueEval[] { text, operand }; - return TextFunction.RIGHT.evaluate(args, -1, (short)-1); - } - - @Test - void testLeftRight_bug49841() { - assertEquals(ErrorEval.VALUE_INVALID, invokeLeft(ANY_STRING_VALUE, NEGATIVE_OPERAND)); - assertEquals(ErrorEval.VALUE_INVALID, invokeRight(ANY_STRING_VALUE, NEGATIVE_OPERAND)); - } - - @Test - void testLeftRightNegativeOperand() { - assertEquals(ErrorEval.VALUE_INVALID, invokeRight(ANY_STRING_VALUE, NEGATIVE_OPERAND)); - assertEquals(ErrorEval.VALUE_INVALID, invokeLeft(ANY_STRING_VALUE, NEGATIVE_OPERAND)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLen.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLen.java deleted file mode 100644 index b4d8aa7a13..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLen.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for Excel function LEN() - * - * @author Josh Micich - */ -final class TestLen { - - private static ValueEval invokeLen(ValueEval text) { - ValueEval[] args = new ValueEval[] { text, }; - return TextFunction.LEN.evaluate(args, -1, (short)-1); - } - - private void confirmLen(ValueEval text, int expected) { - ValueEval result = invokeLen(text); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval)result).getNumberValue(), 0); - } - - private void confirmLen(ValueEval text, ErrorEval expectedError) { - ValueEval result = invokeLen(text); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - @Test - void testBasic() { - confirmLen(new StringEval("galactic"), 8); - } - - /** - * Valid cases where text arg is not exactly a string - */ - @Test - void testUnusualArgs() { - - // text (first) arg type is number, other args are strings with fractional digits - confirmLen(new NumberEval(123456), 6); - confirmLen(BoolEval.FALSE, 5); - confirmLen(BoolEval.TRUE, 4); - confirmLen(BlankEval.instance, 0); - } - - @Test - void testErrors() { - confirmLen(ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunction.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunction.java deleted file mode 100644 index 8825f01814..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunction.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * LogicalFunction unit tests. - */ -class TestLogicalFunction { - - private FormulaEvaluator evaluator; - private Row row3; - private Cell cell1; - private Cell cell2; - - @BeforeEach - void setUp() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - buildWorkbook(wb); - } - } - - private void buildWorkbook(Workbook wb) { - Sheet sh = wb.createSheet(); - Row row1 = sh.createRow(0); - Row row2 = sh.createRow(1); - row3 = sh.createRow(2); - - row1.createCell(0, CellType.NUMERIC); - row1.createCell(1, CellType.NUMERIC); - - row2.createCell(0, CellType.NUMERIC); - row2.createCell(1, CellType.NUMERIC); - - row3.createCell(0); - row3.createCell(1); - - CellReference a1 = new CellReference("A1"); - CellReference a2 = new CellReference("A2"); - CellReference b1 = new CellReference("B1"); - CellReference b2 = new CellReference("B2"); - - sh.getRow(a1.getRow()).getCell(a1.getCol()).setCellValue(35); - sh.getRow(a2.getRow()).getCell(a2.getCol()).setCellValue(0); - sh.getRow(b1.getRow()).getCell(b1.getCol()).setCellFormula("A1/A2"); - sh.getRow(b2.getRow()).getCell(b2.getCol()).setCellFormula("NA()"); - - evaluator = wb.getCreationHelper().createFormulaEvaluator(); - } - - @Test - void testIsErr() { - cell1 = row3.createCell(0); - cell1.setCellFormula("ISERR(B1)"); // produces #DIV/0! - cell2 = row3.createCell(1); - cell2.setCellFormula("ISERR(B2)"); // produces #N/A - - CellValue cell1Value = evaluator.evaluate(cell1); - CellValue cell2Value = evaluator.evaluate(cell2); - - assertTrue(cell1Value.getBooleanValue()); - assertFalse(cell2Value.getBooleanValue()); - } - - @Test - void testIsError() { - cell1 = row3.createCell(0); - cell1.setCellFormula("ISERROR(B1)"); // produces #DIV/0! - cell2 = row3.createCell(1); - cell2.setCellFormula("ISERROR(B2)"); // produces #N/A - - CellValue cell1Value = evaluator.evaluate(cell1); - CellValue cell2Value = evaluator.evaluate(cell2); - - assertTrue(cell1Value.getBooleanValue()); - assertTrue(cell2Value.getBooleanValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunctionsFromSpreadsheet.java deleted file mode 100644 index 84deb0fc7b..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests for logical ISxxx functions as loaded from a test data spreadsheet.

- */ -class TestLogicalFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestLogicalFunctionsFromSpreadsheet.class, "LogicalFunctionsTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLookupFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLookupFunctionsFromSpreadsheet.java deleted file mode 100644 index 84d3674b70..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLookupFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,37 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests lookup functions (VLOOKUP, HLOOKUP, LOOKUP, MATCH) as loaded from a test data spreadsheet.

- * These tests have been separated from the common function and operator tests because the lookup - * functions have more complex test cases and test data setup. - * - * Tests for bug fixes and specific/tricky behaviour can be found in the corresponding test class - * (TestXxxx) of the target (Xxxx) implementor, where execution can be observed - * more easily. - */ -final class TestLookupFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestLookupFunctionsFromSpreadsheet.class, "LookupFunctionsTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMatch.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMatch.java deleted file mode 100644 index 3721c688df..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMatch.java +++ /dev/null @@ -1,288 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.NumericValueEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Test cases for MATCH() - */ -final class TestMatch { - /** less than or equal to */ - private static final NumberEval MATCH_LARGEST_LTE = new NumberEval(1); - private static final NumberEval MATCH_EXACT = new NumberEval(0); - /** greater than or equal to */ - private static final NumberEval MATCH_SMALLEST_GTE = new NumberEval(-1); - - private static final StringEval MATCH_INVALID = new StringEval("blabla"); - - private static ValueEval invokeMatch(ValueEval lookup_value, ValueEval lookup_array, ValueEval match_type) { - ValueEval[] args = { lookup_value, lookup_array, match_type, }; - return new Match().evaluate(args, -1, (short)-1); - } - - private static ValueEval invokeMatch(ValueEval lookup_value, ValueEval lookup_array) { - ValueEval[] args = { lookup_value, lookup_array, }; - return new Match().evaluate(args, -1, (short)-1); - } - - private static void confirmInt(int expected, ValueEval actualEval) { - assertTrue(actualEval instanceof NumericValueEval, "Expected numeric result but had " + actualEval); - NumericValueEval nve = (NumericValueEval)actualEval; - assertEquals(expected, nve.getNumberValue(), 0); - } - - @Test - void testSimpleNumber() { - - ValueEval[] values = { - new NumberEval(4), - new NumberEval(5), - new NumberEval(10), - new NumberEval(10), - new NumberEval(25), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - confirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE)); - confirmInt(2, invokeMatch(new NumberEval(5), ae)); - confirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new NumberEval(10), ae, MATCH_LARGEST_LTE)); - confirmInt(3, invokeMatch(new NumberEval(10), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new NumberEval(20), ae, MATCH_LARGEST_LTE)); - assertEquals(ErrorEval.NA, invokeMatch(new NumberEval(20), ae, MATCH_EXACT)); - } - - @Test - void testReversedNumber() { - - ValueEval[] values = { - new NumberEval(25), - new NumberEval(10), - new NumberEval(10), - new NumberEval(10), - new NumberEval(4), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - confirmInt(2, invokeMatch(new NumberEval(10), ae, MATCH_SMALLEST_GTE)); - confirmInt(2, invokeMatch(new NumberEval(10), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new NumberEval(9), ae, MATCH_SMALLEST_GTE)); - confirmInt(1, invokeMatch(new NumberEval(20), ae, MATCH_SMALLEST_GTE)); - confirmInt(5, invokeMatch(new NumberEval(3), ae, MATCH_SMALLEST_GTE)); - assertEquals(ErrorEval.NA, invokeMatch(new NumberEval(20), ae, MATCH_EXACT)); - assertEquals(ErrorEval.NA, invokeMatch(new NumberEval(26), ae, MATCH_SMALLEST_GTE)); - } - - @Test - void testSimpleString() { - // Arrange - ValueEval[] values = { - new StringEval("Albert"), - new StringEval("Charles"), - new StringEval("Ed"), - new StringEval("Greg"), - new StringEval("Ian"), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - // Note String comparisons are case insensitive - confirmInt(3, invokeMatch(new StringEval("Ed"), ae, MATCH_LARGEST_LTE)); - confirmInt(3, invokeMatch(new StringEval("eD"), ae, MATCH_LARGEST_LTE)); - confirmInt(3, invokeMatch(new StringEval("Ed"), ae, MATCH_EXACT)); - confirmInt(3, invokeMatch(new StringEval("ed"), ae, MATCH_EXACT)); - - assertEquals(ErrorEval.NA, invokeMatch(new StringEval("Hugh"), ae, MATCH_EXACT)); - } - - @Test - void testSimpleWildcardValuesString() { - // Arrange - ValueEval[] values = { - new StringEval("Albert"), - new StringEval("Charles"), - new StringEval("Ed"), - new StringEval("Greg"), - new StringEval("Ian"), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - // Note String comparisons are case insensitive - confirmInt(3, invokeMatch(new StringEval("e*"), ae, MATCH_EXACT)); - confirmInt(3, invokeMatch(new StringEval("*d"), ae, MATCH_EXACT)); - - confirmInt(1, invokeMatch(new StringEval("Al*"), ae, MATCH_EXACT)); - confirmInt(2, invokeMatch(new StringEval("Char*"), ae, MATCH_EXACT)); - - confirmInt(4, invokeMatch(new StringEval("*eg"), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new StringEval("G?eg"), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new StringEval("??eg"), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new StringEval("G*?eg"), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new StringEval("Hugh"), ae, MATCH_LARGEST_LTE)); - - confirmInt(5, invokeMatch(new StringEval("*Ian*"), ae, MATCH_EXACT)); - confirmInt(5, invokeMatch(new StringEval("*Ian*"), ae, MATCH_LARGEST_LTE)); - } - - @Test - void testTildeString() { - - ValueEval[] values = { - new StringEval("what?"), - new StringEval("all*") - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A2", values); - - confirmInt(1, invokeMatch(new StringEval("what~?"), ae, MATCH_EXACT)); - confirmInt(2, invokeMatch(new StringEval("all~*"), ae, MATCH_EXACT)); - } - - @Test - void testSimpleBoolean() { - - ValueEval[] values = { - BoolEval.FALSE, - BoolEval.FALSE, - BoolEval.TRUE, - BoolEval.TRUE, - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A4", values); - - // Note String comparisons are case insensitive - confirmInt(2, invokeMatch(BoolEval.FALSE, ae, MATCH_LARGEST_LTE)); - confirmInt(1, invokeMatch(BoolEval.FALSE, ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(BoolEval.TRUE, ae, MATCH_LARGEST_LTE)); - confirmInt(3, invokeMatch(BoolEval.TRUE, ae, MATCH_EXACT)); - } - - @Test - void testHeterogeneous() { - - ValueEval[] values = { - new NumberEval(4), - BoolEval.FALSE, - new NumberEval(5), - new StringEval("Albert"), - BoolEval.FALSE, - BoolEval.TRUE, - new NumberEval(10), - new StringEval("Charles"), - new StringEval("Ed"), - new NumberEval(10), - new NumberEval(25), - BoolEval.TRUE, - new StringEval("Ed"), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A13", values); - - assertEquals(ErrorEval.NA, invokeMatch(new StringEval("Aaron"), ae, MATCH_LARGEST_LTE)); - - confirmInt(5, invokeMatch(BoolEval.FALSE, ae, MATCH_LARGEST_LTE)); - confirmInt(2, invokeMatch(BoolEval.FALSE, ae, MATCH_EXACT)); - confirmInt(3, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE)); - confirmInt(3, invokeMatch(new NumberEval(5), ae, MATCH_EXACT)); - - confirmInt(8, invokeMatch(new StringEval("CHARLES"), ae, MATCH_EXACT)); - //wildcard values - confirmInt(8, invokeMatch(new StringEval("CHAR*"), ae, MATCH_EXACT)); - confirmInt(8, invokeMatch(new StringEval("*CHARLES"), ae, MATCH_EXACT)); - - confirmInt(4, invokeMatch(new StringEval("Ben"), ae, MATCH_LARGEST_LTE)); - - confirmInt(13, invokeMatch(new StringEval("ED"), ae, MATCH_LARGEST_LTE)); - confirmInt(13, invokeMatch(new StringEval("ED*"), ae, MATCH_LARGEST_LTE)); - confirmInt(13, invokeMatch(new StringEval("*ED"), ae, MATCH_LARGEST_LTE)); - confirmInt(9, invokeMatch(new StringEval("ED"), ae, MATCH_EXACT)); - confirmInt(9, invokeMatch(new StringEval("ED*"), ae, MATCH_EXACT)); - - confirmInt(13, invokeMatch(new StringEval("Hugh"), ae, MATCH_LARGEST_LTE)); - assertEquals(ErrorEval.NA, invokeMatch(new StringEval("Hugh"), ae, MATCH_EXACT)); - - confirmInt(11, invokeMatch(new NumberEval(30), ae, MATCH_LARGEST_LTE)); - confirmInt(12, invokeMatch(BoolEval.TRUE, ae, MATCH_LARGEST_LTE)); - } - - - /** - * Ensures that the match_type argument can be an AreaEval.
- * Bugzilla 44421 - */ - @Test - void testMatchArgTypeArea() { - - ValueEval[] values = { - new NumberEval(4), - new NumberEval(5), - new NumberEval(10), - new NumberEval(10), - new NumberEval(25), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - AreaEval matchAE = EvalFactory.createAreaEval("C1:C1", new ValueEval[] { MATCH_LARGEST_LTE, }); - - try { - confirmInt(4, invokeMatch(new NumberEval(10), ae, matchAE)); - } catch (RuntimeException e) { - if(e.getMessage().startsWith("Unexpected match_type type")) { - // identified bug 44421 - fail(e.getMessage()); - } - // some other error ?? - throw e; - } - } - - @Test - void testInvalidMatchType() { - - ValueEval[] values = { - new NumberEval(4), - new NumberEval(5), - new NumberEval(10), - new NumberEval(10), - new NumberEval(25), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - confirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE)); - - assertEquals(ErrorEval.REF_INVALID, invokeMatch(new StringEval("Ben"), ae, MATCH_INVALID), - "Should return #REF! for invalid match type"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMatchFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMatchFunctionsFromSpreadsheet.java deleted file mode 100644 index 7f6f8ca2e6..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMatchFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests Match functions as loaded from a test data spreadsheet.

- * - * Tests for bug fixes and specific/tricky behaviour can be found in the corresponding test class - * (TestXxxx) of the target (Xxxx) implementor, where execution can be observed - * more easily. - */ -final class TestMatchFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestMatchFunctionsFromSpreadsheet.class, "MatchFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMathX.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMathX.java deleted file mode 100644 index e408fceb7e..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMathX.java +++ /dev/null @@ -1,1035 +0,0 @@ -/* -* 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. -*/ -/* - * Created on May 23, 2005 - * - */ -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.formula.functions.XYNumericFunction.Accumulator; -import org.junit.jupiter.api.Test; - - -/** - * @author Amol S. Deshmukh < amolweb at ya hoo dot com > - * - */ -public class TestMathX extends BaseTestNumeric { - - @Test - void testAcosh() { - double d; - - d = MathX.acosh(0); - assertTrue( Double.isNaN(d), "Acosh 0 is NaN" ); - - d = MathX.acosh(1); - assertDouble("Acosh 1 ", 0, d); - - d = MathX.acosh(-1); - assertTrue( Double.isNaN(d), "Acosh -1 is NaN" ); - - d = MathX.acosh(100); - assertDouble("Acosh 100 ", 5.298292366d, d); - - d = MathX.acosh(101.001); - assertDouble("Acosh 101.001 ", 5.308253091d, d); - - d = MathX.acosh(200000); - assertDouble("Acosh 200000 ", 12.89921983d, d); - - } - - @Test - void testAsinh() { - double d; - - d = MathX.asinh(0); - assertDouble("asinh 0", d, 0); - - d = MathX.asinh(1); - assertDouble("asinh 1 ", 0.881373587, d); - - d = MathX.asinh(-1); - assertDouble("asinh -1 ", -0.881373587, d); - - d = MathX.asinh(-100); - assertDouble("asinh -100 ", -5.298342366, d); - - d = MathX.asinh(100); - assertDouble("asinh 100 ", 5.298342366, d); - - d = MathX.asinh(200000); - assertDouble("asinh 200000", 12.899219826096400, d); - - d = MathX.asinh(-200000); - assertDouble("asinh -200000 ", -12.899223853137, d); - - } - - @Test - void testAtanh() { - double d; - d = MathX.atanh(0); - assertDouble("atanh 0", d, 0); - - d = MathX.atanh(1); - assertDouble("atanh 1 ", Double.POSITIVE_INFINITY, d); - - d = MathX.atanh(-1); - assertDouble("atanh -1 ", Double.NEGATIVE_INFINITY, d); - - d = MathX.atanh(-100); - assertDouble("atanh -100 ", Double.NaN, d); - - d = MathX.atanh(100); - assertDouble("atanh 100 ", Double.NaN, d); - - d = MathX.atanh(200000); - assertDouble("atanh 200000", Double.NaN, d); - - d = MathX.atanh(-200000); - assertDouble("atanh -200000 ", Double.NaN, d); - - d = MathX.atanh(0.1); - assertDouble("atanh 0.1", 0.100335348, d); - - d = MathX.atanh(-0.1); - assertDouble("atanh -0.1 ", -0.100335348, d); - - } - - @Test - void testCosh() { - double d; - d = MathX.cosh(0); - assertDouble("cosh 0", 1, d); - - d = MathX.cosh(1); - assertDouble("cosh 1 ", 1.543080635, d); - - d = MathX.cosh(-1); - assertDouble("cosh -1 ", 1.543080635, d); - - d = MathX.cosh(-100); - assertDouble("cosh -100 ", 1.344058570908070E+43, d); - - d = MathX.cosh(100); - assertDouble("cosh 100 ", 1.344058570908070E+43, d); - - d = MathX.cosh(15); - assertDouble("cosh 15", 1634508.686, d); - - d = MathX.cosh(-15); - assertDouble("cosh -15 ", 1634508.686, d); - - d = MathX.cosh(0.1); - assertDouble("cosh 0.1", 1.005004168, d); - - d = MathX.cosh(-0.1); - assertDouble("cosh -0.1 ", 1.005004168, d); - - } - - @Test - void testTanh() { - double d; - d = MathX.tanh(0); - assertDouble("tanh 0", 0, d); - - d = MathX.tanh(1); - assertDouble("tanh 1 ", 0.761594156, d); - - d = MathX.tanh(-1); - assertDouble("tanh -1 ", -0.761594156, d); - - d = MathX.tanh(-100); - assertDouble("tanh -100 ", -1, d); - - d = MathX.tanh(100); - assertDouble("tanh 100 ", 1, d); - - d = MathX.tanh(15); - assertDouble("tanh 15", 1, d); - - d = MathX.tanh(-15); - assertDouble("tanh -15 ", -1, d); - - d = MathX.tanh(0.1); - assertDouble("tanh 0.1", 0.099667995, d); - - d = MathX.tanh(-0.1); - assertDouble("tanh -0.1 ", -0.099667995, d); - - } - - @Test - void testMax() { - double[] d = new double[100]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - double m = MathX.max(d); - assertDouble("Max ", 20.1, m); - - d = new double[1000]; - m = MathX.max(d); - assertDouble("Max ", 0, m); - - d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1; - d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1; - d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1; - d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1; - d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1; - m = MathX.max(d); - assertDouble("Max ", 20.1, m); - - d = new double[20]; - d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1; - d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1; - d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1; - d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1; - d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1; - m = MathX.max(d); - assertDouble("Max ", -1.1, m); - - } - - @Test - void testMin() { - double[] d = new double[100]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - double m = MathX.min(d); - assertDouble("Min ", 0, m); - - d = new double[20]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - m = MathX.min(d); - assertDouble("Min ", 1.1, m); - - d = new double[1000]; - m = MathX.min(d); - assertDouble("Min ", 0, m); - - d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1; - d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1; - d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1; - d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1; - d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1; - m = MathX.min(d); - assertDouble("Min ", -19.1, m); - - d = new double[20]; - d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1; - d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1; - d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1; - d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1; - d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1; - m = MathX.min(d); - assertDouble("Min ", -20.1, m); - } - - @Test - void testProduct() { - assertDouble("Product ", 0, MathX.product(null)); - assertDouble("Product ", 0, MathX.product(new double[] {})); - assertDouble("Product ", 0, MathX.product(new double[] {1, 0})); - - assertDouble("Product ", 1, MathX.product(new double[] { 1 })); - assertDouble("Product ", 1, MathX.product(new double[] { 1, 1 })); - assertDouble("Product ", 10, MathX.product(new double[] { 10, 1 })); - assertDouble("Product ", -2, MathX.product(new double[] { 2, -1 })); - assertDouble("Product ", 99988000209999d, MathX.product(new double[] { 99999, 99999, 9999 })); - - double[] d = new double[100]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - double m = MathX.product(d); - assertDouble("Product ", 0, m); - - d = new double[20]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - m = MathX.product(d); - assertDouble("Product ", 3459946360003355534d, m); - - d = new double[1000]; - m = MathX.product(d); - assertDouble("Product ", 0, m); - - d = new double[20]; - d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1; - d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1; - d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1; - d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1; - d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1; - m = MathX.product(d); - assertDouble("Product ", 3459946360003355534d, m); - } - - @Test - void testMod() { - - //example from Excel help - assertDouble(1.0, MathX.mod(3, 2)); - assertDouble(1.0, MathX.mod(-3, 2)); - assertDouble(-1.0, MathX.mod(3, -2)); - assertDouble(-1.0, MathX.mod(-3, -2)); - - assertDouble(0.0, MathX.mod(0, 2)); - assertDouble(Double.NaN, MathX.mod(3, 0)); - assertDouble(1.4, MathX.mod(3.4, 2)); - assertDouble(-1.4, MathX.mod(-3.4, -2)); - assertDouble(0.6000000000000001, MathX.mod(-3.4, 2.0));// should actually be 0.6 - assertDouble(-0.6000000000000001, MathX.mod(3.4, -2.0));// should actually be -0.6 - assertDouble(3.0, MathX.mod(3, Double.MAX_VALUE)); - assertDouble(2.0, MathX.mod(Double.MAX_VALUE, 3)); - - // Bugzilla 50033 - assertDouble(1.0, MathX.mod(13, 12)); - } - - @Test - void testNChooseK() { - int n=100; - int k=50; - double d = MathX.nChooseK(n, k); - assertDouble("NChooseK ", 1.00891344545564E29, d); - - n = -1; k = 1; - d = MathX.nChooseK(n, k); - assertDouble("NChooseK ", Double.NaN, d); - - n = 1; k = -1; - d = MathX.nChooseK(n, k); - assertDouble("NChooseK ", Double.NaN, d); - - n = 0; k = 1; - d = MathX.nChooseK(n, k); - assertDouble("NChooseK ", Double.NaN, d); - - n = 1; k = 0; - d = MathX.nChooseK(n, k); - assertDouble("NChooseK ", 1, d); - - n = 10; k = 9; - d = MathX.nChooseK(n, k); - assertDouble("NChooseK ", 10, d); - - n = 10; k = 10; - d = MathX.nChooseK(n, k); - assertDouble("NChooseK ", 1, d); - - n = 10; k = 1; - d = MathX.nChooseK(n, k); - assertDouble("NChooseK ", 10, d); - - n = 1000; k = 1; - d = MathX.nChooseK(n, k); - assertDouble("NChooseK ", 1000, d); // awesome ;) - - n = 1000; k = 2; - d = MathX.nChooseK(n, k); - assertDouble("NChooseK ", 499500, d); // awesome ;) - - n = 13; k = 7; - d = MathX.nChooseK(n, k); - assertDouble("NChooseK ", 1716, d); - - } - - @Test - void testSign() { - final short minus = -1; - final short zero = 0; - final short plus = 1; - double d; - - - assertDouble("Sign ", minus, MathX.sign(minus)); - assertDouble("Sign ", plus, MathX.sign(plus)); - assertDouble("Sign ", zero, MathX.sign(zero)); - - d = 0; - assertDouble("Sign ", zero, MathX.sign(d)); - - d = -1.000001; - assertDouble("Sign ", minus, MathX.sign(d)); - - d = -.000001; - assertDouble("Sign ", minus, MathX.sign(d)); - - d = -1E-200; - assertDouble("Sign ", minus, MathX.sign(d)); - - d = Double.NEGATIVE_INFINITY; - assertDouble("Sign ", minus, MathX.sign(d)); - - d = -200.11; - assertDouble("Sign ", minus, MathX.sign(d)); - - d = -2000000000000.11; - assertDouble("Sign ", minus, MathX.sign(d)); - - d = 1.000001; - assertDouble("Sign ", plus, MathX.sign(d)); - - d = .000001; - assertDouble("Sign ", plus, MathX.sign(d)); - - d = 1E-200; - assertDouble("Sign ", plus, MathX.sign(d)); - - d = Double.POSITIVE_INFINITY; - assertDouble("Sign ", plus, MathX.sign(d)); - - d = 200.11; - assertDouble("Sign ", plus, MathX.sign(d)); - - d = 2000000000000.11; - assertDouble("Sign ", plus, MathX.sign(d)); - - } - - @Test - void testSinh() { - double d; - d = MathX.sinh(0); - assertDouble("sinh 0", 0, d); - - d = MathX.sinh(1); - assertDouble("sinh 1 ", 1.175201194, d); - - d = MathX.sinh(-1); - assertDouble("sinh -1 ", -1.175201194, d); - - d = MathX.sinh(-100); - assertDouble("sinh -100 ", -1.344058570908070E+43, d); - - d = MathX.sinh(100); - assertDouble("sinh 100 ", 1.344058570908070E+43, d); - - d = MathX.sinh(15); - assertDouble("sinh 15", 1634508.686, d); - - d = MathX.sinh(-15); - assertDouble("sinh -15 ", -1634508.686, d); - - d = MathX.sinh(0.1); - assertDouble("sinh 0.1", 0.10016675, d); - - d = MathX.sinh(-0.1); - assertDouble("sinh -0.1 ", -0.10016675, d); - - } - - @Test - void testSum() { - double[] d = new double[100]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - double s = MathX.sum(d); - assertDouble("Sum ", 212, s); - - d = new double[1000]; - s = MathX.sum(d); - assertDouble("Sum ", 0, s); - - d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1; - d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1; - d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1; - d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1; - d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1; - s = MathX.sum(d); - assertDouble("Sum ", 10, s); - - d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1; - d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1; - d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1; - d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1; - d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1; - s = MathX.sum(d); - assertDouble("Sum ", -212, s); - - } - - @Test - void testSumsq() { - double[] d = new double[100]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - double s = MathX.sumsq(d); - assertDouble("Sumsq ", 2912.2, s); - - d = new double[1000]; - s = MathX.sumsq(d); - assertDouble("Sumsq ", 0, s); - - d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1; - d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1; - d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1; - d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1; - d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1; - s = MathX.sumsq(d); - assertDouble("Sumsq ", 2912.2, s); - - d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1; - d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1; - d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1; - d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1; - d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1; - s = MathX.sumsq(d); - assertDouble("Sumsq ", 2912.2, s); - } - - @Test - void testFactorial() { - int n; - double s; - - n = 0; - s = MathX.factorial(n); - assertDouble("Factorial ", 1, s); - - n = 1; - s = MathX.factorial(n); - assertDouble("Factorial ", 1, s); - - n = 10; - s = MathX.factorial(n); - assertDouble("Factorial ", 3628800, s); - - n = 99; - s = MathX.factorial(n); - assertDouble("Factorial ", 9.33262154439E+155, s); - - n = -1; - s = MathX.factorial(n); - assertDouble("Factorial ", Double.NaN, s); - - n = Integer.MAX_VALUE; - s = MathX.factorial(n); - assertDouble("Factorial ", Double.POSITIVE_INFINITY, s); - } - - @Test - void testSumx2my2() { - double[] xarr; - double[] yarr; - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumx2my2(xarr, yarr, 100); - - xarr = new double[]{-1, -2, -3, -4, -5, -6, -7, -8, -9, -10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumx2my2(xarr, yarr, 100); - - xarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumx2my2(xarr, yarr, -100); - - xarr = new double[]{10}; - yarr = new double[]{9}; - confirmSumx2my2(xarr, yarr, 19); - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumx2my2(xarr, yarr, 0); - } - - @Test - void testSumx2py2() { - double[] xarr; - double[] yarr; - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumx2py2(xarr, yarr, 670); - - xarr = new double[]{-1, -2, -3, -4, -5, -6, -7, -8, -9, -10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumx2py2(xarr, yarr, 670); - - xarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumx2py2(xarr, yarr, 670); - - xarr = new double[]{10}; - yarr = new double[]{9}; - confirmSumx2py2(xarr, yarr, 181); - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumx2py2(xarr, yarr, 770); - } - - @Test - void testSumxmy2() { - double[] xarr; - double[] yarr; - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumxmy2(xarr, yarr, 10); - - xarr = new double[]{-1, -2, -3, -4, -5, -6, -7, -8, -9, -10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumxmy2(xarr, yarr, 1330); - - xarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumxmy2(xarr, yarr, 10); - - xarr = new double[]{10}; - yarr = new double[]{9}; - confirmSumxmy2(xarr, yarr, 1); - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumxmy2(xarr, yarr, 0); - } - - private static void confirmSumx2my2(double[] xarr, double[] yarr, double expectedResult) { - confirmXY(new Sumx2my2().createAccumulator(), xarr, yarr, expectedResult); - } - private static void confirmSumx2py2(double[] xarr, double[] yarr, double expectedResult) { - confirmXY(new Sumx2py2().createAccumulator(), xarr, yarr, expectedResult); - } - private static void confirmSumxmy2(double[] xarr, double[] yarr, double expectedResult) { - confirmXY(new Sumxmy2().createAccumulator(), xarr, yarr, expectedResult); - } - - private static void confirmXY(Accumulator acc, double[] xarr, double[] yarr, - double expectedResult) { - double result = 0.0; - for (int i = 0; i < xarr.length; i++) { - result += acc.accumulate(xarr[i], yarr[i]); - } - assertDouble(expectedResult, result); - } - - @Test - void testRound() { - double d; - int p; - - d = 0; p = 0; - assertDouble("round ", 0, MathX.round(d, p)); - - d = 10; p = 0; - assertDouble("round ", 10, MathX.round(d, p)); - - d = 123.23; p = 0; - assertDouble("round ", 123, MathX.round(d, p)); - - d = -123.23; p = 0; - assertDouble("round ", -123, MathX.round(d, p)); - - d = 123.12; p = 2; - assertDouble("round ", 123.12, MathX.round(d, p)); - - d = 88.123459; p = 5; - assertDouble("round ", 88.12346, MathX.round(d, p)); - - d = 0; p = 2; - assertDouble("round ", 0, MathX.round(d, p)); - - d = 0; p = -1; - assertDouble("round ", 0, MathX.round(d, p)); - - d = 0.01; p = -1; - assertDouble("round ", 0, MathX.round(d, p)); - - d = 123.12; p = -2; - assertDouble("round ", 100, MathX.round(d, p)); - - d = 88.123459; p = -3; - assertDouble("round ", 0, MathX.round(d, p)); - - d = 49.00000001; p = -1; - assertDouble("round ", 50, MathX.round(d, p)); - - d = 149.999999; p = -2; - assertDouble("round ", 100, MathX.round(d, p)); - - d = 150.0; p = -2; - assertDouble("round ", 200, MathX.round(d, p)); - - d = 2162.615d; p = 2; - assertDouble("round ", 2162.62d, MathX.round(d, p)); - - d = 0.049999999999999975d; p = 2; - assertDouble("round ", 0.05d, MathX.round(d, p)); - - d = 0.049999999999999975d; p = 1; - assertDouble("round ", 0.1d, MathX.round(d, p)); - - d = Double.NaN; p = 1; - assertDouble("round ", Double.NaN, MathX.round(d, p)); - - d = Double.POSITIVE_INFINITY; p = 1; - assertDouble("round ", Double.NaN, MathX.round(d, p)); - - d = Double.NEGATIVE_INFINITY; p = 1; - assertDouble("round ", Double.NaN, MathX.round(d, p)); - - d = Double.MAX_VALUE; p = 1; - assertDouble("round ", Double.MAX_VALUE, MathX.round(d, p)); - - d = Double.MIN_VALUE; p = 1; - assertDouble("round ", 0.0d, MathX.round(d, p)); - } - - @Test - void testRoundDown() { - double d; - int p; - - d = 0; p = 0; - assertDouble("roundDown ", 0, MathX.roundDown(d, p)); - - d = 10; p = 0; - assertDouble("roundDown ", 10, MathX.roundDown(d, p)); - - d = 123.99; p = 0; - assertDouble("roundDown ", 123, MathX.roundDown(d, p)); - - d = -123.99; p = 0; - assertDouble("roundDown ", -123, MathX.roundDown(d, p)); - - d = 123.99; p = 2; - assertDouble("roundDown ", 123.99, MathX.roundDown(d, p)); - - d = 88.123459; p = 5; - assertDouble("roundDown ", 88.12345, MathX.roundDown(d, p)); - - d = 0; p = 2; - assertDouble("roundDown ", 0, MathX.roundDown(d, p)); - - d = 0; p = -1; - assertDouble("roundDown ", 0, MathX.roundDown(d, p)); - - d = 0.01; p = -1; - assertDouble("roundDown ", 0, MathX.roundDown(d, p)); - - d = 199.12; p = -2; - assertDouble("roundDown ", 100, MathX.roundDown(d, p)); - - d = 88.123459; p = -3; - assertDouble("roundDown ", 0, MathX.roundDown(d, p)); - - d = 99.00000001; p = -1; - assertDouble("roundDown ", 90, MathX.roundDown(d, p)); - - d = 100.00001; p = -2; - assertDouble("roundDown ", 100, MathX.roundDown(d, p)); - - d = 150.0; p = -2; - assertDouble("roundDown ", 100, MathX.roundDown(d, p)); - - d = 0.0499999999999975d; p = 2; - assertDouble("roundDown ", 0.04d, MathX.roundDown(d, p)); - - d = 0.049999999999999975d; p = 1; - assertDouble("roundDown ", 0.0d, MathX.roundDown(d, p)); - - d = Double.NaN; p = 1; - assertDouble("roundDown ", Double.NaN, MathX.roundDown(d, p)); - - d = Double.POSITIVE_INFINITY; p = 1; - assertDouble("roundDown ", Double.NaN, MathX.roundDown(d, p)); - - d = Double.NEGATIVE_INFINITY; p = 1; - assertDouble("roundDown ", Double.NaN, MathX.roundDown(d, p)); - - d = Double.MAX_VALUE; p = 1; - assertDouble("roundDown ", Double.MAX_VALUE, MathX.roundDown(d, p)); - - d = Double.MIN_VALUE; p = 1; - assertDouble("roundDown ", 0.0d, MathX.roundDown(d, p)); - - d = 3987 * 0.2; p = 2; - assertDouble("roundDown ", 797.40, MathX.round(d, p)); - } - - @Test - void testRoundUp() { - double d; - int p; - - d = 0; p = 0; - assertDouble("roundUp ", 0, MathX.roundUp(d, p)); - - d = 10; p = 0; - assertDouble("roundUp ", 10, MathX.roundUp(d, p)); - - d = 123.23; p = 0; - assertDouble("roundUp ", 124, MathX.roundUp(d, p)); - - d = -123.23; p = 0; - assertDouble("roundUp ", -124, MathX.roundUp(d, p)); - - d = 123.12; p = 2; - assertDouble("roundUp ", 123.12, MathX.roundUp(d, p)); - - d = 88.123459; p = 5; - assertDouble("roundUp ", 88.12346, MathX.roundUp(d, p)); - - d = 0; p = 2; - assertDouble("roundUp ", 0, MathX.roundUp(d, p)); - - d = 0; p = -1; - assertDouble("roundUp ", 0, MathX.roundUp(d, p)); - - d = 0.01; p = -1; - assertDouble("roundUp ", 10, MathX.roundUp(d, p)); - - d = 123.12; p = -2; - assertDouble("roundUp ", 200, MathX.roundUp(d, p)); - - d = 88.123459; p = -3; - assertDouble("roundUp ", 1000, MathX.roundUp(d, p)); - - d = 49.00000001; p = -1; - assertDouble("roundUp ", 50, MathX.roundUp(d, p)); - - d = 149.999999; p = -2; - assertDouble("roundUp ", 200, MathX.roundUp(d, p)); - - d = 150.0; p = -2; - assertDouble("roundUp ", 200, MathX.roundUp(d, p)); - - d = 0.049999999999999975d; p = 2; - assertDouble("roundUp ", 0.05d, MathX.roundUp(d, p)); - - d = 0.049999999999999975d; p = 1; - assertDouble("roundUp ", 0.1d, MathX.roundUp(d, p)); - - d = Double.NaN; p = 1; - assertDouble("roundUp ", Double.NaN, MathX.roundUp(d, p)); - - d = Double.POSITIVE_INFINITY; p = 1; - assertDouble("roundUp ", Double.NaN, MathX.roundUp(d, p)); - - d = Double.NEGATIVE_INFINITY; p = 1; - assertDouble("roundUp ", Double.NaN, MathX.roundUp(d, p)); - - d = Double.MAX_VALUE; p = 1; - assertDouble("roundUp ", Double.MAX_VALUE, MathX.roundUp(d, p)); - - // Excel's min positive value is several orders of magnitude larger than Java's (Java 8: 4.9e-324, Excel 2016 on Windows 10: 2.2259157957E-308) - d = Double.MIN_VALUE; p = 1; - assertDouble("roundUp ", 0.0d, MathX.roundUp(d, p)); - d = 2.2259157957E-308; p = 1; - assertDouble("roundUp ", 0.1d, MathX.roundUp(d, p)); - - //github-43: https://github.com/apache/poi/pull/43 - // "ROUNDUP(3987*0.2, 2) currently fails by returning 797.41") - d = 3987 * 0.2; p = 2; - assertDouble("roundUp ", 797.40, MathX.roundUp(d, p)); - } - - @Test - void testCeiling() { - double d; - double s; - - d = 0; s = 0; - assertDouble("ceiling ", 0, MathX.ceiling(d, s)); - - d = 1; s = 0; - assertDouble("ceiling ", 0, MathX.ceiling(d, s)); - - d = 0; s = 1; - assertDouble("ceiling ", 0, MathX.ceiling(d, s)); - - d = -1; s = 0; - assertDouble("ceiling ", 0, MathX.ceiling(d, s)); - - d = 0; s = -1; - assertDouble("ceiling ", 0, MathX.ceiling(d, s)); - - d = 10; s = 1.11; - assertDouble("ceiling ", 11.1, MathX.ceiling(d, s)); - - d = 11.12333; s = 0.03499; - assertDouble("ceiling ", 11.12682, MathX.ceiling(d, s)); - - d = -11.12333; s = 0.03499; - assertDouble("ceiling ", Double.NaN, MathX.ceiling(d, s)); - - d = 11.12333; s = -0.03499; - assertDouble("ceiling ", Double.NaN, MathX.ceiling(d, s)); - - d = -11.12333; s = -0.03499; - assertDouble("ceiling ", -11.12682, MathX.ceiling(d, s)); - - d = 100; s = 0.001; - assertDouble("ceiling ", 100, MathX.ceiling(d, s)); - - d = -0.001; s = -9.99; - assertDouble("ceiling ", -9.99, MathX.ceiling(d, s)); - - d = 4.42; s = 0.05; - assertDouble("ceiling ", 4.45, MathX.ceiling(d, s)); - - d = 0.05; s = 4.42; - assertDouble("ceiling ", 4.42, MathX.ceiling(d, s)); - - d = 0.6666; s = 3.33; - assertDouble("ceiling ", 3.33, MathX.ceiling(d, s)); - - d = 2d/3; s = 3.33; - assertDouble("ceiling ", 3.33, MathX.ceiling(d, s)); - - // samples from http://www.excelfunctions.net/Excel-Ceiling-Function.html - // and https://support.office.com/en-us/article/CEILING-function-0a5cd7c8-0720-4f0a-bd2c-c943e510899f - d = 22.25; s = 0.1; - assertDouble("ceiling ", 22.3, MathX.ceiling(d, s)); - d = 22.25; s = 0.5; - assertDouble("ceiling ", 22.5, MathX.ceiling(d, s)); - d = 22.25; s = 1; - assertDouble("ceiling ", 23, MathX.ceiling(d, s)); - d = 22.25; s = 10; - assertDouble("ceiling ", 30, MathX.ceiling(d, s)); - d = 22.25; s = 20; - assertDouble("ceiling ", 40, MathX.ceiling(d, s)); - d = -22.25; s = -0.1; - assertDouble("ceiling ", -22.3, MathX.ceiling(d, s)); - d = -22.25; s = -1; - assertDouble("ceiling ", -23, MathX.ceiling(d, s)); - d = -22.25; s = -5; - assertDouble("ceiling ", -25, MathX.ceiling(d, s)); - - d = 22.25; s = 1; - assertDouble("ceiling ", 23, MathX.ceiling(d, s)); - d = 22.25; s = -1; - assertDouble("ceiling ", Double.NaN, MathX.ceiling(d, s)); - d = -22.25; s = 1; - assertDouble("ceiling ", -22, MathX.ceiling(d, s)); // returns an error in Excel 2007 & earlier - d = -22.25; s = -1; - assertDouble("ceiling ", -23, MathX.ceiling(d, s)); - - // test cases for newer versions of Excel where d can be negative for - d = -11.12333; s = 0.03499; - assertDouble("ceiling ", -11.09183, MathX.ceiling(d, s)); - } - - @Test - void testFloor() { - double d; - double s; - - d = 0; s = 0; - assertDouble("floor ", 0, MathX.floor(d, s)); - - d = 1; s = 0; - assertDouble("floor ", Double.NaN, MathX.floor(d, s)); - - d = 0; s = 1; - assertDouble("floor ", 0, MathX.floor(d, s)); - - d = -1; s = 0; - assertDouble("floor ", Double.NaN, MathX.floor(d, s)); - - d = 0; s = -1; - assertDouble("floor ", 0, MathX.floor(d, s)); - - d = 10; s = 1.11; - assertDouble("floor ", 9.99, MathX.floor(d, s)); - - d = 11.12333; s = 0.03499; - assertDouble("floor ", 11.09183, MathX.floor(d, s)); - - d = -11.12333; s = 0.03499; - assertDouble("floor ", Double.NaN, MathX.floor(d, s)); - - d = 11.12333; s = -0.03499; - assertDouble("floor ", Double.NaN, MathX.floor(d, s)); - - d = -11.12333; s = -0.03499; - assertDouble("floor ", -11.09183, MathX.floor(d, s)); - - d = 100; s = 0.001; - assertDouble("floor ", 100, MathX.floor(d, s)); - - d = -0.001; s = -9.99; - assertDouble("floor ", 0, MathX.floor(d, s)); - - d = 4.42; s = 0.05; - assertDouble("floor ", 4.4, MathX.floor(d, s)); - - d = 0.05; s = 4.42; - assertDouble("floor ", 0, MathX.floor(d, s)); - - d = 0.6666; s = 3.33; - assertDouble("floor ", 0, MathX.floor(d, s)); - - d = 2d/3; s = 3.33; - assertDouble("floor ", 0, MathX.floor(d, s)); - - // samples from http://www.excelfunctions.net/Excel-Ceiling-Function.html - // and https://support.office.com/en-us/article/CEILING-function-0a5cd7c8-0720-4f0a-bd2c-c943e510899f - d = 3.7; s = 2; - assertDouble("floor ", 2, MathX.floor(d, s)); - d = -2.5; s = -2; - assertDouble("floor ", -2, MathX.floor(d, s)); - d = 2.5; s = -2; - assertDouble("floor ", Double.NaN, MathX.floor(d, s)); - d = 1.58; s = 0.1; - assertDouble("floor ", 1.5, MathX.floor(d, s)); - d = 0.234; s = 0.01; - assertDouble("floor ", 0.23, MathX.floor(d, s)); - - // see bug 62839 - d = -123; - s = 10; - assertDouble("floor ", -130, MathX.floor(d, s)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMid.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMid.java deleted file mode 100644 index 866c65fb4a..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMid.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.RefEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for Excel function MID() - * - * @author Josh Micich - */ -final class TestMid { - - - private static ValueEval invokeMid(ValueEval text, ValueEval startPos, ValueEval numChars) { - ValueEval[] args = new ValueEval[] { text, startPos, numChars, }; - return TextFunction.MID.evaluate(args, -1, (short)-1); - } - - private void confirmMid(ValueEval text, ValueEval startPos, ValueEval numChars, String expected) { - ValueEval result = invokeMid(text, startPos, numChars); - assertEquals(StringEval.class, result.getClass()); - assertEquals(expected, ((StringEval)result).getStringValue()); - } - - private void confirmMid(ValueEval text, ValueEval startPos, ValueEval numChars, ErrorEval expectedError) { - ValueEval result = invokeMid(text, startPos, numChars); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - @Test - void testBasic() { - - confirmMid(new StringEval("galactic"), new NumberEval(3), new NumberEval(4), "lact"); - } - - /** - * Valid cases where args are not precisely (string, int, int) but can be resolved OK. - */ - @Test - void testUnusualArgs() { - // startPos with fractional digits - confirmMid(new StringEval("galactic"), new NumberEval(3.1), new NumberEval(4), "lact"); - - // string startPos - confirmMid(new StringEval("galactic"), new StringEval("3"), new NumberEval(4), "lact"); - - // text (first) arg type is number, other args are strings with fractional digits - confirmMid(new NumberEval(123456), new StringEval("3.1"), new StringEval("2.9"), "34"); - - // startPos is 1x1 area ref, numChars is cell ref - AreaEval aeStart = EvalFactory.createAreaEval("A1:A1", new ValueEval[] { new NumberEval(2), } ); - RefEval reNumChars = EvalFactory.createRefEval("B1", new NumberEval(3)); - confirmMid(new StringEval("galactic"), aeStart, reNumChars, "ala"); - - confirmMid(new StringEval("galactic"), new NumberEval(3.1), BlankEval.instance, ""); - - confirmMid(new StringEval("galactic"), new NumberEval(3), BoolEval.FALSE, ""); - confirmMid(new StringEval("galactic"), new NumberEval(3), BoolEval.TRUE, "l"); - confirmMid(BlankEval.instance, new NumberEval(3), BoolEval.TRUE, ""); - - } - - /** - * Extreme values for startPos and numChars - */ - @Test - void testExtremes() { - confirmMid(new StringEval("galactic"), new NumberEval(4), new NumberEval(400), "actic"); - - confirmMid(new StringEval("galactic"), new NumberEval(30), new NumberEval(4), ""); - confirmMid(new StringEval("galactic"), new NumberEval(3), new NumberEval(0), ""); - } - - /** - * All sorts of ways to make MID return defined errors. - */ - @Test - void testErrors() { - confirmMid(ErrorEval.NAME_INVALID, new NumberEval(3), new NumberEval(4), ErrorEval.NAME_INVALID); - confirmMid(new StringEval("galactic"), ErrorEval.NAME_INVALID, new NumberEval(4), ErrorEval.NAME_INVALID); - confirmMid(new StringEval("galactic"), new NumberEval(3), ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - confirmMid(new StringEval("galactic"), ErrorEval.DIV_ZERO, ErrorEval.NAME_INVALID, ErrorEval.DIV_ZERO); - - confirmMid(new StringEval("galactic"), BlankEval.instance, new NumberEval(3.1), ErrorEval.VALUE_INVALID); - - confirmMid(new StringEval("galactic"), new NumberEval(0), new NumberEval(4), ErrorEval.VALUE_INVALID); - confirmMid(new StringEval("galactic"), new NumberEval(1), new NumberEval(-1), ErrorEval.VALUE_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMirr.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMirr.java deleted file mode 100644 index f640cb54ee..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMirr.java +++ /dev/null @@ -1,149 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -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; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link org.apache.poi.ss.formula.functions.Mirr} - * - * @author Carlos Delgado (carlos dot del dot est at gmail dot com) - * @author Cedric Walter (cedric dot walter at gmail dot com) - * @see org.apache.poi.ss.formula.functions.TestIrr - */ -final class TestMirr { - - @Test - void testMirr() throws EvaluationException { - Mirr mirr = new Mirr(); - double mirrValue; - - double financeRate = 0.12; - double reinvestRate = 0.1; - double[] values = {-120000d, 39000d, 30000d, 21000d, 37000d, 46000d, reinvestRate, financeRate}; - // MIRR should not failed with these parameters - mirrValue = mirr.evaluate(values); - assertEquals(0.126094130366, mirrValue, 0.0000000001); - - reinvestRate = 0.05; - financeRate = 0.08; - values = new double[]{-7500d, 3000d, 5000d, 1200d, 4000d, reinvestRate, financeRate}; - // MIRR should not failed with these parameters - mirrValue = mirr.evaluate(values); - assertEquals(0.18736225093, mirrValue, 0.0000000001); - - reinvestRate = 0.065; - financeRate = 0.1; - values = new double[]{-10000, 3400d, 6500d, 1000d, reinvestRate, financeRate}; - // MIRR should not failed with these parameters - mirrValue = mirr.evaluate(values); - assertEquals(0.07039493966, mirrValue, 0.0000000001); - - reinvestRate = 0.07; - financeRate = 0.01; - values = new double[]{-10000d, -3400d, -6500d, -1000d, reinvestRate, financeRate}; - // MIRR should not failed with these parameters - mirrValue = mirr.evaluate(values); - assertEquals(-1, mirrValue, 0.0); - - } - - @Test - void testMirrErrors_expectDIV0() { - Mirr mirr = new Mirr(); - - double reinvestRate = 0.05; - double financeRate = 0.08; - double[] incomes = {120000d, 39000d, 30000d, 21000d, 37000d, 46000d, reinvestRate, financeRate}; - - EvaluationException e = assertThrows(EvaluationException.class, () -> mirr.evaluate(incomes)); - assertEquals(ErrorEval.DIV_ZERO, e.getErrorEval()); - } - - @Test - void testEvaluateInSheet() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - - row.createCell(0).setCellValue(-7500d); - row.createCell(1).setCellValue(3000d); - row.createCell(2).setCellValue(5000d); - row.createCell(3).setCellValue(1200d); - row.createCell(4).setCellValue(4000d); - - row.createCell(5).setCellValue(0.05d); - row.createCell(6).setCellValue(0.08d); - - HSSFCell cell = row.createCell(7); - cell.setCellFormula("MIRR(A1:E1, F1, G1)"); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCell(cell); - double res = cell.getNumericCellValue(); - assertEquals(0.18736225093, res, 0.00000001); - } - - @Test - void testMirrFromSpreadsheet() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("mirrTest.xls"); - HSSFSheet sheet = wb.getSheet("Mirr"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - int failureCount = 0; - int[] resultRows = {9, 19, 29, 45}; - - for (int rowNum : resultRows) { - HSSFRow row = sheet.getRow(rowNum); - HSSFCell cellA = row.getCell(0); - try { - CellValue cv = fe.evaluate(cellA); - assertFormulaResult(cv, cellA); - } catch (Throwable e) { - failureCount++; - } - } - - HSSFRow row = sheet.getRow(37); - HSSFCell cellA = row.getCell(0); - CellValue cv = fe.evaluate(cellA); - assertEquals(ErrorEval.DIV_ZERO.getErrorCode(), cv.getErrorValue()); - - assertEquals(0, failureCount, "IRR assertions failed"); - } - - private static void assertFormulaResult(CellValue cv, HSSFCell cell) { - double actualValue = cv.getNumberValue(); - double expectedValue = cell.getNumericCellValue(); // cached formula result calculated by Excel - assertEquals(CellType.NUMERIC, cv.getCellType(), "Invalid formula result: " + cv); - assertEquals(expectedValue, actualValue, 1E-8); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMultiOperandNumericFunction.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMultiOperandNumericFunction.java deleted file mode 100644 index 3c6e88a273..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMultiOperandNumericFunction.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.ss.formula.eval.MissingArgEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -class TestMultiOperandNumericFunction { - - @Test - void testSettings() { - MultiOperandNumericFunction fun = new MultiOperandNumericFunction(true, true) { - @Override - protected double evaluate(double[] values) throws EvaluationException { - return 0; - } - - }; - assertEquals(SpreadsheetVersion.EXCEL2007.getMaxFunctionArgs(), fun.getMaxNumOperands()); - } - - @Test - void missingArgEvalsAreCountedAsZeroIfPolicyIsCoerce() { - MultiOperandNumericFunction instance = new Stub(true, true, MultiOperandNumericFunction.Policy.COERCE); - ValueEval result = instance.evaluate(new ValueEval[]{MissingArgEval.instance}, 0, 0); - assertTrue(result instanceof NumberEval); - assertEquals(0.0, ((NumberEval)result).getNumberValue(), 0); - } - - @Test - void missingArgEvalsAreSkippedIfZeroIfPolicyIsSkipped() { - MultiOperandNumericFunction instance = new Stub(true, true, MultiOperandNumericFunction.Policy.SKIP); - ValueEval result = instance.evaluate(new ValueEval[]{new NumberEval(1), MissingArgEval.instance}, 0, 0); - assertTrue(result instanceof NumberEval); - assertEquals(1.0, ((NumberEval)result).getNumberValue(), 0); - } - - private static class Stub extends MultiOperandNumericFunction { - protected Stub( - boolean isReferenceBoolCounted, boolean isBlankCounted, MultiOperandNumericFunction.Policy missingArgEvalPolicy) { - super(isReferenceBoolCounted, isBlankCounted); - setMissingArgPolicy(missingArgEvalPolicy); - } - - @Override - protected double evaluate(double[] values) throws EvaluationException { - return values[0]; - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestNper.java b/src/testcases/org/apache/poi/ss/formula/functions/TestNper.java deleted file mode 100644 index 9f958f0205..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestNper.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaError; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link FinanceFunction#NPER} - */ -final class TestNper { - - @Test - void testSimpleEvaluate() { - ValueEval[] args = { - new NumberEval(0.05), - new NumberEval(250), - new NumberEval(-1000), - }; - ValueEval result = FinanceFunction.NPER.evaluate(args, 0, (short)0); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals(4.57353557, ((NumberEval)result).getNumberValue(), 0.00000001); - } - - @Test - void testEvaluate_bug_45732() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFCell cell = sheet.createRow(0).createCell(0); - - cell.setCellFormula("NPER(12,4500,100000,100000)"); - cell.setCellValue(15.0); - assertEquals("NPER(12,4500,100000,100000)", cell.getCellFormula()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType()); - assertEquals(15.0, cell.getNumericCellValue(), 0.0); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - fe.evaluateFormulaCell(cell); - assertEquals(CellType.ERROR, cell.getCachedFormulaResultType()); - assertEquals(FormulaError.NUM.getCode(), cell.getErrorCellValue()); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestNpv.java b/src/testcases/org/apache/poi/ss/formula/functions/TestNpv.java deleted file mode 100644 index 191ff37fef..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestNpv.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -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; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Npv} - * - * @see Excel Help - */ -final class TestNpv { - - @Test - void testEvaluateInSheetExample2() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - - sheet.createRow(1).createCell(0).setCellValue(0.08d); - sheet.createRow(2).createCell(0).setCellValue(-40000d); - sheet.createRow(3).createCell(0).setCellValue(8000d); - sheet.createRow(4).createCell(0).setCellValue(9200d); - sheet.createRow(5).createCell(0).setCellValue(10000d); - sheet.createRow(6).createCell(0).setCellValue(12000d); - sheet.createRow(7).createCell(0).setCellValue(14500d); - - HSSFCell cell = row.createCell(8); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - // Enumeration - cell.setCellFormula("NPV(A2, A4,A5,A6,A7,A8)+A3"); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCell(cell); - double res = cell.getNumericCellValue(); - assertEquals(1922.06d, Math.round(res * 100d) / 100d, 0); - - // Range - cell.setCellFormula("NPV(A2, A4:A8)+A3"); - - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCell(cell); - res = cell.getNumericCellValue(); - assertEquals(1922.06d, Math.round(res * 100d) / 100d, 0); - } - - /** - * evaluate formulas with NPV and compare the result with - * the cached formula result pre-calculated by Excel - */ - @Test - void testNpvFromSpreadsheet(){ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("IrrNpvTestCaseData.xls"); - HSSFSheet sheet = wb.getSheet("IRR-NPV"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - int failureCount = 0; - // TODO YK: Formulas in rows 16 and 17 operate with ArrayPtg which isn't yet supported - // FormulaEvaluator as of r1041407 throws "Unexpected ptg class (org.apache.poi.ss.formula.ptg.ArrayPtg)" - for(int rownum = 9; rownum <= 15; rownum++){ - HSSFRow row = sheet.getRow(rownum); - HSSFCell cellB = row.getCell(1); - try { - CellValue cv = fe.evaluate(cellB); - assertFormulaResult(cv, cellB); - } catch (Throwable e){ - failureCount++; - } - } - - assertEquals(0, failureCount, "IRR evaluations failed"); - } - - private static void assertFormulaResult(CellValue cv, HSSFCell cell){ - double actualValue = cv.getNumberValue(); - double expectedValue = cell.getNumericCellValue(); // cached formula result calculated by Excel - assertEquals(expectedValue, actualValue, 1E-4); // should agree within 0.01% - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestOct2Dec.java b/src/testcases/org/apache/poi/ss/formula/functions/TestOct2Dec.java deleted file mode 100644 index 89c19277d2..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestOct2Dec.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link org.apache.poi.ss.formula.functions.Oct2Dec} - * - * @author cedric dot walter @ gmail dot com - */ -final class TestOct2Dec { - - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Oct2Dec().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval) result).getStringValue(), msg); - } - - private static void confirmValueError(String msg, String number1, ErrorEval numError) { - ValueEval result = invokeValue(number1); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(numError, result, msg); - } - - @Test - void testBasic() { - confirmValue("Converts octal '' to decimal (0)", "", "0"); - confirmValue("Converts octal 54 to decimal (44)", "54", "44"); - confirmValue("Converts octal 7777777533 to decimal (-165)", "7777777533", "-165"); - confirmValue("Converts octal 7000000000 to decimal (-134217728)", "7000000000", "-134217728"); - confirmValue("Converts octal 7776667533 to decimal (-299173)", "7776667533", "-299173"); - } - - @Test - void testErrors() { - confirmValueError("not a valid octal number","ABCDEFGH", ErrorEval.NUM_ERROR); - confirmValueError("not a valid octal number","99999999", ErrorEval.NUM_ERROR); - confirmValueError("not a valid octal number","3.14159", ErrorEval.NUM_ERROR); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestOffset.java b/src/testcases/org/apache/poi/ss/formula/functions/TestOffset.java deleted file mode 100644 index fd2ada7b97..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestOffset.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.functions.Offset.LinearOffsetRange; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; - -/** - * Tests for OFFSET function implementation - * - * @author Josh Micich - */ -final class TestOffset { - - /** - * Excel's double to int conversion (for function 'OFFSET()') behaves more like Math.floor(). - * Note - negative values are not symmetrical - * Fractional values are silently truncated. - * Truncation is toward negative infinity. - */ - @ParameterizedTest - @CsvSource({ - "100.09, 100", "100.01, 100", "100.00, 100", "99.99, 99", "+2.01, +2", - "+2.00, +2", "+1.99, +1", "+1.01, +1", "+1.00, +1", "+0.99, 0", - "+0.01, 0", "0.00, 0","-0.01, -1", "-0.99, -1", "-1.00, -1", - "-1.01, -2", "-1.99, -2", "-2.00, -2", "-2.01, -3" - }) - void testDoubleConversion(double doubleVal, int expected) throws EvaluationException { - assertEquals(expected, Offset.evaluateIntArg(new NumberEval(doubleVal), -1, -1)); - } - - @Test - void testLinearOffsetRange() { - LinearOffsetRange lor; - - lor = new LinearOffsetRange(3, 2); - assertEquals(3, lor.getFirstIndex()); - assertEquals(4, lor.getLastIndex()); - lor = lor.normaliseAndTranslate(0); // expected no change - assertEquals(3, lor.getFirstIndex()); - assertEquals(4, lor.getLastIndex()); - - lor = lor.normaliseAndTranslate(5); - assertEquals(8, lor.getFirstIndex()); - assertEquals(9, lor.getLastIndex()); - - // negative length - - lor = new LinearOffsetRange(6, -4).normaliseAndTranslate(0); - assertEquals(3, lor.getFirstIndex()); - assertEquals(6, lor.getLastIndex()); - - - // bounds checking - lor = new LinearOffsetRange(0, 100); - assertFalse(lor.isOutOfBounds(0, 16383)); - lor = lor.normaliseAndTranslate(16300); - assertTrue(lor.isOutOfBounds(0, 16383)); - assertFalse(lor.isOutOfBounds(0, 65535)); - } - - @Test - void testOffsetWithEmpty23Arguments() throws IOException { - try (Workbook workbook = new HSSFWorkbook()) { - Cell cell = workbook.createSheet().createRow(0).createCell(0); - cell.setCellFormula("OFFSET(B1,,)"); - - String value = "EXPECTED_VALUE"; - Cell valueCell = cell.getRow().createCell(1); - valueCell.setCellValue(value); - - workbook.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - assertEquals(CellType.STRING, cell.getCachedFormulaResultType()); - assertEquals(value, cell.getStringCellValue()); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestPPMT.java b/src/testcases/org/apache/poi/ss/formula/functions/TestPPMT.java deleted file mode 100644 index 0b908063fc..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestPPMT.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -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.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Test cases for PPMT() - * - */ -final class TestPPMT { - - - /** - * http://office.microsoft.com/en-001/excel-help/ppmt-function-HP010342774.aspx - */ - @Test - void testFromFile() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("finance.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet example1 = wb.getSheet("PPMT"); - HSSFCell ex1cell1 = example1.getRow(5).getCell(0); - fe.evaluate(ex1cell1); - assertEquals(-75.62, ex1cell1.getNumericCellValue(), 0.1); - - HSSFCell ex1cell2 = example1.getRow(16).getCell(0); - fe.evaluate(ex1cell2); - assertEquals(-27598.05, ex1cell2.getNumericCellValue(), 0.1); - - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestPmt.java b/src/testcases/org/apache/poi/ss/formula/functions/TestPmt.java deleted file mode 100644 index 0640450a03..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestPmt.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.FormulaError; -import org.junit.jupiter.api.Test; - -final class TestPmt { - - private static void confirm(double expected, NumberEval ne) { - // only asserting accuracy to 4 fractional digits - assertEquals(expected, ne.getNumberValue(), 0.00005); - } - private static ValueEval invoke(ValueEval[] args) { - return FinanceFunction.PMT.evaluate(args, -1, (short)-1); - } - /** - * Invocation when not expecting an error result - */ - private static NumberEval invokeNormal(ValueEval[] args) { - ValueEval ev = invoke(args); - assertFalse(ev instanceof ErrorEval, "Normal evaluation failed with error code: " + ev); - return (NumberEval) ev; - } - - private static void confirm(double expected, double rate, double nper, double pv, double fv, boolean isBeginning) { - ValueEval[] args = { - new NumberEval(rate), - new NumberEval(nper), - new NumberEval(pv), - new NumberEval(fv), - new NumberEval(isBeginning ? 1 : 0), - }; - confirm(expected, invokeNormal(args)); - } - - @Test - void testBasic() { - confirm(-1037.0321, (0.08/12), 10, 10000, 0, false); - confirm(-1030.1643, (0.08/12), 10, 10000, 0, true); - } - - @Test - void test3args() { - - ValueEval[] args = { - new NumberEval(0.005), - new NumberEval(24), - new NumberEval(1000), - }; - ValueEval ev = invoke(args); - if(ev instanceof ErrorEval) { - ErrorEval err = (ErrorEval) ev; - assertNotEquals(FormulaError.VALUE.getCode(), err.getErrorCode(), "Identified bug 44691"); - } - - confirm(-44.3206, invokeNormal(args)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestPoisson.java b/src/testcases/org/apache/poi/ss/formula/functions/TestPoisson.java deleted file mode 100644 index 35ee88c29d..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestPoisson.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for Excel function POISSON(x,mean,cumulative) - * @author Kalpesh Parmar - */ -class TestPoisson { - - private static final double DELTA = 1E-15; - - private static ValueEval invokePoisson(double x, double mean, boolean cumulative) - { - - ValueEval[] valueEvals = new ValueEval[3]; - valueEvals[0] = new NumberEval(x); - valueEvals[1] = new NumberEval(mean); - valueEvals[2] = BoolEval.valueOf(cumulative); - - return NumericFunction.POISSON.evaluate(valueEvals,-1,-1); - } - - @Test - void testCumulativeProbability() - { - double x = 1; - double mean = 0.2; - double result = 0.9824769036935787; // known result - - NumberEval myResult = (NumberEval)invokePoisson(x,mean,true); - - assertEquals(myResult.getNumberValue(), result, DELTA); - } - - @Test - void testNonCumulativeProbability() - { - double x = 0; - double mean = 0.2; - double result = 0.8187307530779818; // known result - - NumberEval myResult = (NumberEval)invokePoisson(x,mean,false); - - assertEquals(myResult.getNumberValue(), result, DELTA); - } - - @Test - void testNegativeMean() - { - double x = 0; - double mean = -0.2; - - ErrorEval myResult = (ErrorEval)invokePoisson(x,mean,false); - - assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), myResult.getErrorCode()); - } - - @Test - void testNegativeX() - { - double x = -1; - double mean = 0.2; - - ErrorEval myResult = (ErrorEval)invokePoisson(x,mean,false); - - assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), myResult.getErrorCode()); - } - - @Test - void testXAsDecimalNumber() - { - double x = 1.1; - double mean = 0.2; - double result = 0.9824769036935787; // known result - - NumberEval myResult = (NumberEval)invokePoisson(x,mean,true); - - assertEquals(myResult.getNumberValue(), result, DELTA); - } - - @Test - void testXZeroMeanZero() - { - double x = 0; - double mean = 0; - double result = 1; // known result in excel - - NumberEval myResult = (NumberEval)invokePoisson(x,mean,true); - - assertEquals(myResult.getNumberValue(), result, DELTA); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestProduct.java b/src/testcases/org/apache/poi/ss/formula/functions/TestProduct.java deleted file mode 100644 index 7f5bc5a1dc..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestProduct.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.MissingArgEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class TestProduct { - @Test - void missingArgsAreIgnored() { - ValueEval result = getInstance().evaluate(new ValueEval[]{new NumberEval(2.0), MissingArgEval.instance}, 0, 0); - assertTrue(result instanceof NumberEval); - assertEquals(2, ((NumberEval)result).getNumberValue(), 0); - } - - /** - * Actually PRODUCT() requires at least one arg but the checks are performed elsewhere. - * However, PRODUCT(,) is a valid call (which should return 0). So it makes sense to - * assert that PRODUCT() is also 0 (at least, nothing explodes). - */ - @Test - void missingArgEvalReturns0() { - ValueEval result = getInstance().evaluate(new ValueEval[0], 0, 0); - assertTrue(result instanceof NumberEval); - assertEquals(0, ((NumberEval)result).getNumberValue(), 0); - } - - @Test - void twoMissingArgEvalsReturn0() { - ValueEval result = getInstance().evaluate(new ValueEval[]{MissingArgEval.instance, MissingArgEval.instance}, 0, 0); - assertTrue(result instanceof NumberEval); - assertEquals(0, ((NumberEval)result).getNumberValue(), 0); - } - - @Test - void acceptanceTest() { - final ValueEval[] args = { - new NumberEval(2.0), - MissingArgEval.instance, - new StringEval("6"), - BoolEval.TRUE}; - ValueEval result = getInstance().evaluate(args, 0, 0); - assertTrue(result instanceof NumberEval); - assertEquals(12, ((NumberEval)result).getNumberValue(), 0); - } - - private static Function getInstance() { - return AggregateFunction.PRODUCT; - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotient.java b/src/testcases/org/apache/poi/ss/formula/functions/TestQuotient.java deleted file mode 100644 index 15968199b5..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotient.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Quotient} - * - * @author cedric dot walter @ gmail dot com - */ -class TestQuotient { - private static ValueEval invokeValue(String numerator, String denominator) { - ValueEval[] args = new ValueEval[]{new StringEval(numerator), new StringEval(denominator)}; - return new Quotient().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String numerator, String denominator, String expected) { - ValueEval result = invokeValue(numerator, denominator); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval) result).getStringValue(), msg); - } - - private static void confirmValueError(String msg, String numerator, String denominator, ErrorEval numError) { - ValueEval result = invokeValue(numerator, denominator); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(numError, result, msg); - } - - @Test - void testBasic() { - confirmValue("Integer portion of 5/2 (2)", "5", "2", "2"); - confirmValue("Integer portion of 4.5/3.1 (1)", "4.5", "3.1", "1"); - - confirmValue("Integer portion of -10/3 (-3)", "-10", "3", "-3"); - confirmValue("Integer portion of -5.5/2 (-2)", "-5.5", "2", "-2"); - - confirmValue("Integer portion of Pi/Avogadro (0)", "3.14159", "6.02214179E+23", "0"); - } - - @Test - void testErrors() { - confirmValueError("numerator is nonnumeric", "ABCD", "", ErrorEval.VALUE_INVALID); - confirmValueError("denominator is nonnumeric", "", "ABCD", ErrorEval.VALUE_INVALID); - - confirmValueError("dividing by zero", "3.14159", "0", ErrorEval.DIV_ZERO); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotientFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestQuotientFunctionsFromSpreadsheet.java deleted file mode 100644 index bbbfba1882..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotientFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests QUOTIENT() as loaded from a test data spreadsheet.

- */ -class TestQuotientFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestQuotientFunctionsFromSpreadsheet.class, "QuotientFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestRank.java b/src/testcases/org/apache/poi/ss/formula/functions/TestRank.java deleted file mode 100644 index 90da6fdb0a..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRank.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -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.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; - -/** - * Test cases for RANK() - */ -final class TestRank { - - @Test - void testFromFile() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("rank.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet example1 = wb.getSheet("Example 1"); - HSSFCell ex1cell1 = example1.getRow(7).getCell(0); - assertEquals(3.0, fe.evaluate(ex1cell1).getNumberValue(), 0); - HSSFCell ex1cell2 = example1.getRow(8).getCell(0); - assertEquals(5.0, fe.evaluate(ex1cell2).getNumberValue(), 0); - - HSSFSheet example2 = wb.getSheet("Example 2"); - for(int rownum = 1; rownum<= 10; rownum ++){ - HSSFCell cell = example2.getRow(rownum).getCell(2); - double cachedResult = cell.getNumericCellValue(); //cached formula result - assertEquals(cachedResult, fe.evaluate(cell).getNumberValue(), 0); - } - - HSSFSheet example3 = wb.getSheet("Example 3"); - for(int rownum = 1; rownum<= 10; rownum ++){ - HSSFCell cellD = example3.getRow(rownum).getCell(3); - double cachedResultD = cellD.getNumericCellValue(); //cached formula result - assertEquals(cachedResultD, fe.evaluate(cellD).getNumberValue(), 0, new CellReference(cellD).formatAsString()); - - HSSFCell cellE = example3.getRow(rownum).getCell(4); - double cachedResultE = cellE.getNumericCellValue(); //cached formula result - assertEquals(cachedResultE, fe.evaluate(cellE).getNumberValue(), 0, new CellReference(cellE).formatAsString()); - - HSSFCell cellF = example3.getRow(rownum).getCell(5); - double cachedResultF = cellF.getNumericCellValue(); //cached formula result - assertEquals(cachedResultF, fe.evaluate(cellF).getNumberValue(), 0, new CellReference(cellF).formatAsString()); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestRelationalOperations.java b/src/testcases/org/apache/poi/ss/formula/functions/TestRelationalOperations.java deleted file mode 100644 index 0e87b38210..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRelationalOperations.java +++ /dev/null @@ -1,196 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.CacheAreaEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.RelationalOperationEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -class TestRelationalOperations { - - /** - * (1, 1)(1, 1) = 1 - * - * evaluates to - * - * (TRUE, TRUE)(TRUE, TRUE) - * - */ - @Test - void testEqMatrixByScalar_Numbers() { - ValueEval[] values = new ValueEval[4]; - for (int i = 0; i < values.length; i++) { - values[i] = new NumberEval(1); - } - - ValueEval arg1 = EvalFactory.createAreaEval("A1:B2", values); - ValueEval arg2 = EvalFactory.createRefEval("D1", new NumberEval(1)); - - RelationalOperationEval eq = (RelationalOperationEval)RelationalOperationEval.EqualEval; - ValueEval result = eq.evaluateArray(new ValueEval[]{ arg1, arg2}, 2, 5); - - assertEquals(CacheAreaEval.class, result.getClass(), "expected CacheAreaEval"); - CacheAreaEval ce = (CacheAreaEval)result; - assertEquals(2, ce.getWidth()); - assertEquals(2, ce.getHeight()); - for(int i =0; i < ce.getHeight(); i++){ - for(int j = 0; j < ce.getWidth(); j++){ - assertEquals(BoolEval.TRUE, ce.getRelativeValue(i, j)); - } - } - } - - @Test - void testEqMatrixByScalar_String() { - ValueEval[] values = new ValueEval[4]; - for (int i = 0; i < values.length; i++) { - values[i] = new StringEval("ABC"); - } - - ValueEval arg1 = EvalFactory.createAreaEval("A1:B2", values); - ValueEval arg2 = EvalFactory.createRefEval("D1", new StringEval("ABC")); - RelationalOperationEval eq = (RelationalOperationEval)RelationalOperationEval.EqualEval; - ValueEval result = eq.evaluateArray(new ValueEval[]{ arg1, arg2}, 2, 5); - - assertEquals(CacheAreaEval.class, result.getClass(), "expected CacheAreaEval"); - CacheAreaEval ce = (CacheAreaEval)result; - assertEquals(2, ce.getWidth()); - assertEquals(2, ce.getHeight()); - for(int i =0; i < ce.getHeight(); i++){ - for(int j = 0; j < ce.getWidth(); j++){ - assertEquals(BoolEval.TRUE, ce.getRelativeValue(i, j)); - } - } - } - - @Test - void testEqMatrixBy_Row() { - ValueEval[] matrix = { - new NumberEval(-1), new NumberEval(1), - new NumberEval(-1), new NumberEval(1) - }; - - - ValueEval[] row = { - new NumberEval(1), new NumberEval(1), new NumberEval(1) - }; - - ValueEval[] expected = { - BoolEval.FALSE, BoolEval.TRUE, ErrorEval.VALUE_INVALID, - BoolEval.FALSE, BoolEval.TRUE, ErrorEval.VALUE_INVALID - }; - - ValueEval arg1 = EvalFactory.createAreaEval("A1:B2", matrix); - ValueEval arg2 = EvalFactory.createAreaEval("A4:C4", row); - RelationalOperationEval eq = (RelationalOperationEval)RelationalOperationEval.EqualEval; - ValueEval result = eq.evaluateArray(new ValueEval[]{ arg1, arg2}, 4, 5); - - assertEquals(CacheAreaEval.class, result.getClass(), "expected CacheAreaEval"); - CacheAreaEval ce = (CacheAreaEval)result; - assertEquals(3, ce.getWidth()); - assertEquals(2, ce.getHeight()); - int idx = 0; - for(int i =0; i < ce.getHeight(); i++){ - for(int j = 0; j < ce.getWidth(); j++){ - assertEquals(expected[idx++], ce.getRelativeValue(i, j), "[" + i + "," + j + "]"); - } - } - } - - @Test - void testEqMatrixBy_Column() { - ValueEval[] matrix = { - new NumberEval(-1), new NumberEval(1), - new NumberEval(-1), new NumberEval(1) - }; - - - ValueEval[] column = { - new NumberEval(1), - new NumberEval(1), - new NumberEval(1) - }; - - ValueEval[] expected = { - BoolEval.FALSE, BoolEval.TRUE, - BoolEval.FALSE, BoolEval.TRUE, - ErrorEval.VALUE_INVALID, ErrorEval.VALUE_INVALID - }; - - ValueEval arg1 = EvalFactory.createAreaEval("A1:B2", matrix); - ValueEval arg2 = EvalFactory.createAreaEval("A6:A8", column); - RelationalOperationEval eq = (RelationalOperationEval)RelationalOperationEval.EqualEval; - ValueEval result = eq.evaluateArray(new ValueEval[]{ arg1, arg2}, 4, 6); - - assertEquals(CacheAreaEval.class, result.getClass(), "expected CacheAreaEval"); - CacheAreaEval ce = (CacheAreaEval)result; - assertEquals(2, ce.getWidth()); - assertEquals(3, ce.getHeight()); - int idx = 0; - for(int i =0; i < ce.getHeight(); i++){ - for(int j = 0; j < ce.getWidth(); j++){ - assertEquals(expected[idx++], ce.getRelativeValue(i, j), "[" + i + "," + j + "]"); - } - } - } - - @Test - void testEqMatrixBy_Matrix() { - // A1:B2 - ValueEval[] matrix1 = { - new NumberEval(-1), new NumberEval(1), - new NumberEval(-1), new NumberEval(1) - }; - - // A10:C12 - ValueEval[] matrix2 = { - new NumberEval(1), new NumberEval(1), new NumberEval(1), - new NumberEval(1), new NumberEval(1), new NumberEval(1), - new NumberEval(1), new NumberEval(1), new NumberEval(1) - }; - - ValueEval[] expected = { - BoolEval.FALSE, BoolEval.TRUE, ErrorEval.VALUE_INVALID, - BoolEval.FALSE, BoolEval.TRUE, ErrorEval.VALUE_INVALID, - ErrorEval.VALUE_INVALID, ErrorEval.VALUE_INVALID, ErrorEval.VALUE_INVALID - }; - - ValueEval arg1 = EvalFactory.createAreaEval("A1:B2", matrix1); - ValueEval arg2 = EvalFactory.createAreaEval("A10:C12", matrix2); - RelationalOperationEval eq = (RelationalOperationEval)RelationalOperationEval.EqualEval; - ValueEval result = eq.evaluateArray(new ValueEval[]{ arg1, arg2}, 4, 6); - - assertEquals(CacheAreaEval.class, result.getClass(), "expected CacheAreaEval"); - CacheAreaEval ce = (CacheAreaEval)result; - assertEquals(3, ce.getWidth()); - assertEquals(3, ce.getHeight()); - int idx = 0; - for(int i =0; i < ce.getHeight(); i++){ - for(int j = 0; j < ce.getWidth(); j++){ - assertEquals(expected[idx++], ce.getRelativeValue(i, j), "[" + i + "," + j + "]"); - } - } - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestReptFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestReptFunctionsFromSpreadsheet.java deleted file mode 100644 index 2a7132e813..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestReptFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests REPT() as loaded from a test data spreadsheet.

- */ -class TestReptFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestReptFunctionsFromSpreadsheet.class, "ReptFunctionTestCaseData.xls"); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestRomanFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestRomanFunctionsFromSpreadsheet.java deleted file mode 100644 index ffe0c75c00..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRomanFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests Roman() as loaded from a test data spreadsheet.

- */ -class TestRomanFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestRomanFunctionsFromSpreadsheet.class, "RomanFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestRoundFuncs.java b/src/testcases/org/apache/poi/ss/formula/functions/TestRoundFuncs.java deleted file mode 100644 index 4450528822..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRoundFuncs.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * Test cases for ROUND(), ROUNDUP(), ROUNDDOWN() - * - * @author Josh Micich - */ -final class TestRoundFuncs { - // github-43 - // https://github.com/apache/poi/pull/43 - @Disabled("ROUNDUP(3987*0.2, 2) currently fails by returning 797.41") - @Test - void testRoundUp() { - assertRoundUpEquals(797.40, 3987*0.2, 2, 1e-10); - } - - @Test - void testRoundDown() { - assertRoundDownEquals(797.40, 3987*0.2, 2, 1e-10); - } - - @Test - void testRound() { - assertRoundEquals(797.40, 3987*0.2, 2, 1e-10); - } - - @Test - void testRoundDownWithStringArg() { - ValueEval strArg = new StringEval("abc"); - ValueEval[] args = { strArg, new NumberEval(2), }; - ValueEval result = NumericFunction.ROUNDDOWN.evaluate(args, -1, (short)-1); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testRoundUpWithStringArg() { - ValueEval strArg = new StringEval("abc"); - ValueEval[] args = { strArg, new NumberEval(2), }; - ValueEval result = NumericFunction.ROUNDUP.evaluate(args, -1, (short)-1); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - - - private static void assertRoundFuncEquals(Function func, double expected, double number, double places, double tolerance) { - ValueEval[] args = { new NumberEval( number ), new NumberEval(places), }; - NumberEval result = (NumberEval) func.evaluate(args, -1, (short)-1); - assertEquals(expected, result.getNumberValue(), tolerance); - } - - private static void assertRoundEquals(double expected, double number, double places, double tolerance) { - TestRoundFuncs.assertRoundFuncEquals(NumericFunction.ROUND, expected, number, places, tolerance); - } - - private static void assertRoundUpEquals(double expected, double number, double places, double tolerance) { - TestRoundFuncs.assertRoundFuncEquals(NumericFunction.ROUNDUP, expected, number, places, tolerance); - } - - private static void assertRoundDownEquals(double expected, double number, double places, double tolerance) { - TestRoundFuncs.assertRoundFuncEquals(NumericFunction.ROUNDDOWN, expected, number, places, tolerance); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestRowCol.java b/src/testcases/org/apache/poi/ss/formula/functions/TestRowCol.java deleted file mode 100644 index eb2812e0e4..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRowCol.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for ROW(), ROWS(), COLUMN(), COLUMNS() - * - * @author Josh Micich - */ -final class TestRowCol { - - @Test - void testCol() { - Function target = new Column(); - { - ValueEval[] args = { EvalFactory.createRefEval("C5"), }; - double actual = NumericFunctionInvoker.invoke(target, args); - assertEquals(3, actual, 0D); - } - { - ValueEval[] args = { EvalFactory.createAreaEval("E2:H12", new ValueEval[44]), }; - double actual = NumericFunctionInvoker.invoke(target, args); - assertEquals(5, actual, 0D); - } - } - - @Test - void testRow() { - Function target = new RowFunc(); - { - ValueEval[] args = { EvalFactory.createRefEval("C5"), }; - double actual = NumericFunctionInvoker.invoke(target, args); - assertEquals(5, actual, 0D); - } - { - ValueEval[] args = { EvalFactory.createAreaEval("E2:H12", new ValueEval[44]), }; - double actual = NumericFunctionInvoker.invoke(target, args); - assertEquals(2, actual, 0D); - } - } - - @Test - void testColumns() { - - confirmColumnsFunc("A1:F1", 6, 1); - confirmColumnsFunc("A1:C2", 3, 2); - confirmColumnsFunc("A1:B3", 2, 3); - confirmColumnsFunc("A1:A6", 1, 6); - - ValueEval[] args = { EvalFactory.createRefEval("C5"), }; - double actual = NumericFunctionInvoker.invoke(new Columns(), args); - assertEquals(1, actual, 0D); - } - - @Test - void testRows() { - - confirmRowsFunc("A1:F1", 6, 1); - confirmRowsFunc("A1:C2", 3, 2); - confirmRowsFunc("A1:B3", 2, 3); - confirmRowsFunc("A1:A6", 1, 6); - - ValueEval[] args = { EvalFactory.createRefEval("C5"), }; - double actual = NumericFunctionInvoker.invoke(new Rows(), args); - assertEquals(1, actual, 0D); - } - - private static void confirmRowsFunc(String areaRefStr, int nCols, int nRows) { - ValueEval[] args = { EvalFactory.createAreaEval(areaRefStr, new ValueEval[nCols * nRows]), }; - - double actual = NumericFunctionInvoker.invoke(new Rows(), args); - assertEquals(nRows, actual, 0D); - } - - - private static void confirmColumnsFunc(String areaRefStr, int nCols, int nRows) { - ValueEval[] args = { EvalFactory.createAreaEval(areaRefStr, new ValueEval[nCols * nRows]), }; - - double actual = NumericFunctionInvoker.invoke(new Columns(), args); - assertEquals(nCols, actual, 0D); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSlope.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSlope.java deleted file mode 100644 index 5c8bc1eb33..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSlope.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Test for Excel function SLOPE() - * - * @author Johan Karlsteen - */ -final class TestSlope { - private static final Function SLOPE = new Slope(); - - private static ValueEval invoke(Function function, ValueEval xArray, ValueEval yArray) { - ValueEval[] args = new ValueEval[] { xArray, yArray, }; - return function.evaluate(args, -1, (short)-1); - } - - private void confirm(Function function, ValueEval xArray, ValueEval yArray, double expected) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval)result).getNumberValue(), 0); - } - private void confirmError(Function function, ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - private void confirmError(ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - confirmError(SLOPE, xArray, yArray, expectedError); - } - - @Test - void testBasic() { - Double exp = Math.pow(10, 7.5); - ValueEval[] yValues = { - new NumberEval(3+exp), - new NumberEval(4+exp), - new NumberEval(2+exp), - new NumberEval(5+exp), - new NumberEval(4+exp), - new NumberEval(7+exp), - }; - ValueEval areaEvalY = createAreaEval(yValues); - - ValueEval[] xValues = { - new NumberEval(1), - new NumberEval(2), - new NumberEval(3), - new NumberEval(4), - new NumberEval(5), - new NumberEval(6), - }; - ValueEval areaEvalX = createAreaEval(xValues); - confirm(SLOPE, areaEvalX, areaEvalY, 0.7752808988764045); - // Excel 2010 gives 0.775280898876405 - } - - /** - * number of items in array is not limited to 30 - */ - @Test - void testLargeArrays() { - ValueEval[] yValues = createMockNumberArray(100, 3); // [1,2,0,1,2,0,...,0,1] - yValues[0] = new NumberEval(2.0); // Changes first element to 2 - ValueEval[] xValues = createMockNumberArray(100, 101); // [1,2,3,4,...,99,100] - - confirm(SLOPE, createAreaEval(xValues), createAreaEval(yValues), -1.231527093596059); - // Excel 2010 gives -1.23152709359606 - } - - private ValueEval[] createMockNumberArray(int size, double value) { - ValueEval[] result = new ValueEval[size]; - for (int i = 0; i < result.length; i++) { - result[i] = new NumberEval((i+1)%value); - } - return result; - } - - private static ValueEval createAreaEval(ValueEval[] values) { - String refStr = "A1:A" + values.length; - return EvalFactory.createAreaEval(refStr, values); - } - - @Test - void testErrors() { - ValueEval[] xValues = { - ErrorEval.REF_INVALID, - new NumberEval(2), - }; - ValueEval areaEvalX = createAreaEval(xValues); - ValueEval[] yValues = { - new NumberEval(2), - ErrorEval.NULL_INTERSECTION, - }; - ValueEval areaEvalY = createAreaEval(yValues); - ValueEval[] zValues = { // wrong size - new NumberEval(2), - }; - ValueEval areaEvalZ = createAreaEval(zValues); - - // if either arg is an error, that error propagates - confirmError(ErrorEval.REF_INVALID, ErrorEval.NAME_INVALID, ErrorEval.REF_INVALID); - confirmError(areaEvalX, ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - confirmError(ErrorEval.NAME_INVALID, areaEvalX, ErrorEval.NAME_INVALID); - - // array sizes must match - confirmError(areaEvalX, areaEvalZ, ErrorEval.NA); - confirmError(areaEvalZ, areaEvalY, ErrorEval.NA); - - // any error in an array item propagates up - confirmError(areaEvalX, areaEvalX, ErrorEval.REF_INVALID); - - // search for errors array by array, not pair by pair - confirmError(areaEvalX, areaEvalY, ErrorEval.NULL_INTERSECTION); - confirmError(areaEvalY, areaEvalX, ErrorEval.REF_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java b/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java deleted file mode 100644 index 9fb322f978..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java +++ /dev/null @@ -1,328 +0,0 @@ -/* -* 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. -*/ -/* - * Created on May 30, 2005 - * - */ -package org.apache.poi.ss.formula.functions; - - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -class TestStatsLib extends BaseTestNumeric { - - @Test - void testDevsq() { - double[] v; - double d, x; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - d = StatsLib.devsq(v); - x = 82.5; - assertDouble("devsq ", x, d); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - d = StatsLib.devsq(v); - x = 0; - assertDouble("devsq ", x, d); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - d = StatsLib.devsq(v); - x = 0; - assertDouble("devsq ", x, d); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - d = StatsLib.devsq(v); - x = 2.5; - assertDouble("devsq ", x, d); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - d = StatsLib.devsq(v); - x = 10953.7416965767; - assertDouble("devsq ", x, d); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.devsq(v); - x = 82.5; - assertDouble("devsq ", x, d); - } - - @Test - void testKthLargest() { - double[] v; - double d, x; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - d = StatsLib.kthLargest(v, 3); - x = 8; - assertDouble("kthLargest ", x, d); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - d = StatsLib.kthLargest(v, 3); - x = 1; - assertDouble("kthLargest ", x, d); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - d = StatsLib.kthLargest(v, 3); - x = 0; - assertDouble("kthLargest ", x, d); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - d = StatsLib.kthLargest(v, 3); - x = 2; - assertDouble("kthLargest ", x, d); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - d = StatsLib.kthLargest(v, 3); - x = 5.37828; - assertDouble("kthLargest ", x, d); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.kthLargest(v, 3); - x = -3; - assertDouble("kthLargest ", x, d); - } - - @Disabled("... implement ...") - void testKthSmallest() { - } - - @Test - void testAvedev() { - double[] v; - double d, x; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - d = StatsLib.avedev(v); - x = 2.5; - assertDouble("avedev ", x, d); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - d = StatsLib.avedev(v); - x = 0; - assertDouble("avedev ", x, d); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - d = StatsLib.avedev(v); - x = 0; - assertDouble("avedev ", x, d); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - d = StatsLib.avedev(v); - x = 0.5; - assertDouble("avedev ", x, d); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - d = StatsLib.avedev(v); - x = 36.42176053333; - assertDouble("avedev ", x, d); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.avedev(v); - x = 2.5; - assertDouble("avedev ", x, d); - } - - @Test - void testMedian() { - double[] v; - double d, x; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - d = StatsLib.median(v); - x = 5.5; - assertDouble("median ", x, d); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - d = StatsLib.median(v); - x = 1; - assertDouble("median ", x, d); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - d = StatsLib.median(v); - x = 0; - assertDouble("median ", x, d); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - d = StatsLib.median(v); - x = 1.5; - assertDouble("median ", x, d); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - d = StatsLib.median(v); - x = 5.37828; - assertDouble("median ", x, d); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.median(v); - x = -5.5; - assertDouble("median ", x, d); - - v = new double[] {-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.median(v); - x = -6; - assertDouble("median ", x, d); - - v = new double[] {1,2,3,4,5,6,7,8,9}; - d = StatsLib.median(v); - x = 5; - assertDouble("median ", x, d); - } - - @Test - void testMode() { - double[] v; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - confirmMode(v, null); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - confirmMode(v, 1.0); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - confirmMode(v, 0.0); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - confirmMode(v, 1.0); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - confirmMode(v, null); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - confirmMode(v, null); - - v = new double[] {1,2,3,4,1,1,1,1,0,0,0,0,0}; - confirmMode(v, 1.0); - - v = new double[] {0,1,2,3,4,1,1,1,0,0,0,0,1}; - confirmMode(v, 0.0); - } - - private static void confirmMode(double[] v, double expectedResult) { - confirmMode(v, (Double)expectedResult); - } - - private static void confirmMode(double[] v, Double expectedResult) { - double actual; - try { - actual = Mode.evaluate(v); - assertNotNull(expectedResult, "Expected N/A exception was not thrown"); - } catch (EvaluationException e) { - if (expectedResult == null) { - assertEquals(ErrorEval.NA, e.getErrorEval()); - return; - } - throw new RuntimeException(e); - } - assertDouble("mode", expectedResult, actual); - } - - @Test - void testStddev() { - double[] v; - double d, x; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - d = StatsLib.stdev(v); - x = 3.02765035410; - assertDouble("stdev ", x, d); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - d = StatsLib.stdev(v); - x = 0; - assertDouble("stdev ", x, d); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - d = StatsLib.stdev(v); - x = 0; - assertDouble("stdev ", x, d); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - d = StatsLib.stdev(v); - x = 0.52704627669; - assertDouble("stdev ", x, d); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - d = StatsLib.stdev(v); - x = 52.33006233652; - assertDouble("stdev ", x, d); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.stdev(v); - x = 3.02765035410; - assertDouble("stdev ", x, d); - } - - @Test - void testVar() { - double[] v; - double d, x; - - v = new double[] {3.50, 5.00, 7.23, 2.99}; - d = StatsLib.var(v); - x = 3.6178; - assertDouble("var ", x, d); - - v = new double[] {34.5, 2.0, 8.9, -4.0}; - d = StatsLib.var(v); - x = 286.99; - assertDouble("var ", x, d); - - v = new double[] {7.0, 25.0, 21.69}; - d = StatsLib.var(v); - x = 91.79203333; - assertDouble("var ", x, d); - - v = new double[] {1345,1301,1368,1322,1310,1370,1318,1350,1303,1299}; - d = StatsLib.var(v); - x = 754.2666667; - assertDouble("var ", x, d); - } - - @Test - void testVarp() { - double[] v; - double d, x; - - v = new double[] {3.50, 5.00, 7.23, 2.99}; - d = StatsLib.varp(v); - x = 2.71335; - assertDouble("varp ", x, d); - - v = new double[] {34.5, 2.0, 8.9, -4.0}; - d = StatsLib.varp(v); - x = 215.2425; - assertDouble("varp ", x, d); - - v = new double[] {7.0, 25.0, 21.69}; - d = StatsLib.varp(v); - x = 61.19468889; - assertDouble("varp ", x, d); - - v = new double[] {1345,1301,1368,1322,1310,1370,1318,1350,1303,1299}; - d = StatsLib.varp(v); - x = 678.84; - assertDouble("varp ", x, d); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSubstitute.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSubstitute.java deleted file mode 100644 index 3735232878..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSubstitute.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.StringValueEval; -import org.apache.poi.ss.usermodel.FormulaError; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class TestSubstitute { - @Test - void testSubstitute() { - Substitute fun = new Substitute(); - assertEquals("ADEFC", ((StringValueEval)fun.evaluate(0, 1, - new StringEval("ABC"), new StringEval("B"), new StringEval("DEF"))).getStringValue()); - - assertEquals("ACDEC", ((StringValueEval)fun.evaluate(0, 1, - new StringEval("ABC"), new StringEval("B"), new StringEval("CDE"))).getStringValue()); - - assertEquals("ACDECCDEA", ((StringValueEval)fun.evaluate(0, 1, - new StringEval("ABCBA"), new StringEval("B"), new StringEval("CDE"))).getStringValue()); - } - - @Test - void testSubstituteInvalidArg() { - Substitute fun = new Substitute(); - assertEquals(ErrorEval.valueOf(FormulaError.VALUE.getLongCode()), - fun.evaluate(0, 1, - ErrorEval.valueOf(FormulaError.VALUE.getLongCode()), new StringEval("B"), new StringEval("DEF"))); - - assertEquals(ErrorEval.valueOf(FormulaError.VALUE.getLongCode()), - fun.evaluate(0, 1, - ErrorEval.valueOf(FormulaError.VALUE.getLongCode()), new StringEval("B"), new StringEval("DEF"), - new NumberEval(1))); - - // fails on occurrence below 1 - assertEquals(ErrorEval.valueOf(FormulaError.VALUE.getLongCode()), - fun.evaluate(0, 1, - new StringEval("ABC"), new StringEval("B"), new StringEval("CDE"), new NumberEval(0))); - } - - @Test - void testSubstituteOne() { - Substitute fun = new Substitute(); - assertEquals("ADEFC", ((StringValueEval)fun.evaluate(0, 1, - new StringEval("ABC"), new StringEval("B"), new StringEval("DEF"), new NumberEval(1))).getStringValue()); - - assertEquals("ACDEC", ((StringValueEval)fun.evaluate(0, 1, - new StringEval("ABC"), new StringEval("B"), new StringEval("CDE"), new NumberEval(1))).getStringValue()); - } - - @Test - void testSubstituteNotFound() { - Substitute fun = new Substitute(); - assertEquals("ABC", ((StringValueEval)fun.evaluate(0, 1, - new StringEval("ABC"), new StringEval("B"), new StringEval("DEF"), new NumberEval(12))).getStringValue()); - - assertEquals("ABC", ((StringValueEval)fun.evaluate(0, 1, - new StringEval("ABC"), new StringEval("B"), new StringEval("CDE"), new NumberEval(2))).getStringValue()); - } - - @Test - void testSearchEmpty() { - Substitute fun = new Substitute(); - assertEquals("ABC", ((StringValueEval)fun.evaluate(0, 1, - new StringEval("ABC"), new StringEval(""), new StringEval("CDE"))).getStringValue()); - assertEquals("ABC", ((StringValueEval)fun.evaluate(0, 1, - new StringEval("ABC"), new StringEval(""), new StringEval("CDE"), new NumberEval(1))).getStringValue()); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSubtotal.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSubtotal.java deleted file mode 100644 index 3f4eb88dd8..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSubtotal.java +++ /dev/null @@ -1,430 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NotImplementedException; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Subtotal} - */ -final class TestSubtotal { - private static final int FUNCTION_AVERAGE = 1; - private static final int FUNCTION_COUNT = 2; - private static final int FUNCTION_MAX = 4; - private static final int FUNCTION_MIN = 5; - private static final int FUNCTION_PRODUCT = 6; - private static final int FUNCTION_STDEV = 7; - private static final int FUNCTION_SUM = 9; - - private static final double[] TEST_VALUES0 = { - 1, 2, - 3, 4, - 5, 6, - 7, 8, - 9, 10 - }; - - private static void confirmSubtotal(int function, double expected) { - ValueEval[] values = new ValueEval[TEST_VALUES0.length]; - for (int i = 0; i < TEST_VALUES0.length; i++) { - values[i] = new NumberEval(TEST_VALUES0[i]); - } - - AreaEval arg1 = EvalFactory.createAreaEval("C1:D5", values); - ValueEval[] args = {new NumberEval(function), arg1}; - - ValueEval result = new Subtotal().evaluate(args, 0, 0); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval) result).getNumberValue(), 0.0); - } - - @Test - void testBasics() { - confirmSubtotal(FUNCTION_SUM, 55.0); - confirmSubtotal(FUNCTION_AVERAGE, 5.5); - confirmSubtotal(FUNCTION_COUNT, 10.0); - confirmSubtotal(FUNCTION_MAX, 10.0); - confirmSubtotal(FUNCTION_MIN, 1.0); - confirmSubtotal(FUNCTION_PRODUCT, 3628800.0); - confirmSubtotal(FUNCTION_STDEV, 3.0276503540974917); - } - - @Test - void testAvg() throws IOException { - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(1,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue(1); - Cell a5 = sh.createRow(5).createCell(1); - a5.setCellValue(7); - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(1,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(1,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(1,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(2.0, a3.getNumericCellValue(), 0); - assertEquals(8.0, a6.getNumericCellValue(), 0); - assertEquals(3.0, a7.getNumericCellValue(), 0); - assertEquals(3.0, a8.getNumericCellValue(), 0); - wb.close(); - - } - - @Test - void testSum() throws IOException { - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(9,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue(1); - Cell a5 = sh.createRow(5).createCell(1); - a5.setCellValue(7); - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(9,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(9,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(9,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(4.0, a3.getNumericCellValue(), 0); - assertEquals(26.0, a6.getNumericCellValue(), 0); - assertEquals(12.0, a7.getNumericCellValue(), 0); - assertEquals(12.0, a8.getNumericCellValue(), 0); - wb.close(); - } - - @Test - void testCount() throws IOException { - - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(2,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue("POI"); // A4 is string and not counted - /*Cell a5 =*/ sh.createRow(5).createCell(1); // A5 is blank and not counted - - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(2,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(2,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(2,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(2.0, a3.getNumericCellValue(), 0); - assertEquals(6.0, a6.getNumericCellValue(), 0); - assertEquals(2.0, a7.getNumericCellValue(), 0); - assertEquals(2.0, a8.getNumericCellValue(), 0); - wb.close(); - } - - @Test - void testCounta() throws IOException { - - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(3,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue("POI"); // A4 is string and not counted - /*Cell a5 =*/ sh.createRow(5).createCell(1); // A5 is blank and not counted - - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(3,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(3,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(3,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(2.0, a3.getNumericCellValue(), 0); - assertEquals(8.0, a6.getNumericCellValue(), 0); - assertEquals(3.0, a7.getNumericCellValue(), 0); - assertEquals(3.0, a8.getNumericCellValue(), 0); - wb.close(); - } - - @Test - void testMax() throws IOException { - - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(4,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue(1); - Cell a5 = sh.createRow(5).createCell(1); - a5.setCellValue(7); - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(4,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(4,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(4,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(3.0, a3.getNumericCellValue(), 0); - assertEquals(16.0, a6.getNumericCellValue(), 0); - assertEquals(7.0, a7.getNumericCellValue(), 0); - assertEquals(7.0, a8.getNumericCellValue(), 0); - wb.close(); - } - - @Test - void testMin() throws IOException { - - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(5,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue(1); - Cell a5 = sh.createRow(5).createCell(1); - a5.setCellValue(7); - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(5,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(5,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(5,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(1.0, a3.getNumericCellValue(), 0); - assertEquals(4.0, a6.getNumericCellValue(), 0); - assertEquals(1.0, a7.getNumericCellValue(), 0); - assertEquals(1.0, a8.getNumericCellValue(), 0); - wb.close(); - } - - @Test - void testStdev() throws IOException { - - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(7,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue(1); - Cell a5 = sh.createRow(5).createCell(1); - a5.setCellValue(7); - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(7,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(7,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(7,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(1.41421, a3.getNumericCellValue(), 0.0001); - assertEquals(7.65685, a6.getNumericCellValue(), 0.0001); - assertEquals(2.82842, a7.getNumericCellValue(), 0.0001); - assertEquals(2.82842, a8.getNumericCellValue(), 0.0001); - wb.close(); - } - - @Test - void test50209() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellFormula("SUBTOTAL(9,B2)"); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(9,B2:B3)"); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - fe.evaluateAll(); - assertEquals(1.0, a2.getNumericCellValue(), 0); - assertEquals(1.0, a3.getNumericCellValue(), 0); - wb.close(); - } - - private static void confirmExpectedResult(FormulaEvaluator evaluator, String msg, Cell cell, double expected) { - - CellValue value = evaluator.evaluate(cell); - if (value.getErrorValue() != 0) - throw new RuntimeException(msg + ": " + value.formatAsString()); - assertEquals(expected, value.getNumberValue(), 0, msg); - } - - @Test - void testFunctionsFromTestSpreadsheet() throws IOException { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SubtotalsNested.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - - assertEquals(10.0, sheet.getRow(1).getCell(1).getNumericCellValue(), 0, "B2"); - assertEquals(20.0, sheet.getRow(2).getCell(1).getNumericCellValue(), 0, "B3"); - - //Test simple subtotal over one area - Cell cellA3 = sheet.getRow(3).getCell(1); - confirmExpectedResult(evaluator, "B4", cellA3, 30.0); - - //Test existence of the second area - assertNotNull(sheet.getRow(1).getCell(2), "C2 must not be null"); - assertEquals(7.0, sheet.getRow(1).getCell(2).getNumericCellValue(), 0, "C2"); - - Cell cellC1 = sheet.getRow(1).getCell(3); - Cell cellC2 = sheet.getRow(2).getCell(3); - Cell cellC3 = sheet.getRow(3).getCell(3); - - //Test Functions SUM, COUNT and COUNTA calculation of SUBTOTAL - //a) areas A and B are used - //b) first 2 subtotals don't consider the value of nested subtotal in A3 - confirmExpectedResult(evaluator, "SUBTOTAL(SUM;B2:B8;C2:C8)", cellC1, 37.0); - confirmExpectedResult(evaluator, "SUBTOTAL(COUNT;B2:B8,C2:C8)", cellC2, 3.0); - confirmExpectedResult(evaluator, "SUBTOTAL(COUNTA;B2:B8,C2:C8)", cellC3, 5.0); - - // test same functions ignoring hidden rows over a copy of the same data - cellC1 = sheet.getRow(11).getCell(3); - cellC2 = sheet.getRow(12).getCell(3); - cellC3 = sheet.getRow(13).getCell(3); - confirmExpectedResult(evaluator, "SUBTOTAL(SUM NO HIDDEN;B22:B28;C22:C28)", cellC1, 17.0); - confirmExpectedResult(evaluator, "SUBTOTAL(COUNT NO HIDDEN;B22:B28,C22:C28)", cellC2, 2.0); - confirmExpectedResult(evaluator, "SUBTOTAL(COUNTA NO HIDDEN;B22:B28,C22:C28)", cellC3, 4.0); - - - workbook.close(); - } - - @Test - void testUnimplemented() throws IOException { - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a3 = sh.createRow(3).createCell(1); - - // formula, throws NotImplemnted? - String[][] formulas = { - { "SUBTOTAL(8,B2:B3)", NotImplementedException.class.getName() }, - { "SUBTOTAL(10,B2:B3)", NotImplementedException.class.getName() }, - { "SUBTOTAL(11,B2:B3)", NotImplementedException.class.getName() }, - { "SUBTOTAL(0,B2:B3)", null }, - { "SUBTOTAL(9)", FormulaParseException.class.getName() }, - { "SUBTOTAL()", FormulaParseException.class.getName() }, - }; - - for (String[] f : formulas) { - Exception actualEx = null; - try { - a3.setCellFormula(f[0]); - fe.evaluateAll(); - assertEquals(FormulaError.VALUE.getCode(), a3.getErrorCellValue(), f[0]); - } catch (Exception e) { - actualEx = e; - } - String msg = - "Check "+(f[1] == null ? "unexpected exception" : f[1])+" here, "+ - "adjust these tests if it was actually implemented - "+f[0]; - assertEquals(f[1], (actualEx == null ? null : actualEx.getClass().getName()), msg); - } - - Subtotal subtotal = new Subtotal(); - assertEquals(ErrorEval.VALUE_INVALID, subtotal.evaluate(new ValueEval[] {}, 0, 0)); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSumif.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSumif.java deleted file mode 100644 index 4bd60295a8..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSumif.java +++ /dev/null @@ -1,119 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.NumericValueEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Test cases for SUMPRODUCT() - */ -final class TestSumif { - private static final NumberEval _30 = new NumberEval(30); - private static final NumberEval _40 = new NumberEval(40); - private static final NumberEval _50 = new NumberEval(50); - private static final NumberEval _60 = new NumberEval(60); - - private static ValueEval invokeSumif(int rowIx, int colIx, ValueEval...args) { - return new Sumif().evaluate(args, rowIx, colIx); - } - - private static void confirmDouble(double expected, ValueEval actualEval) { - assertTrue(actualEval instanceof NumericValueEval, "Expected numeric result"); - NumericValueEval nve = (NumericValueEval)actualEval; - assertEquals(expected, nve.getNumberValue(), 0); - } - - @Test - void testBasic() { - ValueEval[] arg0values = new ValueEval[] { _30, _30, _40, _40, _50, _50 }; - ValueEval[] arg2values = new ValueEval[] { _30, _40, _50, _60, _60, _60 }; - - AreaEval arg0; - AreaEval arg2; - - arg0 = EvalFactory.createAreaEval("A3:B5", arg0values); - arg2 = EvalFactory.createAreaEval("D1:E3", arg2values); - - confirm(60.0, arg0, new NumberEval(30.0)); - confirm(70.0, arg0, new NumberEval(30.0), arg2); - confirm(100.0, arg0, new StringEval(">45")); - confirm(100.0, arg0, new StringEval(">=45")); - confirm(100.0, arg0, new StringEval(">=50.0")); - confirm(140.0, arg0, new StringEval("<45")); - confirm(140.0, arg0, new StringEval("<=45")); - confirm(140.0, arg0, new StringEval("<=40.0")); - confirm(160.0, arg0, new StringEval("<>40.0")); - confirm(80.0, arg0, new StringEval("=40.0")); - - - } - private static void confirm(double expectedResult, ValueEval...args) { - confirmDouble(expectedResult, invokeSumif(-1, -1, args)); - } - - - /** - * test for bug observed near svn r882931 - */ - @Test - void testCriteriaArgRange() { - ValueEval[] arg0values = new ValueEval[] { _50, _60, _50, _50, _50, _30, }; - ValueEval[] arg1values = new ValueEval[] { _30, _40, _50, _60, }; - - AreaEval arg0; - AreaEval arg1; - ValueEval ve; - - arg0 = EvalFactory.createAreaEval("A3:B5", arg0values); - arg1 = EvalFactory.createAreaEval("A2:D2", arg1values); // single row range - - ve = invokeSumif(0, 2, arg0, arg1); // invoking from cell C1 - if (ve instanceof NumberEval) { - NumberEval ne = (NumberEval) ve; - assertNotEquals(30.0, ne.getNumberValue(), "identified error in SUMIF - criteria arg not evaluated properly"); - } - - confirmDouble(200, ve); - - arg0 = EvalFactory.createAreaEval("C1:D3", arg0values); - arg1 = EvalFactory.createAreaEval("B1:B4", arg1values); // single column range - - ve = invokeSumif(3, 0, arg0, arg1); // invoking from cell A4 - - confirmDouble(60, ve); - } - - @Test - void testEvaluateException() { - assertEquals(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, BlankEval.instance, new NumberEval(30.0))); - assertEquals(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, BlankEval.instance, new NumberEval(30.0), new NumberEval(30.0))); - assertEquals(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, new NumberEval(30.0), BlankEval.instance, new NumberEval(30.0))); - assertEquals(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, new NumberEval(30.0), new NumberEval(30.0), BlankEval.instance)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSumifs.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSumifs.java deleted file mode 100644 index 6aa1962953..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSumifs.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -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.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.NumericValueEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Test cases for SUMIFS() - */ -final class TestSumifs { - - private static final OperationEvaluationContext EC = new OperationEvaluationContext(null, null, 0, 1, 0, null); - - private static ValueEval invokeSumifs(ValueEval[] args) { - return new Sumifs().evaluate(args, EC); - } - - private static void confirmDouble(double expected, ValueEval actualEval) { - assertTrue(actualEval instanceof NumericValueEval, "Expected numeric result"); - NumericValueEval nve = (NumericValueEval)actualEval; - assertEquals(expected, nve.getNumberValue(), 0); - } - - private static void confirm(double expectedResult, ValueEval[] args) { - confirmDouble(expectedResult, invokeSumifs(args)); - } - - /** - * Example 1 from - * http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx - */ - @Test - void testExample1() { - // mimic test sample from http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx - ValueEval[] a2a9 = new ValueEval[] { - new NumberEval(5), - new NumberEval(4), - new NumberEval(15), - new NumberEval(3), - new NumberEval(22), - new NumberEval(12), - new NumberEval(10), - new NumberEval(33) - }; - - ValueEval[] b2b9 = new ValueEval[] { - new StringEval("Apples"), - new StringEval("Apples"), - new StringEval("Artichokes"), - new StringEval("Artichokes"), - new StringEval("Bananas"), - new StringEval("Bananas"), - new StringEval("Carrots"), - new StringEval("Carrots"), - }; - - ValueEval[] c2c9 = new ValueEval[] { - new NumberEval(1), - new NumberEval(2), - new NumberEval(1), - new NumberEval(2), - new NumberEval(1), - new NumberEval(2), - new NumberEval(1), - new NumberEval(2) - }; - - ValueEval[] args; - // "=SUMIFS(A2:A9, B2:B9, "=A*", C2:C9, 1)" - args = new ValueEval[]{ - EvalFactory.createAreaEval("A2:A9", a2a9), - EvalFactory.createAreaEval("B2:B9", b2b9), - new StringEval("A*"), - EvalFactory.createAreaEval("C2:C9", c2c9), - new NumberEval(1), - }; - confirm(20.0, args); - - // "=SUMIFS(A2:A9, B2:B9, "<>Bananas", C2:C9, 1)" - args = new ValueEval[]{ - EvalFactory.createAreaEval("A2:A9", a2a9), - EvalFactory.createAreaEval("B2:B9", b2b9), - new StringEval("<>Bananas"), - EvalFactory.createAreaEval("C2:C9", c2c9), - new NumberEval(1), - }; - confirm(30.0, args); - - // a test case that returns ErrorEval.VALUE_INVALID : - // the dimensions of the first and second criteria ranges are different - // "=SUMIFS(A2:A9, B2:B8, "<>Bananas", C2:C9, 1)" - args = new ValueEval[]{ - EvalFactory.createAreaEval("A2:A9", a2a9), - EvalFactory.createAreaEval("B2:B8", new ValueEval[] { - new StringEval("Apples"), - new StringEval("Apples"), - new StringEval("Artichokes"), - new StringEval("Artichokes"), - new StringEval("Bananas"), - new StringEval("Bananas"), - new StringEval("Carrots"), - }), - new StringEval("<>Bananas"), - EvalFactory.createAreaEval("C2:C9", c2c9), - new NumberEval(1), - }; - assertEquals(ErrorEval.VALUE_INVALID, invokeSumifs(args)); - - } - - /** - * Example 2 from - * http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx - */ - @Test - void testExample2() { - ValueEval[] b2e2 = new ValueEval[] { - new NumberEval(100), - new NumberEval(390), - new NumberEval(8321), - new NumberEval(500) - }; - // 1% 0.5% 3% 4% - ValueEval[] b3e3 = new ValueEval[] { - new NumberEval(0.01), - new NumberEval(0.005), - new NumberEval(0.03), - new NumberEval(0.04) - }; - - // 1% 1.3% 2.1% 2% - ValueEval[] b4e4 = new ValueEval[] { - new NumberEval(0.01), - new NumberEval(0.013), - new NumberEval(0.021), - new NumberEval(0.02) - }; - - // 0.5% 3% 1% 4% - ValueEval[] b5e5 = new ValueEval[] { - new NumberEval(0.005), - new NumberEval(0.03), - new NumberEval(0.01), - new NumberEval(0.04) - }; - - ValueEval[] args; - - // "=SUMIFS(B2:E2, B3:E3, ">3%", B4:E4, ">=2%")" - args = new ValueEval[]{ - EvalFactory.createAreaEval("B2:E2", b2e2), - EvalFactory.createAreaEval("B3:E3", b3e3), - new StringEval(">0.03"), // 3% in the MSFT example - EvalFactory.createAreaEval("B4:E4", b4e4), - new StringEval(">=0.02"), // 2% in the MSFT example - EvalFactory.createAreaEval("B5:E5", b5e5), - new StringEval(">=0.01"), // 1% in the MSFT example - }; - confirm(500.0, args); - } - - /** - * Example 3 from - * http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx - */ - @Test - void testExample3() { - //3.3 0.8 5.5 5.5 - ValueEval[] b2e2 = new ValueEval[] { - new NumberEval(3.3), - new NumberEval(0.8), - new NumberEval(5.5), - new NumberEval(5.5) - }; - // 55 39 39 57.5 - ValueEval[] b3e3 = new ValueEval[] { - new NumberEval(55), - new NumberEval(39), - new NumberEval(39), - new NumberEval(57.5) - }; - - // 6.5 19.5 6 6.5 - ValueEval[] b4e4 = new ValueEval[] { - new NumberEval(6.5), - new NumberEval(19.5), - new NumberEval(6), - new NumberEval(6.5) - }; - - ValueEval[] args; - - // "=SUMIFS(B2:E2, B3:E3, ">=40", B4:E4, "<10")" - args = new ValueEval[]{ - EvalFactory.createAreaEval("B2:E2", b2e2), - EvalFactory.createAreaEval("B3:E3", b3e3), - new StringEval(">=40"), - EvalFactory.createAreaEval("B4:E4", b4e4), - new StringEval("<10"), - }; - confirm(8.8, args); - } - - /** - * Example 5 from - * http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx - * - * Criteria entered as reference and by using wildcard characters - */ - @Test - void testFromFile() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("sumifs.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet example1 = wb.getSheet("Example 1"); - HSSFCell ex1cell1 = example1.getRow(10).getCell(2); - fe.evaluate(ex1cell1); - assertEquals(20.0, ex1cell1.getNumericCellValue(), 0); - HSSFCell ex1cell2 = example1.getRow(11).getCell(2); - fe.evaluate(ex1cell2); - assertEquals(30.0, ex1cell2.getNumericCellValue(), 0); - - HSSFSheet example2 = wb.getSheet("Example 2"); - HSSFCell ex2cell1 = example2.getRow(6).getCell(2); - fe.evaluate(ex2cell1); - assertEquals(500.0, ex2cell1.getNumericCellValue(), 0); - HSSFCell ex2cell2 = example2.getRow(7).getCell(2); - fe.evaluate(ex2cell2); - assertEquals(8711.0, ex2cell2.getNumericCellValue(), 0); - - HSSFSheet example3 = wb.getSheet("Example 3"); - HSSFCell ex3cell = example3.getRow(5).getCell(2); - fe.evaluate(ex3cell); - assertEquals(8.8, ex3cell.getNumericCellValue(), 0); - - HSSFSheet example4 = wb.getSheet("Example 4"); - HSSFCell ex4cell = example4.getRow(8).getCell(2); - fe.evaluate(ex4cell); - assertEquals(3.5, ex4cell.getNumericCellValue(), 0); - - HSSFSheet example5 = wb.getSheet("Example 5"); - HSSFCell ex5cell = example5.getRow(8).getCell(2); - fe.evaluate(ex5cell); - assertEquals(625000., ex5cell.getNumericCellValue(), 0); - - } - - @Test - void testBug56655() { - ValueEval[] a2a9 = new ValueEval[] { - new NumberEval(5), - new NumberEval(4), - new NumberEval(15), - new NumberEval(3), - new NumberEval(22), - new NumberEval(12), - new NumberEval(10), - new NumberEval(33) - }; - - ValueEval[] args = new ValueEval[]{ - EvalFactory.createAreaEval("A2:A9", a2a9), - ErrorEval.VALUE_INVALID, - new StringEval("A*"), - }; - - ValueEval result = invokeSumifs(args); - assertTrue(result instanceof ErrorEval, "Expect to have an error when an input is an invalid value, but had: " + result.getClass()); - - args = new ValueEval[]{ - EvalFactory.createAreaEval("A2:A9", a2a9), - EvalFactory.createAreaEval("A2:A9", a2a9), - ErrorEval.VALUE_INVALID, - }; - - result = invokeSumifs(args); - assertTrue(result instanceof ErrorEval, "Expect to have an error when an input is an invalid value, but had: " + result.getClass()); - } - - @Test - void testBug56655b() { -/* - setCellFormula(sheet, 0, 0, "B1*C1"); - sheet.getRow(0).createCell(1).setCellValue("A"); - setCellFormula(sheet, 1, 0, "B1*C1"); - sheet.getRow(1).createCell(1).setCellValue("A"); - setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); - */ - ValueEval[] a0a1 = new ValueEval[] { - NumberEval.ZERO, - NumberEval.ZERO - }; - - ValueEval[] args = new ValueEval[]{ - EvalFactory.createAreaEval("A0:A1", a0a1), - EvalFactory.createAreaEval("A0:A1", a0a1), - ErrorEval.VALUE_INVALID - }; - - ValueEval result = invokeSumifs(args); - assertTrue(result instanceof ErrorEval, "Expect to have an error when an input is an invalid value, but had: " + result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testBug56655c() { -/* - setCellFormula(sheet, 0, 0, "B1*C1"); - sheet.getRow(0).createCell(1).setCellValue("A"); - setCellFormula(sheet, 1, 0, "B1*C1"); - sheet.getRow(1).createCell(1).setCellValue("A"); - setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); - */ - ValueEval[] a0a1 = new ValueEval[] { - NumberEval.ZERO, - NumberEval.ZERO - }; - - ValueEval[] args = new ValueEval[]{ - EvalFactory.createAreaEval("A0:A1", a0a1), - EvalFactory.createAreaEval("A0:A1", a0a1), - ErrorEval.NAME_INVALID - }; - - ValueEval result = invokeSumifs(args); - assertTrue(result instanceof ErrorEval, "Expect to have an error when an input is an invalid value, but had: " + result.getClass()); - assertEquals(ErrorEval.NAME_INVALID, result); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSumproduct.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSumproduct.java deleted file mode 100644 index 35ee48d26c..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSumproduct.java +++ /dev/null @@ -1,123 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.NumericValueEval; -import org.apache.poi.ss.formula.eval.RefEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Test cases for SUMPRODUCT() - * - * @author Josh Micich - */ -final class TestSumproduct { - - private static ValueEval invokeSumproduct(ValueEval[] args) { - // srcCellRow and srcCellColumn are ignored by SUMPRODUCT - return new Sumproduct().evaluate(args, -1, (short)-1); - } - - private static void confirmDouble(double expected, ValueEval actualEval) { - assertTrue(actualEval instanceof NumericValueEval, "Expected numeric result"); - NumericValueEval nve = (NumericValueEval)actualEval; - assertEquals(expected, nve.getNumberValue(), 0); - } - - @Test - void testScalarSimple() { - - RefEval refEval = EvalFactory.createRefEval("A1", new NumberEval(3)); - ValueEval[] args = { - refEval, - new NumberEval(2), - }; - ValueEval result = invokeSumproduct(args); - confirmDouble(6D, result); - } - - @Test - void testAreaSimple() { - ValueEval[] aValues = { - new NumberEval(2), - new NumberEval(4), - new NumberEval(5), - }; - ValueEval[] bValues = { - new NumberEval(3), - new NumberEval(6), - new NumberEval(7), - }; - AreaEval aeA = EvalFactory.createAreaEval("A1:A3", aValues); - AreaEval aeB = EvalFactory.createAreaEval("B1:B3", bValues); - - ValueEval[] args = { aeA, aeB, }; - ValueEval result = invokeSumproduct(args); - confirmDouble(65D, result); - } - - /** - * For scalar products, the terms may be 1x1 area refs - */ - @Test - void testOneByOneArea() { - - AreaEval ae = EvalFactory.createAreaEval("A1:A1", new ValueEval[] { new NumberEval(7), }); - - ValueEval[] args = { - ae, - new NumberEval(2), - }; - ValueEval result = invokeSumproduct(args); - confirmDouble(14D, result); - } - - @Test - void testMismatchAreaDimensions() { - - AreaEval aeA = EvalFactory.createAreaEval("A1:A3", new ValueEval[3]); - AreaEval aeB = EvalFactory.createAreaEval("B1:D1", new ValueEval[3]); - - ValueEval[] args; - args = new ValueEval[] { aeA, aeB, }; - assertEquals(ErrorEval.VALUE_INVALID, invokeSumproduct(args)); - - args = new ValueEval[] { aeA, new NumberEval(5), }; - assertEquals(ErrorEval.VALUE_INVALID, invokeSumproduct(args)); - } - - @Test - void testAreaWithErrorCell() { - ValueEval[] aValues = { - ErrorEval.REF_INVALID, - null, - }; - AreaEval aeA = EvalFactory.createAreaEval("A1:A2", aValues); - AreaEval aeB = EvalFactory.createAreaEval("B1:B2", new ValueEval[2]); - - ValueEval[] args = { aeA, aeB, }; - assertEquals(ErrorEval.REF_INVALID, invokeSumproduct(args)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTFunc.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTFunc.java deleted file mode 100644 index 03cb480e47..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTFunc.java +++ /dev/null @@ -1,140 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Test cases for Excel function T() - * - * @author Josh Micich - */ -final class TestTFunc { - - /** - * @return the result of calling function T() with the specified argument - */ - private static ValueEval invokeT(ValueEval arg) { - ValueEval[] args = { arg, }; - ValueEval result = new T().evaluate(args, -1, (short)-1); - assertNotNull(result, "result may never be null"); - return result; - } - - /** - * Simulates call: T(A1) - * where cell A1 has the specified innerValue - */ - private ValueEval invokeTWithReference(ValueEval innerValue) { - ValueEval arg = EvalFactory.createRefEval("$B$2", innerValue); - return invokeT(arg); - } - - private static void confirmText(String text) { - ValueEval arg = new StringEval(text); - ValueEval eval = invokeT(arg); - StringEval se = (StringEval) eval; - assertEquals(text, se.getStringValue()); - } - - @Test - void testTextValues() { - confirmText("abc"); - confirmText(""); - confirmText(" "); - confirmText("~"); - confirmText("123"); - confirmText("TRUE"); - } - - private static void confirmError(ValueEval arg) { - ValueEval eval = invokeT(arg); - assertSame(arg, eval); - } - - @Test - void testErrorValues() { - - confirmError(ErrorEval.VALUE_INVALID); - confirmError(ErrorEval.NA); - confirmError(ErrorEval.REF_INVALID); - } - - private static void confirmString(ValueEval eval, String expected) { - assertTrue(eval instanceof StringEval); - assertEquals(expected, ((StringEval)eval).getStringValue()); - } - - private static void confirmOther(ValueEval arg) { - ValueEval eval = invokeT(arg); - confirmString(eval, ""); - } - - @Test - void testOtherValues() { - confirmOther(new NumberEval(2)); - confirmOther(BoolEval.FALSE); - confirmOther(BlankEval.instance); // can this particular case be verified? - } - - @Test - void testRefValues() { - ValueEval eval; - - eval = invokeTWithReference(new StringEval("def")); - confirmString(eval, "def"); - eval = invokeTWithReference(new StringEval(" ")); - confirmString(eval, " "); - - eval = invokeTWithReference(new NumberEval(2)); - confirmString(eval, ""); - eval = invokeTWithReference(BoolEval.TRUE); - confirmString(eval, ""); - - eval = invokeTWithReference(ErrorEval.NAME_INVALID); - assertSame(eval, ErrorEval.NAME_INVALID); - } - - @Test - void testAreaArg() { - ValueEval[] areaValues = new ValueEval[] { - new StringEval("abc"), new StringEval("def"), - new StringEval("ghi"), new StringEval("jkl"), - }; - AreaEval ae = EvalFactory.createAreaEval("C10:D11", areaValues); - - ValueEval ve = invokeT(ae); - confirmString(ve, "abc"); - - areaValues[0] = new NumberEval(5.0); - ve = invokeT(ae); - confirmString(ve, ""); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestText.java b/src/testcases/org/apache/poi/ss/formula/functions/TestText.java deleted file mode 100644 index ddcdd35165..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestText.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.text.DateFormatSymbols; -import java.text.DecimalFormatSymbols; -import java.text.SimpleDateFormat; -import java.util.TimeZone; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * Test case for TEXT() - */ -final class TestText { - @Test - void testTextWithStringFirstArg() { - ValueEval strArg = new StringEval("abc"); - ValueEval formatArg = new StringEval("abc"); - ValueEval[] args = { strArg, formatArg }; - ValueEval result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testTextWithDeciamlFormatSecondArg() { - ValueEval numArg = new NumberEval(321321.321); - ValueEval formatArg = new StringEval("#,###.00000"); - ValueEval[] args = { numArg, formatArg }; - ValueEval result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale()); - char groupSeparator = dfs.getGroupingSeparator(); - char decimalSeparator = dfs.getDecimalSeparator(); - ValueEval testResult = new StringEval("321" + groupSeparator + "321" + decimalSeparator + "32100"); - assertEquals(testResult.toString(), result.toString()); - numArg = new NumberEval(321.321); - formatArg = new StringEval("00000.00000"); - args[0] = numArg; - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval("00321" + decimalSeparator + "32100"); - assertEquals(testResult.toString(), result.toString()); - - formatArg = new StringEval("$#.#"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval("$321" + decimalSeparator + "3"); - assertEquals(testResult.toString(), result.toString()); - } - - @Test - void testTextWithFractionFormatSecondArg() { - ValueEval numArg = new NumberEval(321.321); - ValueEval formatArg = new StringEval("# #/#"); - ValueEval[] args = { numArg, formatArg }; - ValueEval result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - ValueEval testResult = new StringEval("321 1/3"); - assertEquals(testResult.toString(), result.toString()); - - formatArg = new StringEval("# #/##"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval("321 26/81"); - assertEquals(testResult.toString(), result.toString()); - - formatArg = new StringEval("#/##"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval("26027/81"); - assertEquals(testResult.toString(), result.toString()); - } - - @Test - void testTextWithDateFormatSecondArg() { - TimeZone userTZ = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - try { - // Test with Java style M=Month - ValueEval numArg = new NumberEval(321.321); - ValueEval formatArg = new StringEval("dd:MM:yyyy hh:mm:ss"); - ValueEval[] args = { numArg, formatArg }; - ValueEval result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - ValueEval testResult = new StringEval("16:11:1900 07:42:14"); - assertEquals(testResult.toString(), result.toString()); - - // Excel also supports "m before h is month" - formatArg = new StringEval("dd:mm:yyyy hh:mm:ss"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval("16:11:1900 07:42:14"); - assertEquals(testResult.toString(), result.toString()); - - // this line is intended to compute how "November" would look like in the current locale - // update: now the locale will be (if not set otherwise) always Locale.getDefault() (see LocaleUtil) - DateFormatSymbols dfs = DateFormatSymbols.getInstance(LocaleUtil.getUserLocale()); - SimpleDateFormat sdf = new SimpleDateFormat("MMMM", dfs); - sdf.setTimeZone(LocaleUtil.getUserTimeZone()); - String november = sdf.format(LocaleUtil.getLocaleCalendar(2015,10,1).getTime()); - - // Again with Java style - formatArg = new StringEval("MMMM dd, yyyy"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval(november + " 16, 1900"); - assertEquals(testResult.toString(), result.toString()); - - // And Excel style - formatArg = new StringEval("mmmm dd, yyyy"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval(november + " 16, 1900"); - assertEquals(testResult.toString(), result.toString()); - } finally { - LocaleUtil.setUserTimeZone(userTZ); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java deleted file mode 100644 index d45787b2a5..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java +++ /dev/null @@ -1,124 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.regex.Pattern; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFDataFormat; -import org.apache.poi.hssf.usermodel.HSSFDataFormatter; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link TimeFunc} - */ -final class TestTime { - - private static final int SECONDS_PER_MINUTE = 60; - private static final int SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE; - private static final double SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR; - private HSSFCell cell11; - private HSSFFormulaEvaluator evaluator; - private HSSFWorkbook wb; - private HSSFDataFormatter form; - private HSSFCellStyle style; - - @BeforeEach - void setUp() { - wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - style = wb.createCellStyle(); - HSSFDataFormat fmt = wb.createDataFormat(); - style.setDataFormat(fmt.getFormat("hh:mm:ss")); - - cell11 = sheet.createRow(0).createCell(0); - form = new HSSFDataFormatter(); - - evaluator = new HSSFFormulaEvaluator(wb); - } - - @Test - void testSomeArgumentsMissing() { - confirm("00:00:00", "TIME(, 0, 0)"); - confirm("12:00:00", "TIME(12, , )"); - } - - @Test - void testValid() { - confirm("00:00:01", 0, 0, 1); - confirm("00:01:00", 0, 1, 0); - - confirm("00:00:00", 0, 0, 0); - - confirm("01:00:00", 1, 0, 0); - confirm("12:00:00", 12, 0, 0); - confirm("23:00:00", 23, 0, 0); - confirm("00:00:00", 24, 0, 0); - confirm("01:00:00", 25, 0, 0); - confirm("00:00:00", 48, 0, 0); - confirm("06:00:00", 6, 0, 0); - confirm("06:01:00", 6, 1, 0); - confirm("06:30:00", 6, 30, 0); - - confirm("06:59:00", 6, 59, 0); - confirm("07:00:00", 6, 60, 0); - confirm("07:01:00", 6, 61, 0); - confirm("08:00:00", 6, 120, 0); - confirm("06:00:00", 6, 1440, 0); - confirm("18:49:00", 18, 49, 0); - confirm("18:49:01", 18, 49, 1); - confirm("18:49:30", 18, 49, 30); - confirm("18:49:59", 18, 49, 59); - confirm("18:50:00", 18, 49, 60); - confirm("18:50:01", 18, 49, 61); - confirm("18:50:59", 18, 49, 119); - confirm("18:51:00", 18, 49, 120); - confirm("03:55:07", 18, 49, 32767); - confirm("12:08:01", 18, 32767, 61); - confirm("07:50:01", 32767, 49, 61); - } - private void confirm(String expectedTimeStr, int inH, int inM, int inS) { - confirm(expectedTimeStr, "TIME(" + inH + "," + inM + "," + inS + ")"); - } - - private void confirm(String expectedTimeStr, String formulaText) { - String[] parts = Pattern.compile(":").split(expectedTimeStr); - int expH = Integer.parseInt(parts[0]); - int expM = Integer.parseInt(parts[1]); - int expS = Integer.parseInt(parts[2]); - - double expectedValue = (expH*SECONDS_PER_HOUR + expM*SECONDS_PER_MINUTE + expS)/SECONDS_PER_DAY; - - cell11.setCellFormula(formulaText); - cell11.setCellStyle(style); - evaluator.clearAllCachedResultValues(); - - double actualValue = evaluator.evaluate(cell11).getNumberValue(); - assertEquals(expectedValue, actualValue, 0.0); - - String actualText = form.formatCellValue(cell11, evaluator); - assertEquals(expectedTimeStr, actualText); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTrendFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTrendFunctionsFromSpreadsheet.java deleted file mode 100644 index 55398d31cb..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTrendFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** -* Tests TREND() as loaded from a test data spreadsheet. -*/ -class TestTrendFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestTrendFunctionsFromSpreadsheet.class, "Trend.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTrim.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTrim.java deleted file mode 100644 index efee41b996..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTrim.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for Excel function TRIM() - * - * @author Josh Micich - */ -final class TestTrim { - - - private static ValueEval invokeTrim(ValueEval text) { - ValueEval[] args = new ValueEval[] { text, }; - return TextFunction.TRIM.evaluate(args, -1, (short)-1); - } - - private void confirmTrim(ValueEval text, String expected) { - ValueEval result = invokeTrim(text); - assertEquals(StringEval.class, result.getClass()); - assertEquals(expected, ((StringEval)result).getStringValue()); - } - - private void confirmTrim(ValueEval text, ErrorEval expectedError) { - ValueEval result = invokeTrim(text); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - @Test - void testBasic() { - - confirmTrim(new StringEval(" hi "), "hi"); - confirmTrim(new StringEval("hi "), "hi"); - confirmTrim(new StringEval(" hi"), "hi"); - confirmTrim(new StringEval(" hi there "), "hi there"); - confirmTrim(new StringEval(""), ""); - confirmTrim(new StringEval(" "), ""); - } - - /** - * Valid cases where text arg is not exactly a string - */ - @Test - void testUnusualArgs() { - - // text (first) arg type is number, other args are strings with fractional digits - confirmTrim(new NumberEval(123456), "123456"); - confirmTrim(BoolEval.FALSE, "FALSE"); - confirmTrim(BoolEval.TRUE, "TRUE"); - confirmTrim(BlankEval.instance, ""); - } - - @Test - void testErrors() { - confirmTrim(ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTrunc.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTrunc.java deleted file mode 100644 index 6e1d5d8cac..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTrunc.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Test case for TRUNC() - * - * @author Stephen Wolke (smwolke at geistig.com) - */ -final class TestTrunc extends BaseTestNumeric { - private static final NumericFunction F = null; - - @Test - void testTruncWithStringArg() { - - ValueEval strArg = new StringEval("abc"); - ValueEval[] args = { strArg, new NumberEval(2) }; - ValueEval result = NumericFunction.TRUNC.evaluate(args, -1, (short)-1); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testTruncWithWholeNumber() { - ValueEval[] args = { new NumberEval(200), new NumberEval(2) }; - @SuppressWarnings("static-access") - ValueEval result = F.TRUNC.evaluate(args, -1, (short)-1); - assertDouble("TRUNC", (new NumberEval(200d)).getNumberValue(), ((NumberEval)result).getNumberValue()); - } - - @Test - void testTruncWithDecimalNumber() { - ValueEval[] args = { new NumberEval(2.612777), new NumberEval(3) }; - @SuppressWarnings("static-access") - ValueEval result = F.TRUNC.evaluate(args, -1, (short)-1); - assertDouble("TRUNC", (new NumberEval(2.612d)).getNumberValue(), ((NumberEval)result).getNumberValue()); - } - - @Test - void testTruncWithProblematicDecimalNumber() { - ValueEval[] args = { new NumberEval(0.29), new NumberEval(2) }; - ValueEval result = NumericFunction.TRUNC.evaluate(args, -1, (short)-1); - assertDouble("TRUNC", (new NumberEval(0.29d)).getNumberValue(), ((NumberEval)result).getNumberValue()); - } - - @Test - void testTruncWithProblematicCalculationResult() { - - ValueEval[] args = { new NumberEval(21.624d / 24d + .009d), new NumberEval(2) }; - ValueEval result = NumericFunction.TRUNC.evaluate(args, -1, (short)-1); - assertDouble("TRUNC", (new NumberEval(0.91d)).getNumberValue(), ((NumberEval)result).getNumberValue()); - } - - @Test - void testTruncWithDecimalNumberOneArg() { - ValueEval[] args = { new NumberEval(2.612777) }; - ValueEval result = NumericFunction.TRUNC.evaluate(args, -1, (short)-1); - assertDouble("TRUNC", (new NumberEval(2d)).getNumberValue(), ((NumberEval)result).getNumberValue()); - } - - @Test - void testNegative() { - ValueEval[] args = { new NumberEval(-8.9), new NumberEval(0) }; - @SuppressWarnings("static-access") - ValueEval result = F.TRUNC.evaluate(args, -1, (short)-1); - assertDouble("TRUNC", (new NumberEval(-8)).getNumberValue(), ((NumberEval)result).getNumberValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTwoOperandNumericFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTwoOperandNumericFunctionsFromSpreadsheet.java deleted file mode 100644 index 3cac14426d..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTwoOperandNumericFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests for numeric functions with two arguments such aqs +, -, *, POWER - * as loaded from a test data spreadsheet. - */ -class TestTwoOperandNumericFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestTwoOperandNumericFunctionsFromSpreadsheet.class, "TwoOperandNumericFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestValue.java b/src/testcases/org/apache/poi/ss/formula/functions/TestValue.java deleted file mode 100644 index a733f243de..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestValue.java +++ /dev/null @@ -1,97 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link Value} - */ -final class TestValue { - - private static ValueEval invokeValue(String strText) { - ValueEval[] args = new ValueEval[] { new StringEval(strText), }; - return new Value().evaluate(args, -1, (short) -1); - } - - private static void confirmValue(String strText, double expected) { - ValueEval result = invokeValue(strText); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval) result).getNumberValue(), 0.0); - } - - private static void confirmValueError(String strText) { - ValueEval result = invokeValue(strText); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - void testBasic() { - - confirmValue("100", 100); - confirmValue("-2.3", -2.3); - confirmValue(".5", 0.5); - confirmValue(".5e2", 50); - confirmValue(".5e-2", 0.005); - confirmValue(".5e+2", 50); - confirmValue("+5", 5); - confirmValue("$1,000", 1000); - confirmValue("100.5e1", 1005); - confirmValue("1,0000", 10000); - confirmValue("1,000,0000", 10000000); - confirmValue("1,000,0000,00000", 1000000000000.0); - confirmValue(" 100 ", 100); - confirmValue(" + 100", 100); - confirmValue("10000", 10000); - confirmValue("$-5", -5); - confirmValue("$.5", 0.5); - confirmValue("123e+5", 12300000); - confirmValue("1,000e2", 100000); - confirmValue("$10e2", 1000); - confirmValue("$1,000e2", 100000); - confirmValue("30%", 0.3); - confirmValue("30 %", 0.3); - } - - @Test - void testErrors() { - confirmValueError("1+1"); - confirmValueError("1 1"); - confirmValueError("1,00.0"); - confirmValueError("1,00"); - confirmValueError("$1,00.5e1"); - confirmValueError("1,00.5e1"); - confirmValueError("1,0,000"); - confirmValueError("1,00,000"); - confirmValueError("++100"); - confirmValueError("$$5"); - confirmValueError("-"); - confirmValueError("+"); - confirmValueError("$"); - confirmValueError(",300"); - confirmValueError("0.233,4"); - confirmValueError("1e2.5"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet.java deleted file mode 100644 index 3719d93b35..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests WeekNum() as loaded from a test data spreadsheet.

- */ -class TestWeekNumFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - return data(TestWeekNumFunctionsFromSpreadsheet.class, "WeekNumFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet2013.java b/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet2013.java deleted file mode 100644 index b918d0490e..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet2013.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.provider.Arguments; - -/** - * Tests WeekNum() as loaded from a test data 2013 excel spreadsheet.

- */ -class TestWeekNumFunctionsFromSpreadsheet2013 extends BaseTestFunctionsFromSpreadsheet { - public static Stream data() throws Exception { - //Only open this file with Excel 2013 to keep binary specific to that version - return data(TestWeekNumFunctionsFromSpreadsheet2013.class, "WeekNumFunctionTestCaseData2013.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekdayFunc.java b/src/testcases/org/apache/poi/ss/formula/functions/TestWeekdayFunc.java deleted file mode 100644 index d1c48a265f..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekdayFunc.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.formula.eval.*; -import org.apache.poi.util.StringUtil; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.*; - -/** - * Tests WEEKDAY(serial_number[, return_type]) excep function - * https://support.office.com/en-us/article/WEEKDAY-function-60E44483-2ED1-439F-8BD0-E404C190949A - */ -class TestWeekdayFunc { - private static final double TOLERANCE = 0.001; - - private void assertEvaluateEquals(double expected, double serial_number) { - String formula = "WEEKDAY(" + serial_number + ")"; - ValueEval[] args = new ValueEval[] { new NumberEval(serial_number) }; - NumberEval result = (NumberEval) WeekdayFunc.instance.evaluate(args, 0, 0); - assertEquals(expected, result.getNumberValue(), TOLERANCE, formula); - } - private void assertEvaluateEquals(double expected, double serial_number, double return_type) { - String formula = "WEEKDAY(" + serial_number + ", " + return_type + ")"; - ValueEval[] args = new ValueEval[] { new NumberEval(serial_number), new NumberEval(return_type) }; - NumberEval result = (NumberEval) WeekdayFunc.instance.evaluate(args, 0, 0); - assertEquals(expected, result.getNumberValue(), TOLERANCE, formula); - } - - - @Test - void testEvaluate() { - assertEvaluateEquals(2.0, 1.0); - assertEvaluateEquals(2.0, 1.0, 1.0); - assertEvaluateEquals(1.0, 1.0, 2.0); - assertEvaluateEquals(0.0, 1.0, 3.0); - assertEvaluateEquals(1.0, 1.0, 11.0); - assertEvaluateEquals(7.0, 1.0, 12.0); - assertEvaluateEquals(6.0, 1.0, 13.0); - assertEvaluateEquals(5.0, 1.0, 14.0); - assertEvaluateEquals(4.0, 1.0, 15.0); - assertEvaluateEquals(3.0, 1.0, 16.0); - assertEvaluateEquals(2.0, 1.0, 17.0); - - - assertEvaluateEquals(3.0, 39448.0); - assertEvaluateEquals(3.0, 39448.0, 1.0); - assertEvaluateEquals(2.0, 39448.0, 2.0); - assertEvaluateEquals(1.0, 39448.0, 3.0); - assertEvaluateEquals(2.0, 39448.0, 11.0); - assertEvaluateEquals(1.0, 39448.0, 12.0); - assertEvaluateEquals(7.0, 39448.0, 13.0); - assertEvaluateEquals(6.0, 39448.0, 14.0); - assertEvaluateEquals(5.0, 39448.0, 15.0); - assertEvaluateEquals(4.0, 39448.0, 16.0); - assertEvaluateEquals(3.0, 39448.0, 17.0); - } - - // for testing invalid invocations - private void assertEvaluateEquals(String message, ErrorEval expected, ValueEval... args) { - String formula = "WEEKDAY(" + StringUtil.join(args, ", ") + ")"; - ValueEval result = WeekdayFunc.instance.evaluate(args, 0, 0); - assertEquals(expected, result, formula + ": " + message); - } - - @Test - void testEvaluateInvalid() { - assertEvaluateEquals("no args", ErrorEval.VALUE_INVALID); - assertEvaluateEquals("too many args", ErrorEval.VALUE_INVALID, new NumberEval(1.0), new NumberEval(1.0), new NumberEval(1.0)); - assertEvaluateEquals("negative date", ErrorEval.NUM_ERROR, new NumberEval(-1.0)); - assertEvaluateEquals("cannot coerce serial_number to number", ErrorEval.VALUE_INVALID, new StringEval("")); - assertEvaluateEquals("cannot coerce return_type to number", ErrorEval.VALUE_INVALID, new StringEval("1"), new StringEval("")); - assertEvaluateEquals("return_type is blank", ErrorEval.NUM_ERROR, new StringEval("2"), BlankEval.instance); - assertEvaluateEquals("return_type is missing", ErrorEval.NUM_ERROR, new StringEval("3"), MissingArgEval.instance); - assertEvaluateEquals("invalid return_type", ErrorEval.NUM_ERROR, new NumberEval(1.0), new NumberEval(18.0)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestXYNumericFunction.java b/src/testcases/org/apache/poi/ss/formula/functions/TestXYNumericFunction.java deleted file mode 100644 index b97e80171e..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestXYNumericFunction.java +++ /dev/null @@ -1,140 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.jupiter.api.Test; - -/** - * Tests for Excel functions SUMX2MY2(), SUMX2PY2(), SUMXMY2() - * - * @author Josh Micich - */ -final class TestXYNumericFunction { - private static final Function SUM_SQUARES = new Sumx2py2(); - private static final Function DIFF_SQUARES = new Sumx2my2(); - private static final Function SUM_SQUARES_OF_DIFFS = new Sumxmy2(); - - private static ValueEval invoke(Function function, ValueEval xArray, ValueEval yArray) { - ValueEval[] args = new ValueEval[] { xArray, yArray, }; - return function.evaluate(args, -1, (short)-1); - } - - private void confirm(Function function, ValueEval xArray, ValueEval yArray, double expected) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval)result).getNumberValue(), 0); - } - private void confirmError(Function function, ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - private void confirmError(ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - confirmError(SUM_SQUARES, xArray, yArray, expectedError); - confirmError(DIFF_SQUARES, xArray, yArray, expectedError); - confirmError(SUM_SQUARES_OF_DIFFS, xArray, yArray, expectedError); - } - - @Test - void testBasic() { - ValueEval[] xValues = { - new NumberEval(1), - new NumberEval(2), - }; - ValueEval areaEvalX = createAreaEval(xValues); - confirm(SUM_SQUARES, areaEvalX, areaEvalX, 10.0); - confirm(DIFF_SQUARES, areaEvalX, areaEvalX, 0.0); - confirm(SUM_SQUARES_OF_DIFFS, areaEvalX, areaEvalX, 0.0); - - ValueEval[] yValues = { - new NumberEval(3), - new NumberEval(4), - }; - ValueEval areaEvalY = createAreaEval(yValues); - confirm(SUM_SQUARES, areaEvalX, areaEvalY, 30.0); - confirm(DIFF_SQUARES, areaEvalX, areaEvalY, -20.0); - confirm(SUM_SQUARES_OF_DIFFS, areaEvalX, areaEvalY, 8.0); - } - - /** - * number of items in array is not limited to 30 - */ - @Test - void testLargeArrays() { - ValueEval[] xValues = createMockNumberArray(100, 3); - ValueEval[] yValues = createMockNumberArray(100, 2); - - confirm(SUM_SQUARES, createAreaEval(xValues), createAreaEval(yValues), 1300.0); - confirm(DIFF_SQUARES, createAreaEval(xValues), createAreaEval(yValues), 500.0); - confirm(SUM_SQUARES_OF_DIFFS, createAreaEval(xValues), createAreaEval(yValues), 100.0); - } - - - private ValueEval[] createMockNumberArray(int size, double value) { - ValueEval[] result = new ValueEval[size]; - for (int i = 0; i < result.length; i++) { - result[i] = new NumberEval(value); - } - return result; - } - - private static ValueEval createAreaEval(ValueEval[] values) { - String refStr = "A1:A" + values.length; - return EvalFactory.createAreaEval(refStr, values); - } - - @Test - void testErrors() { - ValueEval[] xValues = { - ErrorEval.REF_INVALID, - new NumberEval(2), - }; - ValueEval areaEvalX = createAreaEval(xValues); - ValueEval[] yValues = { - new NumberEval(2), - ErrorEval.NULL_INTERSECTION, - }; - ValueEval areaEvalY = createAreaEval(yValues); - ValueEval[] zValues = { // wrong size - new NumberEval(2), - }; - ValueEval areaEvalZ = createAreaEval(zValues); - - // if either arg is an error, that error propagates - confirmError(ErrorEval.REF_INVALID, ErrorEval.NAME_INVALID, ErrorEval.REF_INVALID); - confirmError(areaEvalX, ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - confirmError(ErrorEval.NAME_INVALID, areaEvalX, ErrorEval.NAME_INVALID); - - // array sizes must match - confirmError(areaEvalX, areaEvalZ, ErrorEval.NA); - confirmError(areaEvalZ, areaEvalY, ErrorEval.NA); - - // any error in an array item propagates up - confirmError(areaEvalX, areaEvalX, ErrorEval.REF_INVALID); - - // search for errors array by array, not pair by pair - confirmError(areaEvalX, areaEvalY, ErrorEval.REF_INVALID); - confirmError(areaEvalY, areaEvalX, ErrorEval.NULL_INTERSECTION); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/BaseTestPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/BaseTestPtg.java deleted file mode 100644 index 8e566bf929..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/BaseTestPtg.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Convenient abstract class to reduce the amount of boilerplate code needed - * in ptg-related unit tests. - */ -public abstract class BaseTestPtg { - - /** - * Loads a workbook from the given filename in the test data dir. - * - * @param sampleFileName the filename. - * @return the loaded workbook. - */ - protected static HSSFWorkbook loadWorkbook(String sampleFileName) { - return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - /** - * Creates a new Workbook and adds one sheet with the specified name - */ - protected static HSSFWorkbook createWorkbookWithSheet(String sheetName) { - HSSFWorkbook book = new HSSFWorkbook(); - book.createSheet(sheetName); - return book; - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestAbstractFunctionPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestAbstractFunctionPtg.java deleted file mode 100644 index 3d99bc3e6d..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestAbstractFunctionPtg.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.apache.poi.util.LittleEndianOutput; -import org.junit.jupiter.api.Test; - -class TestAbstractFunctionPtg { - - @Test - void testConstructor() { - FunctionPtg ptg = new FunctionPtg(1, 2, null, 255); - assertEquals(1, ptg.getFunctionIndex()); - assertEquals(2, ptg.getDefaultOperandClass()); - assertEquals(255, ptg.getNumberOfOperands()); - } - - @Test - void testInvalidFunctionIndex() { - assertThrows(RuntimeException.class, () -> new FunctionPtg(40000, 2, null, 255)); - } - - @Test - void testInvalidRuntimeClass() { - assertThrows(RuntimeException.class, () -> new FunctionPtg(1, 300, null, 255)); - } - - private static class FunctionPtg extends AbstractFunctionPtg { - - protected FunctionPtg(int functionIndex, int pReturnClass, - byte[] paramTypes, int nParams) { - super(functionIndex, pReturnClass, paramTypes, nParams); - } - - @Override - public byte getSid() { - return -1; - } - - public int getSize() { - return 0; - } - - public void write(LittleEndianOutput out) { - - } - - @Override - public FunctionPtg copy() { - // immutable - return this; - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestArea3DPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestArea3DPtg.java deleted file mode 100644 index 51b8c32f28..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestArea3DPtg.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for Area3DPtg - */ -final class TestArea3DPtg extends BaseTestPtg { - - /** - * confirms that sheet names get properly escaped - */ - @Test - void testToFormulaString() throws IOException { - - Area3DPtg target = new Area3DPtg("A1:B1", (short)0); - - String sheetName = "my sheet"; - try (HSSFWorkbook wb = createWorkbookWithSheet(sheetName)) { - HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(wb); - assertEquals("'my sheet'!A1:B1", target.toFormulaString(book)); - - wb.setSheetName(0, "Sheet1"); - assertEquals("Sheet1!A1:B1", target.toFormulaString(book)); - - wb.setSheetName(0, "C64"); - assertEquals("'C64'!A1:B1", target.toFormulaString(book)); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaErrPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaErrPtg.java deleted file mode 100644 index 91e76c08ef..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaErrPtg.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link AreaErrPtg}. - */ -final class TestAreaErrPtg extends BaseTestPtg { - /** - * Tests reading a file containing this ptg. - */ - @Test - void testReading() throws IOException { - try (HSSFWorkbook workbook = loadWorkbook("AreaErrPtg.xls")) { - assertEquals("SUM(#REF!)", workbook.getSheetAt(0).getRow(0).getCell(2).getCellFormula(), - "Wrong formula string for area error"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaPtg.java deleted file mode 100644 index ea5a2cee50..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaPtg.java +++ /dev/null @@ -1,145 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.util.AreaReference; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link AreaPtg}. - */ -final class TestAreaPtg { - - AreaPtg relative; - AreaPtg absolute; - - @BeforeEach - void setUp() { - short firstRow=5; - short lastRow=13; - short firstCol=7; - short lastCol=17; - relative = new AreaPtg(firstRow,lastRow,firstCol,lastCol,true,true,true,true); - absolute = new AreaPtg(firstRow,lastRow,firstCol,lastCol,false,false,false,false); - } - - @Test - void testSortTopLeftToBottomRight() { - AreaPtg ptg = new AreaPtg(new AreaReference("A$1:$B5", SpreadsheetVersion.EXCEL2007)); - assertEquals("A$1:$B5", ptg.toFormulaString()); - ptg.setFirstColumn(3); - assertEquals("D$1:$B5", ptg.toFormulaString(), - "Area Ptg should not implicitly re-sort itself (except during construction)"); - ptg.sortTopLeftToBottomRight(); - assertEquals("$B$1:D5", ptg.toFormulaString(), - "Area Ptg should restore itself to top-left to lower-right order when explicitly asked"); - } - - @Test - void testSetColumnsAbsolute() { - resetColumns(absolute); - validateReference(true, absolute); - } - - @Test - void testSetColumnsRelative() { - resetColumns(relative); - validateReference(false, relative); - } - - private void validateReference(boolean abs, AreaPtg ref) { - String isWrong = " reference is not "+(abs?"absolute":"relative"); - assertEquals(abs,!ref.isFirstColRelative(),"First column" + isWrong); - assertEquals(abs,!ref.isLastColRelative(), "Last column" + isWrong); - assertEquals(abs,!ref.isFirstRowRelative(),"First row" + isWrong); - assertEquals(abs,!ref.isLastRowRelative(), "Last row" + isWrong); - } - - - private static void resetColumns(AreaPtg aptg) { - int fc = aptg.getFirstColumn(); - int lc = aptg.getLastColumn(); - aptg.setFirstColumn(fc); - aptg.setLastColumn(lc); - assertEquals(fc , aptg.getFirstColumn() ); - assertEquals(lc , aptg.getLastColumn() ); - } - - @Test - void testAbsoluteRelativeRefs() { - AreaPtg sca1 = new AreaPtg(4, 5, 6, 7, true, false, true, false); - AreaPtg sca2 = new AreaPtg(4, 5, 6, 7, false, true, false, true); - AreaPtg sca3 = new AreaPtg(5, 5, 7, 7, true, false, true, false); - AreaPtg sca4 = new AreaPtg(5, 5, 7, 7, false, true, false, true); - - assertEquals("G5:$H$6", sca1.toFormulaString(), "first rel., last abs."); - assertEquals("$G$5:H6", sca2.toFormulaString(), "first abs., last rel."); - assertEquals("H6:$H$6", sca3.toFormulaString(), "first rel., last abs."); - assertEquals("$H$6:H6", sca4.toFormulaString(), "first abs., last rel."); - - AreaPtg cla1 = cloneArea(sca1); - AreaPtg cla2 = cloneArea(sca2); - AreaPtg cla3 = cloneArea(sca3); - AreaPtg cla4 = cloneArea(sca4); - - assertEquals("G5:$H$6", cla1.toFormulaString(), "first rel., last abs."); - assertEquals("$G$5:H6", cla2.toFormulaString(), "first abs., last rel."); - assertEquals("H6:$H$6", cla3.toFormulaString(), "first rel., last abs."); - assertEquals("$H$6:H6", cla4.toFormulaString(), "first abs., last rel."); - } - - private AreaPtg cloneArea(AreaPtg a) { - return new AreaPtg( - a.getFirstRow(), a.getLastRow(), a.getFirstColumn(), a.getLastColumn(), - a.isFirstRowRelative(), a.isLastRowRelative(), a.isFirstColRelative(), a.isLastColRelative() - ); - } - - @Test - void testFormulaParser() { - String formula1="SUM($E$5:$E$6)"; - String expectedFormula1="SUM($F$5:$F$6)"; - String newFormula1 = shiftAllColumnsBy1(formula1); - assertEquals(expectedFormula1, newFormula1, "Absolute references changed"); - - String formula2="SUM(E5:E6)"; - String expectedFormula2="SUM(F5:F6)"; - String newFormula2 = shiftAllColumnsBy1(formula2); - assertEquals(expectedFormula2, newFormula2, "Relative references changed"); - } - - private static String shiftAllColumnsBy1(String formula) { - int letUsShiftColumn1By1Column=1; - Ptg[] ptgs = HSSFFormulaParser.parse(formula, null); - for (Ptg ptg : ptgs) { - if (ptg instanceof AreaPtg ) - { - AreaPtg aptg = (AreaPtg)ptg; - aptg.setFirstColumn((short)(aptg.getFirstColumn()+letUsShiftColumn1By1Column)); - aptg.setLastColumn((short)(aptg.getLastColumn()+letUsShiftColumn1By1Column)); - } - } - return HSSFFormulaParser.toFormulaString(null, ptgs); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java deleted file mode 100644 index c5a1b44bd0..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; -import org.apache.poi.util.LittleEndianInput; -import org.junit.jupiter.api.Test; - -/** - * Tests for ArrayPtg - */ -final class TestArrayPtg { - - private static final byte[] ENCODED_PTG_DATA = { - 0x40, - 0, 0, 0, 0, 0, 0, 0, - }; - private static final byte[] ENCODED_CONSTANT_DATA = { - 2, // 3 columns - 1, 0, // 2 rows - 4, 1, 0, 0, 0, 0, 0, 0, 0, // TRUE - 2, 4, 0, 0, 65, 66, 67, 68, // "ABCD" - 2, 1, 0, 0, 69, // "E" - 1, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 4, 0, 0, 0, 0, 0, 0, 0, 0, // FALSE - 2, 2, 0, 0, 70, 71, // "FG" - }; - - private static ArrayPtg create(byte[] initialData, byte[] constantData) { - ArrayInitialPtg ptgInit = new ArrayInitialPtg(TestcaseRecordInputStream.createLittleEndian(initialData)); - return ptgInit.finishReading(TestcaseRecordInputStream.createLittleEndian(constantData)); - } - - /** - * Lots of problems with ArrayPtg's decoding and encoding of the element value data - */ - @Test - void testReadWriteTokenValueBytes() { - ArrayPtg ptg = create(ENCODED_PTG_DATA, ENCODED_CONSTANT_DATA); - assertEquals(3, ptg.getColumnCount()); - assertEquals(2, ptg.getRowCount()); - Object[][] values = ptg.getTokenArrayValues(); - assertEquals(2, values.length); - - - assertEquals(Boolean.TRUE, values[0][0]); - assertEquals("ABCD", values[0][1]); - assertEquals(0d, values[1][0]); - assertEquals(Boolean.FALSE, values[1][1]); - assertEquals("FG", values[1][2]); - - byte[] outBuf = new byte[ENCODED_CONSTANT_DATA.length]; - ptg.writeTokenValueBytes(new LittleEndianByteArrayOutputStream(outBuf, 0)); - - assertNotEquals(4, outBuf[0], "Identified bug 42564b"); - assertArrayEquals(ENCODED_CONSTANT_DATA, outBuf); - } - - - /** - * Excel stores array elements column by column. This test makes sure POI does the same. - */ - @Test - void testElementOrdering() { - ArrayPtg ptg = create(ENCODED_PTG_DATA, ENCODED_CONSTANT_DATA); - assertEquals(3, ptg.getColumnCount()); - assertEquals(2, ptg.getRowCount()); - - assertEquals(0, ptg.getValueIndex(0, 0)); - assertEquals(1, ptg.getValueIndex(1, 0)); - assertEquals(2, ptg.getValueIndex(2, 0)); - assertEquals(3, ptg.getValueIndex(0, 1)); - assertEquals(4, ptg.getValueIndex(1, 1)); - assertEquals(5, ptg.getValueIndex(2, 1)); - } - - /** - * Test for a bug which was temporarily introduced by the fix for bug 42564. - * A spreadsheet was added to make the ordering clearer. - */ - @Test - void testElementOrderingInSpreadsheet() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex42564-elementOrder.xls"); - - // The formula has an array with 3 rows and 5 columns - String formula = wb.getSheetAt(0).getRow(0).getCell(0).getCellFormula(); - - assertNotEquals("Identified bug 42564 b", "SUM({1,6,11;2,7,12;3,8,13;4,9,14;5,10,15})", formula); - assertEquals("SUM({1,2,3,4,5;6,7,8,9,10;11,12,13,14,15})", formula); - } - - @Test - void testToFormulaString() { - ArrayPtg ptg = create(ENCODED_PTG_DATA, ENCODED_CONSTANT_DATA); - // bug 45380 - Unexpected constant class (java.lang.Boolean) - String actualFormula = ptg.toFormulaString(); - assertEquals("{TRUE,\"ABCD\",\"E\";0,FALSE,\"FG\"}", actualFormula); - } - - /** - * worth checking since AttrPtg.sid=0x20 and Ptg.CLASS_* = (0x00, 0x20, and 0x40) - */ - @Test - void testOperandClassDecoding() { - confirmOperandClassDecoding(Ptg.CLASS_REF); - confirmOperandClassDecoding(Ptg.CLASS_VALUE); - confirmOperandClassDecoding(Ptg.CLASS_ARRAY); - } - - private static void confirmOperandClassDecoding(byte operandClass) { - byte[] fullData = concat(ENCODED_PTG_DATA, ENCODED_CONSTANT_DATA); - - // Force encoded operand class for tArray - fullData[0] = (byte) (ArrayPtg.sid + operandClass); - - LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(fullData); - - Ptg[] ptgs = Ptg.readTokens(ENCODED_PTG_DATA.length, in); - assertEquals(1, ptgs.length); - ArrayPtg aPtg = (ArrayPtg) ptgs[0]; - assertEquals(operandClass, aPtg.getPtgClass()); - } - - private static byte[] concat(byte[] a, byte[] b) { - byte[] result = new byte[a.length + b.length]; - System.arraycopy(a, 0, result, 0, a.length); - System.arraycopy(b, 0, result, a.length, b.length); - return result; - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestAttrPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestAttrPtg.java deleted file mode 100644 index 142f4a574f..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestAttrPtg.java +++ /dev/null @@ -1,45 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndianInput; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link AttrPtg}. - */ -final class TestAttrPtg extends BaseTestPtg { - - /** - * Fix for bug visible around svn r706772. - */ - @Test - void testReserializeAttrChoose() { - byte[] data = HexRead.readFromString("19, 04, 03, 00, 08, 00, 11, 00, 1A, 00, 23, 00"); - LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(data); - Ptg[] ptgs = Ptg.readTokens(data.length, in); - byte[] data2 = new byte[data.length]; - // ArrayIndexOutOfBoundsException -> incorrect re-serialization of tAttrChoose - Ptg.serializePtgs(ptgs, data2, 0); - assertArrayEquals(data, data2); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestErrPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestErrPtg.java deleted file mode 100644 index bddba7ff54..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestErrPtg.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link ErrPtg}. - */ -final class TestErrPtg extends BaseTestPtg { - /** - * Tests reading a file containing this ptg. - */ - @Test - void testReading() throws IOException { - try (HSSFWorkbook workbook = loadWorkbook("ErrPtg.xls")) { - HSSFCell cell = workbook.getSheetAt(0).getRow(3).getCell(0); - assertEquals(4.0, cell.getNumericCellValue(), 0.0, "Wrong cell value"); - assertEquals("ERROR.TYPE(#REF!)", cell.getCellFormula(), "Wrong cell formula"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalFunctionFormulas.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalFunctionFormulas.java deleted file mode 100644 index fedc639764..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalFunctionFormulas.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.jupiter.api.Test; - -/** - * Tests for functions from external workbooks (e.g. YEARFRAC). - */ -final class TestExternalFunctionFormulas { - - /** - * tests NameXPtg.toFormulaString(Workbook) and logic in Workbook below that - */ - @Test - void testReadFormulaContainingExternalFunction() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("externalFunctionExample.xls"); - - String expectedFormula = "YEARFRAC(B1,C1)"; - HSSFSheet sht = wb.getSheetAt(0); - String cellFormula = sht.getRow(0).getCell(0).getCellFormula(); - assertEquals(expectedFormula, cellFormula); - - wb.close(); - } - - @Test - void testParse() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("externalFunctionExample.xls"); - Ptg[] ptgs = HSSFFormulaParser.parse("YEARFRAC(B1,C1)", wb); - assertEquals(4, ptgs.length); - assertEquals(NameXPtg.class, ptgs[0].getClass()); - - wb.getSheetAt(0).getRow(0).createCell(6).setCellFormula("YEARFRAC(C1,B1)"); -// if (false) { -// // In case you fancy checking in excel -// try { -// File tempFile = TempFile.createTempFile("testExtFunc", ".xls"); -// FileOutputStream fout = new FileOutputStream(tempFile); -// wb.write(fout); -// fout.close(); -// System.out.println("check out " + tempFile.getAbsolutePath()); -// } catch (IOException e) { -// throw new RuntimeException(e); -// } -// } - wb.close(); - } - - @Test - void testEvaluate() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("externalFunctionExample.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - confirmCellEval(sheet, 0, 0, fe, "YEARFRAC(B1,C1)", 29.0/90.0); - confirmCellEval(sheet, 1, 0, fe, "YEARFRAC(B2,C2)", 0.0); - confirmCellEval(sheet, 2, 0, fe, "YEARFRAC(B3,C3,D3)", 0.0); - confirmCellEval(sheet, 3, 0, fe, "IF(ISEVEN(3),1.2,1.6)", 1.6); - confirmCellEval(sheet, 4, 0, fe, "IF(ISODD(3),1.2,1.6)", 1.2); - wb.close(); - } - - private static void confirmCellEval(HSSFSheet sheet, int rowIx, int colIx, - HSSFFormulaEvaluator fe, String expectedFormula, double expectedResult) { - HSSFCell cell = sheet.getRow(rowIx).getCell(colIx); - assertEquals(expectedFormula, cell.getCellFormula()); - CellValue cv = fe.evaluate(cell); - assertEquals(expectedResult, cv.getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalNameReference.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalNameReference.java deleted file mode 100644 index 0c582c5cf7..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalNameReference.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -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.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; - -/** - * Tests for proper calculation of named ranges from external workbooks. - */ -final class TestExternalNameReference { - double MARKUP_COST_1 = 1.8d; - double MARKUP_COST_2 = 1.5d; - double PART_COST = 12.3d; - double NEW_QUANT = 7.0d; - double NEW_PART_COST = 15.3d; - /** - * tests NameXPtg for external cell reference by name and logic in Workbook below that - */ - @Test - void testReadCalcSheet() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("XRefCalc.xls"); - HSSFName name = wb.getName("QUANT"); - assertNotNull(name); - assertEquals("Sheet1!$A$2", name.getRefersToFormula()); - name = wb.getName("PART"); - assertNotNull(name); - assertEquals("Sheet1!$B$2", name.getRefersToFormula()); - assertEquals("x123",wb.getSheet("Sheet1").getRow(1).getCell(1).getStringCellValue()); - name = wb.getName("UNITCOST"); - assertNotNull(name); - assertEquals("Sheet1!$C$2", name.getRefersToFormula()); - name = wb.getName("UNITCOST"); - assertNotNull(name); - CellReference cellRef = new CellReference(name.getRefersToFormula()); - HSSFCell cell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell(cellRef.getCol()); - assertEquals("VLOOKUP(PART,COSTS,2,FALSE)",cell.getCellFormula()); - name = wb.getName("COST"); - assertNotNull(name); - assertEquals("Sheet1!$D$2", name.getRefersToFormula()); - name = wb.getName("COST"); - assertNotNull(name); - cellRef = new CellReference(name.getRefersToFormula()); - cell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell(cellRef.getCol()); - assertEquals("UNITCOST*Quant",cell.getCellFormula()); - name = wb.getName("TOTALCOST"); - assertNotNull(name); - assertEquals("Sheet1!$E$2", name.getRefersToFormula()); - name = wb.getName("TOTALCOST"); - assertNotNull(name); - cellRef = new CellReference(name.getRefersToFormula()); - cell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell(cellRef.getCol()); - assertEquals("Cost*Markup_Cost",cell.getCellFormula()); - } - - @Test - void testReadReferencedSheet() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("XRefCalcData.xls"); - HSSFName name = wb.getName("COSTS"); - assertNotNull(name); - assertEquals("CostSheet!$A$2:$B$3", name.getRefersToFormula()); - assertEquals("x123",wb.getSheet("CostSheet").getRow(1).getCell(0).getStringCellValue()); - assertEquals(PART_COST,wb.getSheet("CostSheet").getRow(1).getCell(1).getNumericCellValue(), 0); - name = wb.getName("Markup_Cost"); - assertNotNull(name); - assertEquals("MarkupSheet!$B$1", name.getRefersToFormula()); - assertEquals(MARKUP_COST_1,wb.getSheet("MarkupSheet").getRow(0).getCell(1).getNumericCellValue(), 0); - } - - @Test - void testEvaluate() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("XRefCalc.xls"); - HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook("XRefCalcData.xls"); - HSSFName name = wb.getName("QUANT"); - assertNotNull(name); - CellReference cellRef = new CellReference(name.getRefersToFormula()); - HSSFCell cell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell(cellRef.getCol()); - cell.setCellValue(NEW_QUANT); - cell = wb2.getSheet("CostSheet").getRow(1).getCell(1); - cell.setCellValue(NEW_PART_COST); - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); - HSSFFormulaEvaluator evaluatorCost = new HSSFFormulaEvaluator(wb2); - String[] bookNames = { "XRefCalc.xls", "XRefCalcData.xls" }; - HSSFFormulaEvaluator[] evaluators = { evaluator, evaluatorCost, }; - HSSFFormulaEvaluator.setupEnvironment(bookNames, evaluators); - name = wb.getName("UNITCOST"); - assertNotNull(name); - cellRef = new CellReference(name.getRefersToFormula()); - HSSFCell uccell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell(cellRef.getCol()); - name = wb.getName("COST"); - assertNotNull(name); - cellRef = new CellReference(name.getRefersToFormula()); - HSSFCell ccell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell(cellRef.getCol()); - name = wb.getName("TOTALCOST"); - assertNotNull(name); - cellRef = new CellReference(name.getRefersToFormula()); - HSSFCell tccell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell(cellRef.getCol()); - evaluator.evaluateFormulaCell(uccell); - evaluator.evaluateFormulaCell(ccell); - evaluator.evaluateFormulaCell(tccell); - assertEquals(NEW_PART_COST, uccell.getNumericCellValue(), 0); - assertEquals(NEW_PART_COST*NEW_QUANT, ccell.getNumericCellValue(), 0); - assertEquals(NEW_PART_COST*NEW_QUANT*MARKUP_COST_2, tccell.getNumericCellValue(), 0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncPtg.java deleted file mode 100644 index fd6027fa93..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncPtg.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.jupiter.api.Test; - -/** - * Make sure the FuncPtg performs as expected - */ -final class TestFuncPtg { - - @Test - void testRead() { - // This function index represents the LEN() function - byte[] fakeData = { 0x20, 0x00,}; - - FuncPtg ptg = FuncPtg.create(TestcaseRecordInputStream.createLittleEndian(fakeData) ); - assertEquals( 0x20, ptg.getFunctionIndex(), "Len formula index is not 32(20H)" ); - assertEquals( 1, ptg.getNumberOfOperands(), "Number of operands in the len formula" ); - assertEquals( "LEN", ptg.getName(), "Function Name" ); - assertEquals( 3, ptg.getSize(), "Ptg Size" ); - } - - @Test - void testNumberOfOperands() { - FuncPtg funcPtg = FuncPtg.create(27); // ROUND() - takes 2 args - assertEquals(2, funcPtg.getNumberOfOperands()); - assertEquals("ROUND", funcPtg.getName()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncVarPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncVarPtg.java deleted file mode 100644 index 2eb91217cb..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncVarPtg.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; - -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * @author Josh Micich - */ -final class TestFuncVarPtg { - - /** - * The first fix for bugzilla 44675 broke the encoding of SUM formulas (and probably others). - * The operand classes of the parameters to SUM() should be coerced to 'reference' not 'value'. - * In the case of SUM, Excel evaluates the formula to '#VALUE!' if a parameter operand class is - * wrong. In other cases Excel seems to tolerate bad operand classes.

- * This functionality is related to the setParameterRVA() methods of FormulaParser - */ - @Test - void testOperandClass() { - HSSFWorkbook book = new HSSFWorkbook(); - Ptg[] ptgs = HSSFFormulaParser.parse("sum(A1:A2)", book); - assertEquals(2, ptgs.length); - assertEquals(AreaPtg.class, ptgs[0].getClass()); - - switch(ptgs[0].getPtgClass()) { - case Ptg.CLASS_REF: - // correct behaviour - break; - case Ptg.CLASS_VALUE: - fail("Identified bug 44675b"); - break; - default: - fail("Unexpected operand class"); - break; - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestIntersectionPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestIntersectionPtg.java deleted file mode 100644 index 91ed33b1e9..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestIntersectionPtg.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link IntersectionPtg}. - */ -final class TestIntersectionPtg extends BaseTestPtg { - /** - * Tests reading a file containing this ptg. - */ - @Test - void testReading() throws IOException { - try (HSSFWorkbook workbook = loadWorkbook("IntersectionPtg.xls")) { - HSSFCell cell = workbook.getSheetAt(0).getRow(4).getCell(2); - assertEquals(5.0, cell.getNumericCellValue(), 0.0, "Wrong cell value"); - assertEquals("SUM(A1:B2 B2:C3)", cell.getCellFormula(), "Wrong cell formula"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestPercentPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestPercentPtg.java deleted file mode 100644 index 7a806f15cd..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestPercentPtg.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link PercentPtg}. - */ -final class TestPercentPtg extends BaseTestPtg { - /** - * Tests reading a file containing this ptg. - */ - @Test - void testReading() throws IOException { - try (HSSFWorkbook workbook = loadWorkbook("PercentPtg.xls")) { - HSSFSheet sheet = workbook.getSheetAt(0); - - assertEquals(53000.0, sheet.getRow(0).getCell(0).getNumericCellValue(), 0.0, - "Wrong numeric value for original number"); - assertEquals(5300.0, sheet.getRow(1).getCell(0).getNumericCellValue(), 0.0, - "Wrong numeric value for percent formula result"); - assertEquals("A1*10%", sheet.getRow(1).getCell(0).getCellFormula(), - "Wrong formula string for percent formula"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestRangePtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestRangePtg.java deleted file mode 100644 index 6ff906c96c..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestRangePtg.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link RangePtg}. - */ -final class TestRangePtg extends BaseTestPtg { - /** - * Tests reading a file containing this ptg. - */ - @Test - void testReading() throws IOException { - try (HSSFWorkbook workbook = loadWorkbook("RangePtg.xls")) { - HSSFCell cell = workbook.getSheetAt(0).getRow(3).getCell(1); - assertEquals(10.0, cell.getNumericCellValue(), 0.0, "Wrong cell value"); - assertEquals("SUM(pineapple:B2)", cell.getCellFormula(), "Wrong cell formula"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestRef3DPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestRef3DPtg.java deleted file mode 100644 index 2a1b44e6fc..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestRef3DPtg.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for Ref3DPtg - */ -final class TestRef3DPtg extends BaseTestPtg { - @Test - void testToFormulaString() throws IOException { - - Ref3DPtg target = new Ref3DPtg("A1", (short)0); - - try (HSSFWorkbook wb = createWorkbookWithSheet("my sheet")) { - HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(wb); - assertEquals("'my sheet'!A1", target.toFormulaString(book)); - - wb.setSheetName(0, "ProfitAndLoss"); - assertEquals("ProfitAndLoss!A1", target.toFormulaString(book)); - - wb.setSheetName(0, "profit+loss"); - assertEquals("'profit+loss'!A1", target.toFormulaString(book)); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestReferencePtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestReferencePtg.java deleted file mode 100644 index f4170286ca..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestReferencePtg.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.LittleEndianInput; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link RefPtg}. - */ -final class TestReferencePtg { - /** - * Tests reading a file containing this ptg. - */ - @Test - void testReading() { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ReferencePtg.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - - // First row - assertEquals(55.0, sheet.getRow(0).getCell(0).getNumericCellValue(), 0.0, - "Wrong numeric value for original number"); - assertEquals(55.0, sheet.getRow(0).getCell(1).getNumericCellValue(), 0.0, - "Wrong numeric value for referemce"); - assertEquals("A1", sheet.getRow(0).getCell(1).getCellFormula(), "Wrong formula string for reference"); - - // Now moving over the 2**15 boundary - // (Remember that excel row (n) is poi row (n-1) - assertEquals(32767.0, sheet.getRow(32766).getCell(0).getNumericCellValue(), 0.0, "Wrong numeric value for original number"); - assertEquals(32767.0, sheet.getRow(32766).getCell(1).getNumericCellValue(), 0.0, "Wrong numeric value for referemce"); - assertEquals("A32767", sheet.getRow(32766).getCell(1).getCellFormula(), "Wrong formula string for reference"); - - assertEquals(32768.0, sheet.getRow(32767).getCell(0).getNumericCellValue(), 0.0, "Wrong numeric value for original number"); - assertEquals(32768.0, sheet.getRow(32767).getCell(1).getNumericCellValue(), 0.0, "Wrong numeric value for referemce"); - assertEquals("A32768", sheet.getRow(32767).getCell(1).getCellFormula(), "Wrong formula string for reference"); - - assertEquals(32769.0, sheet.getRow(32768).getCell(0).getNumericCellValue(), 0.0, "Wrong numeric value for original number"); - assertEquals(32769.0, sheet.getRow(32768).getCell(1).getNumericCellValue(), 0.0, "Wrong numeric value for referemce"); - assertEquals("A32769", sheet.getRow(32768).getCell(1).getCellFormula(), "Wrong formula string for reference"); - - assertEquals(32770.0, sheet.getRow(32769).getCell(0).getNumericCellValue(), 0.0, "Wrong numeric value for original number"); - assertEquals(32770.0, sheet.getRow(32769).getCell(1).getNumericCellValue(), 0.0, "Wrong numeric value for referemce"); - assertEquals("A32770", sheet.getRow(32769).getCell(1).getCellFormula(), "Wrong formula string for reference"); - } - - @Test - void testBug44921() throws IOException { - try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex44921-21902.xls")) { - assertDoesNotThrow(() -> HSSFTestDataSamples.writeOutAndReadBack(wb)); - } - } - - private static final byte[] tRefN_data = { - 0x2C, 33, 44, 55, 66, - }; - - @Test - void testReadWrite_tRefN_bug45091() { - LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(tRefN_data); - Ptg[] ptgs = Ptg.readTokens(tRefN_data.length, in); - byte[] outData = new byte[5]; - Ptg.serializePtgs(ptgs, outData, 0); - assertNotEquals(0x24, outData[0], "Identified bug 45091"); - assertArrayEquals(tRefN_data, outData); - } - - /** - * test that RefPtgBase can handle references with column index greater than 255, - * see Bugzilla 50096 - */ - @Test - void testColumnGreater255() { - RefPtgBase ptg; - ptg = new RefPtg("IW1"); - assertEquals(256, ptg.getColumn()); - assertEquals("IW1", ptg.formatReferenceAsString()); - - ptg = new RefPtg("JA1"); - assertEquals(260, ptg.getColumn()); - assertEquals("JA1", ptg.formatReferenceAsString()); - } -} - diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java deleted file mode 100644 index 7b85995a02..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link UnionPtg}. - */ -final class TestUnionPtg extends BaseTestPtg { - /** - * Tests reading a file containing this ptg. - */ - @Test - void testReading() throws IOException { - try (HSSFWorkbook workbook = loadWorkbook("UnionPtg.xls")) { - HSSFCell cell = workbook.getSheetAt(0).getRow(4).getCell(2); - assertEquals(24.0, cell.getNumericCellValue(), 0.0, "Wrong cell value"); - assertEquals("SUM(A1:B2,B2:C3)", cell.getCellFormula(), "Wrong cell formula"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/udf/TestUDFFinder.java b/src/testcases/org/apache/poi/ss/formula/udf/TestUDFFinder.java deleted file mode 100644 index 9628c0af97..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/udf/TestUDFFinder.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.udf; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.util.stream.Stream; - -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.atp.AnalysisToolPak; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -public class TestUDFFinder { - public static Stream instances() { - UDFFinder notImplFinder = new DefaultUDFFinder( - new String[] { "NotImplemented" }, - new FreeRefFunction[] { TestUDFFinder::notImplemented } - ); - - AggregatingUDFFinder aggUDF = new AggregatingUDFFinder(notImplFinder); - aggUDF.add(AnalysisToolPak.instance); - - return Stream.of( - Arguments.of("NotImplemented", notImplFinder), - Arguments.of("BESSELJ", new AggregatingUDFFinder(AnalysisToolPak.instance)), - Arguments.of("BESSELJ", aggUDF) - ); - } - - @ParameterizedTest(name = "{0}") - @MethodSource("instances") - void confirmFindFunction(String functionName, UDFFinder instance) { - FreeRefFunction func = instance.findFunction(functionName); - assertNotNull(func); - } - - private static ValueEval notImplemented(ValueEval[] args, OperationEvaluationContext ec) { - throw new RuntimeException("not implemented"); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBorderStyle.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestBorderStyle.java deleted file mode 100644 index dbd7e5fc46..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBorderStyle.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - 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. - - 2012 - Alfresco Software, Ltd. - Alfresco Software has modified source of this file - The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.junit.jupiter.api.Test; - -/** - * Tests of {@link BorderStyle} - */ -public abstract class BaseTestBorderStyle { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestBorderStyle(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - /** - * Test that we use the specified locale when deciding - * how to format normal numbers - */ - @Test - void testBorderStyle() throws IOException { - String ext = _testDataProvider.getStandardFileNameExtension(); - Workbook wb = _testDataProvider.openSampleWorkbook("59264."+ext); - Sheet sh = wb.getSheetAt(0); - - assertBorderStyleEquals(BorderStyle.NONE, getDiagonalCell(sh, 0)); - assertBorderStyleEquals(BorderStyle.THIN, getDiagonalCell(sh, 1)); - assertBorderStyleEquals(BorderStyle.MEDIUM, getDiagonalCell(sh, 2)); - assertBorderStyleEquals(BorderStyle.DASHED, getDiagonalCell(sh, 3)); - assertBorderStyleEquals(BorderStyle.DOTTED, getDiagonalCell(sh, 4)); - assertBorderStyleEquals(BorderStyle.THICK, getDiagonalCell(sh, 5)); - assertBorderStyleEquals(BorderStyle.DOUBLE, getDiagonalCell(sh, 6)); - assertBorderStyleEquals(BorderStyle.HAIR, getDiagonalCell(sh, 7)); - assertBorderStyleEquals(BorderStyle.MEDIUM_DASHED, getDiagonalCell(sh, 8)); - assertBorderStyleEquals(BorderStyle.DASH_DOT, getDiagonalCell(sh, 9)); - assertBorderStyleEquals(BorderStyle.MEDIUM_DASH_DOT, getDiagonalCell(sh, 10)); - assertBorderStyleEquals(BorderStyle.DASH_DOT_DOT, getDiagonalCell(sh, 11)); - assertBorderStyleEquals(BorderStyle.MEDIUM_DASH_DOT_DOT, getDiagonalCell(sh, 12)); - assertBorderStyleEquals(BorderStyle.SLANTED_DASH_DOT, getDiagonalCell(sh, 13)); - - wb.close(); - } - - private Cell getDiagonalCell(Sheet sheet, int n) { - return sheet.getRow(n).getCell(n); - } - - protected void assertBorderStyleEquals(BorderStyle expected, Cell cell) { - CellStyle style = cell.getCellStyle(); - assertEquals(expected, style.getBorderTop()); - assertEquals(expected, style.getBorderBottom()); - assertEquals(expected, style.getBorderLeft()); - assertEquals(expected, style.getBorderRight()); - } - -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java deleted file mode 100644 index bcd8bf272a..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java +++ /dev/null @@ -1,1849 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.apache.logging.log4j.util.Unbox.box; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.awt.font.FontRenderContext; -import java.awt.font.TextAttribute; -import java.awt.font.TextLayout; -import java.awt.geom.Rectangle2D; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.text.AttributedString; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.FileMagic; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.apache.poi.ss.util.PaneInformation; -import org.apache.poi.ss.util.SheetUtil; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * A base class for bugzilla issues that can be described in terms of common ss interfaces. - */ -public abstract class BaseTestBugzillaIssues { - private static final Logger LOG = LogManager.getLogger(BaseTestBugzillaIssues.class); - - private static final String TEST_32 = "Some text with 32 characters to "; - private static final String TEST_255 = "Some very long text that is exactly 255 characters, which are allowed here, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla....."; - private static final String TEST_256 = "Some very long text that is longer than the 255 characters allowed in HSSF here, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla1"; - private static final String TEST_SPECIAL_TITLE = "special \n\t\r\u0002characters"; - private static final String TEST_SPECIAL = "Some text with special \n\t\r\u0002characters to s"; - - private final ITestDataProvider _testDataProvider; - - protected BaseTestBugzillaIssues(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - /** - * Unlike org.junit.Assert.assertEquals(double expected, double actual, double delta), - * where delta is an absolute error value, this function's factor is a relative error, - * so it's easier to express "actual is within 5% of expected". - */ - private static void assertAlmostEquals(double expected, double actual, float factor) { - double diff = Math.abs(expected - actual); - double fuzz = expected * factor; - assertTrue(diff <= fuzz, actual + " not within " + fuzz + " of " + expected); - } - - /** - * Test writing a hyperlink - * Open resulting sheet in Excel and check that A1 contains a hyperlink - * - * Also tests bug 15353 (problems with hyperlinks to Google) - */ - @Test - public final void bug23094() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet s = wb1.createSheet(); - Row r = s.createRow(0); - r.createCell(0).setCellFormula("HYPERLINK(\"http://jakarta.apache.org\",\"Jakarta\")"); - r.createCell(1).setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")"); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - r = wb2.getSheetAt(0).getRow(0); - - Cell cell_0 = r.getCell(0); - assertEquals("HYPERLINK(\"http://jakarta.apache.org\",\"Jakarta\")", cell_0.getCellFormula()); - Cell cell_1 = r.getCell(1); - assertEquals("HYPERLINK(\"http://google.com\",\"Google\")", cell_1.getCellFormula()); - } - } - } - - /** - * test writing a file with large number of unique strings, - * open resulting file in Excel to check results! - */ - @Test - public final void bug15375_2() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet(); - CreationHelper factory = wb1.getCreationHelper(); - - final int num = wb1 instanceof HSSFWorkbook ? 6000 : 1000; - - for (int i = 0; i < num; i++) { - Row row = sheet.createRow(i); - - Cell cell = row.createCell(0); - cell.setCellValue(factory.createRichTextString("Test1" + i)); - cell = row.createCell(1); - cell.setCellValue(factory.createRichTextString("Test2" + i)); - cell = row.createCell(2); - cell.setCellValue(factory.createRichTextString("Test3" + i)); - } - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - sheet = wb2.getSheetAt(0); - for (int i = 0; i < num; i++) { - Row row = sheet.getRow(i); - - assertEquals("Test1" + i, row.getCell(0).getStringCellValue()); - assertEquals("Test2" + i, row.getCell(1).getStringCellValue()); - assertEquals("Test3" + i, row.getCell(2).getStringCellValue()); - } - } - } - } - - /** - * Merged regions were being removed from the parent in cloned sheets - */ - @Test - protected void bug22720() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - wb.createSheet("TEST"); - Sheet template = wb.getSheetAt(0); - - assertEquals(0, template.addMergedRegion(new CellRangeAddress(0, 1, 0, 2))); - assertEquals(1, template.addMergedRegion(new CellRangeAddress(2, 3, 0, 2))); - - Sheet clone = wb.cloneSheet(0); - int originalMerged = template.getNumMergedRegions(); - assertEquals(2, originalMerged, "2 merged regions"); - - //remove merged regions from clone - for (int i = template.getNumMergedRegions() - 1; i >= 0; i--) { - clone.removeMergedRegion(i); - } - - assertEquals(originalMerged, template.getNumMergedRegions(), "Original Sheet's Merged Regions were removed"); - //check if template's merged regions are OK - if (template.getNumMergedRegions() > 0) { - // fetch the first merged region...EXCEPTION OCCURS HERE - template.getMergedRegion(0); - } - } - } - - @Test - public final void bug28031() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet(); - wb1.setSheetName(0, "Sheet1"); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - String formulaText = - "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()); - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - cell = wb2.getSheetAt(0).getRow(0).getCell(0); - assertEquals("IF(ROUND(A2*B2*C2,2)>ROUND(B2*D2,2),ROUND(A2*B2*C2,2),ROUND(B2*D2,2))", cell.getCellFormula()); - } - } - } - - /** - * Bug 21334: "File error: data may have been lost" with a file - * that contains macros and this formula: - * {=SUM(IF(FREQUENCY(IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),""),IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),""))>0,1))} - */ - @Test - public final void bug21334() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sh = wb1.createSheet(); - Cell cell = sh.createRow(0).createCell(0); - String formula = "SUM(IF(FREQUENCY(IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),\"\"),IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),\"\"))>0,1))"; - cell.setCellFormula(formula); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - Cell cell_sv = wb2.getSheetAt(0).getRow(0).getCell(0); - assertEquals(formula, cell_sv.getCellFormula()); - } - } - } - - /** another test for the number of unique strings issue - *test opening the resulting file in Excel*/ - @Test - public final void bug22568() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet("ExcelTest"); - - int col_cnt = 3; - int rw_cnt = 2000; - - Row rw; - rw = sheet.createRow(0); - //Header row - for (int j = 0; j < col_cnt; j++) { - Cell cell = rw.createCell(j); - cell.setCellValue("Col " + (j + 1)); - } - - for (int i = 1; i < rw_cnt; i++) { - rw = sheet.createRow(i); - for (int j = 0; j < col_cnt; j++) { - Cell cell = rw.createCell(j); - cell.setCellValue("Row:" + (i + 1) + ",Column:" + (j + 1)); - } - } - - sheet.setDefaultColumnWidth(18); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - sheet = wb2.getSheetAt(0); - rw = sheet.getRow(0); - //Header row - for (int j = 0; j < col_cnt; j++) { - Cell cell = rw.getCell(j); - assertEquals("Col " + (j + 1), cell.getStringCellValue()); - } - for (int i = 1; i < rw_cnt; i++) { - rw = sheet.getRow(i); - for (int j = 0; j < col_cnt; j++) { - Cell cell = rw.getCell(j); - assertEquals("Row:" + (i + 1) + ",Column:" + (j + 1), cell.getStringCellValue()); - } - } - } - } - } - - /** - * Bug 42448: Can't parse SUMPRODUCT(A!C7:A!C67, B8:B68) / B69 - */ - @Test - public final void bug42448() throws IOException { - String exp = "SUMPRODUCT(A!C7:A!C67, B8:B68) / B69"; - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Cell cell = wb1.createSheet().createRow(0).createCell(0); - cell.setCellFormula(exp); - wb1.createSheet("A"); - cell.setCellFormula(exp); - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - String act = wb2.getSheetAt(0).getRow(0).getCell(0).getCellFormula(); - // XSSF saves formula as-is, HSSF saves as PTG and strips the whitespace - assertEquals(exp.replace(" ",""), act.replace(" ", "")); - } - } - } - - @Test - protected void bug18800() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - wb1.createSheet("TEST"); - Sheet sheet = wb1.cloneSheet(0); - wb1.setSheetName(1, "CLONE"); - sheet.createRow(0).createCell(0).setCellValue("Test"); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - sheet = wb2.getSheet("CLONE"); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - assertEquals("Test", cell.getRichStringCellValue().getString()); - } - } - } - - private static void addNewSheetWithCellsA1toD4(Workbook book, int sheet) { - - Sheet sht = book .createSheet("s" + sheet); - for (int r=0; r < 4; r++) { - - Row row = sht.createRow (r); - for (int c=0; c < 4; c++) { - - Cell cel = row.createCell(c); - cel.setCellValue(sheet*100 + r*10 + c); - } - } - } - - @Test - void bug43093() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - - addNewSheetWithCellsA1toD4(wb, 1); - addNewSheetWithCellsA1toD4(wb, 2); - addNewSheetWithCellsA1toD4(wb, 3); - addNewSheetWithCellsA1toD4(wb, 4); - - Sheet s2 = wb.getSheet("s2"); - Row s2r3 = s2.getRow(3); - Cell s2E4 = s2r3.createCell(4); - s2E4.setCellFormula("SUM(s3!B2:C3)"); - - FormulaEvaluator eva = wb.getCreationHelper().createFormulaEvaluator(); - double d = eva.evaluate(s2E4).getNumberValue(); - - assertEquals(d, (311 + 312 + 321 + 322), 0.0000001); - - } - } - - @Test - protected void bug46729_testMaxFunctionArguments() throws IOException { - String[] func = {"COUNT", "AVERAGE", "MAX", "MIN", "OR", "SUBTOTAL", "SKEW"}; - - SpreadsheetVersion ssVersion = _testDataProvider.getSpreadsheetVersion(); - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = wb.createSheet().createRow(0).createCell(0); - - String fmla; - for (String name : func) { - - fmla = createFunction(name, 5); - cell.setCellFormula(fmla); - - fmla = createFunction(name, ssVersion.getMaxFunctionArgs()); - cell.setCellFormula(fmla); - - FormulaParseException e = assertThrows(FormulaParseException.class, () -> { - String fmla2 = createFunction(name, ssVersion.getMaxFunctionArgs() + 1); - cell.setCellFormula(fmla2); - }); - assertTrue(e.getMessage().startsWith("Too many arguments to function '" + name + "'")); - } - } - } - - private static String createFunction(String name, int maxArgs){ - StringBuilder fmla = new StringBuilder(); - fmla.append(name); - fmla.append("("); - for(int i=0; i < maxArgs; i++){ - if(i > 0) { - fmla.append(','); - } - fmla.append("A1"); - } - fmla.append(")"); - return fmla.toString(); - } - - @Test - public final void bug50681_testAutoSize() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("Sheet1"); - _testDataProvider.trackAllColumnsForAutosizing(sheet); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - - String longValue = "www.hostname.com, www.hostname.com, " + - "www.hostname.com, www.hostname.com, www.hostname.com, " + - "www.hostname.com, www.hostname.com, www.hostname.com, " + - "www.hostname.com, www.hostname.com, www.hostname.com, " + - "www.hostname.com, www.hostname.com, www.hostname.com, " + - "www.hostname.com, www.hostname.com, www.hostname.com, www.hostname.com"; - - cell0.setCellValue(longValue); - - // autoSize will fail if required fonts are not installed, skip this test then - Font font = wb.getFontAt(cell0.getCellStyle().getFontIndex()); - assumeTrue(SheetUtil.canComputeColumnWidth(font), - "Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font); - - assertEquals(0, cell0.getCellStyle().getIndention(), "Expecting no indentation in this test"); - assertEquals(0, cell0.getCellStyle().getRotation(), "Expecting no rotation in this test"); - - // check computing size up to a large size -// StringBuilder b = new StringBuilder(); -// for(int i = 0;i < longValue.length()*5;i++) { -// b.append("w"); -// assertTrue("Had zero length starting at length " + i, computeCellWidthFixed(font, b.toString()) > 0); -// } - double widthManual = computeCellWidthManually(cell0, font); - double widthBeforeCell = SheetUtil.getCellWidth(cell0, 8, null, false); - double widthBeforeCol = SheetUtil.getColumnWidth(sheet, 0, false); - - String info = widthManual + "/" + widthBeforeCell + "/" + widthBeforeCol + "/" + - SheetUtil.canComputeColumnWidth(font) + "/" + computeCellWidthFixed(font, "1") + "/" + computeCellWidthFixed(font, "w") + "/" + - computeCellWidthFixed(font, "1w") + "/" + computeCellWidthFixed(font, "0000") + "/" + computeCellWidthFixed(font, longValue); - assertTrue(widthManual > 0, "Expected to have cell width > 0 when computing manually, but had " + info); - assertTrue(widthBeforeCell > 0, "Expected to have cell width > 0 BEFORE auto-size, but had " + info); - assertTrue(widthBeforeCol > 0, "Expected to have column width > 0 BEFORE auto-size, but had " + info); - - sheet.autoSizeColumn(0); - - double width = SheetUtil.getColumnWidth(sheet, 0, false); - assertTrue(width > 0, "Expected to have column width > 0 AFTER auto-size, but had " + width); - width = SheetUtil.getCellWidth(cell0, 8, null, false); - assertTrue(width > 0, "Expected to have cell width > 0 AFTER auto-size, but had " + width); - - assertEquals(255 * 256, sheet.getColumnWidth(0)); // maximum column width is 255 characters - sheet.setColumnWidth(0, sheet.getColumnWidth(0)); // Bug 50681 reports exception at this point - } - } - - @Test - public final void bug51622_testAutoSizeShouldRecognizeLeadingSpaces() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - _testDataProvider.trackAllColumnsForAutosizing(sheet); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(2); - - cell0.setCellValue("Test Column AutoSize"); - cell1.setCellValue(" Test Column AutoSize"); - cell2.setCellValue("Test Column AutoSize "); - - sheet.autoSizeColumn(0); - sheet.autoSizeColumn(1); - sheet.autoSizeColumn(2); - - int noWhitespaceColWidth = sheet.getColumnWidth(0); - int leadingWhitespaceColWidth = sheet.getColumnWidth(1); - int trailingWhitespaceColWidth = sheet.getColumnWidth(2); - - // Based on the amount of text and whitespace used, and the default font - // assume that the cell with whitespace should be at least 20% wider than - // the cell without whitespace. This number is arbitrary, but should be large - // enough to guarantee that the whitespace cell isn't wider due to chance. - // Experimentally, I calculated the ratio as 1.2478181, though this ratio may change - // if the default font or margins change. - final double expectedRatioThreshold = 1.2f; - double leadingWhitespaceRatio = ((double) leadingWhitespaceColWidth) / noWhitespaceColWidth; - double trailingWhitespaceRatio = ((double) leadingWhitespaceColWidth) / noWhitespaceColWidth; - - assertGreaterThan("leading whitespace is longer than no whitespace", - leadingWhitespaceRatio, expectedRatioThreshold); - assertGreaterThan("trailing whitespace is longer than no whitespace", - trailingWhitespaceRatio, expectedRatioThreshold); - assertEquals(leadingWhitespaceColWidth, trailingWhitespaceColWidth, - "cells with equal leading and trailing whitespace have equal width"); - - } - } - - /** - * Test if a > b. Fails if false. - */ - private void assertGreaterThan(String message, double a, double b) { - assertTrue(a > b, message + ": " + "Expected: " + a + " > " + b); - } - - // FIXME: this function is a self-fulfilling prophecy: this test will always pass as long - // as the code-under-test and the testcase code are written the same way (have the same bugs). - private double computeCellWidthManually(Cell cell0, Font font) { - final FontRenderContext fontRenderContext = new FontRenderContext(null, true, true); - RichTextString rt = cell0.getRichStringCellValue(); - String[] lines = rt.getString().split("\\n"); - assertEquals(1, lines.length); - String txt = lines[0] + "0"; - - AttributedString str = new AttributedString(txt); - copyAttributes(font, str, txt.length()); - - // TODO: support rich text fragments - /*if (rt.numFormattingRuns() > 0) { - }*/ - - TextLayout layout = new TextLayout(str.getIterator(), fontRenderContext); - double frameWidth = getFrameWidth(layout); - return (frameWidth / 8); - } - - private double getFrameWidth(TextLayout layout) { - Rectangle2D bounds = layout.getBounds(); - return bounds.getX() + bounds.getWidth(); - } - - private double computeCellWidthFixed(Font font, String txt) { - final FontRenderContext fontRenderContext = new FontRenderContext(null, true, true); - AttributedString str = new AttributedString(txt); - copyAttributes(font, str, txt.length()); - - TextLayout layout = new TextLayout(str.getIterator(), fontRenderContext); - return getFrameWidth(layout); - } - - private static void copyAttributes(Font font, AttributedString str, int endIdx) { - str.addAttribute(TextAttribute.FAMILY, font.getFontName(), 0, endIdx); - str.addAttribute(TextAttribute.SIZE, (float)font.getFontHeightInPoints()); - if (font.getBold()) { - str.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, 0, endIdx); - } - if (font.getItalic() ) { - str.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, 0, endIdx); - } - if (font.getUnderline() == Font.U_SINGLE ) { - str.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, 0, endIdx); - } - } - - /** - * CreateFreezePane column/row order check - */ - @Test - void bug49381() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - int colSplit = 1; - int rowSplit = 2; - int leftmostColumn = 3; - int topRow = 4; - - Sheet s = wb.createSheet(); - - // Populate - for (int rn = 0; rn <= topRow; rn++) { - Row r = s.createRow(rn); - for (int cn = 0; cn < leftmostColumn; cn++) { - Cell c = r.createCell(cn, CellType.NUMERIC); - c.setCellValue(100 * rn + cn); - } - } - - // Create the Freeze Pane - s.createFreezePane(colSplit, rowSplit, leftmostColumn, topRow); - PaneInformation paneInfo = s.getPaneInformation(); - - // Check it - assertEquals(colSplit, paneInfo.getVerticalSplitPosition()); - assertEquals(rowSplit, paneInfo.getHorizontalSplitPosition()); - assertEquals(leftmostColumn, paneInfo.getVerticalSplitLeftColumn()); - assertEquals(topRow, paneInfo.getHorizontalSplitTopRow()); - - - // Now a row only freezepane - s.createFreezePane(0, 3); - paneInfo = s.getPaneInformation(); - - assertEquals(0, paneInfo.getVerticalSplitPosition()); - assertEquals(3, paneInfo.getHorizontalSplitPosition()); - assertEquals(0, paneInfo.getVerticalSplitLeftColumn()); - assertEquals(3, paneInfo.getHorizontalSplitTopRow()); - - // Now a column only freezepane - s.createFreezePane(4, 0); - paneInfo = s.getPaneInformation(); - - assertEquals(4, paneInfo.getVerticalSplitPosition()); - assertEquals(0, paneInfo.getHorizontalSplitPosition()); - assertEquals(4, paneInfo.getVerticalSplitLeftColumn()); - assertEquals(0, paneInfo.getHorizontalSplitTopRow()); - } - } - - /** - * Test hyperlinks - * open resulting file in excel, and check that there is a link to Google - */ - @Test - void bug15353() throws IOException { - String hyperlinkF = "HYPERLINK(\"http://google.com\",\"Google\")"; - - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet("My sheet"); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellFormula(hyperlinkF); - - assertEquals(hyperlinkF, cell.getCellFormula()); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - sheet = wb2.getSheet("My Sheet"); - row = sheet.getRow(0); - cell = row.getCell(0); - - assertEquals(hyperlinkF, cell.getCellFormula()); - } - } - } - - /** - * HLookup and VLookup with optional arguments - */ - @Test - void bug51024() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet(); - Row r1 = s.createRow(0); - Row r2 = s.createRow(1); - - r1.createCell(0).setCellValue("v A1"); - r2.createCell(0).setCellValue("v A2"); - r1.createCell(1).setCellValue("v B1"); - - Cell c = r1.createCell(4); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - c.setCellFormula("VLOOKUP(\"v A1\", A1:B2, 1)"); - assertEquals("v A1", eval.evaluate(c).getStringValue()); - - c.setCellFormula("VLOOKUP(\"v A1\", A1:B2, 1, 1)"); - assertEquals("v A1", eval.evaluate(c).getStringValue()); - - c.setCellFormula("VLOOKUP(\"v A1\", A1:B2, 1, )"); - assertEquals("v A1", eval.evaluate(c).getStringValue()); - - - c.setCellFormula("HLOOKUP(\"v A1\", A1:B2, 1)"); - assertEquals("v A1", eval.evaluate(c).getStringValue()); - - c.setCellFormula("HLOOKUP(\"v A1\", A1:B2, 1, 1)"); - assertEquals("v A1", eval.evaluate(c).getStringValue()); - - c.setCellFormula("HLOOKUP(\"v A1\", A1:B2, 1, )"); - assertEquals("v A1", eval.evaluate(c).getStringValue()); - } - } - - @Test - void stackoverflow23114397() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - DataFormat format = wb.getCreationHelper().createDataFormat(); - - // How close the sizing should be, given that not all - // systems will have quite the same fonts on them - float fontAccuracy = 0.22f; - - // x% - CellStyle iPercent = wb.createCellStyle(); - iPercent.setDataFormat(format.getFormat("0%")); - // x.x% - CellStyle d1Percent = wb.createCellStyle(); - d1Percent.setDataFormat(format.getFormat("0.0%")); - // x.xx% - CellStyle d2Percent = wb.createCellStyle(); - d2Percent.setDataFormat(format.getFormat("0.00%")); - - Sheet s = wb.createSheet(); - _testDataProvider.trackAllColumnsForAutosizing(s); - Row r1 = s.createRow(0); - - for (int i = 0; i < 3; i++) { - r1.createCell(i, CellType.NUMERIC).setCellValue(0); - } - for (int i = 3; i < 6; i++) { - r1.createCell(i, CellType.NUMERIC).setCellValue(1); - } - for (int i = 6; i < 9; i++) { - r1.createCell(i, CellType.NUMERIC).setCellValue(0.12345); - } - for (int i = 9; i < 12; i++) { - r1.createCell(i, CellType.NUMERIC).setCellValue(1.2345); - } - for (int i = 0; i < 12; i += 3) { - r1.getCell(i).setCellStyle(iPercent); - r1.getCell(i + 1).setCellStyle(d1Percent); - r1.getCell(i + 2).setCellStyle(d2Percent); - } - for (int i = 0; i < 12; i++) { - s.autoSizeColumn(i); - } - - // Check the 0(.00)% ones - assertAlmostEquals(980, s.getColumnWidth(0), fontAccuracy); - assertAlmostEquals(1400, s.getColumnWidth(1), fontAccuracy); - assertAlmostEquals(1700, s.getColumnWidth(2), fontAccuracy); - - // Check the 100(.00)% ones - assertAlmostEquals(1500, s.getColumnWidth(3), fontAccuracy); - assertAlmostEquals(1950, s.getColumnWidth(4), fontAccuracy); - assertAlmostEquals(2225, s.getColumnWidth(5), fontAccuracy); - - // Check the 12(.34)% ones - assertAlmostEquals(1225, s.getColumnWidth(6), fontAccuracy); - assertAlmostEquals(1650, s.getColumnWidth(7), fontAccuracy); - assertAlmostEquals(1950, s.getColumnWidth(8), fontAccuracy); - - // Check the 123(.45)% ones - assertAlmostEquals(1500, s.getColumnWidth(9), fontAccuracy); - assertAlmostEquals(1950, s.getColumnWidth(10), fontAccuracy); - assertAlmostEquals(2225, s.getColumnWidth(11), fontAccuracy); - } - } - - /** - * =ISNUMBER(SEARCH("AM",A1)) evaluation - */ - @Test - void stackoverflow26437323() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet(); - Row r1 = s.createRow(0); - Row r2 = s.createRow(1); - - // A1 is a number - r1.createCell(0).setCellValue(1.1); - // B1 is a string, with the wanted text in it - r1.createCell(1).setCellValue("This is text with AM in it"); - // C1 is a string, with different text - r1.createCell(2).setCellValue("This some other text"); - // D1 is a blank cell - r1.createCell(3, CellType.BLANK); - // E1 is null - - // A2 will hold our test formulas - Cell cf = r2.createCell(0, CellType.FORMULA); - - - // First up, check that TRUE and ISLOGICAL both behave - cf.setCellFormula("TRUE()"); - cf = evaluateCell(wb, cf); - assertTrue(cf.getBooleanCellValue()); - - cf.setCellFormula("ISLOGICAL(TRUE())"); - cf = evaluateCell(wb, cf); - assertTrue(cf.getBooleanCellValue()); - - cf.setCellFormula("ISLOGICAL(4)"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - - // Now, check ISNUMBER / ISTEXT / ISNONTEXT - cf.setCellFormula("ISNUMBER(A1)"); - cf = evaluateCell(wb, cf); - assertTrue(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNUMBER(B1)"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNUMBER(C1)"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNUMBER(D1)"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNUMBER(E1)"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - - cf.setCellFormula("ISTEXT(A1)"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - cf.setCellFormula("ISTEXT(B1)"); - cf = evaluateCell(wb, cf); - assertTrue(cf.getBooleanCellValue()); - - cf.setCellFormula("ISTEXT(C1)"); - cf = evaluateCell(wb, cf); - assertTrue(cf.getBooleanCellValue()); - - cf.setCellFormula("ISTEXT(D1)"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - cf.setCellFormula("ISTEXT(E1)"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - - cf.setCellFormula("ISNONTEXT(A1)"); - cf = evaluateCell(wb, cf); - assertTrue(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNONTEXT(B1)"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNONTEXT(C1)"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNONTEXT(D1)"); - cf = evaluateCell(wb, cf); - assertTrue(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNONTEXT(E1)"); - cf = evaluateCell(wb, cf); - assertTrue(cf.getBooleanCellValue()); // Blank and Null the same - - - // Next up, SEARCH on its own - cf.setCellFormula("SEARCH(\"am\", A1)"); - cf = evaluateCell(wb, cf); - assertEquals(FormulaError.VALUE.getCode(), cf.getErrorCellValue()); - - cf.setCellFormula("SEARCH(\"am\", B1)"); - cf = evaluateCell(wb, cf); - assertEquals(19, (int) cf.getNumericCellValue()); - - cf.setCellFormula("SEARCH(\"am\", C1)"); - cf = evaluateCell(wb, cf); - assertEquals(FormulaError.VALUE.getCode(), cf.getErrorCellValue()); - - cf.setCellFormula("SEARCH(\"am\", D1)"); - cf = evaluateCell(wb, cf); - assertEquals(FormulaError.VALUE.getCode(), cf.getErrorCellValue()); - - - // Finally, bring it all together - cf.setCellFormula("ISNUMBER(SEARCH(\"am\", A1))"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNUMBER(SEARCH(\"am\", B1))"); - cf = evaluateCell(wb, cf); - assertTrue(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNUMBER(SEARCH(\"am\", C1))"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNUMBER(SEARCH(\"am\", D1))"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - cf.setCellFormula("ISNUMBER(SEARCH(\"am\", E1))"); - cf = evaluateCell(wb, cf); - assertFalse(cf.getBooleanCellValue()); - - } - } - - private Cell evaluateCell(Workbook wb, Cell c) { - Sheet s = c.getSheet(); - wb.getCreationHelper().createFormulaEvaluator().evaluateFormulaCell(c); - return s.getRow(c.getRowIndex()).getCell(c.getColumnIndex()); - } - - /** - * Should be able to write then read formulas with references - * to cells in other files, eg '[refs/airport.xls]Sheet1'!$A$2 - * or 'http://192.168.1.2/[blank.xls]Sheet1'!$A$1 . - * Additionally, if a reference to that file is provided, it should - * be possible to evaluate them too - * TODO Fix this to evaluate for XSSF - * TODO Fix this to work at all for HSSF - */ - @Disabled("Fix this to evaluate for XSSF, Fix this to work at all for HSSF") - @Test - void bug46670() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet s = wb1.createSheet(); - Row r1 = s.createRow(0); - - - // References to try - String ext = _testDataProvider.getStandardFileNameExtension(); - String refLocal = "'[test." + ext + "]Sheet1'!$A$2"; - String refHttp = "'[http://example.com/test." + ext + "]Sheet1'!$A$2"; - String otherCellText = "In Another Workbook"; - - - // Create the references - r1.createCell(0, CellType.FORMULA).setCellFormula(refLocal); - r1.createCell(1, CellType.FORMULA).setCellFormula(refHttp); - - - // Check they were set correctly - assertEquals(refLocal, r1.getCell(0).getCellFormula()); - assertEquals(refHttp, r1.getCell(1).getCellFormula()); - - - // Reload, and ensure they were serialised and read correctly - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - s = wb2.getSheetAt(0); - r1 = s.getRow(0); - - final Cell c1 = r1.getCell(0); - final Cell c2 = r1.getCell(1); - assertEquals(refLocal, c1.getCellFormula()); - assertEquals(refHttp, c2.getCellFormula()); - - // Try to evaluate, without giving a way to get at the other file - assertThrows(Exception.class, () -> evaluateCell(wb2, c1), - "Shouldn't be able to evaluate without the other file"); - assertThrows(Exception.class, () -> evaluateCell(wb2, c2), - "Shouldn't be able to evaluate without the other file"); - - // Set up references to the other file - try (Workbook wb3 = _testDataProvider.createWorkbook()) { - wb3.createSheet().createRow(1).createCell(0).setCellValue(otherCellText); - - Map evaluators = new HashMap<>(); - evaluators.put(refLocal, wb3.getCreationHelper().createFormulaEvaluator()); - evaluators.put(refHttp, wb3.getCreationHelper().createFormulaEvaluator()); - - FormulaEvaluator evaluator = wb2.getCreationHelper().createFormulaEvaluator(); - evaluator.setupReferencedWorkbooks(evaluators); - - // Try to evaluate, with the other file - evaluator.evaluateFormulaCell(c1); - evaluator.evaluateFormulaCell(c2); - - assertEquals(otherCellText, c1.getStringCellValue()); - assertEquals(otherCellText, c2.getStringCellValue()); - } - } - } - } - - @Test - void test56574OverwriteExistingRow() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - { // create the Formula-Cell - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellFormula("A2"); - } - - { // check that it is there now - Row row = sheet.getRow(0); - - /* CTCell[] cArray = ((XSSFRow)row).getCTRow().getCArray(); - assertEquals(1, cArray.length);*/ - - Cell cell = row.getCell(0); - assertEquals(CellType.FORMULA, cell.getCellType()); - } - - { // overwrite the row - Row row = sheet.createRow(0); - assertNotNull(row); - } - - { // creating a row in place of another should remove the existing data, - // check that the cell is gone now - Row row = sheet.getRow(0); - - /*CTCell[] cArray = ((XSSFRow)row).getCTRow().getCArray(); - assertEquals(0, cArray.length);*/ - - Cell cell = row.getCell(0); - assertNull(cell); - } - - // the calculation chain in XSSF is empty in a newly created workbook, so we cannot check if it is correctly updated - /*assertNull(((XSSFWorkbook)wb).getCalculationChain()); - assertNotNull(((XSSFWorkbook)wb).getCalculationChain().getCTCalcChain()); - assertNotNull(((XSSFWorkbook)wb).getCalculationChain().getCTCalcChain().getCArray()); - assertEquals(0, ((XSSFWorkbook)wb).getCalculationChain().getCTCalcChain().getCArray().length);*/ - - } - } - - /** - * With HSSF, if you create a font, don't change it, and - * create a 2nd, you really do get two fonts that you - * can alter as and when you want. - * With XSSF, that wasn't the case, but this verifies - * that it now is again - */ - @Test - void bug48718() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - int startingFonts = wb instanceof HSSFWorkbook ? 4 : 1; - - assertEquals(startingFonts, wb.getNumberOfFonts()); - - // Get a font, and slightly change it - Font a = wb.createFont(); - assertEquals(startingFonts + 1, wb.getNumberOfFonts()); - a.setFontHeightInPoints((short) 23); - assertEquals(startingFonts + 1, wb.getNumberOfFonts()); - - // Get two more, unchanged - /*Font b =*/ - wb.createFont(); - assertEquals(startingFonts + 2, wb.getNumberOfFonts()); - /*Font c =*/ - wb.createFont(); - assertEquals(startingFonts + 3, wb.getNumberOfFonts()); - } - } - - @Test - void bug57430() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - wb.createSheet("Sheet1"); - - Name name1 = wb.createName(); - name1.setNameName("FMLA"); - assertDoesNotThrow(() -> name1.setRefersToFormula("Sheet1!$B$3")); - } - } - - @Test - void bug56981() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - CellStyle vertTop = wb1.createCellStyle(); - vertTop.setVerticalAlignment(VerticalAlignment.TOP); - CellStyle vertBottom = wb1.createCellStyle(); - vertBottom.setVerticalAlignment(VerticalAlignment.BOTTOM); - Sheet sheet = wb1.createSheet("Sheet 1"); - Row row = sheet.createRow(0); - Cell top = row.createCell(0); - Cell bottom = row.createCell(1); - top.setCellValue("Top"); - top.setCellStyle(vertTop); // comment this out to get all bottom-aligned - // cells - bottom.setCellValue("Bottom"); - bottom.setCellStyle(vertBottom); - row.setHeightInPoints(85.75f); // make it obvious - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - Cell cell = wb2.getSheetAt(0).getRow(0).getCell(1); - assertEquals(VerticalAlignment.BOTTOM, cell.getCellStyle().getVerticalAlignment()); - } - } - } - - @Test - void test57973() throws IOException { - String[] vals = { "Cell0", "F4", "C3" }; - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - CreationHelper helper1 = wb1.getCreationHelper(); - Sheet sheet1 = wb1.createSheet(); - Drawing drawing1 = sheet1.createDrawingPatriarch(); - - for (int i=0; i< vals.length; i++) { - Cell cell = sheet1.createRow(i).createCell(i); - cell.setCellValue(vals[i]); - ClientAnchor anchor = helper1.createClientAnchor(); - anchor.setCol1(i); - anchor.setCol2(i); - anchor.setRow1(i); - anchor.setRow2(i); - - Comment comment = drawing1.createCellComment(anchor); - RichTextString str = helper1.createRichTextString("Hello, World"+i); - comment.setString(str); - comment.setAuthor("Apache POI"); - cell.setCellComment(comment); - comment.setColumn(i); - comment.setRow(i); - - //apply custom font to the text in the comment - Font font = wb1.createFont(); - font.setFontName("Arial"); - font.setFontHeightInPoints((short) (14+i)); - font.setBold(true); - font.setColor(IndexedColors.RED.getIndex()); - str.applyFont(font); - } - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - Sheet sheet2 = wb2.getSheetAt(0); - - for (int i=0; i\"\",MID(A1,1,2),\" \")"); - ev.evaluateAll(); - assertEquals("ab", cell.getStringCellValue()); - - cell = row.createCell(6); - cell.setCellFormula("IF(B1<>\"\",MID(A1,1,2),\"empty\")"); - ev.evaluateAll(); - assertEquals("empty", cell.getStringCellValue()); - - cell = row.createCell(7); - cell.setCellFormula("IF(A1<>\"\",IF(C1<>\"\",MID(A1,1,2),\"c1\"),\"c2\")"); - ev.evaluateAll(); - assertEquals("ab", cell.getStringCellValue()); - - // Write it back out, and re-read - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - ev = wb2.getCreationHelper().createFormulaEvaluator(); - s = wb2.getSheetAt(0); - row = s.getRow(0); - - // Check read ok, and re-evaluate fine - cell = row.getCell(5); - assertEquals("ab", cell.getStringCellValue()); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("IF(A1<>\"\",MID(A1,1,2),\" \")", cell.getCellFormula()); - ev.evaluateFormulaCell(cell); - assertEquals("ab", cell.getStringCellValue()); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("IF(A1<>\"\",MID(A1,1,2),\" \")", cell.getCellFormula()); - - cell = row.getCell(6); - assertEquals("empty", cell.getStringCellValue()); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("IF(B1<>\"\",MID(A1,1,2),\"empty\")", cell.getCellFormula()); - ev.evaluateFormulaCell(cell); - assertEquals("empty", cell.getStringCellValue()); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("IF(B1<>\"\",MID(A1,1,2),\"empty\")", cell.getCellFormula()); - - cell = row.getCell(7); - assertEquals("ab", cell.getStringCellValue()); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("IF(A1<>\"\",IF(C1<>\"\",MID(A1,1,2),\"c1\"),\"c2\")", cell.getCellFormula()); - ev.evaluateFormulaCell(cell); - assertEquals("ab", cell.getStringCellValue()); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("IF(A1<>\"\",IF(C1<>\"\",MID(A1,1,2),\"c1\"),\"c2\")", cell.getCellFormula()); - } - } - } - - @Test - void bug58260() throws IOException { - //Create workbook and worksheet - try (Workbook wb = _testDataProvider.createWorkbook()) { - //Sheet worksheet = wb.createSheet("sample"); - - //Loop through and add all values from array list - // use a fixed seed to always produce the same file which makes comparing stuff easier - //Random rnd = new Random(4352345); - int maxStyles = (wb instanceof HSSFWorkbook) ? 4009 : 64000; - for (int i = 0; i < maxStyles; i++) { - //Create new row - //Row row = worksheet.createRow(i); - - //Create cell style - CellStyle style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.RIGHT); - if ((wb instanceof HSSFWorkbook)) { - // there are some predefined styles - assertEquals(i + 21, style.getIndex()); - } else { - // getIndex() returns short, which is not sufficient for > 32767 - // we should really change the API to be "int" for getIndex() but - // that needs API changes - assertEquals(i + 1, style.getIndex() & 0xffff); - } - - //Create cell - //Cell cell = row.createCell(0); - - //Set cell style - //cell.setCellStyle(style); - - //Set cell value - //cell.setCellValue("r" + rnd.nextInt()); - } - - // should fail if we try to add more now - assertThrows(IllegalStateException.class, wb::createCellStyle, - "Should fail after " + maxStyles + " styles, but did not fail"); - - /*//add column width for appearance sake - worksheet.setColumnWidth(0, 5000); - - // Write the output to a file - System.out.println("Writing..."); - OutputStream fileOut = new FileOutputStream("C:\\temp\\58260." + _testDataProvider.getStandardFileNameExtension()); - - // the resulting file can be compressed nicely, so we need to disable the zip bomb detection here - double before = ZipSecureFile.getMinInflateRatio(); - try { - ZipSecureFile.setMinInflateRatio(0.00001); - wb.write(fileOut); - } finally { - fileOut.close(); - ZipSecureFile.setMinInflateRatio(before); - }*/ - - } - } - - @Test - void test50319() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = wb.createSheet("Test"); - sheet.createRow(0); - sheet.groupRow(0, 0); - sheet.setRowGroupCollapsed(0, true); - - sheet.groupColumn(0, 0); - assertDoesNotThrow(() -> sheet.setColumnGroupCollapsed(0, true)); - } - } - - // Bug 58648: FormulaParser throws exception in parseSimpleFactor() when getCellFormula() - // is called on a cell and the formula contains spaces between closing parentheses ") )" - @Test - void test58648() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = wb.createSheet().createRow(0).createCell(0); - assertDoesNotThrow(() -> cell.setCellFormula("((1 + 1) )")); - } - } - - /** - * If someone sets a null string as a cell value, treat - * it as an empty cell, and avoid a NPE on auto-sizing - */ - @Test - void test57034() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet(); - Cell cell = s.createRow(0).createCell(0); - cell.setCellValue((String) null); - assertEquals(CellType.BLANK, cell.getCellType()); - - _testDataProvider.trackAllColumnsForAutosizing(s); - - s.autoSizeColumn(0); - assertEquals(2048, s.getColumnWidth(0)); - - s.autoSizeColumn(0, true); - assertEquals(2048, s.getColumnWidth(0)); - } - } - - @Test - void test52684() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellValue(12312345123L); - - DataFormat format = wb.createDataFormat(); - CellStyle style = wb.createCellStyle(); - style.setDataFormat(format.getFormat("000-00000-000")); - cell.setCellStyle(style); - - assertEquals("000-00000-000", - cell.getCellStyle().getDataFormatString()); - assertEquals(164, cell.getCellStyle().getDataFormat()); - - DataFormatter formatter = new DataFormatter(); - - assertEquals("12-312-345-123", formatter.formatCellValue(cell)); - } - } - - @Test - void test58896() throws IOException { - final int nrows = 160; - final int ncols = 139; - - // Create a workbook - try (Workbook wb = _testDataProvider.createWorkbook(nrows+1)) { - final Sheet sh = wb.createSheet(); - LOG.atDebug().log("{} column autosizing timing...", wb.getClass().getName()); - - final long t0 = time(); - _testDataProvider.trackAllColumnsForAutosizing(sh); - for (int r = 0; r < nrows; r++) { - final Row row = sh.createRow(r); - for (int c = 0; c < ncols; c++) { - final Cell cell = row.createCell(c); - cell.setCellValue("Cell[r=" + r + ",c=" + c + "]"); - } - } - final double populateSheetTime = delta(t0); - final double populateSheetTimePerCell_ns = (1000000 * populateSheetTime / (nrows * ncols)); - LOG.atDebug().log("Populate sheet time: {} ms ({} ns/cell)", populateSheetTime, populateSheetTimePerCell_ns); - - LOG.atDebug().log("Autosizing..."); - final long t1 = time(); - for (int c = 0; c < ncols; c++) { - final long t2 = time(); - sh.autoSizeColumn(c); - LOG.atDebug().log("Column {} took {} ms", box(c),delta(t2)); - } - final double autoSizeColumnsTime = delta(t1); - final double autoSizeColumnsTimePerColumn = autoSizeColumnsTime / ncols; - final double bestFitWidthTimePerCell_ns = 1000000 * autoSizeColumnsTime / (ncols * nrows); - - LOG.atDebug().log("Auto sizing columns took a total of {} ms ({} ms per column)", autoSizeColumnsTime, autoSizeColumnsTimePerColumn); - LOG.atDebug().log("Best fit width time per cell: {} ns", bestFitWidthTimePerCell_ns); - - final double totalTime_s = (populateSheetTime + autoSizeColumnsTime) / 1000; - LOG.atDebug().log("Total time: {} s", totalTime_s); - } - - //if (bestFitWidthTimePerCell_ns > 50000) { - // fail("Best fit width time per cell exceeded 50000 ns: " + bestFitWidthTimePerCell_ns + " ns"); - //} - - //if (totalTime_s > 10) { - // fail("Total time exceeded 10 seconds: " + totalTime_s + " s"); - //} - } - - protected long time() { - return System.currentTimeMillis(); - } - - protected double delta(long startTimeMillis) { - return time() - startTimeMillis; - } - - @Test - void bug59393_commentsCanHaveSameAnchor() throws IOException { - // only executed for HSSF currently - assumeTrue("xls".equals(_testDataProvider.getStandardFileNameExtension())); - - try (Workbook wb = _testDataProvider.createWorkbook()) { - - Sheet sheet = wb.createSheet(); - - CreationHelper helper = wb.getCreationHelper(); - ClientAnchor anchor = helper.createClientAnchor(); - Drawing drawing = sheet.createDrawingPatriarch(); - - Row row = sheet.createRow(0); - - Cell cell1 = row.createCell(0); - Cell cell2 = row.createCell(1); - Cell cell3 = row.createCell(2); - - Comment comment1 = drawing.createCellComment(anchor); - RichTextString richTextString1 = helper.createRichTextString("comment1"); - comment1.setString(richTextString1); - cell1.setCellComment(comment1); - - // fails with IllegalArgumentException("Multiple cell comments in one cell are not allowed, cell: A1") - // because createCellComment tries to create a cell at A1 - // (from CellAddress(anchor.getRow1(), anchor.getCell1())), - // but cell A1 already has a comment (comment1). - // Need to atomically create a comment and attach it to a cell. - // Current workaround: change anchor between each usage - // anchor.setCol1(1); - Comment comment2 = drawing.createCellComment(anchor); - RichTextString richTextString2 = helper.createRichTextString("comment2"); - comment2.setString(richTextString2); - assertDoesNotThrow(() -> cell2.setCellComment(comment2)); - - // anchor.setCol1(2); - Comment comment3 = drawing.createCellComment(anchor); - RichTextString richTextString3 = helper.createRichTextString("comment3"); - comment3.setString(richTextString3); - assertDoesNotThrow(() -> cell3.setCellComment(comment3)); - } - } - - - @Test - protected void bug57798() throws Exception { - String fileName = "57798." + _testDataProvider.getStandardFileNameExtension(); - try (Workbook workbook = _testDataProvider.openSampleWorkbook(fileName)) { - - Sheet sheet = workbook.getSheet("Sheet1"); - - // ******************************* - // First cell of array formula, OK - int rowId = 0; - int cellId = 1; - - Row row = sheet.getRow(rowId); - Cell cell = row.getCell(cellId); - - assertEquals("A1", cell.getCellFormula()); - if (CellType.FORMULA == cell.getCellType()) { - CellType formulaResultType = cell.getCachedFormulaResultType(); - assertEquals(CellType.STRING, formulaResultType); - } - - // ******************************* - // Second cell of array formula, NOT OK for xlsx files - rowId = 1; - cellId = 1; - - row = sheet.getRow(rowId); - cell = row.getCell(cellId); - assertEquals("A1", cell.getCellFormula()); - - if (CellType.FORMULA == cell.getCellType()) { - CellType formulaResultType = cell.getCachedFormulaResultType(); - assertEquals(CellType.STRING, formulaResultType); - } - } - } - - @Disabled - @Test - void test57929() throws IOException { - // Create a workbook with print areas on 2 sheets - try (Workbook wb = _testDataProvider.createWorkbook()) { - wb.createSheet("Sheet0"); - wb.createSheet("Sheet1"); - wb.setPrintArea(0, "$A$1:$C$6"); - wb.setPrintArea(1, "$B$1:$C$5"); - - // Verify the print areas were set correctly - assertEquals("Sheet0!$A$1:$C$6", wb.getPrintArea(0)); - assertEquals("Sheet1!$B$1:$C$5", wb.getPrintArea(1)); - - // Remove the print area on Sheet0 and change the print area on Sheet1 - wb.removePrintArea(0); - wb.setPrintArea(1, "$A$1:$A$1"); - - // Verify that the changes were made - assertNull(wb.getPrintArea(0), "Sheet0 before write"); - assertEquals(wb.getPrintArea(1), "Sheet1 before write", "Sheet1!$A$1:$A$1"); - - // Verify that the changes are non-volatile - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb)) { - // CURRENTLY FAILS with "Sheet0!$A$1:$C$6" - assertNull(wb2.getPrintArea(0), "Sheet0 after write"); - assertEquals(wb2.getPrintArea(1), "Sheet1 after write", "Sheet1!$A$1:$A$1"); - } - } - } - - - @Test - void test55384() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sh = wb.createSheet(); - for (int rownum = 0; rownum < 10; rownum++) { - Row row = sh.createRow(rownum); - for (int cellnum = 0; cellnum < 3; cellnum++) { - Cell cell = row.createCell(cellnum); - cell.setCellValue(rownum + cellnum); - } - } - Row row = sh.createRow(10); - // setting no precalculated value works just fine. - Cell cell1 = row.createCell(0); - cell1.setCellFormula("SUM(A1:A10)"); - - // but setting a precalculated STRING value fails totally in SXSSF - Cell cell2 = row.createCell(1); - cell2.setCellFormula("SUM(B1:B10)"); - cell2.setCellValue("55"); - - // setting a precalculated int value works as expected - Cell cell3 = row.createCell(2); - cell3.setCellFormula("SUM(C1:C10)"); - cell3.setCellValue(65); - - assertEquals(CellType.FORMULA, cell1.getCellType()); - assertEquals(CellType.FORMULA, cell2.getCellType()); - assertEquals(CellType.FORMULA, cell3.getCellType()); - - assertEquals("SUM(A1:A10)", cell1.getCellFormula()); - assertEquals("SUM(B1:B10)", cell2.getCellFormula()); - assertEquals("SUM(C1:C10)", cell3.getCellFormula()); - - try (Workbook wbBack = _testDataProvider.writeOutAndReadBack(wb)) { - checkFormulaPreevaluatedString(wbBack); - } - } - } - - private void checkFormulaPreevaluatedString(Workbook readFile) { - Sheet sheet = readFile.getSheetAt(0); - Row row = sheet.getRow(sheet.getLastRowNum()); - assertEquals(10, row.getRowNum()); - - for (Cell cell : row) { - CellType ctype = cell.getCellType(); - assertTrue(ctype == CellType.STRING || ctype == CellType.FORMULA, "unexpected cell type"); - - String cellValue = (ctype == CellType.STRING) - ? cell.getRichStringCellValue().getString() - : cell.getCellFormula(); - - assertNotNull(cellValue); - cellValue = cellValue.isEmpty() ? null : cellValue; - assertNotNull(cellValue); - } - } - - // bug 60197: setSheetOrder should update sheet-scoped named ranges to maintain references to the sheets before the re-order - @Test - protected void bug60197_NamedRangesReferToCorrectSheetWhenSheetOrderIsChanged() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet1 = wb.createSheet("Sheet1"); - Sheet sheet2 = wb.createSheet("Sheet2"); - Sheet sheet3 = wb.createSheet("Sheet3"); - - Name nameOnSheet1 = wb.createName(); - nameOnSheet1.setSheetIndex(wb.getSheetIndex(sheet1)); - nameOnSheet1.setNameName("NameOnSheet1"); - nameOnSheet1.setRefersToFormula("Sheet1!A1"); - - Name nameOnSheet2 = wb.createName(); - nameOnSheet2.setSheetIndex(wb.getSheetIndex(sheet2)); - nameOnSheet2.setNameName("NameOnSheet2"); - nameOnSheet2.setRefersToFormula("Sheet2!A1"); - - Name nameOnSheet3 = wb.createName(); - nameOnSheet3.setSheetIndex(wb.getSheetIndex(sheet3)); - nameOnSheet3.setNameName("NameOnSheet3"); - nameOnSheet3.setRefersToFormula("Sheet3!A1"); - - // workbook-scoped name - Name name = wb.createName(); - name.setNameName("WorkbookScopedName"); - name.setRefersToFormula("Sheet2!A1"); - - assertEquals("Sheet1", nameOnSheet1.getSheetName()); - assertEquals("Sheet2", nameOnSheet2.getSheetName()); - assertEquals("Sheet3", nameOnSheet3.getSheetName()); - assertEquals(-1, name.getSheetIndex()); - assertEquals("Sheet2!A1", name.getRefersToFormula()); - - // rearrange the sheets several times to make sure the names always refer to the right sheet - for (int i = 0; i <= 9; i++) { - wb.setSheetOrder("Sheet3", i % 3); - - // Current bug in XSSF: - // Call stack: - // XSSFWorkbook.write(OutputStream) - // XSSFWorkbook.commit() - // XSSFWorkbook.saveNamedRanges() - // This dumps the current namedRanges to CTDefinedName and writes these to the CTWorkbook - // Then the XSSFName namedRanges list is cleared and rebuilt - // Thus, any XSSFName object becomes invalid after a write - // This re-assignment to the XSSFNames is not necessary if wb.write is not called. - nameOnSheet1 = wb.getName("NameOnSheet1"); - nameOnSheet2 = wb.getName("NameOnSheet2"); - nameOnSheet3 = wb.getName("NameOnSheet3"); - name = wb.getName("WorkbookScopedName"); - - // The name should still refer to the same sheet after the sheets are re-ordered - assertEquals(i % 3, wb.getSheetIndex("Sheet3")); - assertEquals("Sheet1", nameOnSheet1.getSheetName()); - assertEquals("Sheet2", nameOnSheet2.getSheetName()); - assertEquals("Sheet3", nameOnSheet3.getSheetName()); - assertEquals(-1, name.getSheetIndex()); - assertEquals("Sheet2!A1", name.getRefersToFormula()); - - // make sure the changes to the names stick after writing out the workbook - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb)) { - - // See note above. XSSFNames become invalid after workbook write - // Without reassignment here, an XmlValueDisconnectedException may occur - nameOnSheet1 = wb2.getName("NameOnSheet1"); - nameOnSheet2 = wb2.getName("NameOnSheet2"); - nameOnSheet3 = wb2.getName("NameOnSheet3"); - name = wb2.getName("WorkbookScopedName"); - - // Saving the workbook should not change the sheet names - assertEquals(i % 3, wb2.getSheetIndex("Sheet3")); - assertEquals("Sheet1", nameOnSheet1.getSheetName()); - assertEquals("Sheet2", nameOnSheet2.getSheetName()); - assertEquals("Sheet3", nameOnSheet3.getSheetName()); - assertEquals(-1, name.getSheetIndex()); - assertEquals("Sheet2!A1", name.getRefersToFormula()); - - // Verify names in wb2 - nameOnSheet1 = wb2.getName("NameOnSheet1"); - nameOnSheet2 = wb2.getName("NameOnSheet2"); - nameOnSheet3 = wb2.getName("NameOnSheet3"); - name = wb2.getName("WorkbookScopedName"); - - assertEquals(i % 3, wb2.getSheetIndex("Sheet3")); - assertEquals("Sheet1", nameOnSheet1.getSheetName()); - assertEquals("Sheet2", nameOnSheet2.getSheetName()); - assertEquals("Sheet3", nameOnSheet3.getSheetName()); - assertEquals(-1, name.getSheetIndex()); - assertEquals("Sheet2!A1", name.getRefersToFormula()); - } - } - } - } - - @Test - void test59200() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - final Sheet sheet = wb.createSheet(); - - DataValidation dataValidation; - CellRangeAddressList headerCell = new CellRangeAddressList(0, 1, 0, 1); - DataValidationConstraint constraint = sheet.getDataValidationHelper().createCustomConstraint("A1<>\"\""); - - dataValidation = sheet.getDataValidationHelper().createValidation(constraint, headerCell); - - // HSSF has 32/255 limits as part of the Spec, XSSF has no limit in the spec, but Excel applies a 255 length limit! - // more than 255 fail for all - checkFails(dataValidation, TEST_256, TEST_32); - checkFails(dataValidation, TEST_32, TEST_256); - - // null does work - checkPasses(dataValidation, null, null); - - // more than 32 title fail for HSSFWorkbook - if (wb instanceof HSSFWorkbook) { - checkFails(dataValidation, TEST_255, TEST_32); - } else { - checkPasses(dataValidation, TEST_255, TEST_32); - } - - // special characters work - checkPasses(dataValidation, TEST_SPECIAL_TITLE, TEST_SPECIAL); - - // 32 length title and 255 length text work for both - checkPasses(dataValidation, TEST_32, TEST_255); - - dataValidation.setShowErrorBox(false); - sheet.addValidationData(dataValidation); - - // write out and read back in to trigger some more validation - final Workbook wbBack = _testDataProvider.writeOutAndReadBack(wb); - - final Sheet sheetBack = wbBack.getSheetAt(0); - final List dataValidations = sheetBack.getDataValidations(); - assertEquals(1, dataValidations.size()); - } - } - - private void checkFails(DataValidation dataValidation, String title, String text) { - assertThrows(IllegalStateException.class, () -> dataValidation.createPromptBox(title, text)); - assertThrows(IllegalStateException.class, () -> dataValidation.createErrorBox(title, text)); - } - - private void checkPasses(DataValidation dataValidation, String title, String text) { - dataValidation.createPromptBox(title, text); - dataValidation.createErrorBox(title, text); - } - - @Test - void test60370() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - final Sheet sheet = wb.createSheet(); - - DataValidation dataValidation; - CellRangeAddressList headerCell = new CellRangeAddressList(0, 1, 0, 1); - DataValidationConstraint constraint = sheet.getDataValidationHelper().createCustomConstraint("A1<>\"\""); - - dataValidation = sheet.getDataValidationHelper().createValidation(constraint, headerCell); - checkPasses(dataValidation, TEST_SPECIAL_TITLE, TEST_SPECIAL); - - dataValidation.setShowErrorBox(true); - dataValidation.setShowPromptBox(true); - sheet.addValidationData(dataValidation); - - // write out and read back in to trigger some more validation - final Workbook wbBack = _testDataProvider.writeOutAndReadBack(wb); - - final Sheet sheetBack = wbBack.getSheetAt(0); - final List dataValidations = sheetBack.getDataValidations(); - assertEquals(1, dataValidations.size()); - } - } - - protected void assertFormula(Workbook wb, Cell intF, String expectedFormula, String expectedResultOrNull) { - assertEquals(CellType.FORMULA, intF.getCellType()); - if (null == expectedResultOrNull) { - assertEquals(CellType.ERROR, intF.getCachedFormulaResultType()); - expectedResultOrNull = "#VALUE!"; - } else { - assertEquals(CellType.NUMERIC, intF.getCachedFormulaResultType()); - } - - assertEquals(expectedFormula, intF.getCellFormula()); - - // Check we can evaluate it correctly - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals(expectedResultOrNull, eval.evaluate(intF).formatAsString()); - } - - @Test - void testWriteDocumentTwice() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("RawData"); - Row row = sheet.createRow(0); - Cell cell; - - cell = row.createCell(0); - cell.setCellValue("Ernie & Bert"); - - cell = row.createCell(1); - // Set a precalculated formula value containing a special character. - cell.setCellValue("Ernie & Bert are cool!"); - cell.setCellFormula("A1 & \" are cool!\""); - - try (ByteArrayOutputStream out1 = new ByteArrayOutputStream(); - ByteArrayOutputStream out2 = new ByteArrayOutputStream()) { - wb.write(out1); - wb.write(out2); - - out1.flush(); - out2.flush(); - - // to avoid flaky tests if the documents are written at slightly different timestamps - // we clear some bytes which contain timestamps - assertArrayEquals( - removeTimestamp(out1.toByteArray()), - removeTimestamp(out2.toByteArray())); - } - } - } - - private byte[] removeTimestamp(byte[] bytes) { - if (FileMagic.valueOf(bytes) == FileMagic.OOXML) { - // This removes the timestamp in the header of the ZIP-Format - // see "Local file header" at https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT - bytes[10] = 0; - bytes[11] = 0; - bytes[12] = 0; - bytes[13] = 0; - } - - return bytes; - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java deleted file mode 100644 index d8a54cfa54..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java +++ /dev/null @@ -1,1417 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.apache.poi.ss.usermodel.FormulaError.forInt; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; -import static org.mockito.Mockito.doCallRealMethod; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.TimeZone; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.eval.NotImplementedException; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; - -/** - * Common superclass for testing implementations of - * {@link org.apache.poi.ss.usermodel.Cell} - */ -@SuppressWarnings("deprecation") -public abstract class BaseTestCell { - - protected final ITestDataProvider _testDataProvider; - - /** - * @param testDataProvider an object that provides test data in HSSF / XSSF specific way - */ - protected BaseTestCell(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - void testSetValues() throws Exception { - try (Workbook book = _testDataProvider.createWorkbook()) { - Sheet sheet = book.createSheet("test"); - Row row = sheet.createRow(0); - - CreationHelper factory = book.getCreationHelper(); - Cell cell = row.createCell(0); - - cell.setCellValue(1.2); - assertEquals(1.2, cell.getNumericCellValue(), 0.0001); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertProhibitedValueAccess(cell, CellType.BOOLEAN, CellType.STRING, - CellType.FORMULA, CellType.ERROR); - - cell.setCellValue(false); - assertFalse(cell.getBooleanCellValue()); - assertEquals(CellType.BOOLEAN, cell.getCellType()); - cell.setCellValue(true); - assertTrue(cell.getBooleanCellValue()); - assertProhibitedValueAccess(cell, CellType.NUMERIC, CellType.STRING, CellType.BOOLEAN, - CellType.FORMULA, CellType.ERROR); - - cell.setCellValue(factory.createRichTextString("Foo")); - assertEquals("Foo", cell.getRichStringCellValue().getString()); - assertEquals("Foo", cell.getStringCellValue()); - assertEquals(CellType.STRING, cell.getCellType()); - assertProhibitedValueAccess(cell, CellType.NUMERIC, CellType.BOOLEAN, - CellType.FORMULA, CellType.ERROR); - - cell.setCellValue("345"); - assertEquals("345", cell.getRichStringCellValue().getString()); - assertEquals("345", cell.getStringCellValue()); - assertEquals(CellType.STRING, cell.getCellType()); - assertProhibitedValueAccess(cell, CellType.NUMERIC, CellType.BOOLEAN, - CellType.FORMULA, CellType.ERROR); - - Calendar c = LocaleUtil.getLocaleCalendar(); - c.setTimeInMillis(123456789); - cell.setCellValue(c.getTime()); - assertEquals(c.getTime().getTime(), cell.getDateCellValue().getTime()); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertProhibitedValueAccess(cell, CellType.BOOLEAN, CellType.STRING, - CellType.FORMULA, CellType.ERROR); - - cell.setCellValue(c); - assertEquals(c.getTime().getTime(), cell.getDateCellValue().getTime()); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertProhibitedValueAccess(cell, CellType.BOOLEAN, CellType.STRING, - CellType.FORMULA, CellType.ERROR); - - cell.setCellErrorValue(FormulaError.NA.getCode()); - assertEquals(FormulaError.NA.getCode(), cell.getErrorCellValue()); - assertEquals(CellType.ERROR, cell.getCellType()); - assertProhibitedValueAccess(cell, CellType.NUMERIC, CellType.BOOLEAN, - CellType.FORMULA, CellType.STRING); - - LocalDateTime ldt = DateUtil.toLocalDateTime(c); - cell.setCellValue(ldt); - assertEquals(ldt, cell.getLocalDateTimeCellValue()); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertProhibitedValueAccess(cell, CellType.BOOLEAN, CellType.STRING, - CellType.FORMULA, CellType.ERROR); - - LocalDate ld = ldt.toLocalDate(); - cell.setCellValue(ld); - assertEquals(ld, cell.getLocalDateTimeCellValue().toLocalDate()); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertProhibitedValueAccess(cell, CellType.BOOLEAN, CellType.STRING, - CellType.FORMULA, CellType.ERROR); - - cell.setCellValue((String)null); - assertEquals("", cell.getStringCellValue()); - assertEquals(CellType.BLANK, cell.getCellType()); - - cell.setCellValue((LocalDate)null); - assertNull(cell.getLocalDateTimeCellValue()); - assertEquals(CellType.BLANK, cell.getCellType()); - - cell.setCellValue((LocalDateTime)null); - assertNull(cell.getLocalDateTimeCellValue()); - assertEquals(CellType.BLANK, cell.getCellType()); - - cell.setCellErrorValue(FormulaError.NA.getCode()); - assertEquals(FormulaError.NA.getCode(), cell.getErrorCellValue()); - assertEquals(CellType.ERROR, cell.getCellType()); - assertProhibitedValueAccess(cell, CellType.NUMERIC, CellType.BOOLEAN, - CellType.FORMULA, CellType.STRING); - } - } - - private static void assertProhibitedValueAccess(Cell cell, CellType ... types) { - for(CellType type : types){ - try { - switch (type) { - case NUMERIC: - cell.getNumericCellValue(); - break; - case STRING: - cell.getStringCellValue(); - break; - case BOOLEAN: - cell.getBooleanCellValue(); - break; - case FORMULA: - cell.getCellFormula(); - break; - case ERROR: - cell.getErrorCellValue(); - break; - default: - fail("Should get exception when reading cell type (" + type + ")."); - } - - } catch (IllegalStateException e){ - // expected during successful test - assertTrue(e.getMessage().startsWith("Cannot get a")); - } - } - } - - /** - * test that Boolean (BoolErrRecord) are supported properly. - */ - @Test - void testBool() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet s = wb1.createSheet("testSheet1"); - Row r; - Cell c; - // B1 - r = s.createRow(0); - c = r.createCell(1); - assertEquals(0, c.getRowIndex()); - assertEquals(1, c.getColumnIndex()); - c.setCellValue(true); - assertTrue(c.getBooleanCellValue(), "B1 value"); - - // C1 - c = r.createCell(2); - assertEquals(0, c.getRowIndex()); - assertEquals(2, c.getColumnIndex()); - c.setCellValue(false); - assertFalse(c.getBooleanCellValue(), "C1 value"); - - // Make sure values are saved and re-read correctly. - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - s = wb2.getSheet("testSheet1"); - r = s.getRow(0); - assertEquals(2, r.getPhysicalNumberOfCells(), "Row 1 should have 2 cells"); - - c = r.getCell(1); - assertEquals(0, c.getRowIndex()); - assertEquals(1, c.getColumnIndex()); - assertEquals(CellType.BOOLEAN, c.getCellType()); - assertTrue(c.getBooleanCellValue(), "B1 value"); - - c = r.getCell(2); - assertEquals(0, c.getRowIndex()); - assertEquals(2, c.getColumnIndex()); - assertEquals(CellType.BOOLEAN, c.getCellType()); - assertFalse(c.getBooleanCellValue(), "C1 value"); - } - } - } - - /** - * test that Error types (BoolErrRecord) are supported properly. - * @see #testBool - */ - @Test - void testErr() throws IOException { - - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet s = wb1.createSheet("testSheet1"); - Row r; - Cell c; - - // B1 - r = s.createRow(0); - c = r.createCell(1); - assertEquals(0, c.getRowIndex()); - assertEquals(1, c.getColumnIndex()); - c.setCellErrorValue(FormulaError.NULL.getCode()); - assertEquals(FormulaError.NULL.getCode(), c.getErrorCellValue(), "B1 value == #NULL!"); - - // C1 - c = r.createCell(2); - assertEquals(0, c.getRowIndex()); - assertEquals(2, c.getColumnIndex()); - c.setCellErrorValue(FormulaError.DIV0.getCode()); - assertEquals(FormulaError.DIV0.getCode(), c.getErrorCellValue(), "C1 value == #DIV/0!"); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - s = wb2.getSheet("testSheet1"); - - r = s.getRow(0); - assertEquals(2, r.getPhysicalNumberOfCells(), "Row 1 should have 2 cells"); - - c = r.getCell(1); - assertEquals(0, c.getRowIndex()); - assertEquals(1, c.getColumnIndex()); - assertEquals(CellType.ERROR, c.getCellType()); - assertEquals(FormulaError.NULL.getCode(), c.getErrorCellValue(), "B1 value == #NULL!"); - - c = r.getCell(2); - assertEquals(0, c.getRowIndex()); - assertEquals(2, c.getColumnIndex()); - assertEquals(CellType.ERROR, c.getCellType()); - assertEquals(FormulaError.DIV0.getCode(), c.getErrorCellValue(), "C1 value == #DIV/0!"); - } - } - } - - /** - * test that Cell Styles being applied to formulas remain intact - */ - @Test - void testFormulaStyle() throws Exception { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet s = wb1.createSheet("testSheet1"); - Row r; - Cell c; - CellStyle cs = wb1.createCellStyle(); - Font f = wb1.createFont(); - f.setFontHeightInPoints((short) 20); - f.setColor(IndexedColors.RED.getIndex()); - f.setBold(true); - f.setFontName("Arial Unicode MS"); - cs.setFillBackgroundColor((short) 3); - cs.setFont(f); - cs.setBorderTop(BorderStyle.THIN); - cs.setBorderRight(BorderStyle.THIN); - cs.setBorderLeft(BorderStyle.THIN); - cs.setBorderBottom(BorderStyle.THIN); - - r = s.createRow(0); - c = r.createCell(0); - c.setCellStyle(cs); - c.setCellFormula("2*3"); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - - assertEquals(CellType.FORMULA, c.getCellType(), "Formula Cell at 0,0"); - cs = c.getCellStyle(); - - assertNotNull(cs, "Formula Cell Style"); - assertEquals(f.getIndex(), cs.getFontIndex(), "Font Index Matches"); - assertEquals(BorderStyle.THIN, cs.getBorderTop(), "Top Border"); - assertEquals(BorderStyle.THIN, cs.getBorderLeft(), "Left Border"); - assertEquals(BorderStyle.THIN, cs.getBorderRight(), "Right Border"); - assertEquals(BorderStyle.THIN, cs.getBorderBottom(), "Bottom Border"); - } - } - } - - /**tests the toString() method of HSSFCell*/ - @Test - void testToString() throws Exception { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Row r = wb1.createSheet("Sheet1").createRow(0); - CreationHelper factory = wb1.getCreationHelper(); - - r.createCell(0).setCellValue(false); - r.createCell(1).setCellValue(true); - r.createCell(2).setCellValue(1.5); - r.createCell(3).setCellValue(factory.createRichTextString("Astring")); - r.createCell(4).setCellErrorValue(FormulaError.DIV0.getCode()); - r.createCell(5).setCellFormula("A1+B1"); - r.createCell(6); // blank - - // create date-formatted cell - Calendar c = LocaleUtil.getLocaleCalendar(); - c.set(2010, Calendar.FEBRUARY, 2, 0, 0, 0); - r.createCell(7).setCellValue(c); - CellStyle dateStyle = wb1.createCellStyle(); - short formatId = wb1.getCreationHelper().createDataFormat().getFormat("m/d/yy h:mm"); // any date format will do - dateStyle.setDataFormat(formatId); - r.getCell(7).setCellStyle(dateStyle); - - assertEquals("FALSE", r.getCell(0).toString(), "Boolean"); - assertEquals("TRUE", r.getCell(1).toString(), "Boolean"); - assertEquals("1.5", r.getCell(2).toString(), "Numeric"); - assertEquals("Astring", r.getCell(3).toString(), "String"); - assertEquals("#DIV/0!", r.getCell(4).toString(), "Error"); - assertEquals("A1+B1", r.getCell(5).toString(), "Formula"); - assertEquals("", r.getCell(6).toString(), "Blank"); - // toString on a date-formatted cell displays dates as dd-MMM-yyyy, which has locale problems with the month - String dateCell1 = r.getCell(7).toString(); - assertTrue(dateCell1.startsWith("02-"), "Date (Day)"); - assertTrue(dateCell1.endsWith("-2010"), "Date (Year)"); - - - //Write out the file, read it in, and then check cell values - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - r = wb2.getSheetAt(0).getRow(0); - assertEquals("FALSE", r.getCell(0).toString(), "Boolean"); - assertEquals("TRUE", r.getCell(1).toString(), "Boolean"); - assertEquals("1.5", r.getCell(2).toString(), "Numeric"); - assertEquals("Astring", r.getCell(3).toString(), "String"); - assertEquals("#DIV/0!", r.getCell(4).toString(), "Error"); - assertEquals("A1+B1", r.getCell(5).toString(), "Formula"); - assertEquals("", r.getCell(6).toString(), "Blank"); - String dateCell2 = r.getCell(7).toString(); - assertEquals(dateCell1, dateCell2, "Date"); - } - } - } - - /** - * Test that setting cached formula result keeps the cell type - */ - @Test - void testSetFormulaValue() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - - Cell c1 = r.createCell(0); - c1.setCellFormula("NA()"); - assertEquals(0.0, c1.getNumericCellValue(), 0.0); - assertEquals(CellType.NUMERIC, c1.getCachedFormulaResultType()); - c1.setCellValue(10); - assertEquals(10.0, c1.getNumericCellValue(), 0.0); - assertEquals(CellType.FORMULA, c1.getCellType()); - assertEquals(CellType.NUMERIC, c1.getCachedFormulaResultType()); - - Cell c2 = r.createCell(1); - c2.setCellFormula("NA()"); - assertEquals(0.0, c2.getNumericCellValue(), 0.0); - assertEquals(CellType.NUMERIC, c2.getCachedFormulaResultType()); - c2.setCellValue("I changed!"); - assertEquals("I changed!", c2.getStringCellValue()); - assertEquals(CellType.FORMULA, c2.getCellType()); - assertEquals(CellType.STRING, c2.getCachedFormulaResultType()); - - //calglin Cell.setCellFormula(null) for a non-formula cell - Cell c3 = r.createCell(2); - c3.setCellFormula(null); - assertEquals(CellType.BLANK, c3.getCellType()); - } - - } - - private Cell createACell(Workbook wb) { - return wb.createSheet("Sheet1").createRow(0).createCell(0); - } - - /** - * bug 58452: Copy cell formulas containing unregistered function names - * Make sure that formulas with unknown/unregistered UDFs can be written to and read back from a file. - */ - @Test - void testFormulaWithUnknownUDF() throws IOException { - try (final Workbook wb1 = _testDataProvider.createWorkbook()) { - final FormulaEvaluator evaluator1 = wb1.getCreationHelper().createFormulaEvaluator(); - final Cell cell1 = wb1.createSheet().createRow(0).createCell(0); - final String formula = "myFunc(\"arg\")"; - cell1.setCellFormula(formula); - confirmFormulaWithUnknownUDF(formula, cell1, evaluator1); - - try (final Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - final FormulaEvaluator evaluator2 = wb2.getCreationHelper().createFormulaEvaluator(); - final Cell cell2 = wb2.getSheetAt(0).getRow(0).getCell(0); - confirmFormulaWithUnknownUDF(formula, cell2, evaluator2); - } - } - } - - private static void confirmFormulaWithUnknownUDF(String expectedFormula, Cell cell, FormulaEvaluator evaluator) { - assertEquals(expectedFormula, cell.getCellFormula()); - assertThrows(NotImplementedException.class, () -> evaluator.evaluate(cell)); - } - - @Test - void testChangeTypeStringToBool() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = createACell(wb); - - cell.setCellValue("TRUE"); - assertEquals(CellType.STRING, cell.getCellType()); - // test conversion of cell from text to boolean - cell.setCellType(CellType.BOOLEAN); - - assertEquals(CellType.BOOLEAN, cell.getCellType()); - assertTrue(cell.getBooleanCellValue()); - cell.setCellType(CellType.STRING); - assertEquals("TRUE", cell.getRichStringCellValue().getString()); - - // 'false' text to bool and back - cell.setCellValue("FALSE"); - cell.setCellType(CellType.BOOLEAN); - assertEquals(CellType.BOOLEAN, cell.getCellType()); - assertFalse(cell.getBooleanCellValue()); - cell.setCellType(CellType.STRING); - assertEquals("FALSE", cell.getRichStringCellValue().getString()); - } - } - - @Test - void testChangeTypeBoolToString() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = createACell(wb); - - cell.setCellValue(true); - // test conversion of cell from boolean to text - cell.setCellType(CellType.STRING); - assertEquals("TRUE", cell.getRichStringCellValue().getString()); - } - } - - @Test - void testChangeTypeErrorToNumber() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = createACell(wb); - cell.setCellErrorValue(FormulaError.NAME.getCode()); - // ClassCastException -> Identified bug 46479b - cell.setCellValue(2.5); - assertEquals(2.5, cell.getNumericCellValue(), 0.0); - } - } - - @Test - void testChangeTypeErrorToBoolean() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Cell cell = createACell(wb); - cell.setCellErrorValue(FormulaError.NAME.getCode()); - cell.setCellValue(true); - // Identify bug 46479c - assertTrue(cell.getBooleanCellValue()); - - wb.close(); - } - - /** - * Test for a bug observed around svn r886733 when using - * {@link FormulaEvaluator#evaluateInCell(Cell)} with a - * string result type. - */ - @Test - void testConvertStringFormulaCell() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cellA1 = createACell(wb); - cellA1.setCellFormula("\"abc\""); - - // default cached formula result is numeric zero - assertEquals(0.0, cellA1.getNumericCellValue(), 0.0); - - FormulaEvaluator fe = cellA1.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - - fe.evaluateFormulaCell(cellA1); - assertEquals("abc", cellA1.getStringCellValue()); - - fe.evaluateInCell(cellA1); - assertFalse(cellA1.getStringCellValue().isEmpty(), "Identified bug with writing back formula result of type string"); - assertEquals("abc", cellA1.getStringCellValue()); - } - } - - /** - * similar to {@link #testConvertStringFormulaCell()} but checks at a - * lower level that {#link {@link Cell#setCellType(CellType)} works properly - */ - @Test - void testSetTypeStringOnFormulaCell() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cellA1 = createACell(wb); - FormulaEvaluator fe = cellA1.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - - cellA1.setCellFormula("\"DEF\""); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCell(cellA1); - assertEquals("DEF", cellA1.getStringCellValue()); - cellA1.setCellType(CellType.STRING); - assertEquals("DEF", cellA1.getStringCellValue()); - - cellA1.setCellFormula("25.061"); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCell(cellA1); - confirmCannotReadString(cellA1); - assertEquals(25.061, cellA1.getNumericCellValue(), 0.0); - cellA1.setCellType(CellType.STRING); - assertEquals("25.061", cellA1.getStringCellValue()); - - cellA1.setCellFormula("TRUE"); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCell(cellA1); - confirmCannotReadString(cellA1); - assertTrue(cellA1.getBooleanCellValue()); - cellA1.setCellType(CellType.STRING); - assertEquals("TRUE", cellA1.getStringCellValue()); - - cellA1.setCellFormula("#NAME?"); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCell(cellA1); - confirmCannotReadString(cellA1); - assertEquals(FormulaError.NAME, forInt(cellA1.getErrorCellValue())); - cellA1.setCellType(CellType.STRING); - assertEquals("#NAME?", cellA1.getStringCellValue()); - } - } - - private static void confirmCannotReadString(Cell cell) { - assertProhibitedValueAccess(cell, CellType.STRING); - } - - /** - * Test for bug in convertCellValueToBoolean to make sure that formula results get converted - */ - @Test - void testChangeTypeFormulaToBoolean() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = createACell(wb); - cell.setCellFormula("1=1"); - cell.setCellValue(true); - cell.setCellType(CellType.BOOLEAN); - assertTrue(cell.getBooleanCellValue(), "Identified bug 46479d"); - assertTrue(cell.getBooleanCellValue()); - } - } - - /** - * Bug 40296: HSSFCell.setCellFormula throws - * ClassCastException if cell is created using HSSFRow.createCell(short column, int type) - */ - @Test - void test40296() throws Exception { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet workSheet = wb1.createSheet("Sheet1"); - Cell cell; - Row row = workSheet.createRow(0); - - cell = row.createCell(0, CellType.NUMERIC); - cell.setCellValue(1.0); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertEquals(1.0, cell.getNumericCellValue(), 0.0); - - cell = row.createCell(1, CellType.NUMERIC); - cell.setCellValue(2.0); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertEquals(2.0, cell.getNumericCellValue(), 0.0); - - cell = row.createCell(2, CellType.FORMULA); - cell.setCellFormula("SUM(A1:B1)"); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("SUM(A1:B1)", cell.getCellFormula()); - - //serialize and check again - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - row = wb2.getSheetAt(0).getRow(0); - cell = row.getCell(0); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertEquals(1.0, cell.getNumericCellValue(), 0.0); - - cell = row.getCell(1); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertEquals(2.0, cell.getNumericCellValue(), 0.0); - - cell = row.getCell(2); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("SUM(A1:B1)", cell.getCellFormula()); - } - } - } - - @Test - void testSetStringInFormulaCell_bug44606() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = wb.createSheet("Sheet1").createRow(0).createCell(0); - cell.setCellFormula("B1&C1"); - assertEquals(CellType.FORMULA, cell.getCellType()); - cell.setCellValue(wb.getCreationHelper().createRichTextString("hello")); - assertEquals(CellType.FORMULA, cell.getCellType()); - } - } - - /** - * Make sure that cell.setBlank() preserves the cell style - */ - @Test - void testSetBlank_bug47028() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - CellStyle style = wb.createCellStyle(); - Cell cell = wb.createSheet("Sheet1").createRow(0).createCell(0); - cell.setCellStyle(style); - int i1 = cell.getCellStyle().getIndex(); - cell.setBlank(); - int i2 = cell.getCellStyle().getIndex(); - assertEquals(i1, i2); - } - } - - /** - * Excel's implementation of floating number arithmetic does not fully adhere to IEEE 754: - * - * From http://support.microsoft.com/kb/78113: - * - *
    - *
  • Positive/Negative Infinities: - * Infinities occur when you divide by 0. Excel does not support infinities, rather, - * it gives a #DIV/0! error in these cases. - *
  • - *
  • - * Not-a-Number (NaN): - * NaN is used to represent invalid operations (such as infinity/infinity, - * infinity-infinity, or the square root of -1). NaNs allow a program to - * continue past an invalid operation. Excel instead immediately generates - * an error such as #NUM! or #DIV/0!. - *
  • - *
- */ - @Test - void testNanAndInfinity() throws Exception { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet workSheet = wb1.createSheet("Sheet1"); - Row row = workSheet.createRow(0); - - Cell cell0 = row.createCell(0); - cell0.setCellValue(Double.NaN); - assertEquals(CellType.ERROR, cell0.getCellType(), "Double.NaN should change cell type to CellType#ERROR"); - assertEquals(FormulaError.NUM, forInt(cell0.getErrorCellValue()), "Double.NaN should change cell value to #NUM!"); - - Cell cell1 = row.createCell(1); - cell1.setCellValue(Double.POSITIVE_INFINITY); - assertEquals(CellType.ERROR, cell1.getCellType(), "Double.POSITIVE_INFINITY should change cell type to CellType#ERROR"); - assertEquals(FormulaError.DIV0, forInt(cell1.getErrorCellValue()), "Double.POSITIVE_INFINITY should change cell value to #DIV/0!"); - - Cell cell2 = row.createCell(2); - cell2.setCellValue(Double.NEGATIVE_INFINITY); - assertEquals(CellType.ERROR, cell2.getCellType(), "Double.NEGATIVE_INFINITY should change cell type to CellType#ERROR"); - assertEquals(FormulaError.DIV0, forInt(cell2.getErrorCellValue()), "Double.NEGATIVE_INFINITY should change cell value to #DIV/0!"); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - row = wb2.getSheetAt(0).getRow(0); - - cell0 = row.getCell(0); - assertEquals(CellType.ERROR, cell0.getCellType()); - assertEquals(FormulaError.NUM, forInt(cell0.getErrorCellValue())); - - cell1 = row.getCell(1); - assertEquals(CellType.ERROR, cell1.getCellType()); - assertEquals(FormulaError.DIV0, forInt(cell1.getErrorCellValue())); - - cell2 = row.getCell(2); - assertEquals(CellType.ERROR, cell2.getCellType()); - assertEquals(FormulaError.DIV0, forInt(cell2.getErrorCellValue())); - } - } - } - - @Test - void testDefaultStyleProperties() throws Exception { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - - Cell cell = wb1.createSheet("Sheet1").createRow(0).createCell(0); - CellStyle style = cell.getCellStyle(); - - assertTrue(style.getLocked()); - assertFalse(style.getHidden()); - assertEquals(0, style.getIndention()); - assertEquals(0, style.getFontIndex()); - assertEquals(HorizontalAlignment.GENERAL, style.getAlignment()); - assertEquals(0, style.getDataFormat()); - assertFalse(style.getWrapText()); - - CellStyle style2 = wb1.createCellStyle(); - assertTrue(style2.getLocked()); - assertFalse(style2.getHidden()); - style2.setLocked(false); - style2.setHidden(true); - assertFalse(style2.getLocked()); - assertTrue(style2.getHidden()); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - cell = wb2.getSheetAt(0).getRow(0).getCell(0); - style = cell.getCellStyle(); - assertFalse(style2.getLocked()); - assertTrue(style2.getHidden()); - assertTrue(style.getLocked()); - assertFalse(style.getHidden()); - - style2.setLocked(true); - style2.setHidden(false); - assertTrue(style2.getLocked()); - assertFalse(style2.getHidden()); - } - } - } - - @Test - void testBug55658SetNumericValue() throws Exception { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sh = wb1.createSheet(); - Row row = sh.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(23); - - cell.setCellValue("some"); - - cell = row.createCell(1); - cell.setCellValue(23); - - cell.setCellValue("24"); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - assertEquals("some", wb2.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); - assertEquals("24", wb2.getSheetAt(0).getRow(0).getCell(1).getStringCellValue()); - } - } - } - - @Test - void testRemoveHyperlink() throws Exception { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sh = wb1.createSheet("test"); - Row row = sh.createRow(0); - CreationHelper helper = wb1.getCreationHelper(); - - Cell cell1 = row.createCell(1); - Hyperlink link1 = helper.createHyperlink(HyperlinkType.URL); - cell1.setHyperlink(link1); - assertNotNull(cell1.getHyperlink()); - cell1.removeHyperlink(); - assertNull(cell1.getHyperlink()); - - Cell cell2 = row.createCell(0); - Hyperlink link2 = helper.createHyperlink(HyperlinkType.URL); - cell2.setHyperlink(link2); - assertNotNull(cell2.getHyperlink()); - cell2.setHyperlink(null); - assertNull(cell2.getHyperlink()); - - Cell cell3 = row.createCell(2); - Hyperlink link3 = helper.createHyperlink(HyperlinkType.URL); - link3.setAddress("https://poi.apache.org/"); - cell3.setHyperlink(link3); - assertNotNull(cell3.getHyperlink()); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - assertNotNull(wb2); - - cell1 = wb2.getSheet("test").getRow(0).getCell(1); - assertNull(cell1.getHyperlink()); - cell2 = wb2.getSheet("test").getRow(0).getCell(0); - assertNull(cell2.getHyperlink()); - cell3 = wb2.getSheet("test").getRow(0).getCell(2); - assertNotNull(cell3.getHyperlink()); - } - } - } - - /** - * Cell with the formula that returns error must return error code(There was - * an problem that cell could not return error value form formula cell). - */ - @Test - void testGetErrorCellValueFromFormulaCell() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellFormula("SQRT(-1)"); - wb.getCreationHelper().createFormulaEvaluator().evaluateFormulaCell(cell); - assertEquals(36, cell.getErrorCellValue()); - } - } - - @Test - void testSetRemoveStyle() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - // different default style indexes for HSSF and XSSF/SXSSF - CellStyle defaultStyle = wb.getCellStyleAt(wb instanceof HSSFWorkbook ? (short) 15 : (short) 0); - - // Starts out with the default style - assertEquals(defaultStyle, cell.getCellStyle()); - - // Create some styles, no change - CellStyle style1 = wb.createCellStyle(); - CellStyle style2 = wb.createCellStyle(); - style1.setDataFormat((short) 2); - style2.setDataFormat((short) 3); - - assertEquals(defaultStyle, cell.getCellStyle()); - - // Apply one, changes - cell.setCellStyle(style1); - assertEquals(style1, cell.getCellStyle()); - - // Apply the other, changes - cell.setCellStyle(style2); - assertEquals(style2, cell.getCellStyle()); - - // Remove, goes back to default - cell.setCellStyle(null); - assertEquals(defaultStyle, cell.getCellStyle()); - - // Add back, returns - cell.setCellStyle(style2); - assertEquals(style2, cell.getCellStyle()); - } - } - - @Test - void test57008() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet(); - - Row row0 = sheet.createRow(0); - Cell cell0 = row0.createCell(0); - cell0.setCellValue("row 0, cell 0 _x0046_ without changes"); - - Cell cell1 = row0.createCell(1); - cell1.setCellValue("row 0, cell 1 _x005fx0046_ with changes"); - - Cell cell2 = row0.createCell(2); - cell2.setCellValue("hgh_x0041_**_x0100_*_x0101_*_x0190_*_x0200_*_x0300_*_x0427_*"); - - checkUnicodeValues(wb1); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - checkUnicodeValues(wb2); - } - } - } - - /** - * Setting a cell value of a null RichTextString should set - * the cell to Blank, test case for 58558 - */ - @SuppressWarnings("ConstantConditions") - @Test - void testSetCellValueNullRichTextString() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - Cell cell = sheet.createRow(0).createCell(0); - - RichTextString nullStr = null; - cell.setCellValue(nullStr); - assertEquals("", cell.getStringCellValue()); - assertEquals(CellType.BLANK, cell.getCellType()); - - cell = sheet.createRow(0).createCell(1); - cell.setCellValue(1.2d); - assertEquals(CellType.NUMERIC, cell.getCellType()); - cell.setCellValue(nullStr); - assertEquals("", cell.getStringCellValue()); - assertEquals(CellType.BLANK, cell.getCellType()); - - cell = sheet.createRow(0).createCell(1); - cell.setCellValue(wb.getCreationHelper().createRichTextString("Test")); - assertEquals(CellType.STRING, cell.getCellType()); - cell.setCellValue(nullStr); - assertEquals("", cell.getStringCellValue()); - assertEquals(CellType.BLANK, cell.getCellType()); - } - } - - private void checkUnicodeValues(Workbook wb) { - assertEquals((wb instanceof HSSFWorkbook ? "row 0, cell 0 _x0046_ without changes" : "row 0, cell 0 F without changes"), - wb.getSheetAt(0).getRow(0).getCell(0).toString()); - assertEquals((wb instanceof HSSFWorkbook ? "row 0, cell 1 _x005fx0046_ with changes" : "row 0, cell 1 _x005fx0046_ with changes"), - wb.getSheetAt(0).getRow(0).getCell(1).toString()); - assertEquals((wb instanceof HSSFWorkbook ? "hgh_x0041_**_x0100_*_x0101_*_x0190_*_x0200_*_x0300_*_x0427_*" : "hghA**\u0100*\u0101*\u0190*\u0200*\u0300*\u0427*"), - wb.getSheetAt(0).getRow(0).getCell(2).toString()); - } - - /** - * The maximum length of cell contents (text) is 32,767 characters. - */ - @Test - void testMaxTextLength() throws IOException{ - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - Cell cell = sheet.createRow(0).createCell(0); - - int maxlen = wb instanceof HSSFWorkbook ? - SpreadsheetVersion.EXCEL97.getMaxTextLength() - : SpreadsheetVersion.EXCEL2007.getMaxTextLength(); - assertEquals(32767, maxlen); - - StringBuilder b = new StringBuilder(); - - // 32767 is okay - for (int i = 0; i < maxlen; i++) { - b.append("X"); - } - cell.setCellValue(b.toString()); - - b.append("X"); - // 32768 produces an invalid XLS file - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> cell.setCellValue(b.toString())); - assertEquals("The maximum length of cell contents (text) is 32767 characters", e.getMessage()); - } - } - - /** - * Tests that the setAsActiveCell and getActiveCell function pairs work together - */ - @Test - void setAsActiveCell() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - - A1.setAsActiveCell(); - assertEquals(A1.getAddress(), sheet.getActiveCell()); - - B1.setAsActiveCell(); - assertEquals(B1.getAddress(), sheet.getActiveCell()); - } - } - - @Test - void getCellComment() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - CreationHelper factory = wb.getCreationHelper(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(1); - - // cell does not have a comment - assertNull(cell.getCellComment()); - - // add a cell comment - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(cell.getColumnIndex()); - anchor.setCol2(cell.getColumnIndex() + 1); - anchor.setRow1(row.getRowNum()); - anchor.setRow2(row.getRowNum() + 3); - - Drawing drawing = sheet.createDrawingPatriarch(); - Comment comment = drawing.createCellComment(anchor); - RichTextString str = factory.createRichTextString("Hello, World!"); - comment.setString(str); - comment.setAuthor("Apache POI"); - cell.setCellComment(comment); - // ideally assertSame, but XSSFCell creates a new XSSFCellComment wrapping the same bean for every call to getCellComment. - assertEquals(comment, cell.getCellComment()); - } - } - - @Test - void testSetErrorValue() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellFormula("A2"); - cell.setCellErrorValue(FormulaError.NAME.getCode()); - - assertEquals(CellType.FORMULA, cell.getCellType(), "Should still be a formula even after we set an error value"); - assertEquals(CellType.ERROR, cell.getCachedFormulaResultType(), "Should still be a formula even after we set an error value"); - assertEquals("A2", cell.getCellFormula()); - assertThrows(IllegalStateException.class, cell::getNumericCellValue); - assertThrows(IllegalStateException.class, cell::getStringCellValue); - assertThrows(IllegalStateException.class, cell::getRichStringCellValue); - assertThrows(IllegalStateException.class, cell::getDateCellValue); - - assertEquals(FormulaError.NAME.getCode(), cell.getErrorCellValue()); - assertNull(cell.getHyperlink()); - } - } - - @Test - void test62216() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell instance = wb.createSheet().createRow(0).createCell(0); - String formula = "2"; - instance.setCellFormula(formula); - instance.setCellErrorValue(FormulaError.NAME.getCode()); - - assertEquals(formula, instance.getCellFormula()); - } - } - - @Test - void testSetNullValues() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = wb.createSheet("test").createRow(0).createCell(0); - - cell.setCellValue((Calendar) null); - assertEquals(CellType.BLANK, cell.getCellType()); - assertEquals("", cell.getStringCellValue()); - - cell.setCellValue((Date) null); - assertEquals(CellType.BLANK, cell.getCellType()); - assertEquals("", cell.getStringCellValue()); - - cell.setCellValue((String) null); - assertEquals(CellType.BLANK, cell.getCellType()); - assertEquals("", cell.getStringCellValue()); - - assertEquals(CellType.BLANK, cell.getCellType()); - assertEquals("", cell.getStringCellValue()); - - cell.setCellValue((RichTextString) null); - assertEquals(CellType.BLANK, cell.getCellType()); - assertEquals("", cell.getStringCellValue()); - - cell.setCellValue((String) null); - assertEquals(CellType.BLANK, cell.getCellType()); - assertEquals("", cell.getStringCellValue()); - } - } - - @Test - void testFormulaSetValueDoesNotChangeType() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellFormula("SQRT(-1)"); - - assertEquals(CellType.FORMULA, cell.getCellType()); - - cell.setCellValue(new Date()); - assertEquals(CellType.FORMULA, cell.getCellType()); - - cell.setCellValue(GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ROOT)); - assertEquals(CellType.FORMULA, cell.getCellType()); - - cell.setCellValue(1.0); - assertEquals(CellType.FORMULA, cell.getCellType()); - - cell.setCellValue("test"); - assertEquals(CellType.FORMULA, cell.getCellType()); - - cell.setCellValue(wb.getCreationHelper().createRichTextString("test")); - assertEquals(CellType.FORMULA, cell.getCellType()); - - cell.setCellValue(false); - assertEquals(CellType.FORMULA, cell.getCellType()); - } - } - - @Test - void testGetNumericCellValueOnABlankCellReturnsZero() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Cell cell = workbook.createSheet().createRow(0).createCell(0); - assertEquals(CellType.BLANK, cell.getCellType()); - assertEquals(0, cell.getNumericCellValue(), 0); - } - } - - @Test - void getDateCellValue_returnsNull_onABlankCell() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Cell cell = workbook.createSheet().createRow(0).createCell(0); - assertEquals(CellType.BLANK, cell.getCellType()); - Date result = cell.getDateCellValue(); - assertNull(result); - } - } - - @Test - void getBooleanCellValue_returnsFalse_onABlankCell() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Cell cell = workbook.createSheet().createRow(0).createCell(0); - assertEquals(CellType.BLANK, cell.getCellType()); - boolean result = cell.getBooleanCellValue(); - assertFalse(result); - } - } - - @Test - void setStringCellValue_ifThrows_shallNotChangeCell() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Cell cell = workbook.createSheet().createRow(0).createCell(0); - - final double value = 2.78; - cell.setCellValue(value); - assertEquals(CellType.NUMERIC, cell.getCellType()); - - int badLength = cell.getSheet().getWorkbook().getSpreadsheetVersion().getMaxTextLength() + 1; - String badStringValue = new String(new byte[badLength], StandardCharsets.UTF_8); - - try { - cell.setCellValue(badStringValue); - } catch (IllegalArgumentException e) { - // no-op, expected to throw but we need to assert something more - } - - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertEquals(value, cell.getNumericCellValue(), 0); - } - } - - @Test - void setStringCellValueWithRichTextString_ifThrows_shallNotChangeCell() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Cell cell = workbook.createSheet().createRow(0).createCell(0); - - final double value = 2.78; - cell.setCellValue(value); - assertEquals(CellType.NUMERIC, cell.getCellType()); - - int badLength = cell.getSheet().getWorkbook().getSpreadsheetVersion().getMaxTextLength() + 1; - RichTextString badStringValue = cell.getSheet().getWorkbook().getCreationHelper(). - createRichTextString(new String(new byte[badLength], StandardCharsets.UTF_8)); - - try { - cell.setCellValue(badStringValue); - } catch (IllegalArgumentException e) { - // no-op, expected to throw but we need to assert something more - } - - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertEquals(value, cell.getNumericCellValue(), 0); - } - } - - @Test - void setCellType_null_throwsIAE() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - assertThrows(IllegalArgumentException.class, () -> cell.setCellType(null)); - } - } - - @Test - void setCellType_NONE_throwsIAE() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - assertThrows(IllegalArgumentException.class, () -> cell.setCellType(CellType._NONE)); - } - } - - - @Test - protected void setBlank_removesArrayFormula_ifCellIsPartOfAnArrayFormulaGroupContainingOnlyThisCell() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - - cell.getSheet().setArrayFormula("1", CellRangeAddress.valueOf("A1")); - cell.setCellValue("foo"); - assertTrue(cell.isPartOfArrayFormulaGroup()); - assertEquals("1", cell.getCellFormula()); - - cell.setBlank(); - - assertEquals(CellType.BLANK, cell.getCellType()); - assertFalse(cell.isPartOfArrayFormulaGroup()); - } - } - - @Test - protected void setBlank_throwsISE_ifCellIsPartOfAnArrayFormulaGroupContainingOtherCells() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - cell.getSheet().setArrayFormula("1", CellRangeAddress.valueOf("A1:B1")); - cell.setCellValue("foo"); - assertThrows(IllegalStateException.class, cell::setBlank); - } - } - - @Test - protected void setCellFormula_throwsISE_ifCellIsPartOfAnArrayFormulaGroupContainingOtherCells() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - - cell.getSheet().setArrayFormula("1", CellRangeAddress.valueOf("A1:B1")); - assertTrue(cell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, cell.getCellType()); - - assertThrows(IllegalStateException.class, () -> cell.setCellFormula("1")); - } - } - - @Test - void removeFormula_preservesValue() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - - cell.setCellFormula("#DIV/0!"); - cell.setCellValue(true); - cell.removeFormula(); - assertEquals(CellType.BOOLEAN, cell.getCellType()); - assertTrue(cell.getBooleanCellValue()); - - cell.setCellFormula("#DIV/0!"); - cell.setCellValue(2); - cell.removeFormula(); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertEquals(2, cell.getNumericCellValue(), 0); - - cell.setCellFormula("#DIV/0!"); - cell.setCellValue("foo"); - cell.removeFormula(); - assertEquals(CellType.STRING, cell.getCellType()); - assertEquals("foo", cell.getStringCellValue()); - - cell.setCellFormula("#DIV/0!"); - cell.setCellErrorValue(FormulaError.NUM.getCode()); - cell.removeFormula(); - assertEquals(CellType.ERROR, cell.getCellType()); - assertEquals(FormulaError.NUM.getCode(), cell.getErrorCellValue()); - } - } - - @Test - protected void removeFormula_turnsCellToBlank_whenFormulaWasASingleCellArrayFormula() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - - cell.getSheet().setArrayFormula("#DIV/0!", CellRangeAddress.valueOf("A1")); - cell.setCellValue(true); - cell.removeFormula(); - assertEquals(CellType.BLANK, cell.getCellType()); - - cell.getSheet().setArrayFormula("#DIV/0!", CellRangeAddress.valueOf("A1")); - cell.setCellValue(2); - cell.removeFormula(); - assertEquals(CellType.BLANK, cell.getCellType()); - - cell.getSheet().setArrayFormula("#DIV/0!", CellRangeAddress.valueOf("A1")); - cell.setCellValue(true); - cell.removeFormula(); - assertEquals(CellType.BLANK, cell.getCellType()); - - cell.getSheet().setArrayFormula("#DIV/0!", CellRangeAddress.valueOf("A1")); - cell.setCellErrorValue(FormulaError.NUM.getCode()); - cell.removeFormula(); - assertEquals(CellType.BLANK, cell.getCellType()); - } - } - - @Test - void setCellFormula_onABlankCell_setsValueToZero() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - cell.setCellFormula("\"foo\""); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType()); - assertEquals(0, cell.getNumericCellValue(), 0); - } - } - - - @Test - void setCellFormula_onANonBlankCell_preservesTheValue() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - cell.setCellValue(true); - cell.setCellFormula("\"foo\""); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.BOOLEAN, cell.getCachedFormulaResultType()); - assertTrue(cell.getBooleanCellValue(), "Expected a boolean cell-value, but had 'false'"); - } - } - - @Test - void setCellFormula_onAFormulaCell_changeFormula_preservesTheValue() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - cell.setCellFormula("\"foo\""); - cell.setCellValue(true); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.BOOLEAN, cell.getCachedFormulaResultType()); - assertTrue(cell.getBooleanCellValue()); - - cell.setCellFormula("\"bar\""); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.BOOLEAN, cell.getCachedFormulaResultType()); - assertTrue(cell.getBooleanCellValue(), "Expected a boolean cell-value, but had 'false'"); - } - } - - @Test - protected void setCellFormula_onASingleCellArrayFormulaCell_preservesTheValue() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - cell.getSheet().setArrayFormula("\"foo\"", CellRangeAddress.valueOf("A1")); - cell.setCellValue(true); - - assertTrue(cell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.BOOLEAN, cell.getCachedFormulaResultType()); - assertTrue(cell.getBooleanCellValue()); - - cell.getSheet().setArrayFormula("\"bar\"", CellRangeAddress.valueOf("A1")); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.BOOLEAN, cell.getCachedFormulaResultType(), - "Expected a boolean cell-value, but had " + cell.getCachedFormulaResultType()); - assertTrue(cell.getBooleanCellValue(), - "Expected a boolean cell-value, but had 'false'"); - } - } - - @Test - void setCellType_FORMULA_onANonFormulaCell_throwsIllegalArgumentException() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - assertThrows(IllegalArgumentException.class, () -> cell.setCellType(CellType.FORMULA)); - } - } - - @Test - void setCellType_FORMULA_onAFormulaCell_doesNothing() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - cell.setCellFormula("3"); - cell.setCellValue("foo"); - - cell.setCellType(CellType.FORMULA); - - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.STRING, cell.getCachedFormulaResultType()); - assertEquals("foo", cell.getStringCellValue()); - } - } - - @Test - void setCellType_FORMULA_onAnArrayFormulaCell_doesNothing() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Cell cell = getInstance(wb); - cell.getSheet().setArrayFormula("3", CellRangeAddress.valueOf("A1:A2")); - cell.setCellValue("foo"); - - cell.setCellType(CellType.FORMULA); - - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals(CellType.STRING, cell.getCachedFormulaResultType()); - assertEquals("foo", cell.getStringCellValue()); - } - } - - @Test - public final void setBlank_delegatesTo_setCellType_BLANK() { - Cell cell = mock(CellBase.class); - doCallRealMethod().when(cell).setBlank(); - - cell.setBlank(); - - verify(cell).setBlank(); - } - - private Cell getInstance(Workbook wb) { - return wb.createSheet().createRow(0).createCell(0); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCellComment.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCellComment.java deleted file mode 100644 index 25bd602c51..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCellComment.java +++ /dev/null @@ -1,421 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.apache.poi.util.Units.EMU_PER_PIXEL; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.util.Units; -import org.junit.jupiter.api.Test; - -/** - * Common superclass for testing implementations of - * {@link Comment} - */ -public abstract class BaseTestCellComment { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestCellComment(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public final void find() throws IOException { - Workbook book = _testDataProvider.createWorkbook(); - Sheet sheet = book.createSheet(); - assertNull(sheet.getCellComment(new CellAddress(0, 0))); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - assertNull(sheet.getCellComment(new CellAddress(0, 0))); - assertNull(cell.getCellComment()); - book.close(); - } - - @Test - public final void create() throws IOException { - String cellText = "Hello, World"; - String commentText = "We can set comments in POI"; - String commentAuthor = "Apache Software Foundation"; - int cellRow = 3; - int cellColumn = 1; - - Workbook wb1 = _testDataProvider.createWorkbook(); - CreationHelper factory = wb1.getCreationHelper(); - - Sheet sheet = wb1.createSheet(); - assertNull(sheet.getCellComment(new CellAddress(cellRow, cellColumn))); - - Cell cell = sheet.createRow(cellRow).createCell(cellColumn); - cell.setCellValue(factory.createRichTextString(cellText)); - assertNull(cell.getCellComment()); - assertNull(sheet.getCellComment(new CellAddress(cellRow, cellColumn))); - - Drawing patr = sheet.createDrawingPatriarch(); - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(2); - anchor.setCol2(5); - anchor.setRow1(1); - anchor.setRow2(2); - Comment comment = patr.createCellComment(anchor); - assertFalse(comment.isVisible()); - comment.setVisible(true); - assertTrue(comment.isVisible()); - RichTextString string1 = factory.createRichTextString(commentText); - comment.setString(string1); - comment.setAuthor(commentAuthor); - cell.setCellComment(comment); - assertNotNull(cell.getCellComment()); - assertNotNull(sheet.getCellComment(new CellAddress(cellRow, cellColumn))); - - //verify our settings - assertEquals(commentAuthor, comment.getAuthor()); - assertEquals(commentText, comment.getString().getString()); - assertEquals(cellRow, comment.getRow()); - assertEquals(cellColumn, comment.getColumn()); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - cell = sheet.getRow(cellRow).getCell(cellColumn); - comment = cell.getCellComment(); - - assertNotNull(comment); - assertEquals(commentAuthor, comment.getAuthor()); - assertEquals(commentText, comment.getString().getString()); - assertEquals(cellRow, comment.getRow()); - assertEquals(cellColumn, comment.getColumn()); - assertTrue(comment.isVisible()); - - // Change slightly, and re-test - comment.setString(factory.createRichTextString("New Comment Text")); - comment.setVisible(false); - - Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2); - wb2.close(); - - sheet = wb3.getSheetAt(0); - cell = sheet.getRow(cellRow).getCell(cellColumn); - comment = cell.getCellComment(); - - assertNotNull(comment); - assertEquals(commentAuthor, comment.getAuthor()); - assertEquals("New Comment Text", comment.getString().getString()); - assertEquals(cellRow, comment.getRow()); - assertEquals(cellColumn, comment.getColumn()); - assertFalse(comment.isVisible()); - - // Test Comment.equals and Comment.hashCode - assertEquals(comment, cell.getCellComment()); - assertEquals(comment.hashCode(), cell.getCellComment().hashCode()); - - wb3.close(); - } - - /** - * test that we can read cell comments from an existing workbook. - */ - @Test - public final void readComments() throws IOException { - - Workbook wb = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension()); - - Sheet sheet = wb.getSheetAt(0); - - Cell cell; - Row row; - Comment comment; - - for (int rownum = 0; rownum < 3; rownum++) { - row = sheet.getRow(rownum); - cell = row.getCell(0); - comment = cell.getCellComment(); - assertNull(comment, "Cells in the first column are not commented"); - assertNull(sheet.getCellComment(new CellAddress(rownum, 0))); - } - - for (int rownum = 0; rownum < 3; rownum++) { - row = sheet.getRow(rownum); - cell = row.getCell(1); - comment = cell.getCellComment(); - assertNotNull(comment, "Cells in the second column have comments"); - assertNotNull(sheet.getCellComment(new CellAddress(rownum, 1)), "Cells in the second column have comments"); - - assertEquals("Yegor Kozlov", comment.getAuthor()); - assertFalse(comment.getString().getString().isEmpty()); - assertEquals(rownum, comment.getRow()); - assertEquals(cell.getColumnIndex(), comment.getColumn()); - } - - wb.close(); - } - - /** - * test that we can modify existing cell comments - */ - @Test - public final void modifyComments() throws IOException { - - Workbook wb1 = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension()); - CreationHelper factory = wb1.getCreationHelper(); - - Sheet sheet = wb1.getSheetAt(0); - - Cell cell; - Row row; - Comment comment; - - for (int rownum = 0; rownum < 3; rownum++) { - row = sheet.getRow(rownum); - cell = row.getCell(1); - comment = cell.getCellComment(); - comment.setAuthor("Mofified[" + rownum + "] by Yegor"); - comment.setString(factory.createRichTextString("Modified comment at row " + rownum)); - } - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - for (int rownum = 0; rownum < 3; rownum++) { - row = sheet.getRow(rownum); - cell = row.getCell(1); - comment = cell.getCellComment(); - - assertEquals("Mofified[" + rownum + "] by Yegor", comment.getAuthor()); - assertEquals("Modified comment at row " + rownum, comment.getString().getString()); - } - - wb2.close(); - } - - @Test - public final void deleteComments() throws IOException { - Workbook wb1 = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension()); - Sheet sheet = wb1.getSheetAt(0); - - // Zap from rows 1 and 3 - assertNotNull(sheet.getRow(0).getCell(1).getCellComment()); - assertNotNull(sheet.getRow(1).getCell(1).getCellComment()); - assertNotNull(sheet.getRow(2).getCell(1).getCellComment()); - - sheet.getRow(0).getCell(1).removeCellComment(); - sheet.getRow(2).getCell(1).setCellComment(null); - - // Check gone so far - assertNull(sheet.getRow(0).getCell(1).getCellComment()); - assertNotNull(sheet.getRow(1).getCell(1).getCellComment()); - assertNull(sheet.getRow(2).getCell(1).getCellComment()); - - // Save and re-load - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - // Check - assertNull(sheet.getRow(0).getCell(1).getCellComment()); - assertNotNull(sheet.getRow(1).getCell(1).getCellComment()); - assertNull(sheet.getRow(2).getCell(1).getCellComment()); - - wb2.close(); - } - - /** - * code from the quick guide - */ - @Test - void quickGuide() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - - CreationHelper factory = wb1.getCreationHelper(); - - Sheet sheet = wb1.createSheet(); - - Cell cell = sheet.createRow(3).createCell(5); - cell.setCellValue("F4"); - - Drawing drawing = sheet.createDrawingPatriarch(); - - ClientAnchor anchor = factory.createClientAnchor(); - Comment comment = drawing.createCellComment(anchor); - RichTextString str = factory.createRichTextString("Hello, World!"); - comment.setString(str); - comment.setAuthor("Apache POI"); - //assign the comment to the cell - cell.setCellComment(comment); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - cell = sheet.getRow(3).getCell(5); - comment = cell.getCellComment(); - assertNotNull(comment); - assertEquals("Hello, World!", comment.getString().getString()); - assertEquals("Apache POI", comment.getAuthor()); - assertEquals(3, comment.getRow()); - assertEquals(5, comment.getColumn()); - - wb2.close(); - } - - @Test - void getClientAnchor() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(10); - Cell cell = row.createCell(5); - CreationHelper factory = wb.getCreationHelper(); - - Drawing drawing = sheet.createDrawingPatriarch(); - - double r_mul, c_mul; - if (sheet instanceof HSSFSheet) { - double rowheight = Units.toEMU(row.getHeightInPoints())/(double)EMU_PER_PIXEL; - r_mul = 256.0/rowheight; - double colwidth = sheet.getColumnWidthInPixels(2); - c_mul = 1024.0/colwidth; - } else { - r_mul = c_mul = EMU_PER_PIXEL; - } - - int dx1 = (int)Math.round(10*c_mul); - int dy1 = (int)Math.round(10*r_mul); - int dx2 = (int)Math.round(3*c_mul); - int dy2 = (int)Math.round(4*r_mul); - int col1 = cell.getColumnIndex()+1; - int row1 = row.getRowNum(); - int col2 = cell.getColumnIndex()+2; - int row2 = row.getRowNum()+1; - - ClientAnchor anchor = drawing.createAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2); - Comment comment = drawing.createCellComment(anchor); - comment.setVisible(true); - cell.setCellComment(comment); - - anchor = comment.getClientAnchor(); - assertEquals(dx1, anchor.getDx1()); - assertEquals(dy1, anchor.getDy1()); - assertEquals(dx2, anchor.getDx2()); - assertEquals(dy2, anchor.getDy2()); - assertEquals(col1, anchor.getCol1()); - assertEquals(row1, anchor.getRow1()); - assertEquals(col2, anchor.getCol2()); - assertEquals(row2, anchor.getRow2()); - - anchor = factory.createClientAnchor(); - comment = drawing.createCellComment(anchor); - cell.setCellComment(comment); - anchor = comment.getClientAnchor(); - - if (sheet instanceof HSSFSheet) { - assertEquals(0, anchor.getCol1()); - assertEquals(0, anchor.getDx1()); - assertEquals(0, anchor.getRow1()); - assertEquals(0, anchor.getDy1()); - assertEquals(0, anchor.getCol2()); - assertEquals(0, anchor.getDx2()); - assertEquals(0, anchor.getRow2()); - assertEquals(0, anchor.getDy2()); - } else { - // when anchor is initialized without parameters, the comment anchor attributes default to - // "1, 15, 0, 2, 3, 15, 3, 16" ... see XSSFVMLDrawing.newCommentShape() - assertEquals( 1, anchor.getCol1()); - assertEquals(15*EMU_PER_PIXEL, anchor.getDx1()); - assertEquals( 0, anchor.getRow1()); - assertEquals( 2*EMU_PER_PIXEL, anchor.getDy1()); - assertEquals( 3, anchor.getCol2()); - assertEquals(15*EMU_PER_PIXEL, anchor.getDx2()); - assertEquals( 3, anchor.getRow2()); - assertEquals(16*EMU_PER_PIXEL, anchor.getDy2()); - } - - wb.close(); - } - - @Test - void attemptToSave2CommentsWithSameCoordinates() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sh = wb.createSheet(); - CreationHelper factory = wb.getCreationHelper(); - Drawing patriarch = sh.createDrawingPatriarch(); - patriarch.createCellComment(factory.createClientAnchor()); - - RuntimeException e = assertThrows(RuntimeException.class, () -> { - patriarch.createCellComment(factory.createClientAnchor()); - _testDataProvider.writeOutAndReadBack(wb); - }, "Should not be able to create a corrupted workbook with multiple cell comments in one cell"); - - if (wb instanceof HSSFWorkbook) { - // HSSFWorkbooks fail when writing out workbook - assertTrue(e instanceof IllegalStateException); - assertEquals("found multiple cell comments for cell $A$1", e.getMessage()); - } else { - // XSSFWorkbooks fail when creating and setting the cell address of the comment - assertTrue(e instanceof IllegalArgumentException); - assertEquals("Multiple cell comments in one cell are not allowed, cell: A1", e.getMessage()); - } - } - } - - @Test - void getAddress() { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - CreationHelper factory = wb.getCreationHelper(); - Drawing patriarch = sh.createDrawingPatriarch(); - Comment comment = patriarch.createCellComment(factory.createClientAnchor()); - - assertEquals(CellAddress.A1, comment.getAddress()); - Cell C2 = sh.createRow(1).createCell(2); - C2.setCellComment(comment); - assertEquals(new CellAddress("C2"), comment.getAddress()); - } - - @Test - void setAddress() { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - CreationHelper factory = wb.getCreationHelper(); - Drawing patriarch = sh.createDrawingPatriarch(); - Comment comment = patriarch.createCellComment(factory.createClientAnchor()); - - assertEquals(CellAddress.A1, comment.getAddress()); - CellAddress C2 = new CellAddress("C2"); - assertEquals("C2", C2.formatAsString()); - comment.setAddress(C2); - assertEquals(C2, comment.getAddress()); - - CellAddress E10 = new CellAddress(9, 4); - assertEquals("E10", E10.formatAsString()); - comment.setAddress(9, 4); - assertEquals(E10, comment.getAddress()); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCloneSheet.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCloneSheet.java deleted file mode 100644 index 7d9cd0c448..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCloneSheet.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Test; - -/** - * Common superclass for testing implementations of - * Workbook.cloneSheet() - */ -public abstract class BaseTestCloneSheet { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestCloneSheet(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - void testCloneSheetBasic() throws IOException{ - Workbook b = _testDataProvider.createWorkbook(); - Sheet s = b.createSheet("Test"); - assertEquals(0, s.addMergedRegion(new CellRangeAddress(0, 1, 0, 1))); - Sheet clonedSheet = b.cloneSheet(0); - - assertEquals(1, clonedSheet.getNumMergedRegions(), "One merged area"); - - b.close(); - } - - /** - * Ensures that pagebreak cloning works properly - */ - @Test - void testPageBreakClones() throws IOException { - Workbook b = _testDataProvider.createWorkbook(); - Sheet s = b.createSheet("Test"); - s.setRowBreak(3); - s.setColumnBreak((short) 6); - - Sheet clone = b.cloneSheet(0); - assertTrue(clone.isRowBroken(3), "Row 3 not broken"); - assertTrue(clone.isColumnBroken((short) 6), "Column 6 not broken"); - - s.removeRowBreak(3); - - assertTrue(clone.isRowBroken(3), "Row 3 still should be broken"); - - b.close(); - } - - @Test - void testCloneSheetIntValid() { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Sheet01"); - wb.cloneSheet(0); - assertEquals(2, wb.getNumberOfSheets()); - assertThrows(IllegalArgumentException.class, () -> wb.cloneSheet(2)); - } - - @Test - void testCloneSheetIntInvalid() { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Sheet01"); - assertThrows(IllegalArgumentException.class, () -> wb.cloneSheet(1)); - assertEquals(1, wb.getNumberOfSheets()); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestColumnShifting.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestColumnShifting.java deleted file mode 100644 index 9acd338e11..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestColumnShifting.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.apache.poi.ss.usermodel.helpers.ColumnShifter; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public abstract class BaseTestColumnShifting { - protected Workbook wb; - protected Sheet sheet1; - protected ColumnShifter columnShifter; - - @BeforeEach - void init() { - int rowIndex = 0; - sheet1 = wb.createSheet("sheet1"); - Row row = sheet1.createRow(rowIndex++); - row.createCell(0, CellType.NUMERIC).setCellValue(0); - row.createCell(3, CellType.NUMERIC).setCellValue(3); - row.createCell(4, CellType.NUMERIC).setCellValue(4); - - row = sheet1.createRow(rowIndex++); - row.createCell(0, CellType.NUMERIC).setCellValue(0.1); - row.createCell(1, CellType.NUMERIC).setCellValue(1.1); - row.createCell(2, CellType.NUMERIC).setCellValue(2.1); - row.createCell(3, CellType.NUMERIC).setCellValue(3.1); - row.createCell(4, CellType.NUMERIC).setCellValue(4.1); - row.createCell(5, CellType.NUMERIC).setCellValue(5.1); - row.createCell(6, CellType.NUMERIC).setCellValue(6.1); - row.createCell(7, CellType.NUMERIC).setCellValue(7.1); - row = sheet1.createRow(rowIndex++); - row.createCell(3, CellType.NUMERIC).setCellValue(3.2); - row.createCell(5, CellType.NUMERIC).setCellValue(5.2); - row.createCell(7, CellType.NUMERIC).setCellValue(7.2); - - initColumnShifter(); - } - - protected void initColumnShifter() {} - - @Test - void testShift3ColumnsRight() { - columnShifter.shiftColumns(1, 2, 3); - - Cell cell = sheet1.getRow(0).getCell(4); - assertNull(cell); - cell = sheet1.getRow(1).getCell(4); - assertEquals(1.1, cell.getNumericCellValue(), 0.01); - cell = sheet1.getRow(1).getCell(5); - assertEquals(2.1, cell.getNumericCellValue(), 0.01); - cell = sheet1.getRow(2).getCell(4); - assertNull(cell); - } - - @Test - void testShiftLeft() { - assertThrows(IllegalStateException.class, () -> columnShifter.shiftColumns(1, 2, -3), - "Shift to negative indices should throw exception"); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestConditionalFormatting.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestConditionalFormatting.java deleted file mode 100644 index 4d3954fa78..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestConditionalFormatting.java +++ /dev/null @@ -1,1385 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFConditionalFormatting; -import org.apache.poi.hssf.usermodel.HSSFConditionalFormattingRule; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold.RangeType; -import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; - -/** - * Base tests for Conditional Formatting, for both HSSF and XSSF - */ -public abstract class BaseTestConditionalFormatting { - private final ITestDataProvider _testDataProvider; - - protected BaseTestConditionalFormatting(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - protected boolean applyLimitOf3() { - return true; - } - - protected abstract void assertColor(String hexExpected, Color actual); - - @Test - void testBasic() throws Throwable { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sh = wb.createSheet(); - SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); - - assertEquals(0, sheetCF.getNumConditionalFormattings()); - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> sheetCF.getConditionalFormattingAt(0)); - assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - - e = assertThrows(IllegalArgumentException.class, () -> sheetCF.removeConditionalFormatting(0)); - assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("1"); - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule("2"); - ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule("3"); - ConditionalFormattingRule rule4 = sheetCF.createConditionalFormattingRule("4"); - - e = assertThrows(IllegalArgumentException.class, () -> sheetCF.addConditionalFormatting(null, rule1)); - assertTrue(e.getMessage().startsWith("regions must not be null")); - - e = assertThrows(IllegalArgumentException.class, () -> sheetCF.addConditionalFormatting( - new CellRangeAddress[]{CellRangeAddress.valueOf("A1:A3")}, (ConditionalFormattingRule) null)); - assertTrue(e.getMessage().startsWith("cfRules must not be null")); - - e = assertThrows(IllegalArgumentException.class, () -> sheetCF.addConditionalFormatting( - new CellRangeAddress[]{CellRangeAddress.valueOf("A1:A3")}, new ConditionalFormattingRule[0])); - assertTrue(e.getMessage().startsWith("cfRules must not be empty")); - - Executable exec = () -> - sheetCF.addConditionalFormatting( - new CellRangeAddress[]{CellRangeAddress.valueOf("A1:A3")}, - new ConditionalFormattingRule[]{rule1, rule2, rule3, rule4}); - - if (applyLimitOf3()) { - e = assertThrows(IllegalArgumentException.class, exec); - assertTrue(e.getMessage().startsWith("Number of rules must not exceed 3")); - } else { - exec.execute(); - } - } - } - - /** - * Test format conditions based on a boolean formula - */ - @Test - void testBooleanFormulaConditions() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sh = wb.createSheet(); - SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("SUM(A1:A5)>10"); - assertEquals(ConditionType.FORMULA, rule1.getConditionType()); - assertEquals("SUM(A1:A5)>10", rule1.getFormula1()); - int formatIndex1 = sheetCF.addConditionalFormatting( - new CellRangeAddress[]{ - CellRangeAddress.valueOf("B1"), - CellRangeAddress.valueOf("C3"), - }, rule1); - assertEquals(0, formatIndex1); - assertEquals(1, sheetCF.getNumConditionalFormattings()); - CellRangeAddress[] ranges1 = sheetCF.getConditionalFormattingAt(formatIndex1).getFormattingRanges(); - assertEquals(2, ranges1.length); - assertEquals("B1", ranges1[0].formatAsString()); - assertEquals("C3", ranges1[1].formatAsString()); - - // adjacent address are merged - int formatIndex2 = sheetCF.addConditionalFormatting( - new CellRangeAddress[]{ - CellRangeAddress.valueOf("B1"), - CellRangeAddress.valueOf("B2"), - CellRangeAddress.valueOf("B3"), - }, rule1); - assertEquals(1, formatIndex2); - assertEquals(2, sheetCF.getNumConditionalFormattings()); - CellRangeAddress[] ranges2 = sheetCF.getConditionalFormattingAt(formatIndex2).getFormattingRanges(); - assertEquals(1, ranges2.length); - assertEquals("B1:B3", ranges2[0].formatAsString()); - } - } - - @Test - void testSingleFormulaConditions() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sh = wb.createSheet(); - SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.EQUAL, "SUM(A1:A5)+10"); - assertEquals(ConditionType.CELL_VALUE_IS, rule1.getConditionType()); - assertEquals("SUM(A1:A5)+10", rule1.getFormula1()); - assertEquals(ComparisonOperator.EQUAL, rule1.getComparisonOperation()); - - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.NOT_EQUAL, "15"); - assertEquals(ConditionType.CELL_VALUE_IS, rule2.getConditionType()); - assertEquals("15", rule2.getFormula1()); - assertEquals(ComparisonOperator.NOT_EQUAL, rule2.getComparisonOperation()); - - ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.NOT_EQUAL, "15"); - assertEquals(ConditionType.CELL_VALUE_IS, rule3.getConditionType()); - assertEquals("15", rule3.getFormula1()); - assertEquals(ComparisonOperator.NOT_EQUAL, rule3.getComparisonOperation()); - - ConditionalFormattingRule rule4 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.GT, "0"); - assertEquals(ConditionType.CELL_VALUE_IS, rule4.getConditionType()); - assertEquals("0", rule4.getFormula1()); - assertEquals(ComparisonOperator.GT, rule4.getComparisonOperation()); - - ConditionalFormattingRule rule5 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.LT, "0"); - assertEquals(ConditionType.CELL_VALUE_IS, rule5.getConditionType()); - assertEquals("0", rule5.getFormula1()); - assertEquals(ComparisonOperator.LT, rule5.getComparisonOperation()); - - ConditionalFormattingRule rule6 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.GE, "0"); - assertEquals(ConditionType.CELL_VALUE_IS, rule6.getConditionType()); - assertEquals("0", rule6.getFormula1()); - assertEquals(ComparisonOperator.GE, rule6.getComparisonOperation()); - - ConditionalFormattingRule rule7 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.LE, "0"); - assertEquals(ConditionType.CELL_VALUE_IS, rule7.getConditionType()); - assertEquals("0", rule7.getFormula1()); - assertEquals(ComparisonOperator.LE, rule7.getComparisonOperation()); - - ConditionalFormattingRule rule8 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.BETWEEN, "0", "5"); - assertEquals(ConditionType.CELL_VALUE_IS, rule8.getConditionType()); - assertEquals("0", rule8.getFormula1()); - assertEquals("5", rule8.getFormula2()); - assertEquals(ComparisonOperator.BETWEEN, rule8.getComparisonOperation()); - - ConditionalFormattingRule rule9 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.NOT_BETWEEN, "0", "5"); - assertEquals(ConditionType.CELL_VALUE_IS, rule9.getConditionType()); - assertEquals("0", rule9.getFormula1()); - assertEquals("5", rule9.getFormula2()); - assertEquals(ComparisonOperator.NOT_BETWEEN, rule9.getComparisonOperation()); - } - } - - @Test - void testCopy() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet1 = wb.createSheet(); - Sheet sheet2 = wb.createSheet(); - SheetConditionalFormatting sheet1CF = sheet1.getSheetConditionalFormatting(); - SheetConditionalFormatting sheet2CF = sheet2.getSheetConditionalFormatting(); - assertEquals(0, sheet1CF.getNumConditionalFormattings()); - assertEquals(0, sheet2CF.getNumConditionalFormattings()); - - ConditionalFormattingRule rule1 = sheet1CF.createConditionalFormattingRule( - ComparisonOperator.EQUAL, "SUM(A1:A5)+10"); - - ConditionalFormattingRule rule2 = sheet1CF.createConditionalFormattingRule( - ComparisonOperator.NOT_EQUAL, "15"); - - // adjacent address are merged - int formatIndex = sheet1CF.addConditionalFormatting( - new CellRangeAddress[]{ - CellRangeAddress.valueOf("A1:A5"), - CellRangeAddress.valueOf("C1:C5") - }, rule1, rule2); - assertEquals(0, formatIndex); - assertEquals(1, sheet1CF.getNumConditionalFormattings()); - - assertEquals(0, sheet2CF.getNumConditionalFormattings()); - sheet2CF.addConditionalFormatting(sheet1CF.getConditionalFormattingAt(formatIndex)); - assertEquals(1, sheet2CF.getNumConditionalFormattings()); - - ConditionalFormatting sheet2cf = sheet2CF.getConditionalFormattingAt(0); - assertEquals(2, sheet2cf.getNumberOfRules()); - assertEquals("SUM(A1:A5)+10", sheet2cf.getRule(0).getFormula1()); - assertEquals(ComparisonOperator.EQUAL, sheet2cf.getRule(0).getComparisonOperation()); - assertEquals(ConditionType.CELL_VALUE_IS, sheet2cf.getRule(0).getConditionType()); - assertEquals("15", sheet2cf.getRule(1).getFormula1()); - assertEquals(ComparisonOperator.NOT_EQUAL, sheet2cf.getRule(1).getComparisonOperation()); - assertEquals(ConditionType.CELL_VALUE_IS, sheet2cf.getRule(1).getConditionType()); - } - } - - @Test - void testRemove() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet1 = wb.createSheet(); - SheetConditionalFormatting sheetCF = sheet1.getSheetConditionalFormatting(); - assertEquals(0, sheetCF.getNumConditionalFormattings()); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.EQUAL, "SUM(A1:A5)"); - - // adjacent address are merged - int formatIndex = sheetCF.addConditionalFormatting( - new CellRangeAddress[]{CellRangeAddress.valueOf("A1:A5")}, rule1); - assertEquals(0, formatIndex); - assertEquals(1, sheetCF.getNumConditionalFormattings()); - sheetCF.removeConditionalFormatting(0); - assertEquals(0, sheetCF.getNumConditionalFormattings()); - - IllegalArgumentException e; - e = assertThrows(IllegalArgumentException.class, () -> sheetCF.getConditionalFormattingAt(0)); - assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - - formatIndex = sheetCF.addConditionalFormatting( - new CellRangeAddress[]{CellRangeAddress.valueOf("A1:A5")}, rule1); - assertEquals(0, formatIndex); - assertEquals(1, sheetCF.getNumConditionalFormattings()); - sheetCF.removeConditionalFormatting(0); - assertEquals(0, sheetCF.getNumConditionalFormattings()); - - e = assertThrows(IllegalArgumentException.class, () -> sheetCF.getConditionalFormattingAt(0)); - assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - } - } - - @Test - void testCreateCF() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - String formula = "7"; - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(formula); - FontFormatting fontFmt = rule1.createFontFormatting(); - fontFmt.setFontStyle(true, false); - - BorderFormatting bordFmt = rule1.createBorderFormatting(); - bordFmt.setBorderBottom(BorderStyle.THIN); - bordFmt.setBorderTop(BorderStyle.THICK); - bordFmt.setBorderLeft(BorderStyle.DASHED); - bordFmt.setBorderRight(BorderStyle.DOTTED); - - PatternFormatting patternFmt = rule1.createPatternFormatting(); - patternFmt.setFillBackgroundColor(IndexedColors.YELLOW.index); - - - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.BETWEEN, "1", "2"); - ConditionalFormattingRule[] cfRules = {rule1, rule2}; - - short col = 1; - CellRangeAddress[] regions = { - new CellRangeAddress(0, 65535, col, col) - }; - - sheetCF.addConditionalFormatting(regions, cfRules); - sheetCF.addConditionalFormatting(regions, cfRules); - - // Verification - assertEquals(2, sheetCF.getNumConditionalFormattings()); - sheetCF.removeConditionalFormatting(1); - assertEquals(1, sheetCF.getNumConditionalFormattings()); - ConditionalFormatting cf = sheetCF.getConditionalFormattingAt(0); - assertNotNull(cf); - - regions = cf.getFormattingRanges(); - assertNotNull(regions); - assertEquals(1, regions.length); - CellRangeAddress r = regions[0]; - assertEquals(1, r.getFirstColumn()); - assertEquals(1, r.getLastColumn()); - assertEquals(0, r.getFirstRow()); - assertEquals(65535, r.getLastRow()); - - assertEquals(2, cf.getNumberOfRules()); - - rule1 = cf.getRule(0); - assertEquals("7", rule1.getFormula1()); - assertNull(rule1.getFormula2()); - - FontFormatting r1fp = rule1.getFontFormatting(); - assertNotNull(r1fp); - - assertTrue(r1fp.isItalic()); - assertFalse(r1fp.isBold()); - - BorderFormatting r1bf = rule1.getBorderFormatting(); - assertNotNull(r1bf); - assertEquals(BorderStyle.THIN, r1bf.getBorderBottom()); - assertEquals(BorderStyle.THICK, r1bf.getBorderTop()); - assertEquals(BorderStyle.DASHED, r1bf.getBorderLeft()); - assertEquals(BorderStyle.DOTTED, r1bf.getBorderRight()); - - PatternFormatting r1pf = rule1.getPatternFormatting(); - assertNotNull(r1pf); -// assertEquals(IndexedColors.YELLOW.index,r1pf.getFillBackgroundColor()); - - rule2 = cf.getRule(1); - assertEquals("2", rule2.getFormula2()); - assertEquals("1", rule2.getFormula1()); - } - } - - @Test - void testClone() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - String formula = "7"; - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(formula); - FontFormatting fontFmt = rule1.createFontFormatting(); - fontFmt.setFontStyle(true, false); - - PatternFormatting patternFmt = rule1.createPatternFormatting(); - patternFmt.setFillBackgroundColor(IndexedColors.YELLOW.index); - - - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.BETWEEN, "1", "2"); - ConditionalFormattingRule[] cfRules = {rule1, rule2}; - - short col = 1; - CellRangeAddress[] regions = { - new CellRangeAddress(0, 65535, col, col) - }; - - sheetCF.addConditionalFormatting(regions, cfRules); - - wb.cloneSheet(0); - assertEquals(2, wb.getNumberOfSheets()); - // bug 45682 leads to runtime exception "needs to define a clone method" - } - } - - @Test - void testShiftRows() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.BETWEEN, "SUM(A10:A15)", "1+SUM(B16:B30)"); - FontFormatting fontFmt = rule1.createFontFormatting(); - fontFmt.setFontStyle(true, false); - - PatternFormatting patternFmt = rule1.createPatternFormatting(); - patternFmt.setFillBackgroundColor(IndexedColors.YELLOW.index); - - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.BETWEEN, "SUM(A10:A15)", "1+SUM(B16:B30)"); - BorderFormatting borderFmt = rule2.createBorderFormatting(); - borderFmt.setBorderDiagonal(BorderStyle.MEDIUM); - - CellRangeAddress[] regions = { - new CellRangeAddress(2, 4, 0, 0), // A3:A5 - }; - sheetCF.addConditionalFormatting(regions, rule1); - sheetCF.addConditionalFormatting(regions, rule2); - - // This row-shift should destroy the CF region - sheet.shiftRows(10, 20, -9); - assertEquals(0, sheetCF.getNumConditionalFormattings()); - - // re-add the CF - sheetCF.addConditionalFormatting(regions, rule1); - sheetCF.addConditionalFormatting(regions, rule2); - - // This row shift should only affect the formulas - sheet.shiftRows(14, 17, 8); - ConditionalFormatting cf1 = sheetCF.getConditionalFormattingAt(0); - assertEquals("SUM(A10:A23)", cf1.getRule(0).getFormula1()); - assertEquals("1+SUM(B24:B30)", cf1.getRule(0).getFormula2()); - ConditionalFormatting cf2 = sheetCF.getConditionalFormattingAt(1); - assertEquals("SUM(A10:A23)", cf2.getRule(0).getFormula1()); - assertEquals("1+SUM(B24:B30)", cf2.getRule(0).getFormula2()); - - sheet.shiftRows(0, 8, 21); - cf1 = sheetCF.getConditionalFormattingAt(0); - assertEquals("SUM(A10:A21)", cf1.getRule(0).getFormula1()); - assertEquals("1+SUM(#REF!)", cf1.getRule(0).getFormula2()); - cf2 = sheetCF.getConditionalFormattingAt(1); - assertEquals("SUM(A10:A21)", cf2.getRule(0).getFormula1()); - assertEquals("1+SUM(#REF!)", cf2.getRule(0).getFormula2()); - } - } - - protected void testRead(String filename) throws IOException { - try (Workbook wb = _testDataProvider.openSampleWorkbook(filename)) { - Sheet sh = wb.getSheet("CF"); - SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); - assertEquals(3, sheetCF.getNumConditionalFormattings()); - - ConditionalFormatting cf1 = sheetCF.getConditionalFormattingAt(0); - assertEquals(2, cf1.getNumberOfRules()); - - CellRangeAddress[] regions1 = cf1.getFormattingRanges(); - assertEquals(1, regions1.length); - assertEquals("A1:A8", regions1[0].formatAsString()); - - // CF1 has two rules: values less than -3 are bold-italic red, values greater than 3 are green - ConditionalFormattingRule rule1 = cf1.getRule(0); - assertEquals(ConditionType.CELL_VALUE_IS, rule1.getConditionType()); - assertEquals(ComparisonOperator.GT, rule1.getComparisonOperation()); - assertEquals("3", rule1.getFormula1()); - assertNull(rule1.getFormula2()); - // fills and borders are not set - assertNull(rule1.getPatternFormatting()); - assertNull(rule1.getBorderFormatting()); - - FontFormatting fmt1 = rule1.getFontFormatting(); -// assertEquals(IndexedColors.GREEN.index, fmt1.getFontColorIndex()); - assertTrue(fmt1.isBold()); - assertFalse(fmt1.isItalic()); - - ConditionalFormattingRule rule2 = cf1.getRule(1); - assertEquals(ConditionType.CELL_VALUE_IS, rule2.getConditionType()); - assertEquals(ComparisonOperator.LT, rule2.getComparisonOperation()); - assertEquals("-3", rule2.getFormula1()); - assertNull(rule2.getFormula2()); - assertNull(rule2.getPatternFormatting()); - assertNull(rule2.getBorderFormatting()); - - FontFormatting fmt2 = rule2.getFontFormatting(); -// assertEquals(IndexedColors.RED.index, fmt2.getFontColorIndex()); - assertTrue(fmt2.isBold()); - assertTrue(fmt2.isItalic()); - - - ConditionalFormatting cf2 = sheetCF.getConditionalFormattingAt(1); - assertEquals(1, cf2.getNumberOfRules()); - CellRangeAddress[] regions2 = cf2.getFormattingRanges(); - assertEquals(1, regions2.length); - assertEquals("B9", regions2[0].formatAsString()); - - ConditionalFormattingRule rule3 = cf2.getRule(0); - assertEquals(ConditionType.FORMULA, rule3.getConditionType()); - assertEquals(ComparisonOperator.NO_COMPARISON, rule3.getComparisonOperation()); - assertEquals("$A$8>5", rule3.getFormula1()); - assertNull(rule3.getFormula2()); - - FontFormatting fmt3 = rule3.getFontFormatting(); -// assertEquals(IndexedColors.RED.index, fmt3.getFontColorIndex()); - assertTrue(fmt3.isBold()); - assertTrue(fmt3.isItalic()); - - PatternFormatting fmt4 = rule3.getPatternFormatting(); -// assertEquals(IndexedColors.LIGHT_CORNFLOWER_BLUE.index, fmt4.getFillBackgroundColor()); -// assertEquals(IndexedColors.AUTOMATIC.index, fmt4.getFillForegroundColor()); - assertEquals(PatternFormatting.NO_FILL, fmt4.getFillPattern()); - // borders are not set - assertNull(rule3.getBorderFormatting()); - - ConditionalFormatting cf3 = sheetCF.getConditionalFormattingAt(2); - CellRangeAddress[] regions3 = cf3.getFormattingRanges(); - assertEquals(1, regions3.length); - assertEquals("B1:B7", regions3[0].formatAsString()); - assertEquals(2, cf3.getNumberOfRules()); - - ConditionalFormattingRule rule4 = cf3.getRule(0); - assertEquals(ConditionType.CELL_VALUE_IS, rule4.getConditionType()); - assertEquals(ComparisonOperator.LE, rule4.getComparisonOperation()); - assertEquals("\"AAA\"", rule4.getFormula1()); - assertNull(rule4.getFormula2()); - - ConditionalFormattingRule rule5 = cf3.getRule(1); - assertEquals(ConditionType.CELL_VALUE_IS, rule5.getConditionType()); - assertEquals(ComparisonOperator.BETWEEN, rule5.getComparisonOperation()); - assertEquals("\"A\"", rule5.getFormula1()); - assertEquals("\"AAA\"", rule5.getFormula2()); - } - } - - protected void testReadOffice2007(String filename) throws IOException { - try (Workbook wb = _testDataProvider.openSampleWorkbook(filename)) { - Sheet s = wb.getSheet("CF"); - - // Sanity check data - assertEquals("Values", s.getRow(0).getCell(0).toString()); - assertEquals("10.0", s.getRow(2).getCell(0).toString()); - - // Check we found all the conditional formatting rules we should have - SheetConditionalFormatting sheetCF = s.getSheetConditionalFormatting(); - int numCF = 3; - int numCF12 = 15; - int numCFEX = 0; // TODO This should be 2, but we don't support CFEX formattings yet, see #58149 - assertEquals(numCF + numCF12 + numCFEX, sheetCF.getNumConditionalFormattings()); - - int fCF = 0, fCF12 = 0, fCFEX = 0; - for (int i = 0; i < sheetCF.getNumConditionalFormattings(); i++) { - ConditionalFormatting cf = sheetCF.getConditionalFormattingAt(i); - if (cf instanceof HSSFConditionalFormatting) { - String str = cf.toString(); - if (str.contains("/* CF_RULE */")) fCF++; - if (str.contains("/* CF_RULE_12 */")) fCF12++; - if (str.contains("[CFEX]")) fCFEX++; - } else { - ConditionType type = cf.getRule(cf.getNumberOfRules() - 1).getConditionType(); - if (type == ConditionType.CELL_VALUE_IS || - type == ConditionType.FORMULA) { - fCF++; - } else { - // TODO Properly detect Ext ones from the xml - fCF12++; - } - } - } - assertEquals(numCF, fCF); - assertEquals(numCF12, fCF12); - assertEquals(numCFEX, fCFEX); - - - // Check the rules / values in detail - - - // Highlight Positive values - Column C - ConditionalFormatting cf = sheetCF.getConditionalFormattingAt(0); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("C2:C17", cf.getFormattingRanges()[0].formatAsString()); - - assertEquals(1, cf.getNumberOfRules()); - ConditionalFormattingRule cr = cf.getRule(0); - assertEquals(ConditionType.CELL_VALUE_IS, cr.getConditionType()); - assertEquals(ComparisonOperator.GT, cr.getComparisonOperation()); - assertEquals("0", cr.getFormula1()); - assertNull(cr.getFormula2()); - // When it matches: - // Sets the font colour to dark green - // Sets the background colour to lighter green - // TODO Should the colours be slightly different between formats? Would CFEX support help for HSSF? - if (cr instanceof HSSFConditionalFormattingRule) { - assertColor("0:8080:0", cr.getFontFormatting().getFontColor()); - assertColor("CCCC:FFFF:CCCC", cr.getPatternFormatting().getFillBackgroundColorColor()); - } else { - assertColor("006100", cr.getFontFormatting().getFontColor()); - assertColor("C6EFCE", cr.getPatternFormatting().getFillBackgroundColorColor()); - } - - - // Highlight 10-30 - Column D - cf = sheetCF.getConditionalFormattingAt(1); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("D2:D17", cf.getFormattingRanges()[0].formatAsString()); - - assertEquals(1, cf.getNumberOfRules()); - cr = cf.getRule(0); - assertEquals(ConditionType.CELL_VALUE_IS, cr.getConditionType()); - assertEquals(ComparisonOperator.BETWEEN, cr.getComparisonOperation()); - assertEquals("10", cr.getFormula1()); - assertEquals("30", cr.getFormula2()); - // When it matches: - // Sets the font colour to dark red - // Sets the background colour to lighter red - // TODO Should the colours be slightly different between formats? Would CFEX support help for HSSF? - if (cr instanceof HSSFConditionalFormattingRule) { - assertColor("8080:0:8080", cr.getFontFormatting().getFontColor()); - assertColor("FFFF:9999:CCCC", cr.getPatternFormatting().getFillBackgroundColorColor()); - } else { - assertColor("9C0006", cr.getFontFormatting().getFontColor()); - assertColor("FFC7CE", cr.getPatternFormatting().getFillBackgroundColorColor()); - } - - - // Data Bars - Column E - cf = sheetCF.getConditionalFormattingAt(2); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("E2:E17", cf.getFormattingRanges()[0].formatAsString()); - assertDataBar(cf, "FF63C384"); - - - // Colours Red->Yellow->Green - Column F - cf = sheetCF.getConditionalFormattingAt(3); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("F2:F17", cf.getFormattingRanges()[0].formatAsString()); - assertColorScale(cf, "F8696B", "FFEB84", "63BE7B"); - - - // Colours Blue->White->Red - Column G - cf = sheetCF.getConditionalFormattingAt(4); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("G2:G17", cf.getFormattingRanges()[0].formatAsString()); - assertColorScale(cf, "5A8AC6", "FCFCFF", "F8696B"); - - - // Icons : Default - Column H, percentage thresholds - cf = sheetCF.getConditionalFormattingAt(5); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("H2:H17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_TRAFFIC_LIGHTS, 0d, 33d, 67d); - - - // Icons : 3 signs - Column I - cf = sheetCF.getConditionalFormattingAt(6); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("I2:I17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_SHAPES, 0d, 33d, 67d); - - - // Icons : 3 traffic lights 2 - Column J - cf = sheetCF.getConditionalFormattingAt(7); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("J2:J17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_TRAFFIC_LIGHTS_BOX, 0d, 33d, 67d); - - - // Icons : 4 traffic lights - Column K - cf = sheetCF.getConditionalFormattingAt(8); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("K2:K17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYRB_4_TRAFFIC_LIGHTS, 0d, 25d, 50d, 75d); - - - // Icons : 3 symbols with backgrounds - Column L - cf = sheetCF.getConditionalFormattingAt(9); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("L2:L17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_SYMBOLS_CIRCLE, 0d, 33d, 67d); - - - // Icons : 3 flags - Column M2 Only - cf = sheetCF.getConditionalFormattingAt(10); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("M2", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_FLAGS, 0d, 33d, 67d); - - // Icons : 3 flags - Column M (all) - cf = sheetCF.getConditionalFormattingAt(11); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("M2:M17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_FLAGS, 0d, 33d, 67d); - - - // Icons : 3 symbols 2 (no background) - Column N - cf = sheetCF.getConditionalFormattingAt(12); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("N2:N17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_SYMBOLS, 0d, 33d, 67d); - - - // Icons : 3 arrows - Column O - cf = sheetCF.getConditionalFormattingAt(13); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("O2:O17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_ARROW, 0d, 33d, 67d); - - - // Icons : 5 arrows grey - Column P - cf = sheetCF.getConditionalFormattingAt(14); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("P2:P17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GREY_5_ARROWS, 0d, 20d, 40d, 60d, 80d); - - - // Icons : 3 stars (ext) - Column Q - // TODO Support EXT formattings - - - // Icons : 4 ratings - Column R - cf = sheetCF.getConditionalFormattingAt(15); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("R2:R17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.RATINGS_4, 0d, 25d, 50d, 75d); - - - // Icons : 5 ratings - Column S - cf = sheetCF.getConditionalFormattingAt(16); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("S2:S17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.RATINGS_5, 0d, 20d, 40d, 60d, 80d); - - - // Custom Icon+Format - Column T - cf = sheetCF.getConditionalFormattingAt(17); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("T2:T17", cf.getFormattingRanges()[0].formatAsString()); - - // TODO Support IconSet + Other CFs with 2 rules -// assertEquals(2, cf.getNumberOfRules()); -// cr = cf.getRule(0); -// assertIconSetPercentages(cr, IconSet.GYR_3_TRAFFIC_LIGHTS_BOX, 0d, 33d, 67d); -// cr = cf.getRule(1); -// assertEquals(ConditionType.FORMULA, cr.getConditionType()); -// assertEquals(ComparisonOperator.NO_COMPARISON, cr.getComparisonOperation()); -// // TODO Why aren't these two the same between formats? -// if (cr instanceof HSSFConditionalFormattingRule) { -// assertEquals("MOD(ROW($T1),2)=1", cr.getFormula1()); -// } else { -// assertEquals("MOD(ROW($T2),2)=1", cr.getFormula1()); -// } -// assertEquals(null, cr.getFormula2()); - - - // Mixed icons - Column U - // TODO Support EXT formattings - - } - } - - @SuppressWarnings("SameParameterValue") - private void assertDataBar(ConditionalFormatting cf, String color) { - assertEquals(1, cf.getNumberOfRules()); - ConditionalFormattingRule cr = cf.getRule(0); - assertDataBar(cr, color); - } - - private void assertDataBar(ConditionalFormattingRule cr, String color) { - assertEquals(ConditionType.DATA_BAR, cr.getConditionType()); - assertEquals(ComparisonOperator.NO_COMPARISON, cr.getComparisonOperation()); - assertNull(cr.getFormula1()); - assertNull(cr.getFormula2()); - - DataBarFormatting databar = cr.getDataBarFormatting(); - assertNotNull(databar); - assertFalse(databar.isIconOnly()); - assertTrue(databar.isLeftToRight()); - assertEquals(0, databar.getWidthMin()); - assertEquals(100, databar.getWidthMax()); - - assertColor(color, databar.getColor()); - - ConditionalFormattingThreshold th; - th = databar.getMinThreshold(); - assertEquals(RangeType.MIN, th.getRangeType()); - assertNull(th.getValue()); - assertNull(th.getFormula()); - th = databar.getMaxThreshold(); - assertEquals(RangeType.MAX, th.getRangeType()); - assertNull(th.getValue()); - assertNull(th.getFormula()); - } - - private void assertIconSetPercentages(ConditionalFormatting cf, IconSet iconset, Double...vals) { - assertEquals(1, cf.getNumberOfRules()); - ConditionalFormattingRule cr = cf.getRule(0); - assertIconSetPercentages(cr, iconset, vals); - } - - private void assertIconSetPercentages(ConditionalFormattingRule cr, IconSet iconset, Double...vals) { - assertEquals(ConditionType.ICON_SET, cr.getConditionType()); - assertEquals(ComparisonOperator.NO_COMPARISON, cr.getComparisonOperation()); - assertNull(cr.getFormula1()); - assertNull(cr.getFormula2()); - - IconMultiStateFormatting icon = cr.getMultiStateFormatting(); - assertNotNull(icon); - assertEquals(iconset, icon.getIconSet()); - assertFalse(icon.isIconOnly()); - assertFalse(icon.isReversed()); - - assertNotNull(icon.getThresholds()); - assertEquals(vals.length, icon.getThresholds().length); - for (int i=0; i0"); - int form = sheet.getSheetConditionalFormatting().addConditionalFormatting(ranges, rule); - assertEquals(0, form); - } - } - - @Test - void testSetCellRangeAddresswithSingleRange() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - final Sheet sheet = wb.createSheet("S1"); - final SheetConditionalFormatting cf = sheet.getSheetConditionalFormatting(); - assertEquals(0, cf.getNumConditionalFormattings()); - ConditionalFormattingRule rule1 = cf.createConditionalFormattingRule("$A$1>0"); - cf.addConditionalFormatting(new CellRangeAddress[]{ - CellRangeAddress.valueOf("A1:A5") - }, rule1); - - assertEquals(1, cf.getNumConditionalFormattings()); - ConditionalFormatting readCf = cf.getConditionalFormattingAt(0); - CellRangeAddress[] formattingRanges = readCf.getFormattingRanges(); - assertEquals(1, formattingRanges.length); - CellRangeAddress formattingRange = formattingRanges[0]; - assertEquals("A1:A5", formattingRange.formatAsString()); - - readCf.setFormattingRanges(new CellRangeAddress[]{ - CellRangeAddress.valueOf("A1:A6") - }); - - readCf = cf.getConditionalFormattingAt(0); - formattingRanges = readCf.getFormattingRanges(); - assertEquals(1, formattingRanges.length); - formattingRange = formattingRanges[0]; - assertEquals("A1:A6", formattingRange.formatAsString()); - } - } - - @Test - void testSetCellRangeAddressWithMultipleRanges() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - final Sheet sheet = wb.createSheet("S1"); - final SheetConditionalFormatting cf = sheet.getSheetConditionalFormatting(); - assertEquals(0, cf.getNumConditionalFormattings()); - ConditionalFormattingRule rule1 = cf.createConditionalFormattingRule("$A$1>0"); - cf.addConditionalFormatting(new CellRangeAddress[]{ - CellRangeAddress.valueOf("A1:A5") - }, rule1); - - assertEquals(1, cf.getNumConditionalFormattings()); - ConditionalFormatting readCf = cf.getConditionalFormattingAt(0); - CellRangeAddress[] formattingRanges = readCf.getFormattingRanges(); - assertEquals(1, formattingRanges.length); - CellRangeAddress formattingRange = formattingRanges[0]; - assertEquals("A1:A5", formattingRange.formatAsString()); - - readCf.setFormattingRanges(new CellRangeAddress[]{ - CellRangeAddress.valueOf("A1:A6"), - CellRangeAddress.valueOf("B1:B6") - }); - - readCf = cf.getConditionalFormattingAt(0); - formattingRanges = readCf.getFormattingRanges(); - assertEquals(2, formattingRanges.length); - formattingRange = formattingRanges[0]; - assertEquals("A1:A6", formattingRange.formatAsString()); - formattingRange = formattingRanges[1]; - assertEquals("B1:B6", formattingRange.formatAsString()); - } - } - - @Test - void testSetCellRangeAddressWithNullRanges() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - final Sheet sheet = wb.createSheet("S1"); - final SheetConditionalFormatting cf = sheet.getSheetConditionalFormatting(); - assertEquals(0, cf.getNumConditionalFormattings()); - ConditionalFormattingRule rule1 = cf.createConditionalFormattingRule("$A$1>0"); - cf.addConditionalFormatting(new CellRangeAddress[]{ - CellRangeAddress.valueOf("A1:A5") - }, rule1); - - assertEquals(1, cf.getNumConditionalFormattings()); - ConditionalFormatting readCf = cf.getConditionalFormattingAt(0); - assertThrows(IllegalArgumentException.class, () -> readCf.setFormattingRanges(null)); - } - } - - - @Test - void test52122() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet("Conditional Formatting Test"); - sheet.setColumnWidth(0, 256 * 10); - sheet.setColumnWidth(1, 256 * 10); - sheet.setColumnWidth(2, 256 * 10); - - // Create some content. - // row 0 - Row row = sheet.createRow(0); - - Cell cell0 = row.createCell(0); - cell0.setCellValue(100); - - Cell cell1 = row.createCell(1); - cell1.setCellValue(120); - - Cell cell2 = row.createCell(2); - cell2.setCellValue(130); - - // row 1 - row = sheet.createRow(1); - - cell0 = row.createCell(0); - cell0.setCellValue(200); - - cell1 = row.createCell(1); - cell1.setCellValue(220); - - cell2 = row.createCell(2); - cell2.setCellValue(230); - - // row 2 - row = sheet.createRow(2); - - cell0 = row.createCell(0); - cell0.setCellValue(300); - - cell1 = row.createCell(1); - cell1.setCellValue(320); - - cell2 = row.createCell(2); - cell2.setCellValue(330); - - // Create conditional formatting, CELL1 should be yellow if CELL0 is not blank. - SheetConditionalFormatting formatting = sheet.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule = formatting.createConditionalFormattingRule("$A$1>75"); - - PatternFormatting pattern = rule.createPatternFormatting(); - pattern.setFillBackgroundColor(IndexedColors.BLUE.index); - pattern.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] range = {CellRangeAddress.valueOf("B2:C2")}; - CellRangeAddress[] range2 = {CellRangeAddress.valueOf("B1:C1")}; - - formatting.addConditionalFormatting(range, rule); - formatting.addConditionalFormatting(range2, rule); - - try (Workbook wbBack = _testDataProvider.writeOutAndReadBack(workbook)) { - Sheet sheetBack = wbBack.getSheetAt(0); - final SheetConditionalFormatting sheetConditionalFormattingBack = sheetBack.getSheetConditionalFormatting(); - assertNotNull(sheetConditionalFormattingBack); - final ConditionalFormatting formattingBack = sheetConditionalFormattingBack.getConditionalFormattingAt(0); - assertNotNull(formattingBack); - final ConditionalFormattingRule ruleBack = formattingBack.getRule(0); - assertNotNull(ruleBack); - final PatternFormatting patternFormattingBack1 = ruleBack.getPatternFormatting(); - assertNotNull(patternFormattingBack1); - assertEquals(IndexedColors.BLUE.index, patternFormattingBack1.getFillBackgroundColor()); - assertEquals(PatternFormatting.SOLID_FOREGROUND, patternFormattingBack1.getFillPattern()); - } - } - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java deleted file mode 100644 index 65ee8ffa49..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java +++ /dev/null @@ -1,262 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.junit.jupiter.api.Test; - -/** - * Tests of implementation of {@link DataFormat} - * - */ -public abstract class BaseTestDataFormat { - - protected static final String POUND_FMT = "\"\u00a3\"#,##0;[Red]\\-\"\u00a3\"#,##0"; - - private final ITestDataProvider _testDataProvider; - - protected BaseTestDataFormat(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - void assertNotBuiltInFormat(String customFmt) { - //check it is not in built-in formats - assertEquals(-1, BuiltinFormats.getBuiltinFormat(customFmt)); - } - - @Test - public final void testBuiltinFormats() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - - DataFormat df = wb.createDataFormat(); - - String[] formats = BuiltinFormats.getAll(); - for (int idx = 0; idx < formats.length; idx++) { - String fmt = formats[idx]; - assertEquals(idx, df.getFormat(fmt)); - } - - //default format for new cells is General - Sheet sheet = wb.createSheet(); - Cell cell = sheet.createRow(0).createCell(0); - assertEquals(0, cell.getCellStyle().getDataFormat()); - assertEquals("General", cell.getCellStyle().getDataFormatString()); - - //create a custom data format - String customFmt = "#0.00 AM/PM"; - //check it is not in built-in formats - assertNotBuiltInFormat(customFmt); - int customIdx = df.getFormat(customFmt); - //The first user-defined format starts at 164. - assertTrue(customIdx >= BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX); - //read and verify the string representation - assertEquals(customFmt, df.getFormat((short) customIdx)); - } - } - - /** - * [Bug 49928] formatCellValue returns incorrect value for \u00a3 formatted cells - */ - @Test - void test49928() throws IOException { - String fileName = "49928.xls" + (getClass().getName().contains("xssf") ? "x" : ""); - try (Workbook wb = _testDataProvider.openSampleWorkbook(fileName)) { - DataFormatter df = new DataFormatter(); - - Sheet sheet = wb.getSheetAt(0); - Cell cell = sheet.getRow(0).getCell(0); - CellStyle style = cell.getCellStyle(); - - // not expected normally, id of a custom format should be greater - // than BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX - short poundFmtIdx = 6; - - assertEquals(POUND_FMT, style.getDataFormatString()); - assertEquals(poundFmtIdx, style.getDataFormat()); - assertEquals("\u00a31", df.formatCellValue(cell)); - - - DataFormat dataFormat = wb.createDataFormat(); - assertEquals(poundFmtIdx, dataFormat.getFormat(POUND_FMT)); - assertEquals(POUND_FMT, dataFormat.getFormat(poundFmtIdx)); - - - // As of 2015-12-27, there is no way to override a built-in number format with POI XSSFWorkbook - // 49928.xlsx has been saved with a poundFmt that overrides the default value (dollar) - poundFmtIdx = wb.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getDataFormat(); - assertEquals(poundFmtIdx, dataFormat.getFormat(POUND_FMT)); - - // now create a custom format with Pound (\u00a3) - - String customFmt = "\u00a3##.00[Yellow]"; - assertNotBuiltInFormat(customFmt); - short customFmtIdx = dataFormat.getFormat(customFmt); - assertTrue(customFmtIdx >= BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX); - assertEquals(customFmt, dataFormat.getFormat(customFmtIdx)); - } - } - - @Test - void testReadbackFormat() throws IOException { - readbackFormat("built-in format", "0.00"); - readbackFormat("overridden built-in format", POUND_FMT); - - String customFormat = "#0.00 AM/PM"; - assertNotBuiltInFormat(customFormat); - readbackFormat("custom format", customFormat); - } - - private void readbackFormat(String msg, String fmt) throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - DataFormat dataFormat = wb.createDataFormat(); - short fmtIdx = dataFormat.getFormat(fmt); - String readbackFmt = dataFormat.getFormat(fmtIdx); - assertEquals(fmt, readbackFmt, msg); - } - } - - /** - * [Bug 58532] Handle formats that go numnum, numK, numM etc - */ - @Test - void test58532() throws IOException { - String fileName = "FormatKM.xls" + (getClass().getName().contains("xssf") ? "x" : ""); - try (Workbook wb = _testDataProvider.openSampleWorkbook(fileName)) { - Sheet s = wb.getSheetAt(0); - DataFormatter fmt = new DataFormatter(); - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - // Column A is the raw values - // Column B is the ##/#K/#M values - // Column C is strings of what they should look like - // Column D is the #.##/#.#K/#.#M values - // Column E is strings of what they should look like - - String formatKMWhole = "[>999999]#,,\"M\";[>999]#,\"K\";#"; - String formatKM3dp = "[>999999]#.000,,\"M\";[>999]#.000,\"K\";#.000"; - - // Check the formats are as expected - Row headers = s.getRow(0); - assertNotNull(headers); - assertEquals(formatKMWhole, headers.getCell(1).getStringCellValue()); - assertEquals(formatKM3dp, headers.getCell(3).getStringCellValue()); - - Row r2 = s.getRow(1); - assertNotNull(r2); - assertEquals(formatKMWhole, r2.getCell(1).getCellStyle().getDataFormatString()); - assertEquals(formatKM3dp, r2.getCell(3).getCellStyle().getDataFormatString()); - - // For all of the contents rows, check that DataFormatter is able - // to format the cells to the same value as the one next to it - for (int rn = 1; rn < s.getLastRowNum(); rn++) { - Row r = s.getRow(rn); - if (r == null) break; - - double value = r.getCell(0).getNumericCellValue(); - - String expWhole = r.getCell(2).getStringCellValue(); - String exp3dp = r.getCell(4).getStringCellValue(); - - assertEquals(expWhole, fmt.formatCellValue(r.getCell(1), eval), - "Wrong formatting of " + value + " for row " + rn); - assertEquals(exp3dp, fmt.formatCellValue(r.getCell(3), eval), - "Wrong formatting of " + value + " for row " + rn); - } - } - } - - /** - * Localized accountancy formats - */ - @Test - public final void test58536() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - DataFormatter formatter = new DataFormatter(); - DataFormat fmt = wb.createDataFormat(); - Sheet sheet = wb.createSheet(); - Row r = sheet.createRow(0); - - char pound = '\u00A3'; - String formatUK = "_-[$" + pound + "-809]* #,##0_-;\\-[$" + pound + "-809]* #,##0_-;_-[$" + pound + "-809]* \"-\"??_-;_-@_-"; - - CellStyle cs = wb.createCellStyle(); - cs.setDataFormat(fmt.getFormat(formatUK)); - - Cell pve = r.createCell(0); - pve.setCellValue(12345); - pve.setCellStyle(cs); - - Cell nve = r.createCell(1); - nve.setCellValue(-12345); - nve.setCellStyle(cs); - - Cell zero = r.createCell(2); - zero.setCellValue(0); - zero.setCellStyle(cs); - - assertEquals(pound + " 12,345", formatter.formatCellValue(pve)); - assertEquals("-" + pound + " 12,345", formatter.formatCellValue(nve)); - // TODO Fix this to not have an extra 0 at the end - //assertEquals(pound+" - ", formatter.formatCellValue(zero)); - } - } - - /** - * Using a single quote (') instead of a comma (,) as - * a number separator, eg 1000 -> 1'000 - */ - @Test - public final void test55265() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - DataFormatter formatter = new DataFormatter(); - DataFormat fmt = wb.createDataFormat(); - Sheet sheet = wb.createSheet(); - Row r = sheet.createRow(0); - - CellStyle cs = wb.createCellStyle(); - cs.setDataFormat(fmt.getFormat("#'##0")); - - Cell zero = r.createCell(0); - zero.setCellValue(0); - zero.setCellStyle(cs); - - Cell sml = r.createCell(1); - sml.setCellValue(12); - sml.setCellStyle(cs); - - Cell med = r.createCell(2); - med.setCellValue(1234); - med.setCellStyle(cs); - - Cell lge = r.createCell(3); - lge.setCellValue(12345678); - lge.setCellStyle(cs); - - assertEquals("0", formatter.formatCellValue(zero)); - assertEquals("12", formatter.formatCellValue(sml)); - assertEquals("1'234", formatter.formatCellValue(med)); - assertEquals("12'345'678", formatter.formatCellValue(lge)); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataValidation.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataValidation.java deleted file mode 100644 index ccfd8293c0..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataValidation.java +++ /dev/null @@ -1,492 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.DataValidation.ErrorStyle; -import org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType; -import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.junit.jupiter.api.Test; - -/** - * Class for testing Excel's data validation mechanism - * - * @author Dragos Buleandra ( dragos.buleandra@trade2b.ro ) - */ -public abstract class BaseTestDataValidation { - private final ITestDataProvider _testDataProvider; - - protected BaseTestDataValidation(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - /** - * Convenient access to ERROR_STYLE constants - */ - protected static final DataValidation.ErrorStyle ES = null; - /** - * Convenient access to OPERATOR constants - */ - protected static final DataValidationConstraint.ValidationType VT = null; - - private static final class ValidationAdder { - - private final CellStyle _style_1; - private final CellStyle _style_2; - private final int _validationType; - private final Sheet _sheet; - private int _currentRowIndex; - private final CellStyle _cellStyle; - - public ValidationAdder(Sheet fSheet, CellStyle style_1, CellStyle style_2, - CellStyle cellStyle, int validationType) { - _sheet = fSheet; - _style_1 = style_1; - _style_2 = style_2; - _cellStyle = cellStyle; - _validationType = validationType; - _currentRowIndex = fSheet.getPhysicalNumberOfRows(); - } - - void addValidation(int operatorType, String firstFormula, String secondFormula, - int errorStyle, String ruleDescr, String promptDescr, - boolean allowEmpty, boolean inputBox, boolean errorBox) { - String[] explicitListValues = null; - - addValidationInternal(operatorType, firstFormula, secondFormula, errorStyle, ruleDescr, - promptDescr, allowEmpty, inputBox, errorBox, true, - explicitListValues); - } - - private void addValidationInternal(int operatorType, String firstFormula, - String secondFormula, int errorStyle, String ruleDescr, String promptDescr, - boolean allowEmpty, boolean inputBox, boolean errorBox, boolean suppressDropDown, - String[] explicitListValues) { - int rowNum = _currentRowIndex++; - - DataValidationHelper dataValidationHelper = _sheet.getDataValidationHelper(); - DataValidationConstraint dc = createConstraint(dataValidationHelper, operatorType, firstFormula, secondFormula, explicitListValues); - - DataValidation dv = dataValidationHelper.createValidation(dc, new CellRangeAddressList(rowNum, rowNum, 0, 0)); - - dv.setEmptyCellAllowed(allowEmpty); - dv.setErrorStyle(errorStyle); - dv.createErrorBox("Invalid Input", "Something is wrong - check condition!"); - dv.createPromptBox("Validated Cell", "Allowable values have been restricted"); - - dv.setShowPromptBox(inputBox); - dv.setShowErrorBox(errorBox); - dv.setSuppressDropDownArrow(suppressDropDown); - - - _sheet.addValidationData(dv); - writeDataValidationSettings(_sheet, _style_1, _style_2, ruleDescr, allowEmpty, - inputBox, errorBox); - if (_cellStyle != null) { - Row row = _sheet.getRow(_sheet.getPhysicalNumberOfRows() - 1); - Cell cell = row.createCell(0); - cell.setCellStyle(_cellStyle); - } - writeOtherSettings(_sheet, _style_1, promptDescr); - } - - private DataValidationConstraint createConstraint(DataValidationHelper dataValidationHelper, int operatorType, String firstFormula, - String secondFormula, String[] explicitListValues) { - if (_validationType == ValidationType.LIST) { - if (explicitListValues != null) { - return dataValidationHelper.createExplicitListConstraint(explicitListValues); - } - return dataValidationHelper.createFormulaListConstraint(firstFormula); - } - if (_validationType == ValidationType.TIME) { - return dataValidationHelper.createTimeConstraint(operatorType, firstFormula, secondFormula); - } - if (_validationType == ValidationType.DATE) { - return dataValidationHelper.createDateConstraint(operatorType, firstFormula, secondFormula, null); - } - if (_validationType == ValidationType.FORMULA) { - return dataValidationHelper.createCustomConstraint(firstFormula); - } - - if (_validationType == ValidationType.INTEGER) { - return dataValidationHelper.createIntegerConstraint(operatorType, firstFormula, secondFormula); - } - if (_validationType == ValidationType.DECIMAL) { - return dataValidationHelper.createDecimalConstraint(operatorType, firstFormula, secondFormula); - } - if (_validationType == ValidationType.TEXT_LENGTH) { - return dataValidationHelper.createTextLengthConstraint(operatorType, firstFormula, secondFormula); - } - return null; - } - - /** - * writes plain text values into cells in a tabular format to form comments readable from within - * the spreadsheet. - */ - private static void writeDataValidationSettings(Sheet sheet, CellStyle style_1, - CellStyle style_2, String strCondition, boolean allowEmpty, boolean inputBox, - boolean errorBox) { - Row row = sheet.createRow(sheet.getPhysicalNumberOfRows()); - // condition's string - Cell cell = row.createCell(1); - cell.setCellStyle(style_1); - setCellValue(cell, strCondition); - // allow empty cells - cell = row.createCell(2); - cell.setCellStyle(style_2); - setCellValue(cell, ((allowEmpty) ? "yes" : "no")); - // show input box - cell = row.createCell(3); - cell.setCellStyle(style_2); - setCellValue(cell, ((inputBox) ? "yes" : "no")); - // show error box - cell = row.createCell(4); - cell.setCellStyle(style_2); - setCellValue(cell, ((errorBox) ? "yes" : "no")); - } - - private static void writeOtherSettings(Sheet sheet, CellStyle style, - String strStettings) { - Row row = sheet.getRow(sheet.getPhysicalNumberOfRows() - 1); - Cell cell = row.createCell(5); - cell.setCellStyle(style); - setCellValue(cell, strStettings); - } - - void addListValidation(String[] explicitListValues, String listFormula, String listValsDescr, - boolean allowEmpty, boolean suppressDropDown) { - String promptDescr = (allowEmpty ? "empty ok" : "not empty") - + ", " + (suppressDropDown ? "no drop-down" : "drop-down"); - addValidationInternal(ValidationType.LIST, listFormula, null, ErrorStyle.STOP, listValsDescr, promptDescr, - allowEmpty, false, true, suppressDropDown, explicitListValues); - } - } - - /** - * Manages the cell styles used for formatting the output spreadsheet - */ - private static final class WorkbookFormatter { - - private final Workbook _wb; - private final CellStyle _style_1; - private final CellStyle _style_2; - private final CellStyle _style_3; - private final CellStyle _style_4; - private Sheet _currentSheet; - - public WorkbookFormatter(Workbook wb) { - _wb = wb; - _style_1 = createStyle(wb, HorizontalAlignment.LEFT); - _style_2 = createStyle(wb, HorizontalAlignment.CENTER); - _style_3 = createStyle(wb, HorizontalAlignment.CENTER, IndexedColors.GREY_25_PERCENT.getIndex(), true); - _style_4 = createHeaderStyle(wb); - } - - private static CellStyle createStyle(Workbook wb, HorizontalAlignment h_align, short color, - boolean bold) { - Font font = wb.createFont(); - if (bold) { - font.setBold(true); - } - - CellStyle cellStyle = wb.createCellStyle(); - cellStyle.setFont(font); - cellStyle.setFillForegroundColor(color); - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); - cellStyle.setAlignment(h_align); - cellStyle.setBorderLeft(BorderStyle.THIN); - cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); - cellStyle.setBorderTop(BorderStyle.THIN); - cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); - cellStyle.setBorderRight(BorderStyle.THIN); - cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex()); - cellStyle.setBorderBottom(BorderStyle.THIN); - cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); - - return cellStyle; - } - - private static CellStyle createStyle(Workbook wb, HorizontalAlignment h_align) { - return createStyle(wb, h_align, IndexedColors.WHITE.getIndex(), false); - } - - private static CellStyle createHeaderStyle(Workbook wb) { - Font font = wb.createFont(); - font.setColor(IndexedColors.WHITE.getIndex()); - font.setBold(true); - - CellStyle cellStyle = wb.createCellStyle(); - cellStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex()); - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cellStyle.setAlignment(HorizontalAlignment.CENTER); - cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); - cellStyle.setBorderLeft(BorderStyle.THIN); - cellStyle.setLeftBorderColor(IndexedColors.WHITE.getIndex()); - cellStyle.setBorderTop(BorderStyle.THIN); - cellStyle.setTopBorderColor(IndexedColors.WHITE.getIndex()); - cellStyle.setBorderRight(BorderStyle.THIN); - cellStyle.setRightBorderColor(IndexedColors.WHITE.getIndex()); - cellStyle.setBorderBottom(BorderStyle.THIN); - cellStyle.setBottomBorderColor(IndexedColors.WHITE.getIndex()); - cellStyle.setFont(font); - return cellStyle; - } - - - public Sheet createSheet(String sheetName) { - _currentSheet = _wb.createSheet(sheetName); - return _currentSheet; - } - - void createDVTypeRow(String strTypeDescription) { - Sheet sheet = _currentSheet; - Row row = sheet.createRow(sheet.getPhysicalNumberOfRows()); - sheet.addMergedRegion(new CellRangeAddress(sheet.getPhysicalNumberOfRows() - 1, sheet.getPhysicalNumberOfRows() - 1, 0, 5)); - Cell cell = row.createCell(0); - setCellValue(cell, strTypeDescription); - cell.setCellStyle(_style_3); - row = sheet.createRow(sheet.getPhysicalNumberOfRows()); - } - - void createHeaderRow() { - Sheet sheet = _currentSheet; - Row row = sheet.createRow(sheet.getPhysicalNumberOfRows()); - row.setHeight((short) 400); - for (int i = 0; i < 6; i++) { - row.createCell(i).setCellStyle(_style_4); - if (i == 2 || i == 3 || i == 4) { - sheet.setColumnWidth(i, 3500); - } else if (i == 5) { - sheet.setColumnWidth(i, 10000); - } else { - sheet.setColumnWidth(i, 8000); - } - } - Cell cell = row.getCell(0); - setCellValue(cell, "Data validation cells"); - cell = row.getCell(1); - setCellValue(cell, "Condition"); - cell = row.getCell(2); - setCellValue(cell, "Allow blank"); - cell = row.getCell(3); - setCellValue(cell, "Prompt box"); - cell = row.getCell(4); - setCellValue(cell, "Error box"); - cell = row.getCell(5); - setCellValue(cell, "Other settings"); - } - - public ValidationAdder createValidationAdder(CellStyle cellStyle, int dataValidationType) { - return new ValidationAdder(_currentSheet, _style_1, _style_2, cellStyle, dataValidationType); - } - - void createDVDescriptionRow(String strTypeDescription) { - Sheet sheet = _currentSheet; - Row row = sheet.getRow(sheet.getPhysicalNumberOfRows() - 1); - sheet.addMergedRegion(new CellRangeAddress(sheet.getPhysicalNumberOfRows() - 1, sheet.getPhysicalNumberOfRows() - 1, 0, 5)); - Cell cell = row.createCell(0); - setCellValue(cell, strTypeDescription); - cell.setCellStyle(_style_3); - row = sheet.createRow(sheet.getPhysicalNumberOfRows()); - } - } - - - private void addCustomValidations(WorkbookFormatter wf) { - wf.createSheet("Custom"); - wf.createHeaderRow(); - - ValidationAdder va = wf.createValidationAdder(null, ValidationType.FORMULA); - va.addValidation(OperatorType.BETWEEN, "ISNUMBER($A2)", null, ErrorStyle.STOP, "ISNUMBER(A2)", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.BETWEEN, "IF(SUM(A2:A3)=5,TRUE,FALSE)", null, ErrorStyle.WARNING, "IF(SUM(A2:A3)=5,TRUE,FALSE)", "Error box type = WARNING", false, false, true); - } - - private static void addSimpleNumericValidations(WorkbookFormatter wf) { - // data validation's number types - wf.createSheet("Numbers"); - - // "Whole number" validation type - wf.createDVTypeRow("Whole number"); - wf.createHeaderRow(); - - ValidationAdder va = wf.createValidationAdder(null, ValidationType.INTEGER); - va.addValidation(OperatorType.BETWEEN, "2", "6", ErrorStyle.STOP, "Between 2 and 6 ", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.NOT_BETWEEN, "2", "6", ErrorStyle.INFO, "Not between 2 and 6 ", "Error box type = INFO", false, true, true); - va.addValidation(OperatorType.EQUAL, "=3+2", null, ErrorStyle.WARNING, "Equal to (3+2)", "Error box type = WARNING", false, false, true); - va.addValidation(OperatorType.NOT_EQUAL, "3", null, ErrorStyle.WARNING, "Not equal to 3", "-", false, false, false); - va.addValidation(OperatorType.GREATER_THAN, "3", null, ErrorStyle.WARNING, "Greater than 3", "-", true, false, false); - va.addValidation(OperatorType.LESS_THAN, "3", null, ErrorStyle.WARNING, "Less than 3", "-", true, true, false); - va.addValidation(OperatorType.GREATER_OR_EQUAL, "4", null, ErrorStyle.STOP, "Greater than or equal to 4", "Error box type = STOP", true, false, true); - va.addValidation(OperatorType.LESS_OR_EQUAL, "4", null, ErrorStyle.STOP, "Less than or equal to 4", "-", false, true, false); - - // "Decimal" validation type - wf.createDVTypeRow("Decimal"); - wf.createHeaderRow(); - - va = wf.createValidationAdder(null, ValidationType.DECIMAL); - va.addValidation(OperatorType.BETWEEN, "2", "6", ErrorStyle.STOP, "Between 2 and 6 ", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.NOT_BETWEEN, "2", "6", ErrorStyle.INFO, "Not between 2 and 6 ", "Error box type = INFO", false, true, true); - va.addValidation(OperatorType.EQUAL, "3", null, ErrorStyle.WARNING, "Equal to 3", "Error box type = WARNING", false, false, true); - va.addValidation(OperatorType.NOT_EQUAL, "3", null, ErrorStyle.WARNING, "Not equal to 3", "-", false, false, false); - va.addValidation(OperatorType.GREATER_THAN, "=12/6", null, ErrorStyle.WARNING, "Greater than (12/6)", "-", true, false, false); - va.addValidation(OperatorType.LESS_THAN, "3", null, ErrorStyle.WARNING, "Less than 3", "-", true, true, false); - va.addValidation(OperatorType.GREATER_OR_EQUAL, "4", null, ErrorStyle.STOP, "Greater than or equal to 4", "Error box type = STOP", true, false, true); - va.addValidation(OperatorType.LESS_OR_EQUAL, "4", null, ErrorStyle.STOP, "Less than or equal to 4", "-", false, true, false); - } - - private static void addListValidations(WorkbookFormatter wf, Workbook wb) { - final String cellStrValue - = "a b c d e f g h i j k l m n o p r s t u v x y z w 0 1 2 3 4 " - + "a b c d e f g h i j k l m n o p r s t u v x y z w 0 1 2 3 4 " - + "a b c d e f g h i j k l m n o p r s t u v x y z w 0 1 2 3 4 " - + "a b c d e f g h i j k l m n o p r s t u v x y z w 0 1 2 3 4 "; - final String dataSheetName = "list_data"; - // "List" Data Validation type - Sheet fSheet = wf.createSheet("Lists"); - Sheet dataSheet = wb.createSheet(dataSheetName); - - - wf.createDVTypeRow("Explicit lists - list items are explicitly provided"); - wf.createDVDescriptionRow("Disadvantage - sum of item's length should be less than 255 characters"); - wf.createHeaderRow(); - - ValidationAdder va = wf.createValidationAdder(null, ValidationType.LIST); - String listValsDescr = "POIFS,HSSF,HWPF,HPSF"; - String[] listVals = listValsDescr.split(","); - va.addListValidation(listVals, null, listValsDescr, false, false); - va.addListValidation(listVals, null, listValsDescr, false, true); - va.addListValidation(listVals, null, listValsDescr, true, false); - va.addListValidation(listVals, null, listValsDescr, true, true); - - - wf.createDVTypeRow("Reference lists - list items are taken from others cells"); - wf.createDVDescriptionRow("Advantage - no restriction regarding the sum of item's length"); - wf.createHeaderRow(); - va = wf.createValidationAdder(null, ValidationType.LIST); - String strFormula = "$A$30:$A$39"; - va.addListValidation(null, strFormula, strFormula, false, false); - - strFormula = dataSheetName + "!$A$1:$A$10"; - va.addListValidation(null, strFormula, strFormula, false, false); - Name namedRange = wb.createName(); - namedRange.setNameName("myName"); - namedRange.setRefersToFormula(dataSheetName + "!$A$2:$A$7"); - strFormula = "myName"; - va.addListValidation(null, strFormula, strFormula, false, false); - strFormula = "offset(myName, 2, 1, 4, 2)"; // Note about last param '2': - // - Excel expects single row or single column when entered in UI, but process this OK otherwise - va.addListValidation(null, strFormula, strFormula, false, false); - - // add list data on same sheet - for (int i = 0; i < 10; i++) { - Row currRow = fSheet.createRow(i + 29); - setCellValue(currRow.createCell(0), cellStrValue); - } - // add list data on another sheet - for (int i = 0; i < 10; i++) { - Row currRow = dataSheet.createRow(i + 0); - setCellValue(currRow.createCell(0), "Data a" + i); - setCellValue(currRow.createCell(1), "Data b" + i); - setCellValue(currRow.createCell(2), "Data c" + i); - } - } - - private static void addDateTimeValidations(WorkbookFormatter wf, Workbook wb) { - wf.createSheet("Dates and Times"); - - DataFormat dataFormat = wb.createDataFormat(); - short fmtDate = dataFormat.getFormat("m/d/yyyy"); - short fmtTime = dataFormat.getFormat("h:mm"); - CellStyle cellStyle_date = wb.createCellStyle(); - cellStyle_date.setDataFormat(fmtDate); - CellStyle cellStyle_time = wb.createCellStyle(); - cellStyle_time.setDataFormat(fmtTime); - - wf.createDVTypeRow("Date ( cells are already formated as date - m/d/yyyy)"); - wf.createHeaderRow(); - - ValidationAdder va = wf.createValidationAdder(cellStyle_date, ValidationType.DATE); - va.addValidation(OperatorType.BETWEEN, "2004/01/02", "2004/01/06", ErrorStyle.STOP, "Between 1/2/2004 and 1/6/2004 ", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.NOT_BETWEEN, "2004/01/01", "2004/01/06", ErrorStyle.INFO, "Not between 1/2/2004 and 1/6/2004 ", "Error box type = INFO", false, true, true); - va.addValidation(OperatorType.EQUAL, "2004/03/02", null, ErrorStyle.WARNING, "Equal to 3/2/2004", "Error box type = WARNING", false, false, true); - va.addValidation(OperatorType.NOT_EQUAL, "2004/03/02", null, ErrorStyle.WARNING, "Not equal to 3/2/2004", "-", false, false, false); - va.addValidation(OperatorType.GREATER_THAN, "=DATEVALUE(\"4-Jul-2001\")", null, ErrorStyle.WARNING, "Greater than DATEVALUE('4-Jul-2001')", "-", true, false, false); - va.addValidation(OperatorType.LESS_THAN, "2004/03/02", null, ErrorStyle.WARNING, "Less than 3/2/2004", "-", true, true, false); - va.addValidation(OperatorType.GREATER_OR_EQUAL, "2004/03/02", null, ErrorStyle.STOP, "Greater than or equal to 3/2/2004", "Error box type = STOP", true, false, true); - va.addValidation(OperatorType.LESS_OR_EQUAL, "2004/03/04", null, ErrorStyle.STOP, "Less than or equal to 3/4/2004", "-", false, true, false); - - // "Time" validation type - wf.createDVTypeRow("Time ( cells are already formated as time - h:mm)"); - wf.createHeaderRow(); - - va = wf.createValidationAdder(cellStyle_time, ValidationType.TIME); - va.addValidation(OperatorType.BETWEEN, "12:00", "16:00", ErrorStyle.STOP, "Between 12:00 and 16:00 ", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.NOT_BETWEEN, "12:00", "16:00", ErrorStyle.INFO, "Not between 12:00 and 16:00 ", "Error box type = INFO", false, true, true); - va.addValidation(OperatorType.EQUAL, "13:35", null, ErrorStyle.WARNING, "Equal to 13:35", "Error box type = WARNING", false, false, true); - va.addValidation(OperatorType.NOT_EQUAL, "13:35", null, ErrorStyle.WARNING, "Not equal to 13:35", "-", false, false, false); - va.addValidation(OperatorType.GREATER_THAN, "12:00", null, ErrorStyle.WARNING, "Greater than 12:00", "-", true, false, false); - va.addValidation(OperatorType.LESS_THAN, "=1/2", null, ErrorStyle.WARNING, "Less than (1/2) -> 12:00", "-", true, true, false); - va.addValidation(OperatorType.GREATER_OR_EQUAL, "14:00", null, ErrorStyle.STOP, "Greater than or equal to 14:00", "Error box type = STOP", true, false, true); - va.addValidation(OperatorType.LESS_OR_EQUAL, "14:00", null, ErrorStyle.STOP, "Less than or equal to 14:00", "-", false, true, false); - } - - private static void addTextLengthValidations(WorkbookFormatter wf) { - wf.createSheet("Text lengths"); - wf.createHeaderRow(); - - ValidationAdder va = wf.createValidationAdder(null, ValidationType.TEXT_LENGTH); - va.addValidation(OperatorType.BETWEEN, "2", "6", ErrorStyle.STOP, "Between 2 and 6 ", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.NOT_BETWEEN, "2", "6", ErrorStyle.INFO, "Not between 2 and 6 ", "Error box type = INFO", false, true, true); - va.addValidation(OperatorType.EQUAL, "3", null, ErrorStyle.WARNING, "Equal to 3", "Error box type = WARNING", false, false, true); - va.addValidation(OperatorType.NOT_EQUAL, "3", null, ErrorStyle.WARNING, "Not equal to 3", "-", false, false, false); - va.addValidation(OperatorType.GREATER_THAN, "3", null, ErrorStyle.WARNING, "Greater than 3", "-", true, false, false); - va.addValidation(OperatorType.LESS_THAN, "3", null, ErrorStyle.WARNING, "Less than 3", "-", true, true, false); - va.addValidation(OperatorType.GREATER_OR_EQUAL, "4", null, ErrorStyle.STOP, "Greater than or equal to 4", "Error box type = STOP", true, false, true); - va.addValidation(OperatorType.LESS_OR_EQUAL, "4", null, ErrorStyle.STOP, "Less than or equal to 4", "-", false, true, false); - } - - @Test - void testDataValidation() throws Exception { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - WorkbookFormatter wf1 = new WorkbookFormatter(wb1); - addSimpleNumericValidations(wf1); - addListValidations(wf1, wb1); - addDateTimeValidations(wf1, wb1); - addTextLengthValidations(wf1); - // Custom Validation type - addCustomValidations(wf1); - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - Sheet sh = wb2.getSheet("Numbers"); - assertEquals(16, sh.getDataValidations().size()); - } - - } - } - - - static void setCellValue(Cell cell, String text) { - cell.setCellValue(text); - } - -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java deleted file mode 100644 index d0d2b0c535..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java +++ /dev/null @@ -1,226 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * @author Yegor Kozlov - */ -public abstract class BaseTestFont { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestFont(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @SuppressWarnings("JUnit5MalformedParameterized") - @ParameterizedTest - @MethodSource("defaultFont") - protected final void baseTestDefaultFont(String defaultName, short defaultSize, short defaultColor) throws IOException { - //get default font and check against default value - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Font fontFind = workbook.findFont(false, defaultColor, defaultSize, defaultName, false, false, Font.SS_NONE, Font.U_NONE); - assertNotNull(fontFind); - - //get default font, then change 2 values and check against different values (height changes) - Font font = workbook.createFont(); - font.setBold(true); - assertTrue(font.getBold()); - font.setUnderline(Font.U_DOUBLE); - assertEquals(Font.U_DOUBLE, font.getUnderline()); - font.setFontHeightInPoints((short) 15); - assertEquals(15 * 20, font.getFontHeight()); - assertEquals(15, font.getFontHeightInPoints()); - fontFind = workbook.findFont(true, defaultColor, (short) (15 * 20), defaultName, false, false, Font.SS_NONE, Font.U_DOUBLE); - assertNotNull(fontFind); - } - } - - @Test - public final void testGetNumberOfFonts() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - int num0 = wb.getNumberOfFonts(); - - Font f1 = wb.createFont(); - f1.setBold(true); - int idx1 = f1.getIndex(); - wb.createCellStyle().setFont(f1); - - Font f2 = wb.createFont(); - f2.setUnderline(Font.U_DOUBLE); - int idx2 = f2.getIndex(); - wb.createCellStyle().setFont(f2); - - Font f3 = wb.createFont(); - f3.setFontHeightInPoints((short) 23); - int idx3 = f3.getIndex(); - wb.createCellStyle().setFont(f3); - - assertEquals(num0 + 3, wb.getNumberOfFonts()); - assertTrue(wb.getFontAt(idx1).getBold()); - assertEquals(Font.U_DOUBLE, wb.getFontAt(idx2).getUnderline()); - assertEquals(23, wb.getFontAt(idx3).getFontHeightInPoints()); - } - } - - /** - * Tests that we can define fonts to a new - * file, save, load, and still see them - */ - @Test - public final void testCreateSave() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet s1 = wb1.createSheet(); - Row r1 = s1.createRow(0); - Cell r1c1 = r1.createCell(0); - r1c1.setCellValue(2.2); - - int num0 = wb1.getNumberOfFonts(); - - Font font = wb1.createFont(); - font.setBold(true); - font.setStrikeout(true); - font.setColor(IndexedColors.YELLOW.getIndex()); - font.setFontName("Courier"); - int font1Idx = font.getIndex(); - wb1.createCellStyle().setFont(font); - assertEquals(num0 + 1, wb1.getNumberOfFonts()); - - CellStyle cellStyleTitle = wb1.createCellStyle(); - cellStyleTitle.setFont(font); - r1c1.setCellStyle(cellStyleTitle); - - // Save and re-load - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - s1 = wb2.getSheetAt(0); - - assertEquals(num0 + 1, wb2.getNumberOfFonts()); - int idx = s1.getRow(0).getCell(0).getCellStyle().getFontIndex(); - Font fnt = wb2.getFontAt(idx); - assertNotNull(fnt); - assertEquals(IndexedColors.YELLOW.getIndex(), fnt.getColor()); - assertEquals("Courier", fnt.getFontName()); - - // Now add an orphaned one - Font font2 = wb2.createFont(); - font2.setItalic(true); - font2.setFontHeightInPoints((short) 15); - int font2Idx = font2.getIndex(); - wb2.createCellStyle().setFont(font2); - assertEquals(num0 + 2, wb2.getNumberOfFonts()); - - // Save and re-load - try (Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2)) { - s1 = wb3.getSheetAt(0); - assertNotNull(s1); - - assertEquals(num0 + 2, wb3.getNumberOfFonts()); - assertNotNull(wb3.getFontAt(font1Idx)); - assertNotNull(wb3.getFontAt(font2Idx)); - - assertEquals(15, wb3.getFontAt(font2Idx).getFontHeightInPoints()); - assertTrue(wb3.getFontAt(font2Idx).getItalic()); - } - } - } - } - - /** - * Test that fonts get added properly - */ - @Test - public final void test45338() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - int num0 = wb.getNumberOfFonts(); - - Sheet s = wb.createSheet(); - s.createRow(0); - s.createRow(1); - s.getRow(0).createCell(0); - s.getRow(1).createCell(0); - - //default font - Font f1 = wb.getFontAt(0); - assertFalse(f1.getBold()); - - // Check that asking for the same font - // multiple times gives you the same thing. - // Otherwise, our tests wouldn't work! - assertSame(wb.getFontAt(0), wb.getFontAt(0)); - - // Look for a new font we have - // yet to add - assertNull( - wb.findFont( - true, (short) 123, (short) (22 * 20), - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - - Font nf = wb.createFont(); - int nfIdx = nf.getIndex(); - assertEquals(num0 + 1, wb.getNumberOfFonts()); - - assertSame(nf, wb.getFontAt(nfIdx)); - - nf.setBold(true); - nf.setColor((short) 123); - nf.setFontHeightInPoints((short) 22); - nf.setFontName("Thingy"); - nf.setItalic(false); - nf.setStrikeout(true); - nf.setTypeOffset((short) 2); - nf.setUnderline((byte) 2); - - assertEquals(num0 + 1, wb.getNumberOfFonts()); - assertEquals(nf, wb.getFontAt(nfIdx)); - - assertEquals(wb.getFontAt(nfIdx), wb.getFontAt(nfIdx)); - assertNotSame(wb.getFontAt(0), wb.getFontAt(nfIdx)); - - // Find it now - assertNotNull( - wb.findFont( - true, (short) 123, (short) (22 * 20), - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - assertSame(nf, - wb.findFont( - true, (short) 123, (short) (22 * 20), - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java deleted file mode 100644 index 6c0e20c888..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java +++ /dev/null @@ -1,738 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; -import java.util.Locale; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.junit.jupiter.api.Test; - -/** - * Common superclass for testing implementation of {@link FormulaEvaluator} - */ -public abstract class BaseTestFormulaEvaluator { - - protected final ITestDataProvider _testDataProvider; - - /** - * @param testDataProvider an object that provides test data in / specific way - */ - protected BaseTestFormulaEvaluator(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - void testSimpleArithmetic() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - - Cell c1 = r.createCell(0); - c1.setCellFormula("1+5"); - assertEquals(0.0, c1.getNumericCellValue(), 0.0); - - Cell c2 = r.createCell(1); - c2.setCellFormula("10/2"); - assertEquals(0.0, c2.getNumericCellValue(), 0.0); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - fe.evaluateFormulaCell(c1); - fe.evaluateFormulaCell(c2); - - assertEquals(6.0, c1.getNumericCellValue(), 0.0001); - assertEquals(5.0, c2.getNumericCellValue(), 0.0001); - - wb.close(); - } - - @Test - void testSumCount() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - r.createCell(0).setCellValue(2.5); - r.createCell(1).setCellValue(1.1); - r.createCell(2).setCellValue(3.2); - r.createCell(4).setCellValue(10.7); - - r = s.createRow(1); - - Cell c1 = r.createCell(0); - c1.setCellFormula("SUM(A1:B1)"); - assertEquals(0.0, c1.getNumericCellValue(), 0.0); - - Cell c2 = r.createCell(1); - c2.setCellFormula("SUM(A1:E1)"); - assertEquals(0.0, c2.getNumericCellValue(), 0.0); - - Cell c3 = r.createCell(2); - c3.setCellFormula("COUNT(A1:A1)"); - assertEquals(0.0, c3.getNumericCellValue(), 0.0); - - Cell c4 = r.createCell(3); - c4.setCellFormula("COUNTA(A1:E1)"); - assertEquals(0.0, c4.getNumericCellValue(), 0.0); - - - // Evaluate and test - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - fe.evaluateFormulaCell(c1); - fe.evaluateFormulaCell(c2); - fe.evaluateFormulaCell(c3); - fe.evaluateFormulaCell(c4); - - assertEquals(3.6, c1.getNumericCellValue(), 0.0001); - assertEquals(17.5, c2.getNumericCellValue(), 0.0001); - assertEquals(1, c3.getNumericCellValue(), 0.0001); - assertEquals(4, c4.getNumericCellValue(), 0.0001); - - wb.close(); - } - - @Test - void testSharedFormulas() throws IOException { - String fileName = "shared_formulas.xls" + (getClass().getName().contains("xssf") ? "x" : ""); - try (Workbook wb = _testDataProvider.openSampleWorkbook(fileName)) { - - Sheet sheet = wb.getSheetAt(0); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell; - - cell = sheet.getRow(1).getCell(0); - assertEquals("B2", cell.getCellFormula()); - assertEquals("ProductionOrderConfirmation", evaluator.evaluate(cell).getStringValue()); - - cell = sheet.getRow(2).getCell(0); - assertEquals("B3", cell.getCellFormula()); - assertEquals("RequiredAcceptanceDate", evaluator.evaluate(cell).getStringValue()); - - cell = sheet.getRow(3).getCell(0); - assertEquals("B4", cell.getCellFormula()); - assertEquals("Header", evaluator.evaluate(cell).getStringValue()); - - cell = sheet.getRow(4).getCell(0); - assertEquals("B5", cell.getCellFormula()); - assertEquals("UniqueDocumentNumberID", evaluator.evaluate(cell).getStringValue()); - } - } - - /** - * Test creation / evaluation of formulas with sheet-level names - */ - @Test - void testSheetLevelFormulas() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Row row; - Sheet sh1 = wb.createSheet("Sheet1"); - Name nm1 = wb.createName(); - nm1.setNameName("sales_1"); - nm1.setSheetIndex(0); - nm1.setRefersToFormula("Sheet1!$A$1"); - row = sh1.createRow(0); - row.createCell(0).setCellValue(3); - row.createCell(1).setCellFormula("sales_1"); - row.createCell(2).setCellFormula("sales_1*2"); - - Sheet sh2 = wb.createSheet("Sheet2"); - Name nm2 = wb.createName(); - nm2.setNameName("sales_1"); - nm2.setSheetIndex(1); - nm2.setRefersToFormula("Sheet2!$A$1"); - - row = sh2.createRow(0); - row.createCell(0).setCellValue(5); - row.createCell(1).setCellFormula("sales_1"); - row.createCell(2).setCellFormula("sales_1*3"); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals(3.0, evaluator.evaluate(sh1.getRow(0).getCell(1)).getNumberValue(), 0.0); - assertEquals(6.0, evaluator.evaluate(sh1.getRow(0).getCell(2)).getNumberValue(), 0.0); - - assertEquals(5.0, evaluator.evaluate(sh2.getRow(0).getCell(1)).getNumberValue(), 0.0); - assertEquals(15.0, evaluator.evaluate(sh2.getRow(0).getCell(2)).getNumberValue(), 0.0); - - wb.close(); - } - - @Test - void testFullColumnRefs() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - cell0.setCellFormula("sum(D:D)"); - Cell cell1 = row.createCell(1); - cell1.setCellFormula("sum(D:E)"); - - // some values in column D - setValue(sheet, 1, 3, 5.0); - setValue(sheet, 2, 3, 6.0); - setValue(sheet, 5, 3, 7.0); - setValue(sheet, 50, 3, 8.0); - - // some values in column E - setValue(sheet, 1, 4, 9.0); - setValue(sheet, 2, 4, 10.0); - setValue(sheet, 30000, 4, 11.0); - - // some other values - setValue(sheet, 1, 2, 100.0); - setValue(sheet, 2, 5, 100.0); - setValue(sheet, 3, 6, 100.0); - - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals(26.0, fe.evaluate(cell0).getNumberValue(), 0.0); - assertEquals(56.0, fe.evaluate(cell1).getNumberValue(), 0.0); - - wb.close(); - } - - @Test - void testRepeatedEvaluation() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - Sheet sheet = wb.createSheet("Sheet1"); - Row r = sheet.createRow(0); - Cell c = r.createCell(0, CellType.FORMULA); - - // Create a value and check it - c.setCellFormula("Date(2011,10,6)"); - CellValue cellValue = fe.evaluate(c); - assertEquals(40822.0, cellValue.getNumberValue(), 0.0); - cellValue = fe.evaluate(c); - assertEquals(40822.0, cellValue.getNumberValue(), 0.0); - - // Change it - c.setCellFormula("Date(2011,10,4)"); - - // Evaluate it, no change as the formula evaluator - // won't know to clear the cache - cellValue = fe.evaluate(c); - assertEquals(40822.0, cellValue.getNumberValue(), 0.0); - - // Manually flush for this cell, and check - fe.notifySetFormula(c); - cellValue = fe.evaluate(c); - assertEquals(40820.0, cellValue.getNumberValue(), 0.0); - - // Change again, without notifying - c.setCellFormula("Date(2010,10,4)"); - cellValue = fe.evaluate(c); - assertEquals(40820.0, cellValue.getNumberValue(), 0.0); - - // Now manually clear all, will see the new value - fe.clearAllCachedResultValues(); - cellValue = fe.evaluate(c); - assertEquals(40455.0, cellValue.getNumberValue(), 0.0); - - wb.close(); - } - - private static void setValue(Sheet sheet, int rowIndex, int colIndex, double value) { - Row row = sheet.getRow(rowIndex); - if (row == null) { - row = sheet.createRow(rowIndex); - } - row.createCell(colIndex).setCellValue(value); - } - - /** - * {@link FormulaEvaluator#evaluate(org.apache.poi.ss.usermodel.Cell)} should behave the same whether the cell - * is null or blank. - */ - @Test - void testEvaluateBlank() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - assertNull(fe.evaluate(null)); - Sheet sheet = wb.createSheet("Sheet1"); - Cell cell = sheet.createRow(0).createCell(0); - assertNull(fe.evaluate(cell)); - wb.close(); - } - - /** - * Test for bug due to attempt to convert a cached formula error result to a boolean - */ - @Test - void testUpdateCachedFormulaResultFromErrorToNumber_bug46479() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("Sheet1"); - Row row = sheet.createRow(0); - Cell cellA1 = row.createCell(0); - Cell cellB1 = row.createCell(1); - cellB1.setCellFormula("A1+1"); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - cellA1.setCellErrorValue(FormulaError.NAME.getCode()); - assertEquals(CellType.ERROR, fe.evaluateFormulaCell(cellB1)); - assertEquals(CellType.FORMULA, cellB1.getCellType()); - - cellA1.setCellValue(2.5); - fe.notifyUpdateCell(cellA1); - try { - fe.evaluateInCell(cellB1); - } catch (IllegalStateException e) { - if (e.getMessage().equalsIgnoreCase("Cannot get a numeric value from a error formula cell")) { - fail("Identified bug 46479a"); - } - } - assertEquals(3.5, cellB1.getNumericCellValue(), 0.0); - } - } - - @Test - void testRounding_bug51339() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - Row row = sheet.createRow(0); - Cell cellA1 = row.createCell(0); - cellA1.setCellValue(2162.615d); - Cell cellB1 = row.createCell(1); - cellB1.setCellFormula("round(a1,2)"); - Cell cellC1 = row.createCell(2); - cellC1.setCellFormula("roundup(a1,2)"); - Cell cellD1 = row.createCell(3); - cellD1.setCellFormula("rounddown(a1,2)"); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - assertEquals(2162.62, fe.evaluateInCell(cellB1).getNumericCellValue(), 0.0); - assertEquals(2162.62, fe.evaluateInCell(cellC1).getNumericCellValue(), 0.0); - assertEquals(2162.61, fe.evaluateInCell(cellD1).getNumericCellValue(), 0.0); - - wb.close(); - } - - @Test - void evaluateInCellReturnsSameCell() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - wb.createSheet().createRow(0).createCell(0); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell = wb.getSheetAt(0).getRow(0).getCell(0); - Cell same = evaluator.evaluateInCell(cell); - assertSame(cell, same); - } - } - - @Test - void testBug61148() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - final Cell cell = wb.createSheet().createRow(0).createCell(0); - cell.setCellFormula("1+2"); - - assertEquals(0, (int)cell.getNumericCellValue()); - assertEquals("1+2", cell.toString()); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - eval.evaluateInCell(cell); - - assertEquals("3.0", cell.toString()); - } - } - - @Test - void testMultisheetFormulaEval() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet1 = wb.createSheet("Sheet1"); - Sheet sheet2 = wb.createSheet("Sheet2"); - Sheet sheet3 = wb.createSheet("Sheet3"); - - // sheet1 A1 - Cell cell = sheet1.createRow(0).createCell(0); - cell.setCellValue(1.0); - - // sheet2 A1 - cell = sheet2.createRow(0).createCell(0); - cell.setCellValue(1.0); - - // sheet2 B1 - cell = sheet2.getRow(0).createCell(1); - cell.setCellValue(1.0); - - // sheet3 A1 - cell = sheet3.createRow(0).createCell(0); - cell.setCellValue(1.0); - - // sheet1 A2 formulae - cell = sheet1.createRow(1).createCell(0); - cell.setCellFormula("SUM(Sheet1:Sheet3!A1)"); - - // sheet1 A3 formulae - cell = sheet1.createRow(2).createCell(0); - cell.setCellFormula("SUM(Sheet1:Sheet3!A1:B1)"); - - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - cell = sheet1.getRow(1).getCell(0); - assertEquals(3.0, cell.getNumericCellValue(), 0); - - cell = sheet1.getRow(2).getCell(0); - assertEquals(4.0, cell.getNumericCellValue(), 0); - } - } - - @Test - void testBug55843() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - Row row2 = sheet.createRow(1); - Cell cellA2 = row2.createCell(0, CellType.FORMULA); - Cell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - cellA2.setCellFormula("IF(B1=0,\"\",((ROW()-ROW(A$1))*12))"); - CellValue evaluate = formulaEvaluator.evaluate(cellA2); - assertEquals("12.0", evaluate.formatAsString()); - - cellA2.setCellFormula("IF(NOT(B1=0),((ROW()-ROW(A$1))*12),\"\")"); - CellValue evaluateN = formulaEvaluator.evaluate(cellA2); - - assertEquals(evaluate.toString(), evaluateN.toString()); - assertEquals("12.0", evaluateN.formatAsString()); - } - } - - @Test - void testBug55843a() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - Row row2 = sheet.createRow(1); - Cell cellA2 = row2.createCell(0, CellType.FORMULA); - Cell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - cellA2.setCellFormula("IF(B1=0,\"\",((ROW(A$1))))"); - CellValue evaluate = formulaEvaluator.evaluate(cellA2); - assertEquals("1.0", evaluate.formatAsString()); - - cellA2.setCellFormula("IF(NOT(B1=0),((ROW(A$1))),\"\")"); - CellValue evaluateN = formulaEvaluator.evaluate(cellA2); - - assertEquals(evaluate.toString(), evaluateN.toString()); - assertEquals("1.0", evaluateN.formatAsString()); - } - } - - @Test - void testBug55843b() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - Row row2 = sheet.createRow(1); - Cell cellA2 = row2.createCell(0, CellType.FORMULA); - Cell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - - cellA2.setCellFormula("IF(B1=0,\"\",((ROW())))"); - CellValue evaluate = formulaEvaluator.evaluate(cellA2); - assertEquals("2.0", evaluate.formatAsString()); - - cellA2.setCellFormula("IF(NOT(B1=0),((ROW())),\"\")"); - CellValue evaluateN = formulaEvaluator.evaluate(cellA2); - - assertEquals(evaluate.toString(), evaluateN.toString()); - assertEquals("2.0", evaluateN.formatAsString()); - } - } - - @Test - void testBug55843c() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - Row row2 = sheet.createRow(1); - Cell cellA2 = row2.createCell(0, CellType.FORMULA); - Cell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - - cellA2.setCellFormula("IF(NOT(B1=0),((ROW())))"); - CellValue evaluateN = formulaEvaluator.evaluate(cellA2); - assertEquals("2.0", evaluateN.formatAsString()); - } - } - - @Test - void testBug55843d() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - Row row2 = sheet.createRow(1); - Cell cellA2 = row2.createCell(0, CellType.FORMULA); - Cell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - - cellA2.setCellFormula("IF(NOT(B1=0),((ROW())),\"\")"); - CellValue evaluateN = formulaEvaluator.evaluate(cellA2); - assertEquals("2.0", evaluateN.formatAsString()); - } - } - - @Test - void testBug55843e() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - Row row2 = sheet.createRow(1); - Cell cellA2 = row2.createCell(0, CellType.FORMULA); - Cell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - - cellA2.setCellFormula("IF(B1=0,\"\",((ROW())))"); - CellValue evaluate = formulaEvaluator.evaluate(cellA2); - assertEquals("2.0", evaluate.formatAsString()); - } - } - - @Test - void testBug55843f() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - Row row2 = sheet.createRow(1); - Cell cellA2 = row2.createCell(0, CellType.FORMULA); - Cell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - - cellA2.setCellFormula("IF(B1=0,\"\",IF(B1=10,3,4))"); - CellValue evaluate = formulaEvaluator.evaluate(cellA2); - assertEquals("3.0", evaluate.formatAsString()); - } - } - - @Test - void testBug56655() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - setCellFormula(sheet, 0, 0, "#VALUE!"); - setCellFormula(sheet, 0, 1, "SUMIFS(A:A,A:A,#VALUE!)"); - - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); - assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); - assertEquals(CellType.ERROR, getCell(sheet, 0, 1).getCachedFormulaResultType()); - assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 1).getErrorCellValue()); - } - } - - @Test - void testBug56655a() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - setCellFormula(sheet, 0, 0, "B1*C1"); - sheet.getRow(0).createCell(1).setCellValue("A"); - setCellFormula(sheet, 1, 0, "B1*C1"); - sheet.getRow(1).createCell(1).setCellValue("A"); - setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); - - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); - assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); - assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultType()); - assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); - assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultType()); - assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); - } - } - - /** - * @param row 0-based - * @param column 0-based - */ - private void setCellFormula(Sheet sheet, int row, int column, String formula) { - Row r = sheet.getRow(row); - if (r == null) { - r = sheet.createRow(row); - } - Cell cell = r.getCell(column); - if (cell == null) { - cell = r.createCell(column); - } - cell.setCellFormula(formula); - } - - /** - * @param rowNo 0-based - * @param column 0-based - */ - private Cell getCell(Sheet sheet, int rowNo, int column) { - return sheet.getRow(rowNo).getCell(column); - } - - @Test - void testBug61532() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - final Cell cell = wb.createSheet().createRow(0).createCell(0); - cell.setCellFormula("1+2"); - - assertEquals(0, (int)cell.getNumericCellValue()); - assertEquals("1+2", cell.toString()); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - CellValue value = eval.evaluate(cell); - - assertEquals(CellType.NUMERIC, value.getCellType()); - assertEquals(3.0, value.getNumberValue(), 0.01); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("1+2", cell.getCellFormula()); - assertEquals("1+2", cell.toString()); - - assertNotNull(eval.evaluateInCell(cell)); - - assertEquals("3.0", cell.toString()); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertEquals(3.0, cell.getNumericCellValue(), 0.01); - } - } - - @Test - void testFormulaEvaluatorEvaluateSimpleFormulaCell() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - final Row row = wb.createSheet().createRow(0); - final Cell a1 = row.createCell(0, CellType.NUMERIC); - a1.setCellValue(1.0); - final Cell a2 = row.createCell(1, CellType.NUMERIC); - a2.setCellValue(2.0); - final Cell a3 = row.createCell(2, CellType.FORMULA); - final String formula = "SUM(A1:B1)"; - a3.setCellFormula(formula); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - CellType resultType = evaluator.evaluateFormulaCell(a3); - assertEquals(CellType.NUMERIC, resultType); - - double result = a3.getNumericCellValue(); - // result is correct - assertTrue(result > 2.0, String.format(Locale.ROOT, "Expected %f to be greater than %f", result, 2.0)); - assertTrue(result < 4.0, String.format(Locale.ROOT, "Expected %f to be less than %f", result, 4.0)); - - // ensure that this works for SUM - assertEquals(CellType.FORMULA, a3.getCellType()); - assertEquals(formula, a3.getCellFormula()); - } - } - - @Test - void testFormulaEvaluatorEvaluateVlookupFormulaCell() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - final Sheet mainSheet = wb.createSheet("main"); - final Sheet otherSheet = wb.createSheet("other"); - final Row otherRow1 = otherSheet.createRow(0); - final Cell label1 = otherRow1.createCell(0, CellType.STRING); - label1.setCellValue("Thing One"); - final Cell id1 = otherRow1.createCell(1, CellType.STRING); - id1.setCellValue("1"); - final Row otherRow2 = otherSheet.createRow(1); - final Cell label2 = otherRow2.createCell(0, CellType.STRING); - label2.setCellValue("Thing Two"); - final Cell id2 = otherRow2.createCell(1, CellType.STRING); - id2.setCellValue("2"); - final DataValidationHelper dvHelper = mainSheet.getDataValidationHelper(); - final int maxRows = SpreadsheetVersion.EXCEL2007.getMaxRows() - 1; - final CellRangeAddressList addressList = new CellRangeAddressList(0, maxRows, 0, 0); - final String constraint = "'other'!$A:$A"; - final DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint(constraint); - final DataValidation dataValidation = dvHelper.createValidation(dvConstraint, addressList); - dataValidation.setShowErrorBox(true); - mainSheet.addValidationData(dataValidation); - wb.setSheetHidden(wb.getSheetIndex(otherSheet), true); - final Row row = mainSheet.createRow(0); - final Cell a1 = row.createCell(0, CellType.STRING); - a1.setCellValue("Thing Two"); - final Cell a2 = row.createCell(1, CellType.FORMULA); - final String formula = "VLOOKUP(A1,other!A:B,2,FALSE)"; - a2.setCellFormula(formula); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - CellType resultType = evaluator.evaluateFormulaCell(a2); - assertEquals(CellType.STRING, resultType); - - // result is correct - String result = a2.getStringCellValue(); - assertEquals("2", result); - - // ensure that this works for vlookup as well - assertEquals(CellType.FORMULA, a2.getCellType()); - assertEquals(formula, a2.getCellFormula()); - } - } - - // setting an evaluation of function arguments with the intersect operator (space) - // see https://bz.apache.org/bugzilla/show_bug.cgi?id=60980 - @Test - void testIntersectionInFunctionArgs_60980() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - - Name n1 = wb.createName(); - n1.setNameName("foo"); - n1.setRefersToFormula("A4:B5"); - Name n2 = wb.createName(); - n2.setNameName("bar"); - n2.setRefersToFormula("B4:C5"); - - Sheet sheet = wb.createSheet(); - Row row3 = sheet.createRow(3); - row3.createCell(0).setCellValue(1); - row3.createCell(1).setCellValue(2); - row3.createCell(2).setCellValue(3); - Row row4 = sheet.createRow(4); - row4.createCell(0).setCellValue(4); - row4.createCell(1).setCellValue(5); - row4.createCell(2).setCellValue(6); - - Cell fmla1 = row3.createCell(4); - fmla1.setCellFormula("SUM(A4:B5 B4:C5)"); - fe.evaluateFormulaCell(fmla1); - assertEquals(7, fmla1.getNumericCellValue(), 0.000); - - Cell fmla2 = row3.createCell(5); - fmla2.setCellFormula("SUM(foo bar)"); - fe.evaluateFormulaCell(fmla2); - assertEquals(7, fmla2.getNumericCellValue(), 0.000); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestHyperlink.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestHyperlink.java deleted file mode 100644 index 44a33c3f20..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestHyperlink.java +++ /dev/null @@ -1,148 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.ss.ITestDataProvider; -import org.junit.jupiter.api.Test; - -/** - * Test diffrent types of Excel hyperlinks - * - * @author Yegor Kozlov - */ -public abstract class BaseTestHyperlink { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestHyperlink(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public final void testBasicTypes() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - CreationHelper createHelper = wb1.getCreationHelper(); - - Cell cell; - Hyperlink link; - Sheet sheet = wb1.createSheet("Hyperlinks"); - - //URL - cell = sheet.createRow(0).createCell((short) 0); - cell.setCellValue("URL Link"); - link = createHelper.createHyperlink(HyperlinkType.URL); - link.setAddress("https://poi.apache.org/"); - cell.setHyperlink(link); - - //link to a file in the current directory - cell = sheet.createRow(1).createCell((short) 0); - cell.setCellValue("File Link"); - link = createHelper.createHyperlink(HyperlinkType.FILE); - link.setAddress("hyperinks-beta4-dump.txt"); - cell.setHyperlink(link); - - //e-mail link - cell = sheet.createRow(2).createCell((short) 0); - cell.setCellValue("Email Link"); - link = createHelper.createHyperlink(HyperlinkType.EMAIL); - //note, if subject contains white spaces, make sure they are url-encoded - link.setAddress("mailto:poi@apache.org?subject=Hyperlinks"); - cell.setHyperlink(link); - - //link to a place in this workbook - - //create a target sheet and cell - Sheet sheet2 = wb1.createSheet("Target Sheet"); - sheet2.createRow(0).createCell((short) 0).setCellValue("Target Cell"); - - cell = sheet.createRow(3).createCell((short) 0); - cell.setCellValue("Worksheet Link"); - link = createHelper.createHyperlink(HyperlinkType.DOCUMENT); - link.setAddress("'Target Sheet'!A1"); - cell.setHyperlink(link); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - link = sheet.getRow(0).getCell(0).getHyperlink(); - - assertEquals("https://poi.apache.org/", link.getAddress()); - link = sheet.getRow(1).getCell(0).getHyperlink(); - assertEquals("hyperinks-beta4-dump.txt", link.getAddress()); - link = sheet.getRow(2).getCell(0).getHyperlink(); - assertEquals("mailto:poi@apache.org?subject=Hyperlinks", link.getAddress()); - link = sheet.getRow(3).getCell(0).getHyperlink(); - assertEquals("'Target Sheet'!A1", link.getAddress()); - - wb2.close(); - } - - // copy a hyperlink via the copy constructor - @Test - void testCopyHyperlink() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - final CreationHelper createHelper = wb.getCreationHelper(); - - final Sheet sheet = wb.createSheet("Hyperlinks"); - final Row row = sheet.createRow(0); - final Cell cell1, cell2; - final Hyperlink link1, link2; - - //URL - cell1 = row.createCell(0); - cell2 = row.createCell(1); - cell1.setCellValue("URL Link"); - link1 = createHelper.createHyperlink(HyperlinkType.URL); - link1.setAddress("https://poi.apache.org/"); - cell1.setHyperlink(link1); - - link2 = copyHyperlink(link1); - - // Change address (type is not changeable) - link2.setAddress("http://apache.org/"); - cell2.setHyperlink(link2); - - // Make sure hyperlinks were deep-copied, and modifying one does not modify the other. - assertNotSame(link1, link2); - assertNotEquals(link1, link2); - assertEquals("https://poi.apache.org/", link1.getAddress()); - assertEquals("http://apache.org/", link2.getAddress()); - assertEquals(link1, cell1.getHyperlink()); - assertEquals(link2, cell2.getHyperlink()); - - // Make sure both hyperlinks were added to the sheet - @SuppressWarnings("unchecked") - final List actualHyperlinks = (List) sheet.getHyperlinkList(); - assertEquals(2, actualHyperlinks.size()); - assertEquals(link1, actualHyperlinks.get(0)); - assertEquals(link2, actualHyperlinks.get(1)); - - wb.close(); - } - - public abstract Hyperlink copyHyperlink(Hyperlink link); -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestNamedRange.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestNamedRange.java deleted file mode 100644 index 60a676fc7b..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestNamedRange.java +++ /dev/null @@ -1,697 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -/** - * Tests of implementations of {@link org.apache.poi.ss.usermodel.Name}. - */ -public abstract class BaseTestNamedRange { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestNamedRange(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public final void testCreate() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - wb.createSheet("Test1"); - wb.createSheet("Testing Named Ranges"); - - Name name1 = wb.createName(); - name1.setNameName("testOne"); - - //setting a duplicate name should throw IllegalArgumentException - Name name2 = wb.createName(); - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> name2.setNameName("testOne")); - assertEquals("The workbook already contains this name: testOne", e.getMessage()); - - //the check for duplicates is case-insensitive - e = assertThrows(IllegalArgumentException.class, () -> name2.setNameName("TESTone")); - assertEquals("The workbook already contains this name: TESTone", e.getMessage()); - - name2.setNameName("testTwo"); - - String ref1 = "Test1!$A$1:$B$1"; - name1.setRefersToFormula(ref1); - assertEquals(ref1, name1.getRefersToFormula()); - assertEquals("Test1", name1.getSheetName()); - - String ref2 = "'Testing Named Ranges'!$A$1:$B$1"; - name1.setRefersToFormula(ref2); - assertEquals("'Testing Named Ranges'!$A$1:$B$1", name1.getRefersToFormula()); - assertEquals("Testing Named Ranges", name1.getSheetName()); - - assertEquals(-1, name1.getSheetIndex()); - name1.setSheetIndex(-1); - assertEquals(-1, name1.getSheetIndex()); - e = assertThrows(IllegalArgumentException.class, () -> name1.setSheetIndex(2)); - assertEquals("Sheet index (2) is out of range (0..1)", e.getMessage()); - - name1.setSheetIndex(1); - assertEquals(1, name1.getSheetIndex()); - - //-1 means the name applies to the entire workbook - name1.setSheetIndex(-1); - assertEquals(-1, name1.getSheetIndex()); - - //names cannot be blank and must begin with a letter or underscore and not contain spaces - String[] invalidNames = {"", "123", "1Name", "Named Range"}; - for (String name : invalidNames) { - assertThrows(IllegalArgumentException.class, () -> name1.setNameName(name), - "should have thrown exceptiuon due to invalid name: " + name); - } - } - } - - @Test - public final void testUnicodeNamedRange() throws Exception { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - wb1.createSheet("Test"); - Name name = wb1.createName(); - name.setNameName("\u03B1"); - name.setRefersToFormula("Test!$D$3:$E$8"); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - Name name2 = wb2.getName("\u03B1"); - - assertNotNull(name2); - assertEquals("\u03B1", name2.getNameName()); - assertEquals("Test!$D$3:$E$8", name2.getRefersToFormula()); - - } - } - } - - @Test - public final void testAddRemove() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - assertEquals(0, wb.getNumberOfNames()); - Name name1 = wb.createName(); - name1.setNameName("name1"); - assertEquals(1, wb.getNumberOfNames()); - - Name name2 = wb.createName(); - name2.setNameName("name2"); - assertEquals(2, wb.getNumberOfNames()); - - Name name3 = wb.createName(); - name3.setNameName("name3"); - assertEquals(3, wb.getNumberOfNames()); - - wb.removeName(wb.getName("name2")); - assertEquals(2, wb.getNumberOfNames()); - } - } - - @Test - public final void testScope() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - wb.createSheet(); - wb.createSheet(); - - wb.createName().setNameName("aaa"); - Exception e = assertThrows(Exception.class, () -> wb.createName().setNameName("aaa")); - assertEquals("The workbook already contains this name: aaa", e.getMessage()); - - Name name1 = wb.createName(); - name1.setSheetIndex(0); - name1.setNameName("aaa"); - - e = assertThrows(Exception.class, () -> { - Name name2 = wb.createName(); - name2.setSheetIndex(0); - name2.setNameName("aaa"); - }); - assertEquals("The sheet already contains this name: aaa", e.getMessage()); - - name1 = wb.createName(); - name1.setSheetIndex(1); - name1.setNameName("aaa"); - - e = assertThrows(Exception.class, () -> { - Name name2 = wb.createName(); - name2.setSheetIndex(1); - name2.setNameName("aaa"); - }); - assertEquals("The sheet already contains this name: aaa", e.getMessage()); - - assertEquals(3, wb.getNames("aaa").size()); - } - } - - /** - * Test case provided by czhang@cambian.com (Chun Zhang) - *

- * Addresses Bug #13775 - */ - @Test - public final void testMultiNamedRange() throws Exception { - - // Create a new workbook - Workbook wb1 = _testDataProvider.createWorkbook(); - - // Create a worksheet 'sheet1' in the new workbook - wb1.createSheet (); - wb1.setSheetName (0, "sheet1"); - - // Create another worksheet 'sheet2' in the new workbook - wb1.createSheet (); - wb1.setSheetName (1, "sheet2"); - - // Create a new named range for worksheet 'sheet1' - Name namedRange1 = wb1.createName(); - - // Set the name for the named range for worksheet 'sheet1' - namedRange1.setNameName("RangeTest1"); - - // Set the reference for the named range for worksheet 'sheet1' - namedRange1.setRefersToFormula("sheet1" + "!$A$1:$L$41"); - - // Create a new named range for worksheet 'sheet2' - Name namedRange2 = wb1.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.setRefersToFormula("sheet2" + "!$A$1:$O$21"); - - // Write the workbook to a file - // Read the Excel file and verify its content - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - Name nm1 = wb2.getName("RangeTest1"); - assertEquals("RangeTest1", nm1.getNameName(), "Name is " + nm1.getNameName()); - assertEquals((wb2.getSheetName(0) + "!$A$1:$L$41"), nm1.getRefersToFormula(), "Reference is " + nm1.getRefersToFormula()); - - Name nm2 = wb2.getName("RangeTest2"); - assertEquals("RangeTest2", nm2.getNameName(), "Name is " + nm2.getNameName()); - assertEquals((wb2.getSheetName(1) + "!$A$1:$O$21"), nm2.getRefersToFormula(), "Reference is " + nm2.getRefersToFormula()); - - wb2.close(); - wb1.close(); - } - - /** - * Test to see if the print areas can be retrieved/created in memory - */ - @Test - public final void testSinglePrintArea() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - 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(retrievedPrintArea, "Print Area not defined for first sheet"); - assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - - workbook.close(); - } - - /** - * For Convenience, don't force sheet names to be used - */ - @Test - public final void testSinglePrintAreaWOSheet() throws Exception - { - Workbook workbook = _testDataProvider.createWorkbook(); - 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(retrievedPrintArea, "Print Area not defined for first sheet"); - assertEquals("'" + sheetName + "'!" + reference, retrievedPrintArea); - - workbook.close(); - } - - /** - * Test to see if the print area made it to the file - */ - @Test - public final void testPrintAreaFile() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - wb1.createSheet("Test Print Area"); - String sheetName = wb1.getSheetName(0); - - - String reference = "$A$1:$B$1"; - wb1.setPrintArea(0, reference); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - - String retrievedPrintArea = wb2.getPrintArea(0); - assertNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); - assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - - wb2.close(); - wb1.close(); - } - - /** - * Test to see if multiple print areas made it to the file - */ - @Test - public final void testMultiplePrintAreaFile() throws Exception { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - - wb1.createSheet("Sheet1"); - wb1.createSheet("Sheet2"); - wb1.createSheet("Sheet3"); - String reference1 = "$A$1:$B$1"; - String reference2 = "$B$2:$D$5"; - String reference3 = "$D$2:$F$5"; - - wb1.setPrintArea(0, reference1); - wb1.setPrintArea(1, reference2); - wb1.setPrintArea(2, reference3); - - //Check created print areas - String retrievedPrintArea; - - retrievedPrintArea = wb1.getPrintArea(0); - assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 1)"); - assertEquals("Sheet1!" + reference1, retrievedPrintArea); - - retrievedPrintArea = wb1.getPrintArea(1); - assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 2)"); - assertEquals("Sheet2!" + reference2, retrievedPrintArea); - - retrievedPrintArea = wb1.getPrintArea(2); - assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 3)"); - assertEquals("Sheet3!" + reference3, retrievedPrintArea); - - // Check print areas after re-reading workbook - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - - retrievedPrintArea = wb2.getPrintArea(0); - assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 1)"); - assertEquals("Sheet1!" + reference1, retrievedPrintArea); - - retrievedPrintArea = wb2.getPrintArea(1); - assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 2)"); - assertEquals("Sheet2!" + reference2, retrievedPrintArea); - - retrievedPrintArea = wb2.getPrintArea(2); - assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 3)"); - assertEquals("Sheet3!" + reference3, retrievedPrintArea); - } - } - } - - /** - * Tests the setting of print areas with coordinates (Row/Column designations) - * - */ - @Test - public final void testPrintAreaCoords() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - workbook.createSheet("Test Print Area"); - String sheetName = workbook.getSheetName(0); - - workbook.setPrintArea(0, 0, 1, 0, 0); - - String retrievedPrintArea = workbook.getPrintArea(0); - - assertNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); - assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - - workbook.close(); - } - - - /** - * Tests the parsing of union area expressions, and re-display in the presence of sheet names - * with special characters. - */ - @Test - public final void testPrintAreaUnion() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - workbook.createSheet("Test Print Area"); - - String reference = "$A$1:$B$1,$D$1:$F$2"; - workbook.setPrintArea(0, reference); - String retrievedPrintArea = workbook.getPrintArea(0); - assertNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); - assertEquals("'Test Print Area'!$A$1:$B$1,'Test Print Area'!$D$1:$F$2", retrievedPrintArea); - - workbook.close(); - } - - /** - * Verifies an existing print area is deleted - * - */ - @Test - public final void testPrintAreaRemove() throws Exception { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - workbook.createSheet("Test Print Area"); - workbook.getSheetName(0); - - workbook.setPrintArea(0, 0, 1, 0, 0); - - String retrievedPrintArea = workbook.getPrintArea(0); - - assertNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); - - workbook.removePrintArea(0); - assertNull(workbook.getPrintArea(0), "PrintArea was not removed"); - } - } - - /** - * Test that multiple named ranges can be added written and read - */ - @Test - public final void testMultipleNamedWrite() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - - - wb1.createSheet("testSheet1"); - String sheetName = wb1.getSheetName(0); - - assertEquals("testSheet1", sheetName); - - //Creating new Named Range - Name newNamedRange = wb1.createName(); - - newNamedRange.setNameName("RangeTest"); - newNamedRange.setRefersToFormula(sheetName + "!$D$4:$E$8"); - - //Creating another new Named Range - Name newNamedRange2 = wb1.createName(); - - newNamedRange2.setNameName("AnotherTest"); - newNamedRange2.setRefersToFormula(sheetName + "!$F$1:$G$6"); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - Name nm = wb2.getName("RangeTest"); - assertEquals("RangeTest", nm.getNameName(), "Name is " + nm.getNameName()); - assertEquals((wb2.getSheetName(0) + "!$D$4:$E$8"), nm.getRefersToFormula(), "Reference is " + nm.getRefersToFormula()); - - nm = wb2.getName("AnotherTest"); - assertEquals("AnotherTest", nm.getNameName(), "Name is " + nm.getNameName()); - assertEquals(newNamedRange2.getRefersToFormula(), nm.getRefersToFormula(), "Reference is " + nm.getRefersToFormula()); - - wb2.close(); - wb1.close(); - } - - /** - * Verifies correct functioning for "single cell named range" (aka "named cell") - */ - @Test - public final void testNamedCell_1() throws Exception { - - // setup for this testcase - String sheetName = "Test Named Cell"; - String cellName = "named_cell"; - String cellValue = "TEST Value"; - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(sheetName); - CreationHelper factory = wb.getCreationHelper(); - sheet.createRow(0).createCell(0).setCellValue(factory.createRichTextString(cellValue)); - - // create named range for a single cell using areareference - Name namedCell = wb.createName(); - namedCell.setNameName(cellName); - String reference = "'" + sheetName + "'" + "!A1:A1"; - namedCell.setRefersToFormula(reference); - - // retrieve the newly created named range - Name aNamedCell = wb.getName(cellName); - assertNotNull(aNamedCell); - - // retrieve the cell at the named range and test its contents - AreaReference aref = wb.getCreationHelper().createAreaReference(aNamedCell.getRefersToFormula()); - assertTrue(aref.isSingleCell(), "Should be exactly 1 cell in the named cell :'" +cellName+"'"); - - CellReference cref = aref.getFirstCell(); - assertNotNull(cref); - Sheet s = wb.getSheet(cref.getSheetName()); - assertNotNull(s); - Row r = sheet.getRow(cref.getRow()); - Cell c = r.getCell(cref.getCol()); - String contents = c.getRichStringCellValue().getString(); - assertEquals(contents, cellValue, "Contents of cell retrieved by its named reference"); - wb.close(); - } - - /** - * Verifies correct functioning for "single cell named range" (aka "named cell") - */ - @Test - public final void testNamedCell_2() throws Exception { - - // setup for this testcase - String sname = "TestSheet", cname = "TestName", cvalue = "TestVal"; - Workbook wb = _testDataProvider.createWorkbook(); - CreationHelper factory = wb.getCreationHelper(); - Sheet sheet = wb.createSheet(sname); - sheet.createRow(0).createCell(0).setCellValue(factory.createRichTextString(cvalue)); - - // create named range for a single cell using cellreference - Name namedCell = wb.createName(); - namedCell.setNameName(cname); - String reference = sname+"!A1"; - namedCell.setRefersToFormula(reference); - - // retrieve the newly created named range - Name aNamedCell = wb.getName(cname); - assertNotNull(aNamedCell); - - // retrieve the cell at the named range and test its contents - CellReference cref = new CellReference(aNamedCell.getRefersToFormula()); - assertNotNull(cref); - Sheet s = wb.getSheet(cref.getSheetName()); - assertNotNull(s); - Row r = sheet.getRow(cref.getRow()); - Cell c = r.getCell(cref.getCol()); - String contents = c.getRichStringCellValue().getString(); - assertEquals(contents, cvalue, "Contents of cell retrieved by its named reference"); - - wb.close(); - } - - - /** - * Bugzilla attachment 23444 (from bug 46973) has a NAME record with the following encoding: - *

-     * 00000000 | 18 00 17 00 00 00 00 08 00 00 00 00 00 00 00 00 | ................
-     * 00000010 | 00 00 00 55 50 53 53 74 61 74 65                | ...UPSState
-     * 
- * - * This caused trouble for anything that requires {@link Name#getRefersToFormula()} - * It is easy enough to re-create the the same data (by not setting the formula). Excel - * seems to gracefully remove this uninitialized name record. It would be nice if POI - * could do the same, but that would involve adjusting subsequent name indexes across - * all formulas.

- * - * For the moment, POI has been made to behave more sensibly with uninitialized name - * records. - */ - @Test - public final void testUninitialisedNameGetRefersToFormula_bug46973() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Name n = wb.createName(); - n.setNameName("UPSState"); - String formula = n.getRefersToFormula(); - - // bug 46973: fails here with IllegalArgumentException - // ptgs must not be null - - assertNull(formula); - // according to exact definition of isDeleted() - assertFalse(n.isDeleted()); - wb.close(); - } - - @Test - public final void testDeletedCell() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Name n = wb.createName(); - n.setNameName("MyName"); - // contrived example to expose bug: - n.setRefersToFormula("if(A1,\"#REF!\", \"\")"); - - assertFalse(n.isDeleted(), "Identified bug in recoginising formulas referring to deleted cells"); - - wb.close(); - } - - @Test - public final void testFunctionNames() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Name n = wb.createName(); - assertFalse(n.isFunctionName()); - - n.setFunction(false); - assertFalse(n.isFunctionName()); - - n.setFunction(true); - assertTrue(n.isFunctionName()); - - n.setFunction(false); - assertFalse(n.isFunctionName()); - - wb.close(); - } - - @Test - public final void testDefferedSetting() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Name n1 = wb.createName(); - assertNull(n1.getRefersToFormula()); - assertEquals("", n1.getNameName()); - - Name n2 = wb.createName(); - assertNull(n2.getRefersToFormula()); - assertEquals("", n2.getNameName()); - - n1.setNameName("sale_1"); - n1.setRefersToFormula("10"); - - n2.setNameName("sale_2"); - n2.setRefersToFormula("20"); - - Exception e = assertThrows(Exception.class, () -> n2.setNameName("sale_1")); - assertEquals("The workbook already contains this name: sale_1", e.getMessage()); - } - } - - @Test - void testBug56930() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - // x1 on sheet1 defines "x=1" - wb.createSheet("sheet1"); - Name x1 = wb.createName(); - - x1.setNameName("x"); - x1.setRefersToFormula("1"); - x1.setSheetIndex(wb.getSheetIndex("sheet1")); - - // x2 on sheet2 defines "x=2" - wb.createSheet("sheet2"); - Name x2 = wb.createName(); - x2.setNameName("x"); - x2.setRefersToFormula("2"); - x2.setSheetIndex(wb.getSheetIndex("sheet2")); - - List names = wb.getNames("x"); - assertEquals(2, names.size(), "Had: " + names); - assertEquals("1", names.get(0).getRefersToFormula()); - assertEquals("2", names.get(1).getRefersToFormula()); - - assertEquals("1", wb.getName("x").getRefersToFormula()); - wb.removeName(wb.getName("x")); - assertEquals("2", wb.getName("x").getRefersToFormula()); - - wb.close(); - } - - // bug 56781: name validation only checks for first character's validity and presence of spaces - // bug 60246: validate name does not allow DOT in named ranges - @ParameterizedTest - @ValueSource(strings = {"Hello", "number1", "_underscore", "underscore_", "p.e.r.o.i.d.s", "\\Backslash", "Backslash\\"}) - void testValid(String valid) throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Name name = wb.createName(); - assertDoesNotThrow(() -> name.setNameName(valid)); - } - } - - @ParameterizedTest - @ValueSource(strings = { - "1number", "Sheet1!A1", "Exclamation!", "Has Space", "Colon:", "A-Minus", "A+Plus", "Dollar$", ".periodAtBeginning", - //special shorthand - "R", "C", - // A1-style cell reference - "A1", - // R1C1-style cell reference - "R1C1", - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters" - }) - void testInvalid(String invalid) { - Workbook wb = _testDataProvider.createWorkbook(); - - Name name = wb.createName(); - IllegalArgumentException e; - e = assertThrows(IllegalArgumentException.class, () -> name.setNameName("")); - assertEquals("Name cannot be blank", e.getMessage()); - - e = assertThrows(IllegalArgumentException.class, () -> name.setNameName(invalid)); - assertTrue(e.getMessage().startsWith("Invalid name: '"+invalid+"'")); - } - - // bug 60260: renaming a sheet with a named range referring to a unicode (non-ASCII) sheet name - @Test - void renameSheetWithNamedRangeReferringToUnicodeSheetName() throws IOException { - String unicodeName = "Sheet\u30FB201"; - String asciiName = "Sheet 1"; - String rangeName = "test_named_range"; - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - wb1.createSheet(unicodeName); - - Name name1 = wb1.createName(); - name1.setNameName(rangeName); - name1.setRefersToFormula("'"+unicodeName+"'!A1:A6"); - - wb1.setSheetName(0, asciiName); - assertEquals(asciiName, name1.getSheetName()); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - Name name2 = wb2.getName(rangeName); - assertNotNull(name2); - // Eventually this will be updated, but currently we don't update the sheet name - assertEquals(asciiName, name2.getSheetName()); - } - } - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java deleted file mode 100644 index d79e594857..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java +++ /dev/null @@ -1,279 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.RenderingHints; -import java.awt.geom.Area; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import javax.imageio.ImageIO; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.ImageUtils; -import org.apache.poi.util.Units; -import org.junit.jupiter.api.Test; - -public abstract class BaseTestPicture { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestPicture(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - - protected abstract Picture getPictureShape(Drawing pat, int picIdx); - - @Test - void resize() throws IOException { - String fileName = "resize_compare.xls" + (getClass().getName().contains("xssf") ? "x" : ""); - double scaleX = 2; - double scaleY = 2; - - try (Workbook wb = _testDataProvider.openSampleWorkbook(fileName)) { - Sheet sh = wb.getSheetAt(0); - Drawing pat = sh.createDrawingPatriarch(); - - Picture input = getPictureShape(pat, 0); - Picture compare = getPictureShape(pat, 1); - - input.resize(scaleX, scaleY); - - ClientAnchor inpCA = input.getClientAnchor(); - ClientAnchor cmpCA = compare.getClientAnchor(); - - double origDy1 = inpCA.getDy1(); - double origDx1 = inpCA.getDx1(); - - Dimension inpDim = ImageUtils.getDimensionFromAnchor(input); - Dimension cmpDim = ImageUtils.getDimensionFromAnchor(compare); - - double emuPX = Units.EMU_PER_PIXEL; - - assertEquals(inpDim.getHeight(), cmpDim.getHeight(), emuPX * 6, "the image height differs"); - assertEquals(inpDim.getWidth(), cmpDim.getWidth(), emuPX * 6, "the image width differs"); - assertEquals(inpCA.getCol1(), cmpCA.getCol1(), "the starting column differs"); - assertEquals(inpCA.getDx1(), cmpCA.getDx1(), 1, "the column x-offset differs"); - assertEquals(inpCA.getDy1(), origDy1, 1, "the column y-offset differs - image has moved"); - assertEquals(inpCA.getDx1(), origDx1, 1, "the column x-offset differs - image has moved"); - assertEquals(inpCA.getDy1(), cmpCA.getDy1(), 1, "the column y-offset differs"); - assertEquals(inpCA.getCol2(), cmpCA.getCol2(), "the ending columns differs"); - // can't compare row heights because of variable test heights - - input.resize(); - inpDim = ImageUtils.getDimensionFromAnchor(input); - - Dimension imgDim = input.getImageDimension(); - - assertEquals(imgDim.getHeight(), inpDim.getHeight() / emuPX, 1, "the image height differs"); - assertEquals(imgDim.getWidth(), inpDim.getWidth() / emuPX, 1, "the image width differs"); - } - } - - - @Test - void testResizeNoColumns() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - Row row = sheet.createRow(0); - - handleResize(wb, sheet, row); - } - } - - @Test - void testResizeWithColumns() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - Row row = sheet.createRow(0); - row.createCell(0); - - handleResize(wb, sheet, row); - } - } - - - private void handleResize(Workbook wb, Sheet sheet, Row row) throws IOException { - Drawing drawing = sheet.createDrawingPatriarch(); - CreationHelper createHelper = wb.getCreationHelper(); - - final byte[] bytes = HSSFITestDataProvider.instance.getTestDataFileContent("logoKarmokar4.png"); - - row.setHeightInPoints(getImageSize(bytes).y); - - int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG); - - //add a picture shape - ClientAnchor anchor = createHelper.createClientAnchor(); - //set top-left corner of the picture, - //subsequent call of Picture#resize() will operate relative to it - anchor.setCol1(0); - anchor.setRow1(0); - - Picture pict = drawing.createPicture(anchor, pictureIdx); - - //auto-size picture relative to its top-left corner - pict.resize(); - } - - private static Point getImageSize( byte [] image) throws IOException { - BufferedImage img = ImageIO.read(new ByteArrayInputStream(image)); - - assertNotNull(img); - - return new Point(img.getWidth(), img.getHeight()); - } - - @Test - void bug64213() throws IOException { - int[] input = { - 200, 50 * 256, -1, - 400, 50 * 256, -1, - 200, 50 * 256, 200, - 400, 50 * 256, 200, - 400, 50 * 256, 400, - }; - - int[] expXSSF = { - 2, 952500, 2, 0, 2, 1905000, 7, 0, - 2, 952500, 2, 0, 2, 2857500, 12, 0, - 2, 952500, 2, 0, 2, 1905000, 2, 952500, - 2, 952500, 2, 0, 2, 2857500, 3, 0, - 2, 952500, 2, 0, 2, 2857500, 2, 1905000 - }; - - int[] expHSSF = { - 2, 292, 2, 0, 2, 584, 7, 226, - 2, 292, 2, 0, 2, 877, 13, 196, - 2, 292, 2, 0, 2, 584, 2, 128, - 2, 292, 2, 0, 2, 877, 3, 0, - 2, 292, 2, 0, 2, 877, 2, 128 - }; - - int[] expected = "xls".equals(_testDataProvider.getStandardFileNameExtension()) ? expHSSF : expXSSF; - - for (int i=0; i<5; i++) { - int[] inp = Arrays.copyOfRange(input, i*3, (i+1)*3); - int[] exp = Arrays.copyOfRange(expected, i*8, (i+1)*8); - int[] act = bug64213Helper(inp[0], inp[1], inp[2]); - assertArrayEquals(exp, act); - } - } - - private int[] bug64213Helper(int imgDim, int colWidth, int rowHeight) throws IOException { - final int col1 = 2; - final int dx1Pixel = 100; - final int row1 = 2; - final float scale = 0.5f; - - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("Sheet1"); - - final byte[] bytes = createTestImage(imgDim, imgDim); - int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG); - - sheet.setColumnWidth(col1, colWidth); - float col1px = sheet.getColumnWidthInPixels(col1); - if (rowHeight > -1) { - sheet.createRow(row1).setHeightInPoints((float) Units.pixelToPoints(rowHeight)); - } - - //create an anchor with upper left cell column/startRow, only one cell anchor since bottom right depends on resizing - CreationHelper helper = wb.getCreationHelper(); - ClientAnchor anchor = helper.createClientAnchor(); - anchor.setCol1(col1); - if (wb instanceof HSSFWorkbook) { - anchor.setDx1((int)(dx1Pixel * 1024 / col1px)); - } else { - anchor.setDx1(dx1Pixel * Units.EMU_PER_PIXEL); - } - anchor.setRow1(row1); - - - //create a picture anchored to Col1 and Row1 - Drawing drawing = sheet.createDrawingPatriarch(); - Picture pict = drawing.createPicture(anchor, pictureIdx); - - //resize the picture to it's native size - pict.resize(); - - //resize the picture scaled proportional - pict.resize(scale); - - ClientAnchor anc = (ClientAnchor)pict.getAnchor(); - return new int[]{ - anc.getCol1(), anc.getDx1(), - anc.getRow1(), anc.getDy1(), - anc.getCol2(), anc.getDx2(), - anc.getRow2(), anc.getDy2() - }; - } - } - - private static byte[] createTestImage(double width, double height) throws IOException { - BufferedImage bi = new BufferedImage((int)width, (int)height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = bi.createGraphics(); - - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - - g.scale((width-1)/width, (height-1)/height); - - g.setStroke(new BasicStroke(1)); - - double ellSize = 5/6d; - Ellipse2D ell = new Ellipse2D.Double(width * (1-ellSize)/2d, height * (1-ellSize)/2d, width * ellSize, height * ellSize); - Color[] colors = { Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW }; - Rectangle2D rect = new Rectangle2D.Double(); - for (int i=0; i<4; i++) { - rect.setRect(width/2 * (i&1),height/2 * (i>>1&1), width/2, height/2); - Area a = new Area(rect); - a.subtract(new Area(ell)); - g.setPaint(colors[i]); - g.fill(a); - g.setColor(java.awt.Color.BLACK); - g.draw(rect); - } - g.draw(ell); - - g.dispose(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(2000); - ImageIO.write(bi, "PNG", bos); - return bos.toByteArray(); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRangeCopier.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestRangeCopier.java deleted file mode 100644 index 6610623545..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRangeCopier.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -@Disabled -public abstract class BaseTestRangeCopier { - protected Sheet sheet1; - protected Sheet sheet2; - protected Workbook workbook; - protected RangeCopier rangeCopier; - protected RangeCopier transSheetRangeCopier; - protected ITestDataProvider testDataProvider; - - protected void initSheets() { - sheet1 = workbook.getSheet("sheet1"); - sheet2 = workbook.getSheet("sheet2"); - } - - @Test - void copySheetRangeWithoutFormulas() { - CellRangeAddress rangeToCopy = CellRangeAddress.valueOf("B1:C2"); //2x2 - CellRangeAddress destRange = CellRangeAddress.valueOf("C2:D3"); //2x2 - rangeCopier.copyRange(rangeToCopy, destRange); - assertEquals("1.1", sheet1.getRow(2).getCell(2).toString()); - assertEquals("2.1", sheet1.getRow(2).getCell(3).toString()); - } - - @Test - void tileTheRangeAway() { - CellRangeAddress tileRange = CellRangeAddress.valueOf("C4:D5"); - CellRangeAddress destRange = CellRangeAddress.valueOf("F4:K5"); - rangeCopier.copyRange(tileRange, destRange); - assertEquals("1.3", getCellContent(sheet1, "H4")); - assertEquals("1.3", getCellContent(sheet1, "J4")); - assertEquals("$C1+G$2", getCellContent(sheet1, "G5")); - assertEquals("SUM(G3:I3)", getCellContent(sheet1, "H5")); - assertEquals("$C1+I$2", getCellContent(sheet1, "I5")); - assertEquals("", getCellContent(sheet1, "L5")); //out of borders - assertEquals("", getCellContent(sheet1, "G7")); //out of borders - } - - @Test - void tileTheRangeOver() { - CellRangeAddress tileRange = CellRangeAddress.valueOf("C4:D5"); - CellRangeAddress destRange = CellRangeAddress.valueOf("A4:C5"); - rangeCopier.copyRange(tileRange, destRange); - assertEquals("1.3", getCellContent(sheet1, "A4")); - assertEquals("$C1+B$2", getCellContent(sheet1, "B5")); - assertEquals("SUM(B3:D3)", getCellContent(sheet1, "C5")); - } - - @Test - void copyRangeToOtherSheet() { - Sheet destSheet = sheet2; - CellRangeAddress tileRange = CellRangeAddress.valueOf("C4:D5"); // on sheet1 - CellRangeAddress destRange = CellRangeAddress.valueOf("F4:J6"); // on sheet2 - transSheetRangeCopier.copyRange(tileRange, destRange); - assertEquals("1.3", getCellContent(destSheet, "H4")); - assertEquals("1.3", getCellContent(destSheet, "J4")); - assertEquals("$C1+G$2", getCellContent(destSheet, "G5")); - assertEquals("SUM(G3:I3)", getCellContent(destSheet, "H5")); - assertEquals("$C1+I$2", getCellContent(destSheet, "I5")); - } - - @Test - void testEmptyRow() { - // leave some rows empty in-between - Row row = sheet1.createRow(23); - row.createCell(0).setCellValue(1.2); - - Sheet destSheet = sheet2; - CellRangeAddress tileRange = CellRangeAddress.valueOf("A1:A100"); // on sheet1 - CellRangeAddress destRange = CellRangeAddress.valueOf("G1:G100"); // on sheet2 - transSheetRangeCopier.copyRange(tileRange, destRange); - - assertEquals("1.2", getCellContent(destSheet, "G24")); - } - - @Test - void testSameSheet() { - // leave some rows empty in-between - Row row = sheet1.createRow(23); - row.createCell(0).setCellValue(1.2); - - CellRangeAddress tileRange = CellRangeAddress.valueOf("A1:A100"); // on sheet1 - CellRangeAddress destRange = CellRangeAddress.valueOf("G1:G100"); // on sheet2 - - // use the a RangeCopier with the same Sheet for source and dest - rangeCopier.copyRange(tileRange, destRange); - - assertEquals("1.2", getCellContent(sheet1, "G24")); - } - - @Test - void testCopyStyles() { - String cellContent = "D6 aligned to the right"; - HorizontalAlignment toTheRight = HorizontalAlignment.RIGHT; - // create cell with content aligned to the right - CellStyle style = workbook.createCellStyle(); - style.setAlignment(toTheRight); - Cell cell = sheet1.createRow(5).createCell(3); - cell.setCellValue(cellContent); - cell.setCellStyle(style); - - Sheet destSheet = sheet2; - CellRangeAddress tileRange = CellRangeAddress.valueOf("D6:D6"); // on sheet1 - CellRangeAddress destRange = CellRangeAddress.valueOf("J6:J6"); // on sheet2 - transSheetRangeCopier.copyRange(tileRange, destRange, true, false); - assertEquals(cellContent, getCellContent(destSheet, "J6")); - assertEquals(toTheRight, getCell(destSheet, "J6").getCellStyle().getAlignment()); - } - - @Test - void testMergedRanges() { - String cellContent = "D6 merged to E7"; - - // create cell merged from D6 to E7 - CellRangeAddress mergedRangeAddress = new CellRangeAddress(5,6,3,4); - Cell cell = sheet1.createRow(5).createCell(3); - cell.setCellValue(cellContent); - sheet1.addMergedRegion(mergedRangeAddress); - - Sheet destSheet = sheet2; - CellRangeAddress tileRange = CellRangeAddress.valueOf("D6:E7"); // on sheet1 - transSheetRangeCopier.copyRange(tileRange, tileRange, false, true); - assertEquals(cellContent, getCellContent(destSheet, "D6")); - assertFalse(destSheet.getMergedRegions().isEmpty()); - destSheet.getMergedRegions().forEach((mergedRegion) -> { - assertTrue(mergedRegion.equals(mergedRangeAddress)); - }); - } - - protected static String getCellContent(Sheet sheet, String coordinates) { - Cell cell = getCell(sheet, coordinates); - return cell == null ? "" : cell.toString(); - } - - protected static Cell getCell(Sheet sheet, String coordinates) { - try { - CellReference p = new CellReference(coordinates); - return sheet.getRow(p.getRow()).getCell(p.getCol()); - } - catch (NullPointerException e) { // row or cell does not exist - return null; - } - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java deleted file mode 100644 index c2205d240c..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java +++ /dev/null @@ -1,537 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.Iterator; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.junit.jupiter.api.Test; - -/** - * A base class for testing implementations of - * {@link org.apache.poi.ss.usermodel.Row} - */ -public abstract class BaseTestRow { - - protected final ITestDataProvider _testDataProvider; - - protected BaseTestRow(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - void testLastAndFirstColumns() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - Row row = sheet.createRow(0); - assertEquals(-1, row.getFirstCellNum()); - assertEquals(-1, row.getLastCellNum()); - - //getting cells from an empty row should returns null - for(int i=0; i < 10; i++) assertNull(row.getCell(i)); - - row.createCell(2); - assertEquals(2, row.getFirstCellNum()); - assertEquals(3, row.getLastCellNum()); - - row.createCell(1); - assertEquals(1, row.getFirstCellNum()); - assertEquals(3, row.getLastCellNum()); - - // check the exact case reported in 'bug' 43901 - notice that the cellNum is '0' based - row.createCell(3); - assertEquals(1, row.getFirstCellNum()); - assertEquals(4, row.getLastCellNum()); - workbook.close(); - } - - /** - * Make sure that there is no cross-talk between rows especially with getFirstCellNum and getLastCellNum - * This test was added in response to bug report 44987. - */ - @Test - void testBoundsInMultipleRows() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - Row rowA = sheet.createRow(0); - - rowA.createCell(10); - rowA.createCell(5); - assertEquals(5, rowA.getFirstCellNum()); - assertEquals(11, rowA.getLastCellNum()); - - Row rowB = sheet.createRow(1); - rowB.createCell(15); - rowB.createCell(30); - assertEquals(15, rowB.getFirstCellNum()); - assertEquals(31, rowB.getLastCellNum()); - - assertEquals(5, rowA.getFirstCellNum()); - assertEquals(11, rowA.getLastCellNum()); - rowA.createCell(50); - assertEquals(51, rowA.getLastCellNum()); - - assertEquals(31, rowB.getLastCellNum()); - workbook.close(); - } - - @Test - void testRemoveCell() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - { - Sheet sheet = wb1.createSheet(); - Row row = sheet.createRow(0); - - assertEquals(0, row.getPhysicalNumberOfCells()); - assertEquals(-1, row.getLastCellNum()); - assertEquals(-1, row.getFirstCellNum()); - - row.createCell(1); - assertEquals(2, row.getLastCellNum()); - assertEquals(1, row.getFirstCellNum()); - assertEquals(1, row.getPhysicalNumberOfCells()); - row.createCell(3); - assertEquals(4, row.getLastCellNum()); - assertEquals(1, row.getFirstCellNum()); - assertEquals(2, row.getPhysicalNumberOfCells()); - row.removeCell(row.getCell(3)); - assertEquals(2, row.getLastCellNum()); - assertEquals(1, row.getFirstCellNum()); - assertEquals(1, row.getPhysicalNumberOfCells()); - row.removeCell(row.getCell(1)); - assertEquals(-1, row.getLastCellNum()); - assertEquals(-1, row.getFirstCellNum()); - assertEquals(0, row.getPhysicalNumberOfCells()); - } - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - { - Sheet sheet = wb2.getSheetAt(0); - Row row = sheet.getRow(0); - assertEquals(-1, row.getLastCellNum()); - assertEquals(-1, row.getFirstCellNum()); - assertEquals(0, row.getPhysicalNumberOfCells()); - } - - wb2.close(); - } - - @Test - void testRowBounds() throws IOException { - int maxRowNum = _testDataProvider.getSpreadsheetVersion().getLastRowIndex(); - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - //Test low row bound - sheet.createRow(0); - //Test low row bound exception - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> sheet.createRow(-1)); - assertTrue(e.getMessage().startsWith("Invalid row number (-1)")); - - //Test high row bound - sheet.createRow(maxRowNum); - //Test high row bound exception - e = assertThrows(IllegalArgumentException.class, () -> sheet.createRow(maxRowNum + 1)); - assertEquals("Invalid row number (" + (maxRowNum + 1) + ") outside allowable range (0.." + maxRowNum + ")", e.getMessage()); - } - } - - @Test - protected void testCellBounds() throws IOException { - int maxCellNum = _testDataProvider.getSpreadsheetVersion().getLastColumnIndex(); - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet(); - - Row row1 = sheet.createRow(0); - //Test low cell bound - IllegalArgumentException e; - e = assertThrows(IllegalArgumentException.class, () -> row1.createCell(-1)); - assertTrue(e.getMessage().startsWith("Invalid column index (-1)")); - - //Test high cell bound - e = assertThrows(IllegalArgumentException.class, () -> row1.createCell(maxCellNum + 1)); - assertTrue(e.getMessage().startsWith("Invalid column index (" + (maxCellNum + 1) + ")")); - - for (int i = 0; i < maxCellNum; i++) { - row1.createCell(i); - } - assertEquals(maxCellNum, row1.getPhysicalNumberOfCells()); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - sheet = wb2.getSheetAt(0); - Row row2 = sheet.getRow(0); - assertEquals(maxCellNum, row2.getPhysicalNumberOfCells()); - for (int i = 0; i < maxCellNum; i++) { - Cell cell = row2.getCell(i); - assertEquals(i, cell.getColumnIndex()); - } - } - } - } - - /** - * Prior to patch 43901, POI was producing files with the wrong last-column - * number on the row - */ - @Test - void testLastCellNumIsCorrectAfterAddCell_bug43901() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("test"); - Row row = sheet.createRow(0); - - // New row has last col -1 - assertEquals(-1, row.getLastCellNum()); - assertNotEquals(0, row.getLastCellNum(), "Identified bug 43901"); - - // Create two cells, will return one higher - // than that for the last number - row.createCell(0); - assertEquals(1, row.getLastCellNum()); - row.createCell(255); - assertEquals(256, row.getLastCellNum()); - workbook.close(); - } - - /** - * Tests for the missing/blank cell policy stuff - */ - @Test - void testGetCellPolicy() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("test"); - Row row = sheet.createRow(0); - - // 0 -> string - // 1 -> num - // 2 missing - // 3 missing - // 4 -> blank - // 5 -> num - row.createCell(0).setCellValue("test"); - row.createCell(1).setCellValue(3.2); - row.createCell(4, CellType.BLANK); - row.createCell(5).setCellValue(4); - - // First up, no policy given, uses default - assertEquals(CellType.STRING, row.getCell(0).getCellType()); - assertEquals(CellType.NUMERIC, row.getCell(1).getCellType()); - assertNull(row.getCell(2)); - assertNull(row.getCell(3)); - assertEquals(CellType.BLANK, row.getCell(4).getCellType()); - assertEquals(CellType.NUMERIC, row.getCell(5).getCellType()); - - // RETURN_NULL_AND_BLANK - same as default - assertEquals(CellType.STRING, row.getCell(0, MissingCellPolicy.RETURN_NULL_AND_BLANK).getCellType()); - assertEquals(CellType.NUMERIC, row.getCell(1, MissingCellPolicy.RETURN_NULL_AND_BLANK).getCellType()); - assertNull(row.getCell(2, MissingCellPolicy.RETURN_NULL_AND_BLANK)); - assertNull(row.getCell(3, MissingCellPolicy.RETURN_NULL_AND_BLANK)); - assertEquals(CellType.BLANK, row.getCell(4, MissingCellPolicy.RETURN_NULL_AND_BLANK).getCellType()); - assertEquals(CellType.NUMERIC, row.getCell(5, MissingCellPolicy.RETURN_NULL_AND_BLANK).getCellType()); - - // RETURN_BLANK_AS_NULL - nearly the same - assertEquals(CellType.STRING, row.getCell(0, MissingCellPolicy.RETURN_BLANK_AS_NULL).getCellType()); - assertEquals(CellType.NUMERIC, row.getCell(1, MissingCellPolicy.RETURN_BLANK_AS_NULL).getCellType()); - assertNull(row.getCell(2, MissingCellPolicy.RETURN_BLANK_AS_NULL)); - assertNull(row.getCell(3, MissingCellPolicy.RETURN_BLANK_AS_NULL)); - assertNull(row.getCell(4, MissingCellPolicy.RETURN_BLANK_AS_NULL)); - assertEquals(CellType.NUMERIC, row.getCell(5, MissingCellPolicy.RETURN_BLANK_AS_NULL).getCellType()); - - // CREATE_NULL_AS_BLANK - creates as needed - assertEquals(CellType.STRING, row.getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellType()); - assertEquals(CellType.NUMERIC, row.getCell(1, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellType()); - assertEquals(CellType.BLANK, row.getCell(2, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellType()); - assertEquals(CellType.BLANK, row.getCell(3, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellType()); - assertEquals(CellType.BLANK, row.getCell(4, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellType()); - assertEquals(CellType.NUMERIC, row.getCell(5, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellType()); - - // Check created ones get the right column - assertEquals(0, row.getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - assertEquals(1, row.getCell(1, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - assertEquals(2, row.getCell(2, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - assertEquals(3, row.getCell(3, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - assertEquals(4, row.getCell(4, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - assertEquals(5, row.getCell(5, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - - - // Now change the cell policy on the workbook, check - // that that is now used if no policy given - workbook.setMissingCellPolicy(MissingCellPolicy.RETURN_BLANK_AS_NULL); - - assertEquals(CellType.STRING, row.getCell(0).getCellType()); - assertEquals(CellType.NUMERIC, row.getCell(1).getCellType()); - assertNull(row.getCell(2)); - assertNull(row.getCell(3)); - assertNull(row.getCell(4)); - assertEquals(CellType.NUMERIC, row.getCell(5).getCellType()); - - workbook.close(); - } - - @Test - protected void testRowHeight() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - Row row1 = sheet.createRow(0); - - assertEquals(sheet.getDefaultRowHeight(), row1.getHeight()); - - sheet.setDefaultRowHeightInPoints(20); - row1.setHeight((short)-1); //reset the row height - assertEquals(20.0f, row1.getHeightInPoints(), 0F); - assertEquals(20*20, row1.getHeight()); - - Row row2 = sheet.createRow(1); - assertEquals(sheet.getDefaultRowHeight(), row2.getHeight()); - row2.setHeight((short)310); - assertEquals(310, row2.getHeight()); - assertEquals(310F/20, row2.getHeightInPoints(), 0F); - - Row row3 = sheet.createRow(2); - row3.setHeightInPoints(25.5f); - assertEquals((short)(25.5f*20), row3.getHeight()); - assertEquals(25.5f, row3.getHeightInPoints(), 0F); - - Row row4 = sheet.createRow(3); - assertFalse(row4.getZeroHeight()); - row4.setZeroHeight(true); - assertTrue(row4.getZeroHeight()); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - row1 = sheet.getRow(0); - row2 = sheet.getRow(1); - row3 = sheet.getRow(2); - row4 = sheet.getRow(3); - assertEquals(20.0f, row1.getHeightInPoints(), 0F); - assertEquals(20*20, row1.getHeight()); - - assertEquals(310, row2.getHeight()); - assertEquals(310F/20, row2.getHeightInPoints(), 0F); - - assertEquals((short)(25.5f*20), row3.getHeight()); - assertEquals(25.5f, row3.getHeightInPoints(), 0F); - - assertFalse(row1.getZeroHeight()); - assertFalse(row2.getZeroHeight()); - assertFalse(row3.getZeroHeight()); - assertTrue(row4.getZeroHeight()); - wb2.close(); - } - - /** - * Test adding cells to a row in various places and see if we can find them again. - */ - @Test - void testCellIterator() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - // One cell at the beginning - Cell cell1 = row.createCell(1); - Iterator it = row.cellIterator(); - assertTrue(it.hasNext()); - assertSame(cell1, it.next()); - assertFalse(it.hasNext()); - - // Add another cell at the end - Cell cell2 = row.createCell(99); - it = row.cellIterator(); - assertTrue(it.hasNext()); - assertSame(cell1, it.next()); - assertTrue(it.hasNext()); - assertSame(cell2, it.next()); - - // Add another cell at the beginning - Cell cell3 = row.createCell(0); - it = row.cellIterator(); - assertTrue(it.hasNext()); - assertSame(cell3, it.next()); - assertTrue(it.hasNext()); - assertSame(cell1, it.next()); - assertTrue(it.hasNext()); - assertSame(cell2, it.next()); - - // Replace cell1 - Cell cell4 = row.createCell(1); - it = row.cellIterator(); - assertTrue(it.hasNext()); - assertSame(cell3, it.next()); - assertTrue(it.hasNext()); - assertSame(cell4, it.next()); - assertTrue(it.hasNext()); - assertSame(cell2, it.next()); - assertFalse(it.hasNext()); - - // Add another cell, specifying the cellType - Cell cell5 = row.createCell(2, CellType.STRING); - it = row.cellIterator(); - assertNotNull(cell5); - assertTrue(it.hasNext()); - assertSame(cell3, it.next()); - assertTrue(it.hasNext()); - assertSame(cell4, it.next()); - assertTrue(it.hasNext()); - assertSame(cell5, it.next()); - assertTrue(it.hasNext()); - assertSame(cell2, it.next()); - assertEquals(CellType.STRING, cell5.getCellType()); - wb.close(); - } - - @Test - void testRowStyle() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet("test"); - Row row1 = sheet.createRow(0); - Row row2 = sheet.createRow(1); - - // Won't be styled currently - assertFalse(row1.isFormatted()); - assertFalse(row2.isFormatted()); - assertNull(row1.getRowStyle()); - assertNull(row2.getRowStyle()); - - // Style one - CellStyle style = wb1.createCellStyle(); - style.setDataFormat((short)4); - row2.setRowStyle(style); - - // Check - assertFalse(row1.isFormatted()); - assertTrue(row2.isFormatted()); - assertNull(row1.getRowStyle()); - assertEquals(style, row2.getRowStyle()); - - // Save, load and re-check - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - - row1 = sheet.getRow(0); - row2 = sheet.getRow(1); - style = wb2.getCellStyleAt(style.getIndex()); - - assertFalse(row1.isFormatted()); - assertTrue(row2.isFormatted()); - assertNull(row1.getRowStyle()); - assertEquals(style, row2.getRowStyle()); - assertEquals(4, style.getDataFormat()); - - wb2.close(); - } - - @Test - protected void testCellShiftingRight() { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("sheet1"); - Row row = sheet.createRow(0); - row.createCell(0, CellType.NUMERIC).setCellValue(0); - row.createCell(1, CellType.NUMERIC).setCellValue(1); - row.createCell(2, CellType.NUMERIC).setCellValue(2);//C - row.createCell(3, CellType.NUMERIC).setCellValue(3);//D - row.createCell(4, CellType.NUMERIC).setCellValue(4);//E - row.createCell(5, CellType.NUMERIC).setCellValue(5);//F - row.createCell(6, CellType.NUMERIC).setCellValue(6);//G - - assertThrows(IllegalArgumentException.class, () -> row.shiftCellsLeft(6, 4, 2), "range [6-4] is illegal"); - row.shiftCellsRight(2, 4, 1); - //should be [0.0, 1.0, null, 2.0, 3.0, 4.0, 6.0, null] - - Cell h1 = row.getCell(7); - assertNull(h1); - Cell g1 = row.getCell(6); - assertEquals(6, g1.getNumericCellValue(), 0.01); - Cell f1 = row.getCell(5); - assertEquals(4, f1.getNumericCellValue(), 0.01); - Cell e1 = row.getCell(4); - assertEquals(3, e1.getNumericCellValue(), 0.01); - Cell d1 = row.getCell(3); - assertEquals(2, d1.getNumericCellValue(), 0.01); - Cell c1 = row.getCell(2); - assertNull(c1); - } - - @Test - protected void testCellShiftingLeft() { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("sheet1"); - Row row = sheet.createRow(0); - row.createCell(0, CellType.NUMERIC).setCellValue(0); - row.createCell(1, CellType.NUMERIC).setCellValue(1); - row.createCell(2, CellType.NUMERIC).setCellValue(2);//C - row.createCell(3, CellType.NUMERIC).setCellValue(3);//D - row.createCell(4, CellType.NUMERIC).setCellValue(4);//E - row.createCell(5, CellType.NUMERIC).setCellValue(5);//F - row.createCell(6, CellType.NUMERIC).setCellValue(6);//G - - assertThrows(IllegalArgumentException.class, () -> row.shiftCellsLeft(4, 6, -2), "step = -1 is illegal"); - row.shiftCellsLeft(4, 6, 2); - //should be [0.0, 1.0, 4.0, 5.0, 6.0, null, null, null] - - Cell b1 = row.getCell(1); - assertEquals(1, b1.getNumericCellValue(), 0.01); - Cell c1 = row.getCell(2); - assertEquals(4, c1.getNumericCellValue(), 0.01); - Cell d1 = row.getCell(3); - assertEquals(5, d1.getNumericCellValue(), 0.01); - Cell e1 = row.getCell(4); - assertEquals(6, e1.getNumericCellValue(), 0.01); - Cell f1 = row.getCell(5); - assertNull(f1); - } - - @Test - void testLastRowEmptySheet() { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("sheet1"); - - assertEquals(-1, sheet.getLastRowNum(), "Sheet without rows should return -1 as lastRowNum"); - Row row = sheet.createRow(0); - assertNotNull(row); - - assertEquals(0, sheet.getLastRowNum(), "Sheet with one row should return 0 as lastRowNum"); - } - - @Test - void testFirstRowEmptySheet() { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("sheet1"); - - assertEquals(-1, sheet.getFirstRowNum(), "Sheet without rows should return -1 as firstRowNum"); - Row row = sheet.createRow(0); - assertNotNull(row); - - assertEquals(0, sheet.getFirstRowNum(), "Sheet with one row should return 0 as firstRowNum"); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java deleted file mode 100644 index 947bd71a9f..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java +++ /dev/null @@ -1,1367 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.apache.poi.POITestCase.assertBetween; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.PaneInformation; -import org.junit.jupiter.api.Test; - -/** - * Common superclass for testing {@link org.apache.poi.hssf.usermodel.HSSFCell}, - * {@link org.apache.poi.xssf.usermodel.XSSFCell} and - * {@link org.apache.poi.xssf.streaming.SXSSFCell} - */ -public abstract class BaseTestSheet { - private static final int ROW_COUNT = 40000; - - protected final ITestDataProvider _testDataProvider; - - protected BaseTestSheet(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - protected void trackColumnsForAutoSizingIfSXSSF(Sheet sheet) { - // do nothing for Sheet base class. This will be overridden for SXSSFSheets. - } - - @Test - protected void createRow() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - assertEquals(0, sheet.getPhysicalNumberOfRows()); - - //Test that we get null for undefined rownumber - assertNull(sheet.getRow(1)); - - // Test row creation with consecutive indexes - Row row1 = sheet.createRow(0); - Row row2 = sheet.createRow(1); - assertEquals(0, row1.getRowNum()); - assertEquals(1, row2.getRowNum()); - Iterator it = sheet.rowIterator(); - assertTrue(it.hasNext()); - assertSame(row1, it.next()); - assertTrue(it.hasNext()); - assertSame(row2, it.next()); - assertEquals(1, sheet.getLastRowNum()); - - // Test row creation with non consecutive index - Row row101 = sheet.createRow(100); - assertNotNull(row101); - assertEquals(100, sheet.getLastRowNum()); - assertEquals(3, sheet.getPhysicalNumberOfRows()); - - // Test overwriting an existing row - Row row2_ovrewritten = sheet.createRow(1); - Cell cell = row2_ovrewritten.createCell(0); - cell.setCellValue(100); - Iterator it2 = sheet.rowIterator(); - assertTrue(it2.hasNext()); - assertSame(row1, it2.next()); - assertTrue(it2.hasNext()); - Row row2_ovrewritten_ref = it2.next(); - assertSame(row2_ovrewritten, row2_ovrewritten_ref); - assertEquals(100.0, row2_ovrewritten_ref.getCell(0).getNumericCellValue(), 0.0); - } - } - - @Test - void createRowBeforeFirstRow() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - final Sheet sh = workbook.createSheet(); - sh.createRow(0); - // Negative rows not allowed - assertThrows(IllegalArgumentException.class, () -> sh.createRow(-1)); - } - } - - @Test - void createRowAfterLastRow() throws IOException { - final SpreadsheetVersion version = _testDataProvider.getSpreadsheetVersion(); - try (Workbook workbook = _testDataProvider.createWorkbook()) { - final Sheet sh = workbook.createSheet(); - sh.createRow(version.getLastRowIndex()); - // Row number must be between 0 and last row - assertThrows(IllegalArgumentException.class, () -> sh.createRow(version.getLastRowIndex() + 1)); - } - } - - @Test - void removeRow() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet1 = workbook.createSheet(); - assertEquals(0, sheet1.getPhysicalNumberOfRows()); - assertEquals(-1, sheet1.getFirstRowNum()); - assertEquals(-1, sheet1.getLastRowNum()); - - Row row0 = sheet1.createRow(0); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - assertEquals(0, sheet1.getFirstRowNum()); - assertEquals(0, sheet1.getLastRowNum()); - sheet1.removeRow(row0); - assertEquals(0, sheet1.getPhysicalNumberOfRows()); - assertEquals(-1, sheet1.getFirstRowNum()); - assertEquals(-1, sheet1.getLastRowNum()); - - sheet1.createRow(1); - Row row2 = sheet1.createRow(2); - assertEquals(2, sheet1.getPhysicalNumberOfRows()); - assertEquals(1, sheet1.getFirstRowNum()); - assertEquals(2, sheet1.getLastRowNum()); - - assertNotNull(sheet1.getRow(1)); - assertNotNull(sheet1.getRow(2)); - sheet1.removeRow(row2); - assertNotNull(sheet1.getRow(1)); - assertNull(sheet1.getRow(2)); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - assertEquals(1, sheet1.getFirstRowNum()); - assertEquals(1, sheet1.getLastRowNum()); - - Row row3 = sheet1.createRow(3); - Sheet sheet2 = workbook.createSheet(); - - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> sheet2.removeRow(row3) - ); - assertEquals("Specified row does not belong to this sheet", ex.getMessage()); - } - } - - @Test - protected void cloneSheet() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - CreationHelper factory = workbook.getCreationHelper(); - Sheet sheet = workbook.createSheet("Test Clone"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - Cell cell2 = row.createCell(1); - cell.setCellValue(factory.createRichTextString("clone_test")); - cell2.setCellFormula("SIN(1)"); - - Sheet clonedSheet = workbook.cloneSheet(0); - Row clonedRow = clonedSheet.getRow(0); - - //Check for a good clone - assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test"); - - //Check that the cells are not somehow linked - cell.setCellValue(factory.createRichTextString("Difference Check")); - cell2.setCellFormula("cos(2)"); - - assertNotEquals("Difference Check", clonedRow.getCell(0).getRichStringCellValue().getString(), - "string cell not properly cloned"); - - assertNotEquals("COS(2)", clonedRow.getCell(1).getCellFormula(), "formula cell not properly cloned"); - - assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test"); - assertEquals(clonedRow.getCell(1).getCellFormula(), "SIN(1)"); - } - } - - /** tests that the sheet name for multiple clones of the same sheet is unique - * BUG 37416 - */ - @Test - protected void cloneSheetMultipleTimes() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - CreationHelper factory = workbook.getCreationHelper(); - Sheet sheet = workbook.createSheet("Test Clone"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(factory.createRichTextString("clone_test")); - //Clone the sheet multiple times - workbook.cloneSheet(0); - workbook.cloneSheet(0); - - assertNotNull(workbook.getSheet("Test Clone")); - assertNotNull(workbook.getSheet("Test Clone (2)")); - assertEquals("Test Clone (3)", workbook.getSheetName(2)); - assertNotNull(workbook.getSheet("Test Clone (3)")); - - workbook.removeSheetAt(0); - workbook.removeSheetAt(0); - workbook.removeSheetAt(0); - workbook.createSheet("abc ( 123)"); - workbook.cloneSheet(0); - assertEquals("abc (124)", workbook.getSheetName(1)); - } - } - - /** - * Setting landscape and portrait stuff on new sheets - */ - @Test - void printSetupLandscapeNew() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheetL = wb1.createSheet("LandscapeS"); - Sheet sheetP = wb1.createSheet("LandscapeP"); - - // Check two aspects of the print setup - assertFalse(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetP.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(1, 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(1, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetP.getPrintSetup().getCopies()); - - // Save and re-load, and check still there - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - sheetL = wb2.getSheet("LandscapeS"); - sheetP = wb2.getSheet("LandscapeP"); - - assertTrue(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetP.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetP.getPrintSetup().getCopies()); - } - } - } - - /** - * Disallow creating wholly or partially overlapping merged regions - * as this results in a corrupted workbook - */ - @Test - void addOverlappingMergedRegions() throws IOException { - try (final Workbook wb = _testDataProvider.createWorkbook()) { - final Sheet sheet = wb.createSheet(); - - final CellRangeAddress baseRegion = new CellRangeAddress(0, 1, 0, 1); //A1:B2 - assertEquals(0, sheet.addMergedRegion(baseRegion)); - - final CellRangeAddress duplicateRegion = new CellRangeAddress(0, 1, 0, 1); //A1:B2 - assertThrows( - IllegalStateException.class, - () -> sheet.addMergedRegion(duplicateRegion), - "Should not be able to add a merged region (" + duplicateRegion.formatAsString() + ") " + - "if sheet already contains the same merged region (" + baseRegion.formatAsString() + ")" - ); - - final CellRangeAddress partiallyOverlappingRegion = new CellRangeAddress(1, 2, 1, 2); //B2:C3 - assertThrows( - IllegalStateException.class, - () -> sheet.addMergedRegion(partiallyOverlappingRegion), - "Should not be able to add a merged region (" + partiallyOverlappingRegion.formatAsString() + ") " + - "if it partially overlaps with an existing merged region (" + baseRegion.formatAsString() + ")" - ); - - final CellRangeAddress subsetRegion = new CellRangeAddress(0, 1, 0, 0); //A1:A2 - assertThrows( - IllegalStateException.class, - () -> sheet.addMergedRegion(subsetRegion), - "Should not be able to add a merged region (" + subsetRegion.formatAsString() + ") " + - "if it is a formal subset of an existing merged region (" + baseRegion.formatAsString() + ")" - ); - - final CellRangeAddress supersetRegion = new CellRangeAddress(0, 2, 0, 2); //A1:C3 - assertThrows( - IllegalStateException.class, - () -> sheet.addMergedRegion(supersetRegion), - "Should not be able to add a merged region (" + supersetRegion.formatAsString() + ") " + - "if it is a formal superset of an existing merged region (" + baseRegion.formatAsString() + ")" - ); - - final CellRangeAddress disjointRegion = new CellRangeAddress(10, 11, 10, 11); - assertEquals(1, sheet.addMergedRegion(disjointRegion)); - } - } - - /* - * Bug 56345: Reject single-cell merged regions - */ - @Test - void addMergedRegionWithSingleCellShouldFail() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - - final Sheet sheet = wb.createSheet(); - final CellRangeAddress region = CellRangeAddress.valueOf("A1:A1"); - assertThrows( - IllegalArgumentException.class, - () -> sheet.addMergedRegion(region), - "Should not be able to add a single-cell merged region (" + region.formatAsString() + ")" - ); - } - } - - /** - * Test adding merged regions. If the region's bounds are outside of the allowed range - * then an IllegalArgumentException should be thrown - * - */ - @Test - void addMerged() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - assertEquals(0, sheet.getNumMergedRegions()); - SpreadsheetVersion ssVersion = _testDataProvider.getSpreadsheetVersion(); - - CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); - assertEquals(0, sheet.addMergedRegion(region)); - assertEquals(1, sheet.getNumMergedRegions()); - - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> sheet.addMergedRegion(new CellRangeAddress(-1, -1, -1, -1)) - ); - assertEquals("Merged region : must contain 2 or more cells", ex.getMessage()); - - ex = assertThrows( - IllegalArgumentException.class, - () -> sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, ssVersion.getLastColumnIndex() + 1)) - ); - assertEquals("Maximum column number is " + ssVersion.getLastColumnIndex(), ex.getMessage()); - - ex = assertThrows( - IllegalArgumentException.class, - () -> sheet.addMergedRegion(new CellRangeAddress(0, ssVersion.getLastRowIndex() + 1, 0, 1)) - ); - assertEquals("Maximum row number is " + ssVersion.getLastRowIndex(), ex.getMessage()); - - assertEquals(1, sheet.getNumMergedRegions()); - } - } - - /** - * When removing one merged region, it would break - * - */ - @Test - void removeMerged() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); - assertEquals(0, sheet.addMergedRegion(region)); - region = new CellRangeAddress(2, 3, 0, 1); - assertEquals(1, sheet.addMergedRegion(region)); - - sheet.removeMergedRegion(0); - - region = sheet.getMergedRegion(0); - assertEquals(2, region.getFirstRow(), "Left over region should be starting at row 2"); - - sheet.removeMergedRegion(0); - - assertEquals(0, sheet.getNumMergedRegions(), "there should be no merged regions left!"); - - //an, add, remove, get(0) would null pointer - assertEquals(0, sheet.addMergedRegion(region)); - assertEquals(1, sheet.getNumMergedRegions(), "there should now be one merged region!"); - sheet.removeMergedRegion(0); - assertEquals(0, sheet.getNumMergedRegions(), "there should now be zero merged regions!"); - //add it again! - region.setLastRow(4); - - assertEquals(0, sheet.addMergedRegion(region)); - assertEquals(1, sheet.getNumMergedRegions(), "there should now be one merged region!"); - - //should exist now! - assertTrue(1 <= sheet.getNumMergedRegions(), "there isn't more than one merged region in there"); - region = sheet.getMergedRegion(0); - assertEquals(4, region.getLastRow(), "the merged row to doesn't match the one we put in "); - } - } - - /** - * Remove multiple merged regions - */ - @Test - void removeMergedRegions() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - Map mergedRegions = new HashMap<>(); - for (int r = 0; r < 10; r++) { - CellRangeAddress region = new CellRangeAddress(r, r, 0, 1); - mergedRegions.put(r, region); - assertEquals(r, sheet.addMergedRegion(region)); - } - assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions()); - - Collection removed = Arrays.asList(0, 2, 3, 6, 8); - mergedRegions.keySet().removeAll(removed); - sheet.removeMergedRegions(removed); - assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions()); - } - } - - private static void assertCollectionEquals(Collection expected, Collection actual) { - Set e = new HashSet<>(expected); - Set a = new HashSet<>(actual); - assertEquals(e, a); - } - - @Test - protected void shiftMerged() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - CreationHelper factory = wb.getCreationHelper(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(factory.createRichTextString("first row, first cell")); - - row = sheet.createRow(1); - cell = row.createCell(1); - cell.setCellValue(factory.createRichTextString("second row, second cell")); - - CellRangeAddress region = CellRangeAddress.valueOf("A2:B2"); - assertEquals(0, sheet.addMergedRegion(region)); - - sheet.shiftRows(1, 1, 1); - - region = sheet.getMergedRegion(0); - - CellRangeAddress expectedRegion = CellRangeAddress.valueOf("A3:B3"); - assertEquals(expectedRegion, region, "Merged region should shift down a row"); - } - } - - /** - * bug 58885: checking for overlapping merged regions when - * adding a merged region is safe, but runs in O(n). - * the check for merged regions when adding a merged region - * can be skipped (unsafe) and run in O(1). - */ - @Test - void addMergedRegionUnsafe() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sh = wb.createSheet(); - CellRangeAddress region1 = CellRangeAddress.valueOf("A1:B2"); - CellRangeAddress region2 = CellRangeAddress.valueOf("B2:C3"); - CellRangeAddress region3 = CellRangeAddress.valueOf("C3:D4"); - CellRangeAddress region4 = CellRangeAddress.valueOf("J10:K11"); - assumeTrue(region1.intersects(region2)); - assumeTrue(region2.intersects(region3)); - - assertEquals(0, sh.addMergedRegionUnsafe(region1)); - assertTrue(sh.getMergedRegions().contains(region1)); - - // adding a duplicate or overlapping merged region should not - // raise an exception with the unsafe version of addMergedRegion. - - assertEquals(1, sh.addMergedRegionUnsafe(region2)); - - // the safe version of addMergedRegion should throw when trying to add a merged region that overlaps an existing region - assertTrue(sh.getMergedRegions().contains(region2)); - assertThrows( - IllegalStateException.class, - () -> sh.addMergedRegion(region3), - "region3 overlaps already added merged region2." - ); - assertFalse(sh.getMergedRegions().contains(region3)); - - // addMergedRegion should not re-validate previously-added merged regions - assertEquals(2, sh.addMergedRegion(region4)); - - // validation methods should detect a problem with previously added merged regions (runs in O(n^2) time) - assertThrows( - IllegalStateException.class, - sh::validateMergedRegions, - "Sheet contains merged regions A1:B2 and B2:C3, which overlap at B2." - ); - } - } - - /** - * Tests the display of gridlines, formulas, and rowcolheadings. - */ - @Test - void displayOptions() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet(); - - assertTrue(sheet.isDisplayGridlines()); - assertTrue(sheet.isDisplayRowColHeadings()); - assertFalse(sheet.isDisplayFormulas()); - assertTrue(sheet.isDisplayZeros()); - - sheet.setDisplayGridlines(false); - sheet.setDisplayRowColHeadings(false); - sheet.setDisplayFormulas(true); - sheet.setDisplayZeros(false); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - sheet = wb2.getSheetAt(0); - - assertFalse(sheet.isDisplayGridlines()); - assertFalse(sheet.isDisplayRowColHeadings()); - assertTrue(sheet.isDisplayFormulas()); - assertFalse(sheet.isDisplayZeros()); - } - } - } - - @Test - void columnWidth() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet1 = wb1.createSheet(); - - //default column width measured in characters - sheet1.setDefaultColumnWidth(10); - assertEquals(10, sheet1.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256 * 10, sheet1.getColumnWidth(0)); - assertEquals(256 * 10, sheet1.getColumnWidth(1)); - assertEquals(256 * 10, sheet1.getColumnWidth(2)); - - //set custom width for D-F - for (char i = 'D'; i <= 'F'; i++) { - //Sheet#setColumnWidth accepts the width in units of 1/256th of a character width - int w = 256 * 12; - sheet1.setColumnWidth(i, w); - assertEquals(w, sheet1.getColumnWidth(i)); - } - //reset the default column width, columns A-C change, D-F still have custom width - sheet1.setDefaultColumnWidth(20); - assertEquals(20, sheet1.getDefaultColumnWidth()); - assertEquals(256 * 20, sheet1.getColumnWidth(0)); - assertEquals(256 * 20, sheet1.getColumnWidth(1)); - assertEquals(256 * 20, sheet1.getColumnWidth(2)); - for (char i = 'D'; i <= 'F'; i++) { - int w = 256 * 12; - assertEquals(w, sheet1.getColumnWidth(i)); - } - - // check for 16-bit signed/unsigned error: - sheet1.setColumnWidth(10, 40000); - assertEquals(40000, sheet1.getColumnWidth(10)); - - //The maximum column width for an individual cell is 255 characters - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> sheet1.setColumnWidth(9, 256 * 256) - ); - assertEquals("The maximum column width for an individual cell is 255 characters.", ex.getMessage()); - - //serialize and read again - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - Sheet sheet2 = wb2.getSheetAt(0); - assertEquals(20, sheet2.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256 * 20, sheet2.getColumnWidth(0)); - assertEquals(256 * 20, sheet2.getColumnWidth(1)); - assertEquals(256 * 20, sheet2.getColumnWidth(2)); - //columns D-F have custom width - for (char i = 'D'; i <= 'F'; i++) { - short w = (256 * 12); - assertEquals(w, sheet2.getColumnWidth(i)); - } - assertEquals(40000, sheet2.getColumnWidth(10)); - } - } - } - - - @Test - void defaultRowHeight() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - sheet.setDefaultRowHeightInPoints(15); - assertEquals((short) 300, sheet.getDefaultRowHeight()); - assertEquals(15.0F, sheet.getDefaultRowHeightInPoints(), 0F); - - Row row = sheet.createRow(1); - // new row inherits default height from the sheet - assertEquals(sheet.getDefaultRowHeight(), row.getHeight()); - - // Set a new default row height in twips and test getting the value in points - sheet.setDefaultRowHeight((short) 360); - assertEquals(18.0f, sheet.getDefaultRowHeightInPoints(), 0F); - assertEquals((short) 360, sheet.getDefaultRowHeight()); - - // Test that defaultRowHeight is a truncated short: E.G. 360inPoints -> 18; 361inPoints -> 18 - sheet.setDefaultRowHeight((short) 361); - assertEquals((float) 361 / 20, sheet.getDefaultRowHeightInPoints(), 0F); - assertEquals((short) 361, sheet.getDefaultRowHeight()); - - // Set a new default row height in points and test getting the value in twips - sheet.setDefaultRowHeightInPoints(17.5f); - assertEquals(17.5f, sheet.getDefaultRowHeightInPoints(), 0F); - assertEquals((short) (17.5f * 20), sheet.getDefaultRowHeight()); - } - } - - /** cell with formula becomes null on cloning a sheet*/ - @Test - protected void bug35084() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet("Sheet1"); - Row r = s.createRow(0); - r.createCell(0).setCellValue(1); - r.createCell(1).setCellFormula("A1*2"); - Sheet s1 = wb.cloneSheet(0); - r = s1.getRow(0); - // sanity check - assertEquals(r.getCell(0).getNumericCellValue(), 1, 0, "double"); - assertNotNull(r.getCell(1)); - assertEquals(r.getCell(1).getCellFormula(), "A1*2", "formula"); - } - } - - /** test that new default column styles get applied */ - @Test - protected void defaultColumnStyle() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - CellStyle style = wb.createCellStyle(); - Sheet sheet = wb.createSheet(); - sheet.setDefaultColumnStyle(0, style); - assertNotNull(sheet.getColumnStyle(0)); - assertEquals(style.getIndex(), sheet.getColumnStyle(0).getIndex()); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - CellStyle style2 = cell.getCellStyle(); - assertNotNull(style2); - assertEquals(style.getIndex(), style2.getIndex(), "style should match"); - } - } - - @Test - void outlineProperties() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet(); - - //TODO defaults are different in HSSF and XSSF - //assertTrue(sheet.getRowSumsBelow()); - //assertTrue(sheet.getRowSumsRight()); - - sheet.setRowSumsBelow(false); - sheet.setRowSumsRight(false); - - assertFalse(sheet.getRowSumsBelow()); - assertFalse(sheet.getRowSumsRight()); - - sheet.setRowSumsBelow(true); - sheet.setRowSumsRight(true); - - assertTrue(sheet.getRowSumsBelow()); - assertTrue(sheet.getRowSumsRight()); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - sheet = wb2.getSheetAt(0); - assertTrue(sheet.getRowSumsBelow()); - assertTrue(sheet.getRowSumsRight()); - } - } - } - - /** - * Test basic display and print properties - */ - @Test - void sheetProperties() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - assertFalse(sheet.getHorizontallyCenter()); - sheet.setHorizontallyCenter(true); - assertTrue(sheet.getHorizontallyCenter()); - sheet.setHorizontallyCenter(false); - assertFalse(sheet.getHorizontallyCenter()); - - assertFalse(sheet.getVerticallyCenter()); - sheet.setVerticallyCenter(true); - assertTrue(sheet.getVerticallyCenter()); - sheet.setVerticallyCenter(false); - assertFalse(sheet.getVerticallyCenter()); - - assertFalse(sheet.isPrintGridlines()); - sheet.setPrintGridlines(true); - assertTrue(sheet.isPrintGridlines()); - - assertFalse(sheet.isPrintRowAndColumnHeadings()); - sheet.setPrintRowAndColumnHeadings(true); - assertTrue(sheet.isPrintRowAndColumnHeadings()); - - assertFalse(sheet.isDisplayFormulas()); - sheet.setDisplayFormulas(true); - assertTrue(sheet.isDisplayFormulas()); - - assertTrue(sheet.isDisplayGridlines()); - sheet.setDisplayGridlines(false); - assertFalse(sheet.isDisplayGridlines()); - - //TODO: default "guts" is different in HSSF and XSSF - //assertTrue(sheet.getDisplayGuts()); - sheet.setDisplayGuts(false); - assertFalse(sheet.getDisplayGuts()); - - assertTrue(sheet.isDisplayRowColHeadings()); - sheet.setDisplayRowColHeadings(false); - assertFalse(sheet.isDisplayRowColHeadings()); - - //TODO: default "autobreaks" is different in HSSF and XSSF - //assertTrue(sheet.getAutobreaks()); - sheet.setAutobreaks(false); - assertFalse(sheet.getAutobreaks()); - - assertFalse(sheet.getScenarioProtect()); - - //TODO: default "fit-to-page" is different in HSSF and XSSF - //assertFalse(sheet.getFitToPage()); - sheet.setFitToPage(true); - assertTrue(sheet.getFitToPage()); - sheet.setFitToPage(false); - assertFalse(sheet.getFitToPage()); - } - } - - @Test - void testGetSetMargin() throws IOException { - double[] defaultMargins = (getClass().getName().contains("xssf")) - ? new double[]{0.7, 0.7, 0.75, 0.75, 0.3, 0.3} - : new double[]{0.75, 0.75, 1.0, 1.0, 0.3, 0.3}; - - double marginLeft = defaultMargins[0]; - double marginRight = defaultMargins[1]; - double marginTop = defaultMargins[2]; - double marginBottom = defaultMargins[3]; - //double marginHeader = defaultMargins[4]; - //double marginFooter = defaultMargins[5]; - - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet("Sheet 1"); - assertEquals(marginLeft, sheet.getMargin(Sheet.LeftMargin), 0.0); - sheet.setMargin(Sheet.LeftMargin, 10.0); - //left margin is custom, all others are default - assertEquals(10.0, sheet.getMargin(Sheet.LeftMargin), 0.0); - assertEquals(marginRight, sheet.getMargin(Sheet.RightMargin), 0.0); - assertEquals(marginTop, sheet.getMargin(Sheet.TopMargin), 0.0); - assertEquals(marginBottom, sheet.getMargin(Sheet.BottomMargin), 0.0); - sheet.setMargin(Sheet.RightMargin, 11.0); - assertEquals(11.0, sheet.getMargin(Sheet.RightMargin), 0.0); - sheet.setMargin(Sheet.TopMargin, 12.0); - assertEquals(12.0, sheet.getMargin(Sheet.TopMargin), 0.0); - sheet.setMargin(Sheet.BottomMargin, 13.0); - assertEquals(13.0, sheet.getMargin(Sheet.BottomMargin), 0.0); - - sheet.setMargin(Sheet.FooterMargin, 5.6); - assertEquals(5.6, sheet.getMargin(Sheet.FooterMargin), 0.0); - sheet.setMargin(Sheet.HeaderMargin, 11.5); - assertEquals(11.5, sheet.getMargin(Sheet.HeaderMargin), 0.0); - - // incorrect margin constant - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> sheet.setMargin((short) 65, 15) - ); - assertEquals("Unknown margin constant: 65", ex.getMessage()); - } - } - - @Test - void rowBreaks() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - //Sheet#getRowBreaks() returns an empty array if no row breaks are defined - assertNotNull(sheet.getRowBreaks()); - assertEquals(0, sheet.getRowBreaks().length); - - sheet.setRowBreak(1); - assertEquals(1, sheet.getRowBreaks().length); - sheet.setRowBreak(15); - assertEquals(2, sheet.getRowBreaks().length); - assertEquals(1, sheet.getRowBreaks()[0]); - assertEquals(15, sheet.getRowBreaks()[1]); - sheet.setRowBreak(1); - assertEquals(2, sheet.getRowBreaks().length); - assertTrue(sheet.isRowBroken(1)); - assertTrue(sheet.isRowBroken(15)); - - //now remove the created breaks - sheet.removeRowBreak(1); - assertEquals(1, sheet.getRowBreaks().length); - sheet.removeRowBreak(15); - assertEquals(0, sheet.getRowBreaks().length); - - assertFalse(sheet.isRowBroken(1)); - assertFalse(sheet.isRowBroken(15)); - } - } - - @Test - void columnBreaks() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - assertNotNull(sheet.getColumnBreaks()); - assertEquals(0, sheet.getColumnBreaks().length); - - assertFalse(sheet.isColumnBroken(0)); - - sheet.setColumnBreak(11); - assertNotNull(sheet.getColumnBreaks()); - assertEquals(11, sheet.getColumnBreaks()[0]); - sheet.setColumnBreak(12); - assertEquals(2, sheet.getColumnBreaks().length); - assertTrue(sheet.isColumnBroken(11)); - assertTrue(sheet.isColumnBroken(12)); - - sheet.removeColumnBreak((short) 11); - assertEquals(1, sheet.getColumnBreaks().length); - sheet.removeColumnBreak((short) 15); //remove non-existing - assertEquals(1, sheet.getColumnBreaks().length); - sheet.removeColumnBreak((short) 12); - assertEquals(0, sheet.getColumnBreaks().length); - - assertFalse(sheet.isColumnBroken(11)); - assertFalse(sheet.isColumnBroken(12)); - } - } - - @Test - void getFirstLastRowNum() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet("Sheet 1"); - sheet.createRow(9); - sheet.createRow(0); - sheet.createRow(1); - assertEquals(0, sheet.getFirstRowNum()); - assertEquals(9, sheet.getLastRowNum()); - } - } - - @Test - void getFooter() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet("Sheet 1"); - assertNotNull(sheet.getFooter()); - sheet.getFooter().setCenter("test center footer"); - assertEquals("test center footer", sheet.getFooter().getCenter()); - } - } - - @Test - void getSetColumnHidden() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet("Sheet 1"); - sheet.setColumnHidden(2, true); - assertTrue(sheet.isColumnHidden(2)); - } - } - - @Test - void protectSheet() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - assertFalse(sheet.getProtect()); - sheet.protectSheet("Test"); - assertTrue(sheet.getProtect()); - sheet.protectSheet(null); - assertFalse(sheet.getProtect()); - } - } - - @Test - void createFreezePane() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - // create a workbook - Sheet sheet = wb.createSheet(); - assertNull(sheet.getPaneInformation()); - sheet.createFreezePane(0, 0); - // still null - assertNull(sheet.getPaneInformation()); - - sheet.createFreezePane(2, 3); - - PaneInformation info = sheet.getPaneInformation(); - - - assertEquals(PaneInformation.PANE_LOWER_RIGHT, info.getActivePane()); - assertEquals(3, info.getHorizontalSplitPosition()); - assertEquals(3, info.getHorizontalSplitTopRow()); - assertEquals(2, info.getVerticalSplitLeftColumn()); - assertEquals(2, info.getVerticalSplitPosition()); - - sheet.createFreezePane(0, 0); - // If both colSplit and rowSplit are zero then the existing freeze pane is removed - assertNull(sheet.getPaneInformation()); - - sheet.createFreezePane(0, 3); - - info = sheet.getPaneInformation(); - - assertEquals(PaneInformation.PANE_LOWER_LEFT, info.getActivePane()); - assertEquals(3, info.getHorizontalSplitPosition()); - assertEquals(3, info.getHorizontalSplitTopRow()); - assertEquals(0, info.getVerticalSplitLeftColumn()); - assertEquals(0, info.getVerticalSplitPosition()); - - sheet.createFreezePane(3, 0); - - info = sheet.getPaneInformation(); - - assertEquals(PaneInformation.PANE_UPPER_RIGHT, info.getActivePane()); - assertEquals(0, info.getHorizontalSplitPosition()); - assertEquals(0, info.getHorizontalSplitTopRow()); - assertEquals(3, info.getVerticalSplitLeftColumn()); - assertEquals(3, info.getVerticalSplitPosition()); - - sheet.createFreezePane(0, 0); - // If both colSplit and rowSplit are zero then the existing freeze pane is removed - assertNull(sheet.getPaneInformation()); - } - } - - - @Test - void getRepeatingRowsAndColumns() throws IOException { - try (Workbook wb = _testDataProvider.openSampleWorkbook( - "RepeatingRowsCols." - + _testDataProvider.getStandardFileNameExtension())) { - - checkRepeatingRowsAndColumns(wb.getSheetAt(0), null, null); - checkRepeatingRowsAndColumns(wb.getSheetAt(1), "1:1", null); - checkRepeatingRowsAndColumns(wb.getSheetAt(2), null, "A:A"); - checkRepeatingRowsAndColumns(wb.getSheetAt(3), "2:3", "A:B"); - } - } - - - @Test - void setRepeatingRowsAndColumnsBug47294() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet1 = wb.createSheet(); - sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - assertEquals("1:4", sheet1.getRepeatingRows().formatAsString()); - - //must handle sheets with quotas, see Bugzilla #47294 - Sheet sheet2 = wb.createSheet("My' Sheet"); - sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - assertEquals("1:4", sheet2.getRepeatingRows().formatAsString()); - } - } - - @Test - void setRepeatingRowsAndColumns() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet1 = wb1.createSheet("Sheet1"); - Sheet sheet2 = wb1.createSheet("Sheet2"); - Sheet sheet3 = wb1.createSheet("Sheet3"); - - checkRepeatingRowsAndColumns(sheet1, null, null); - - sheet1.setRepeatingRows(CellRangeAddress.valueOf("4:5")); - sheet2.setRepeatingColumns(CellRangeAddress.valueOf("A:C")); - sheet3.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - sheet3.setRepeatingColumns(CellRangeAddress.valueOf("A:A")); - - checkRepeatingRowsAndColumns(sheet1, "4:5", null); - checkRepeatingRowsAndColumns(sheet2, null, "A:C"); - checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); - - // write out, read back, and test refrain... - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - sheet1 = wb2.getSheetAt(0); - sheet2 = wb2.getSheetAt(1); - sheet3 = wb2.getSheetAt(2); - - checkRepeatingRowsAndColumns(sheet1, "4:5", null); - checkRepeatingRowsAndColumns(sheet2, null, "A:C"); - checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); - - // check removing repeating rows and columns - sheet3.setRepeatingRows(null); - checkRepeatingRowsAndColumns(sheet3, null, "A:A"); - - sheet3.setRepeatingColumns(null); - checkRepeatingRowsAndColumns(sheet3, null, null); - } - } - } - - private void checkRepeatingRowsAndColumns( - Sheet s, String expectedRows, String expectedCols) { - if (expectedRows == null) { - assertNull(s.getRepeatingRows()); - } else { - assertEquals(expectedRows, s.getRepeatingRows().formatAsString()); - } - if (expectedCols == null) { - assertNull(s.getRepeatingColumns()); - } else { - assertEquals(expectedCols, s.getRepeatingColumns().formatAsString()); - } - } - - @Test - void baseZoom() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - // here we can only verify that setting some zoom values works, - // range-checking is different between the implementations - assertDoesNotThrow(() -> sheet.setZoom(75)); - } - } - - @Test - void baseShowInPane() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - sheet.showInPane(2, 3); - if (wb instanceof HSSFWorkbook) { - assertEquals(2, sheet.getTopRow()); - assertEquals(3, sheet.getLeftCol()); - } - } - } - - @Test - void bug55723() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - CellRangeAddress range = CellRangeAddress.valueOf("A:B"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - // there seems to be currently no generic way to check the setting... - - range = CellRangeAddress.valueOf("B:C"); - filter = sheet.setAutoFilter(range); - assertNotNull(filter); - // there seems to be currently no generic way to check the setting... - } - } - - @Test - void bug55723_Rows() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - CellRangeAddress range = CellRangeAddress.valueOf("A4:B55000"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - } - } - - @Test - void bug55723d_RowsOver65k() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - CellRangeAddress range = CellRangeAddress.valueOf("A4:B75000"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - } - } - - /** - * XSSFSheet autoSizeColumn() on empty RichTextString fails - */ - @Test - void bug48325() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("Test"); - trackColumnsForAutoSizingIfSXSSF(sheet); - CreationHelper factory = wb.getCreationHelper(); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - Font font = wb.createFont(); - RichTextString rts = factory.createRichTextString(""); - rts.applyFont(font); - cell.setCellValue(rts); - - sheet.autoSizeColumn(0); - - assertNotNull(_testDataProvider.writeOutAndReadBack(wb)); - } - } - - @Test - protected void getCellComment() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - Drawing dg = sheet.createDrawingPatriarch(); - Comment comment = dg.createCellComment(workbook.getCreationHelper().createClientAnchor()); - Cell cell = sheet.createRow(9).createCell(2); - comment.setAuthor("test C10 author"); - cell.setCellComment(comment); - - CellAddress ref = new CellAddress(9, 2); - assertNotNull(sheet.getCellComment(ref)); - assertEquals("test C10 author", sheet.getCellComment(ref).getAuthor()); - - assertNotNull(_testDataProvider.writeOutAndReadBack(workbook)); - } - } - - @Test - void getCellComments() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet("TEST"); - - // a sheet with no cell comments should return an empty map (not null or raise NPE). - assertTrue(sheet.getCellComments().isEmpty()); - - Drawing dg = sheet.createDrawingPatriarch(); - ClientAnchor anchor = wb1.getCreationHelper().createClientAnchor(); - - int nRows = 5; - int nCols = 6; - - for (int r = 0; r < nRows; r++) { - sheet.createRow(r); - // Create columns in reverse order - for (int c = nCols - 1; c >= 0; c--) { - // When the comment box is visible, have it show in a 1x3 space - anchor.setCol1(c); - anchor.setCol2(c); - anchor.setRow1(r); - anchor.setRow2(r); - - // Create the comment and set the text-author - Comment comment = dg.createCellComment(anchor); - Cell cell = sheet.getRow(r).createCell(c); - comment.setAuthor("Author " + r); - RichTextString text = wb1.getCreationHelper().createRichTextString("Test comment at row=" + r + ", column=" + c); - comment.setString(text); - - // Assign the comment to the cell - cell.setCellComment(comment); - } - } - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - Sheet sh = wb2.getSheet("TEST"); - Map cellComments = sh.getCellComments(); - assertEquals(nRows * nCols, cellComments.size()); - - for (Entry e : cellComments.entrySet()) { - CellAddress ref = e.getKey(); - Comment aComment = e.getValue(); - assertEquals("Author " + ref.getRow(), aComment.getAuthor()); - String text = "Test comment at row=" + ref.getRow() + ", column=" + ref.getColumn(); - assertEquals(text, aComment.getString().getString()); - } - } - } - } - - @Test - void getHyperlink() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL); - hyperlink.setAddress("https://poi.apache.org/"); - - Sheet sheet = workbook.createSheet(); - Cell cell = sheet.createRow(5).createCell(1); - - assertEquals(0, sheet.getHyperlinkList().size(), "list size before add"); - cell.setHyperlink(hyperlink); - assertEquals(1, sheet.getHyperlinkList().size(), "list size after add"); - - assertEquals(hyperlink, sheet.getHyperlinkList().get(0), "list"); - CellAddress B6 = new CellAddress(5, 1); - assertEquals(hyperlink, sheet.getHyperlink(5, 1), "row, col"); - assertEquals(hyperlink, sheet.getHyperlink(B6), "addr"); - assertNull(sheet.getHyperlink(CellAddress.A1), "no hyperlink at A1"); - } - } - - @Test - void removeAllHyperlinks() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL); - hyperlink.setAddress("https://poi.apache.org/"); - Sheet sheet = workbook.createSheet(); - Cell cell = sheet.createRow(5).createCell(1); - cell.setHyperlink(hyperlink); - - assertEquals(1, workbook.getSheetAt(0).getHyperlinkList().size()); - - // Save a workbook with a hyperlink - try (Workbook workbook2 = _testDataProvider.writeOutAndReadBack(workbook)) { - assertEquals(1, workbook2.getSheetAt(0).getHyperlinkList().size()); - - // Remove all hyperlinks from a saved workbook - workbook2.getSheetAt(0).getRow(5).getCell(1).removeHyperlink(); - assertEquals(0, workbook2.getSheetAt(0).getHyperlinkList().size()); - - // Verify that hyperlink was removed from workbook after writing out - try (Workbook workbook3 = _testDataProvider.writeOutAndReadBack(workbook2)) { - assertEquals(0, workbook3.getSheetAt(0).getHyperlinkList().size()); - } - } - } - } - - - @Test - void newMergedRegionAt() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); - assertEquals(0, sheet.addMergedRegion(region)); - assertEquals("B2:D4", sheet.getMergedRegion(0).formatAsString()); - assertEquals(1, sheet.getNumMergedRegions()); - - assertNotNull(_testDataProvider.writeOutAndReadBack(workbook)); - } - } - - @Test - void showInPaneManyRowsBug55248() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet("Sheet 1"); - - sheet.showInPane(0, 0); - - for (int i = ROW_COUNT / 2; i < ROW_COUNT; i++) { - sheet.createRow(i); - sheet.showInPane(i, 0); - // this one fails: sheet.showInPane((short)i, 0); - } - - int i = 0; - sheet.showInPane(i, i); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - checkRowCount(wb2); - } - } - } - - private void checkRowCount(Workbook wb) { - assertNotNull(wb); - final Sheet sh = wb.getSheet("Sheet 1"); - assertNotNull(sh); - assertEquals(ROW_COUNT-1, sh.getLastRowNum()); - } - - - @Test - void testRightToLeft() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - - assertFalse(sheet.isRightToLeft()); - sheet.setRightToLeft(true); - assertTrue(sheet.isRightToLeft()); - sheet.setRightToLeft(false); - assertFalse(sheet.isRightToLeft()); - } - } - - @Test - void testNoMergedRegionsIsEmptyList() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - assertTrue(sheet.getMergedRegions().isEmpty()); - } - } - - /** - * Tests that the setAsActiveCell and getActiveCell function pairs work together - */ - @Test - void setActiveCell() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet(); - CellAddress B42 = new CellAddress("B42"); - - // active cell behavior is undefined if not set. - // HSSFSheet defaults to A1 active cell, while XSSFSheet defaults to null. - CellAddress ac = sheet.getActiveCell(); - assertTrue(ac == null || CellAddress.A1.equals(ac), "If not set, active cell should default to null or A1"); - - sheet.setActiveCell(B42); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - sheet = wb2.getSheetAt(0); - assertEquals(B42, sheet.getActiveCell()); - } - } - } - - - @Test - void autoSizeDate() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet("Sheet1"); - Row r = s.createRow(0); - r.createCell(0).setCellValue(1); - r.createCell(1).setCellValue(123456); - - // for the streaming-variant we need to enable autosize-tracking to make it work - trackColumnsForAutoSizingIfSXSSF(s); - - // Will be sized fairly small - s.autoSizeColumn((short) 0); - s.autoSizeColumn((short) 1); - - // Size ranges due to different fonts on different machines - assertBetween("Single number column width", s.getColumnWidth(0), 350, 570); - assertBetween("6 digit number column width", s.getColumnWidth(1), 1500, 2100); - - // Set a date format - CellStyle cs = wb.createCellStyle(); - DataFormat f = wb.createDataFormat(); - cs.setDataFormat(f.getFormat("yyyy-mm-dd MMMM hh:mm:ss")); - r.getCell(0).setCellStyle(cs); - r.getCell(1).setCellStyle(cs); - - assertTrue(DateUtil.isCellDateFormatted(r.getCell(0))); - assertTrue(DateUtil.isCellDateFormatted(r.getCell(1))); - - // Should get much bigger now - s.autoSizeColumn((short) 0); - s.autoSizeColumn((short) 1); - - assertBetween("Date column width", s.getColumnWidth(0), 4750, 7300); - assertBetween("Date column width", s.getColumnWidth(1), 4750, 7300); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java deleted file mode 100644 index 3afec95478..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java +++ /dev/null @@ -1,380 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Common superclass for testing automatic sizing of sheet columns - * - * @author Yegor Kozlov - */ -public abstract class BaseTestSheetAutosizeColumn { - - private final ITestDataProvider _testDataProvider; - - private static Locale userLocale; - - @BeforeAll - public static void initLocale() { - userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.ROOT); - } - - @AfterAll - public static void resetLocale() { - LocaleUtil.setUserLocale(userLocale); - } - - protected BaseTestSheetAutosizeColumn(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - protected void trackColumnsForAutoSizingIfSXSSF(Sheet sheet) { - // do nothing for Sheet base class. This will be overridden for SXSSFSheets. - } - - @Test - void numericCells() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - DataFormat df = workbook.getCreationHelper().createDataFormat(); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - - Row row = sheet.createRow(0); - row.createCell(0).setCellValue(0); // getCachedFormulaResult() returns 0 for not evaluated formula cells - row.createCell(1).setCellValue(10); - row.createCell(2).setCellValue("10"); - row.createCell(3).setCellFormula("(A1+B1)*1.0"); // a formula that returns '10' - - Cell cell4 = row.createCell(4); // numeric cell with a custom style - CellStyle style4 = workbook.createCellStyle(); - style4.setDataFormat(df.getFormat("0.0000")); - cell4.setCellStyle(style4); - cell4.setCellValue(10); // formatted as '10.0000' - - row.createCell(5).setCellValue("10.0000"); - - // autosize not-evaluated cells, formula cells are sized as if the result is 0 - for (int i = 0; i < 6; i++) sheet.autoSizeColumn(i); - - assertTrue(sheet.getColumnWidth(0) < sheet.getColumnWidth(1)); // width of '0' is less then width of '10' - assertEquals(sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // 10 and '10' should be sized equally - assertEquals(sheet.getColumnWidth(3), sheet.getColumnWidth(0)); // formula result is unknown, the width is calculated for '0' - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(5)); // 10.0000 and '10.0000' - - // evaluate formulas and re-autosize - evaluateWorkbook(workbook); - - for (int i = 0; i < 6; i++) sheet.autoSizeColumn(i); - - assertTrue(sheet.getColumnWidth(0) < sheet.getColumnWidth(1)); // width of '0' is less then width of '10' - assertEquals(sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // columns 1, 2 and 3 should have the same width - assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(3)); // columns 1, 2 and 3 should have the same width - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(5)); // 10.0000 and '10.0000' - - workbook.close(); - } - - @Test - void booleanCells() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - - Row row = sheet.createRow(0); - row.createCell(0).setCellValue(0); // getCachedFormulaResult() returns 0 for not evaluated formula cells - row.createCell(1).setCellValue(true); - row.createCell(2).setCellValue("TRUE"); - row.createCell(3).setCellFormula("1 > 0"); // a formula that returns true - - // autosize not-evaluated cells, formula cells are sized as if the result is 0 - for (int i = 0; i < 4; i++) sheet.autoSizeColumn(i); - - assertTrue(sheet.getColumnWidth(1) > sheet.getColumnWidth(0)); // 'true' is wider than '0' - assertEquals(sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // 10 and '10' should be sized equally - assertEquals(sheet.getColumnWidth(3), sheet.getColumnWidth(0)); // formula result is unknown, the width is calculated for '0' - - // evaluate formulas and re-autosize - evaluateWorkbook(workbook); - - for (int i = 0; i < 4; i++) sheet.autoSizeColumn(i); - - assertTrue(sheet.getColumnWidth(1) > sheet.getColumnWidth(0)); // 'true' is wider than '0' - assertEquals(sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // columns 1, 2 and 3 should have the same width - assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(3)); // columns 1, 2 and 3 should have the same width - - workbook.close(); - } - - @Test - void dateCells() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - DataFormat df = workbook.getCreationHelper().createDataFormat(); - - CellStyle style1 = workbook.createCellStyle(); - style1.setDataFormat(df.getFormat("m")); - - CellStyle style3 = workbook.createCellStyle(); - style3.setDataFormat(df.getFormat("mmm")); - - CellStyle style5 = workbook.createCellStyle(); //rotated text - style5.setDataFormat(df.getFormat("mmm/dd/yyyy")); - - Calendar calendar = LocaleUtil.getLocaleCalendar(2010, 0, 1); // Jan 1 2010 - - Row row = sheet.createRow(0); - row.createCell(0).setCellValue(DateUtil.getJavaDate(0)); //default date - - Cell cell1 = row.createCell(1); - cell1.setCellValue(calendar); - cell1.setCellStyle(style1); - row.createCell(2).setCellValue("1"); // column 1 should be sized as '1' - - Cell cell3 = row.createCell(3); - cell3.setCellValue(calendar); - cell3.setCellStyle(style3); - row.createCell(4).setCellValue("Jan"); - - Cell cell5 = row.createCell(5); - cell5.setCellValue(calendar); - cell5.setCellStyle(style5); - row.createCell(6).setCellValue("Jan/01/2010"); - - Cell cell7 = row.createCell(7); - cell7.setCellFormula("DATE(2010,1,1)"); - cell7.setCellStyle(style3); // should be sized as 'Jan' - - // autosize not-evaluated cells, formula cells are sized as if the result is 0 - for (int i = 0; i < 8; i++) sheet.autoSizeColumn(i); - - assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(1)); // date formatted as 'm' - assertTrue(sheet.getColumnWidth(3) > sheet.getColumnWidth(1)); // 'mmm' is wider than 'm' - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(3)); // date formatted as 'mmm' - assertTrue(sheet.getColumnWidth(5) > sheet.getColumnWidth(3)); // 'mmm/dd/yyyy' is wider than 'mmm' - assertEquals(sheet.getColumnWidth(6), sheet.getColumnWidth(5)); // date formatted as 'mmm/dd/yyyy' - - // YK: width of not-evaluated formulas that return data is not determined - // POI seems to conevert '0' to Excel date which is the beginng of the Excel's date system - - // evaluate formulas and re-autosize - evaluateWorkbook(workbook); - - for (int i = 0; i < 8; i++) sheet.autoSizeColumn(i); - - assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(1)); // date formatted as 'm' - assertTrue(sheet.getColumnWidth(3) > sheet.getColumnWidth(1)); // 'mmm' is wider than 'm' - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(3)); // date formatted as 'mmm' - assertTrue(sheet.getColumnWidth(5) > sheet.getColumnWidth(3)); // 'mmm/dd/yyyy' is wider than 'mmm' - assertEquals(sheet.getColumnWidth(6), sheet.getColumnWidth(5)); // date formatted as 'mmm/dd/yyyy' - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(7)); // date formula formatted as 'mmm' - - workbook.close(); - } - - @Test - void stringCells() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - Row row = sheet.createRow(0); - - Font defaultFont = workbook.getFontAt(0); - - CellStyle style1 = workbook.createCellStyle(); - Font font1 = workbook.createFont(); - font1.setFontHeight((short)(2*defaultFont.getFontHeight())); - style1.setFont(font1); - - row.createCell(0).setCellValue("x"); - row.createCell(1).setCellValue("xxxx"); - row.createCell(2).setCellValue("xxxxxxxxxxxx"); - row.createCell(3).setCellValue("Apache\nSoftware Foundation"); // the text is splitted into two lines - row.createCell(4).setCellValue("Software Foundation"); - - Cell cell5 = row.createCell(5); - cell5.setCellValue("Software Foundation"); - cell5.setCellStyle(style1); // same as in column 4 but the font is twice larger than the default font - - for (int i = 0; i < 10; i++) sheet.autoSizeColumn(i); - - assertTrue(2*sheet.getColumnWidth(0) < sheet.getColumnWidth(1)); // width is roughly proportional to the number of characters - assertTrue(2*sheet.getColumnWidth(1) < sheet.getColumnWidth(2)); - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(3)); - assertTrue(sheet.getColumnWidth(5) > sheet.getColumnWidth(4)); //larger font results in a wider column width - - workbook.close(); - } - - @Test - void rotatedText() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - Row row = sheet.createRow(0); - - CellStyle style1 = workbook.createCellStyle(); - style1.setRotation((short)90); - - Cell cell0 = row.createCell(0); - cell0.setCellValue("Apache Software Foundation"); - cell0.setCellStyle(style1); - - Cell cell1 = row.createCell(1); - cell1.setCellValue("Apache Software Foundation"); - - for (int i = 0; i < 2; i++) sheet.autoSizeColumn(i); - - int w0 = sheet.getColumnWidth(0); - int w1 = sheet.getColumnWidth(1); - - assertTrue(w0*5 < w1); // rotated text occupies at least five times less horizontal space than normal text - - workbook.close(); - } - - @Test - void mergedCells() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - - Row row = sheet.createRow(0); - assertEquals(0, sheet.addMergedRegion(CellRangeAddress.valueOf("A1:B1"))); - - Cell cell0 = row.createCell(0); - cell0.setCellValue("Apache Software Foundation"); - - int defaulWidth = sheet.getColumnWidth(0); - sheet.autoSizeColumn(0); - // column is unchanged if merged regions are ignored (Excel like behavior) - assertEquals(defaulWidth, sheet.getColumnWidth(0)); - - sheet.autoSizeColumn(0, true); - assertTrue(sheet.getColumnWidth(0) > defaulWidth); - - workbook.close(); - } - - /** - * Auto-Sizing a column needs to work when we have rows - * passed the 32767 boundary. See bug #48079 - */ - @Test - void largeRowNumbers() throws Exception { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - boolean isHssf = workbook instanceof HSSFWorkbook; - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - - Row r0 = sheet.createRow(0); - r0.createCell(0).setCellValue("I am ROW 0"); - Row r200 = sheet.createRow(200); - r200.createCell(0).setCellValue("I am ROW 200"); - - // This should work fine - sheet.autoSizeColumn(0); - int colWidth1 = sheet.getColumnWidth(0); - - // Get close to 32767 - Row r32765 = sheet.createRow(32765); - r32765.createCell(0).setCellValue("Nearly there..."); - sheet.autoSizeColumn(0); - int colWidth2 = sheet.getColumnWidth(0); - assertTrue(colWidth1 <= colWidth2); - colWidth1 = colWidth2; - - // To it - Row r32767 = sheet.createRow(32767); - r32767.createCell(0).setCellValue("At the boundary"); - sheet.autoSizeColumn(0); - colWidth2 = sheet.getColumnWidth(0); - assertTrue(colWidth1 <= colWidth2); - colWidth1 = colWidth2; - - // And passed it - Row r32768 = sheet.createRow(32768); - r32768.createCell(0).setCellValue("Passed"); - Row r32769 = sheet.createRow(32769); - r32769.createCell(0).setCellValue("More Passed"); - sheet.autoSizeColumn(0); - colWidth2 = sheet.getColumnWidth(0); - assertTrue(colWidth1 <= colWidth2); - colWidth1 = colWidth2; - - // Long way passed - Row r60708 = sheet.createRow(60708); - r60708.createCell(0).setCellValue("Near the end"); - sheet.autoSizeColumn(0); - colWidth2 = sheet.getColumnWidth(0); - assertTrue(colWidth1 <= colWidth2); - } - } - - // TODO should we have this stuff in the FormulaEvaluator? - private void evaluateWorkbook(Workbook workbook){ - FormulaEvaluator eval = workbook.getCreationHelper().createFormulaEvaluator(); - for(int i=0; i < workbook.getNumberOfSheets(); i++) { - Sheet sheet = workbook.getSheetAt(i); - for (Row r : sheet) { - for (Cell c : r) { - if (c.getCellType() == CellType.FORMULA){ - eval.evaluateFormulaCell(c); - } - } - } - } - } - - - @Test - void testExcelExporter() throws IOException { - try (final Workbook wb = _testDataProvider.createWorkbook()) { - boolean isHssf = wb instanceof HSSFWorkbook; - final Sheet sheet = wb.createSheet("test"); - trackColumnsForAutoSizingIfSXSSF(sheet); - final Row row = sheet.createRow(0); - final Cell cell = row.createCell(0); - - CellStyle csDateTime = wb.createCellStyle(); - csDateTime.setAlignment(HorizontalAlignment.LEFT); - - cell.setCellValue(new Date(Long.parseLong("1439800763994"))); - cell.setCellStyle(csDateTime); - - sheet.autoSizeColumn(0); - assertTrue(sheet.getColumnWidth(0) > 2500); - } - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetHiding.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetHiding.java deleted file mode 100644 index 5d09f30016..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetHiding.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public abstract class BaseTestSheetHiding { - - protected final ITestDataProvider _testDataProvider; - protected Workbook wbH; - protected Workbook wbU; - - private final String _file1, _file2; - - /** - * @param testDataProvider an object that provides test data in HSSF / specific way - */ - protected BaseTestSheetHiding(ITestDataProvider testDataProvider, - String file1, String file2) { - _testDataProvider = testDataProvider; - _file1 = file1; - _file2 = file2; - } - - @BeforeEach - void setUp() { - wbH = _testDataProvider.openSampleWorkbook(_file1); - wbU = _testDataProvider.openSampleWorkbook(_file2); - } - - @AfterEach - void teadDown() throws IOException { - wbH.close(); - wbU.close(); - } - - @Test - public final void testSheetVisibility() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - wb.createSheet("MySheet"); - - assertFalse(wb.isSheetHidden(0)); - assertFalse(wb.isSheetVeryHidden(0)); - assertEquals(SheetVisibility.VISIBLE, wb.getSheetVisibility(0)); - - wb.setSheetVisibility(0, SheetVisibility.HIDDEN); - assertTrue(wb.isSheetHidden(0)); - assertFalse(wb.isSheetVeryHidden(0)); - assertEquals(SheetVisibility.HIDDEN, wb.getSheetVisibility(0)); - - wb.setSheetVisibility(0, SheetVisibility.VERY_HIDDEN); - assertFalse(wb.isSheetHidden(0)); - assertTrue(wb.isSheetVeryHidden(0)); - assertEquals(SheetVisibility.VERY_HIDDEN, wb.getSheetVisibility(0)); - - wb.setSheetVisibility(0, SheetVisibility.VISIBLE); - assertFalse(wb.isSheetHidden(0)); - assertFalse(wb.isSheetVeryHidden(0)); - assertEquals(SheetVisibility.VISIBLE, wb.getSheetVisibility(0)); - - // verify limits-check - - // check sheet-index with one more => throws exception - assertThrows(IllegalArgumentException.class, () -> wb.setSheetVisibility(1, SheetVisibility.HIDDEN)); - - // check sheet-index with index out of bounds => throws exception - assertThrows(IllegalArgumentException.class, () -> wb.setSheetVisibility(10, SheetVisibility.HIDDEN)); - } - } - - /** - * Test that we get the right number of sheets, - * with the right text on them, no matter what - * the hidden flags are - */ - @Test - void testTextSheets() { - // Both should have two sheets - assertEquals(2, wbH.getNumberOfSheets()); - assertEquals(2, wbU.getNumberOfSheets()); - - // All sheets should have one row - assertEquals(0, wbH.getSheetAt(0).getLastRowNum()); - assertEquals(0, wbH.getSheetAt(1).getLastRowNum()); - assertEquals(0, wbU.getSheetAt(0).getLastRowNum()); - assertEquals(0, wbU.getSheetAt(1).getLastRowNum()); - - // All rows should have one column - assertEquals(1, wbH.getSheetAt(0).getRow(0).getLastCellNum()); - assertEquals(1, wbH.getSheetAt(1).getRow(0).getLastCellNum()); - assertEquals(1, wbU.getSheetAt(0).getRow(0).getLastCellNum()); - assertEquals(1, wbU.getSheetAt(1).getRow(0).getLastCellNum()); - - // Text should be sheet based - assertEquals("Sheet1A1", wbH.getSheetAt(0).getRow(0).getCell(0).getRichStringCellValue().getString()); - assertEquals("Sheet2A1", wbH.getSheetAt(1).getRow(0).getCell(0).getRichStringCellValue().getString()); - assertEquals("Sheet1A1", wbU.getSheetAt(0).getRow(0).getCell(0).getRichStringCellValue().getString()); - assertEquals("Sheet2A1", wbU.getSheetAt(1).getRow(0).getCell(0).getRichStringCellValue().getString()); - } - - /** - * Check that we can get and set the hidden flags - * as expected - */ - @Test - void testHideUnHideFlags() { - assertTrue(wbH.isSheetHidden(0)); - assertFalse(wbH.isSheetHidden(1)); - assertFalse(wbU.isSheetHidden(0)); - assertFalse(wbU.isSheetHidden(1)); - } - - /** - * Turn the sheet with none hidden into the one with - * one hidden - */ - @Test - void testHide() throws IOException { - wbU.setSheetHidden(0, true); - assertTrue(wbU.isSheetHidden(0)); - assertFalse(wbU.isSheetHidden(1)); - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wbU); - assertTrue(wb2.isSheetHidden(0)); - assertFalse(wb2.isSheetHidden(1)); - wb2.close(); - } - - /** - * Turn the sheet with one hidden into the one with - * none hidden - */ - @Test - void testUnHide() throws IOException { - wbH.setSheetHidden(0, false); - assertFalse(wbH.isSheetHidden(0)); - assertFalse(wbH.isSheetHidden(1)); - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wbH); - assertFalse(wb2.isSheetHidden(0)); - assertFalse(wb2.isSheetHidden(1)); - wb2.close(); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftColumns.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftColumns.java deleted file mode 100644 index 9a1a463363..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftColumns.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellUtil; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public abstract class BaseTestSheetShiftColumns { - protected Sheet sheet1; - protected Sheet sheet2; - protected Workbook workbook; - - protected ITestDataProvider _testDataProvider; - - @BeforeEach - void init() { - int rowIndex = 0; - sheet1 = workbook.createSheet("sheet1"); - Row row = sheet1.createRow(rowIndex++); - row.createCell(0, CellType.NUMERIC).setCellValue(0); - row.createCell(1, CellType.NUMERIC).setCellValue(1); - row.createCell(2, CellType.NUMERIC).setCellValue(2); - - row = sheet1.createRow(rowIndex++); - row.createCell(0, CellType.NUMERIC).setCellValue(0.1); - row.createCell(1, CellType.NUMERIC).setCellValue(1.1); - row.createCell(2, CellType.NUMERIC).setCellValue(2.1); - row = sheet1.createRow(rowIndex++); - row.createCell(0, CellType.NUMERIC).setCellValue(0.2); - row.createCell(1, CellType.NUMERIC).setCellValue(1.2); - row.createCell(2, CellType.NUMERIC).setCellValue(2.2); - row = sheet1.createRow(rowIndex++); - row.createCell(0, CellType.FORMULA).setCellFormula("A2*B3"); - row.createCell(1, CellType.NUMERIC).setCellValue(1.3); - row.createCell(2, CellType.FORMULA).setCellFormula("B1-B3"); - row = sheet1.createRow(rowIndex++); - row.createCell(0, CellType.FORMULA).setCellFormula("SUM(C1:C4)"); - row.createCell(1, CellType.FORMULA).setCellFormula("SUM(A3:C3)"); - row.createCell(2, CellType.FORMULA).setCellFormula("$C1+C$2"); - row = sheet1.createRow(rowIndex++); - row.createCell(1, CellType.NUMERIC).setCellValue(1.5); - row = sheet1.createRow(rowIndex); - row.createCell(1, CellType.BOOLEAN).setCellValue(false); - Cell textCell = row.createCell(2, CellType.STRING); - textCell.setCellValue("TEXT"); - textCell.setCellStyle(newCenterBottomStyle()); - - sheet2 = workbook.createSheet("sheet2"); - row = sheet2.createRow(0); row.createCell(0, CellType.NUMERIC).setCellValue(10); - row.createCell(1, CellType.NUMERIC).setCellValue(11); - row.createCell(2, CellType.FORMULA).setCellFormula("SUM(sheet1!B3:C3)"); - row = sheet2.createRow(1); - row.createCell(0, CellType.NUMERIC).setCellValue(21); - row.createCell(1, CellType.NUMERIC).setCellValue(22); - row.createCell(2, CellType.NUMERIC).setCellValue(23); - row = sheet2.createRow(2); - row.createCell(0, CellType.FORMULA).setCellFormula("sheet1!A4+sheet1!C2+A2"); - row.createCell(1, CellType.FORMULA).setCellFormula("SUM(sheet1!A3:$C3)"); - row = sheet2.createRow(3); - row.createCell(0, CellType.STRING).setCellValue("dummy"); - } - - private CellStyle newCenterBottomStyle() { - CellStyle style = workbook.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.BOTTOM); - return style; - } - - @Test - void testShiftOneColumnRight() { - sheet1.shiftColumns(1, 2, 1); - double c1Value = sheet1.getRow(0).getCell(2).getNumericCellValue(); - assertEquals(1d, c1Value, 0.01); - String formulaA4 = sheet1.getRow(3).getCell(0).getCellFormula(); - assertEquals("A2*C3", formulaA4); - String formulaC4 = sheet1.getRow(3).getCell(3).getCellFormula(); - assertEquals("C1-C3", formulaC4); - String formulaB5 = sheet1.getRow(4).getCell(2).getCellFormula(); - assertEquals("SUM(A3:D3)", formulaB5); - String formulaD5 = sheet1.getRow(4).getCell(3).getCellFormula(); // $C1+C$2 - assertEquals("$D1+D$2", formulaD5); - - Cell newb5Null = sheet1.getRow(4).getCell(1); - assertNull(newb5Null); - boolean logicalValue = sheet1.getRow(6).getCell(2).getBooleanCellValue(); - assertFalse(logicalValue); - Cell textCell = sheet1.getRow(6).getCell(3); - assertEquals(textCell.getStringCellValue(), "TEXT"); - assertEquals(textCell.getCellStyle().getAlignment(), HorizontalAlignment.CENTER); - - // other sheet - String formulaC1 = sheet2.getRow(0).getCell(2).getCellFormula(); // SUM(sheet1!B3:C3) - assertEquals("SUM(sheet1!C3:D3)", formulaC1); - String formulaA3 = sheet2.getRow(2).getCell(0).getCellFormula(); // sheet1!A4+sheet1!C2+A2 - assertEquals("sheet1!A4+sheet1!D2+A2", formulaA3); - } - - @Test - void testShiftTwoColumnsRight() { - sheet1.shiftColumns(1, 2, 2); - String formulaA4 = sheet1.getRow(3).getCell(0).getCellFormula(); - assertEquals("A2*D3", formulaA4); - String formulaD4 = sheet1.getRow(3).getCell(4).getCellFormula(); - assertEquals("D1-D3", formulaD4); - String formulaD5 = sheet1.getRow(4).getCell(3).getCellFormula(); - assertEquals("SUM(A3:E3)", formulaD5); - - Cell b5Null = sheet1.getRow(4).getCell(1); - assertNull(b5Null); - Object c6Null = sheet1.getRow(5).getCell(2); // null cell A5 is shifted - // for 2 columns, so now - // c5 should be null - assertNull(c6Null); - } - - @Test - void testShiftOneColumnLeft() { - sheet1.shiftColumns(1, 2, -1); - - String formulaA5 = sheet1.getRow(4).getCell(0).getCellFormula(); - assertEquals("SUM(A3:B3)", formulaA5); - String formulaB4 = sheet1.getRow(3).getCell(1).getCellFormula(); - assertEquals("A1-A3", formulaB4); - String formulaB5 = sheet1.getRow(4).getCell(1).getCellFormula(); - assertEquals("$B1+B$2", formulaB5); - Cell newb6Null = sheet1.getRow(5).getCell(1); - assertNull(newb6Null); - } - - @Test - void testShiftTwoColumnsLeft() { - assertThrows(IllegalStateException.class, () -> sheet1.shiftColumns(1, 2, -2)); - } - - @Test - protected void testShiftHyperlinks() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - - // How to create hyperlinks - // https://poi.apache.org/spreadsheet/quick-guide.html#Hyperlinks - CreationHelper helper = wb.getCreationHelper(); - CellStyle hlinkStyle = wb.createCellStyle(); - Font hlinkFont = wb.createFont(); - hlinkFont.setUnderline(Font.U_SINGLE); - hlinkFont.setColor(IndexedColors.BLUE.getIndex()); - hlinkStyle.setFont(hlinkFont); - - // 3D relative document link - // CellAddress=A1, shifted to A4 - Cell cell = row.createCell(0); - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.DOCUMENT, "test!E1"); - - // URL - cell = row.createCell(1); - // CellAddress=B1, shifted to B4 - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.URL, "https://poi.apache.org/"); - - // row0 will be shifted on top of row1, so this URL should be removed - // from the workbook - Row overwrittenRow = sheet.createRow(3); - cell = overwrittenRow.createCell(2); - // CellAddress=C4, will be overwritten (deleted) - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.EMAIL, "mailto:poi@apache.org"); - - Row unaffectedRow = sheet.createRow(20); - cell = unaffectedRow.createCell(3); - // CellAddress=D21, will be unaffected - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.FILE, "54524.xlsx"); - - cell = wb.createSheet("other").createRow(0).createCell(0); - // CellAddress=Other!A1, will be unaffected - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.URL, "http://apache.org/"); - - int startRow = 0; - int endRow = 4; - int n = 3; - sheet.shiftColumns(startRow, endRow, n); - - Workbook read = _testDataProvider.writeOutAndReadBack(wb); - wb.close(); - - Sheet sh = read.getSheet("test"); - - Row shiftedRow = sh.getRow(0); - - // document link anchored on a shifted cell should be moved - // Note that hyperlinks do not track what they point to, so this - // hyperlink should still refer to test!E1 - verifyHyperlink(shiftedRow.getCell(3), HyperlinkType.DOCUMENT, "test!E1"); - - // URL, EMAIL, and FILE links anchored on a shifted cell should be moved - verifyHyperlink(shiftedRow.getCell(4), HyperlinkType.URL, "https://poi.apache.org/"); - - // Make sure hyperlinks were moved and not copied - assertNull(sh.getHyperlink(0, 0), "Document hyperlink should be moved, not copied"); - assertNull(sh.getHyperlink(1, 0), "URL hyperlink should be moved, not copied"); - - assertEquals(4, sh.getHyperlinkList().size()); - read.close(); - } - - private void createHyperlink(CreationHelper helper, Cell cell, HyperlinkType linkType, String ref) { - cell.setCellValue(ref); - Hyperlink link = helper.createHyperlink(linkType); - link.setAddress(ref); - cell.setHyperlink(link); - } - - private void verifyHyperlink(Cell cell, HyperlinkType linkType, String ref) { - assertTrue(cellHasHyperlink(cell)); - assertNotNull(cell); - Hyperlink link = cell.getHyperlink(); - assertEquals(linkType, link.getType()); - assertEquals(ref, link.getAddress()); - } - - private boolean cellHasHyperlink(Cell cell) { - return (cell != null) && (cell.getHyperlink() != null); - } - - @Test - protected void shiftMergedColumnsToMergedColumnsRight() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - - // populate sheet cells - populateSheetCells(sheet); - CellRangeAddress A1_A5 = new CellRangeAddress(0, 4, 0, 0); // NOSONAR, it's more readable this way - CellRangeAddress B1_B3 = new CellRangeAddress(0, 2, 1, 1); // NOSONAR, it's more readable this way - - assertEquals(0, sheet.addMergedRegion(B1_B3)); - assertEquals(1, sheet.addMergedRegion(A1_A5)); - - // A1:A5 should be moved to B1:B5 - // B1:B3 will be removed - sheet.shiftColumns(0, 0, 1); - assertEquals(1, sheet.getNumMergedRegions()); - assertEquals(CellRangeAddress.valueOf("B1:B5"), sheet.getMergedRegion(0)); - - wb.close(); - } - - @Test - protected void shiftMergedColumnsToMergedColumnsLeft() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - populateSheetCells(sheet); - - CellRangeAddress A1_A5 = new CellRangeAddress(0, 4, 0, 0); // NOSONAR, it's more readable this way - CellRangeAddress B1_B3 = new CellRangeAddress(0, 2, 1, 1); // NOSONAR, it's more readable this way - - assertEquals(0, sheet.addMergedRegion(A1_A5)); - assertEquals(1, sheet.addMergedRegion(B1_B3)); - - // A1:E1 should be removed - // B1:B3 will be A1:A3 - sheet.shiftColumns(1, 5, -1); - - assertEquals(1, sheet.getNumMergedRegions()); - assertEquals(CellRangeAddress.valueOf("A1:A3"), sheet.getMergedRegion(0)); - - wb.close(); - } - - private void populateSheetCells(Sheet sheet) { - // populate sheet cells - for (int i = 0; i < 2; i++) { - Row row = sheet.createRow(i); - for (int j = 0; j < 5; j++) { - Cell cell = row.createCell(j); - cell.setCellValue(i + "x" + j); - } - } - } - - @Test - protected void testShiftWithMergedRegions() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - row.createCell(0).setCellValue(1.1); - row = sheet.createRow(1); - row.createCell(0).setCellValue(2.2); - CellRangeAddress region = new CellRangeAddress(0, 2, 0, 0); - assertEquals("A1:A3", region.formatAsString()); - - assertEquals(0, sheet.addMergedRegion(region)); - - sheet.shiftColumns(0, 1, 2); - region = sheet.getMergedRegion(0); - assertEquals("C1:C3", region.formatAsString()); - wb.close(); - } - - protected abstract Workbook openWorkbook(String spreadsheetFileName) throws IOException; - protected abstract Workbook getReadBackWorkbook(Workbook wb) throws IOException; - - protected static final String AMDOCS = "Amdocs"; - protected static final String AMDOCS_TEST = "Amdocs:\ntest\n"; - - @Test - protected void testCommentsShifting() throws IOException { - Workbook inputWb = openWorkbook("56017.xlsx"); - - Sheet sheet = inputWb.getSheetAt(0); - Comment comment = sheet.getCellComment(new CellAddress(0, 0)); - assertNotNull(comment); - assertEquals(AMDOCS, comment.getAuthor()); - assertEquals(AMDOCS_TEST, comment.getString().getString()); - - sheet.shiftColumns(0, 1, 1); - - // comment in column 0 is gone - comment = sheet.getCellComment(new CellAddress(0, 0)); - assertNull(comment); - - // comment is column in column 1 - comment = sheet.getCellComment(new CellAddress(0, 1)); - assertNotNull(comment); - assertEquals(AMDOCS, comment.getAuthor()); - assertEquals(AMDOCS_TEST, comment.getString().getString()); - - Workbook wbBack = getReadBackWorkbook(inputWb); - inputWb.close(); - assertNotNull(wbBack); - - Sheet sheetBack = wbBack.getSheetAt(0); - - // comment in column 0 is gone - comment = sheetBack.getCellComment(new CellAddress(0, 0)); - assertNull(comment); - - // comment is now in column 1 - comment = sheetBack.getCellComment(new CellAddress(0, 1)); - assertNotNull(comment); - assertEquals(AMDOCS, comment.getAuthor()); - assertEquals(AMDOCS_TEST, comment.getString().getString()); - wbBack.close(); - } - - // transposed version of TestXSSFSheetShiftRows.testBug54524() - @Test - protected void testBug54524() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row firstRow = sheet.createRow(0); - firstRow.createCell(0).setCellValue(""); - firstRow.createCell(1).setCellValue(1); - firstRow.createCell(2).setCellValue(2); - firstRow.createCell(3).setCellFormula("SUM(B1:C1)"); - firstRow.createCell(4).setCellValue("X"); - - sheet.shiftColumns(3, 5, -1); - - Cell cell = CellUtil.getCell(sheet.getRow(0), 1); - assertEquals(1.0, cell.getNumericCellValue(), 0); - cell = CellUtil.getCell(sheet.getRow(0), 2); - assertEquals("SUM(B1:B1)", cell.getCellFormula()); - cell = CellUtil.getCell(sheet.getRow(0), 3); - assertEquals("X", cell.getStringCellValue()); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java deleted file mode 100644 index 67d351bffc..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java +++ /dev/null @@ -1,819 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.apache.poi.POITestCase.skipTest; -import static org.apache.poi.POITestCase.testPassesNow; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; - -/** - * Tests row shifting capabilities. - * - * @author Shawn Laubach (slaubach at apache dot com) - * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) - */ -public abstract class BaseTestSheetShiftRows { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestSheetShiftRows(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - /** - * Tests the shiftRows function. Does three different shifts. - * After each shift, writes the workbook to file and reads back to - * check. This ensures that if some changes code that breaks - * writing or what not, they realize it. - */ - @Test - public final void testShiftRows() throws IOException { - // Read initial file in - String sampleName = "SimpleMultiCell." + _testDataProvider.getStandardFileNameExtension(); - Workbook wb1 = _testDataProvider.openSampleWorkbook(sampleName); - Sheet s = wb1.getSheetAt( 0 ); - - // Shift the second row down 1 and write to temp file - s.shiftRows( 1, 1, 1 ); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - // Read from temp file and check the number of cells in each - // row (in original file each row was unique) - s = wb2.getSheetAt( 0 ); - - assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 1); - confirmEmptyRow(s, 1); - assertEquals(s.getRow(2).getPhysicalNumberOfCells(), 2); - assertEquals(s.getRow(3).getPhysicalNumberOfCells(), 4); - assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5); - - // 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 ); - Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2); - wb2.close(); - - // Read and ensure things are where they should be - s = wb3.getSheetAt(0); - confirmEmptyRow(s, 0); - confirmEmptyRow(s, 1); - confirmEmptyRow(s, 2); - assertEquals(s.getRow(3).getPhysicalNumberOfCells(), 1); - confirmEmptyRow(s, 4); - assertEquals(s.getRow(5).getPhysicalNumberOfCells(), 2); - - wb3.close(); - - // Read the first file again - Workbook wb4 = _testDataProvider.openSampleWorkbook(sampleName); - s = wb4.getSheetAt( 0 ); - - // Shift rows 3 and 4 up and write to temp file - s.shiftRows( 2, 3, -2 ); - Workbook wb5 = _testDataProvider.writeOutAndReadBack(wb4); - wb4.close(); - s = wb5.getSheetAt( 0 ); - assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 3); - assertEquals(s.getRow(1).getPhysicalNumberOfCells(), 4); - confirmEmptyRow(s, 2); - confirmEmptyRow(s, 3); - assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5); - wb5.close(); - } - private static void confirmEmptyRow(Sheet s, int rowIx) { - Row row = s.getRow(rowIx); - assertTrue(row == null || row.getPhysicalNumberOfCells() == 0); - } - - /** - * Tests when rows are null. - */ - @Test - public final void testShiftRow() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet(); - s.createRow(0).createCell(0).setCellValue("TEST1"); - s.createRow(3).createCell(0).setCellValue("TEST2"); - assertDoesNotThrow(() -> s.shiftRows(0, 4, 1)); - } - } - - /** - * When shifting rows, the page breaks should go with it - */ - @Test - protected void testShiftRowBreaks() throws IOException { - // TODO - enable XSSF test - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet(); - Row row = s.createRow(4); - row.createCell(0).setCellValue("test"); - s.setRowBreak(4); - - s.shiftRows(4, 4, 2); - assertTrue(s.isRowBroken(6), "Row number 6 should have a pagebreak"); - } - } - - @Test - void testShiftWithComments() throws IOException { - Workbook wb1 = _testDataProvider.openSampleWorkbook("comments." + _testDataProvider.getStandardFileNameExtension()); - - Sheet sheet = wb1.getSheet("Sheet1"); - assertEquals(3, sheet.getLastRowNum()); - - // Verify comments are in the position expected - assertNotNull(sheet.getCellComment(new CellAddress(0,0))); - assertNull(sheet.getCellComment(new CellAddress(1,0))); - assertNotNull(sheet.getCellComment(new CellAddress(2,0))); - assertNotNull(sheet.getCellComment(new CellAddress(3,0))); - - String comment1 = sheet.getCellComment(new CellAddress(0,0)).getString().getString(); - assertEquals(comment1,"comment top row1 (index0)\n"); - String comment3 = sheet.getCellComment(new CellAddress(2,0)).getString().getString(); - assertEquals(comment3,"comment top row3 (index2)\n"); - String comment4 = sheet.getCellComment(new CellAddress(3,0)).getString().getString(); - assertEquals(comment4,"comment top row4 (index3)\n"); - - //Workbook wbBack = _testDataProvider.writeOutAndReadBack(wb); - - // Shifting all but first line down to test comments shifting - sheet.shiftRows(1, sheet.getLastRowNum(), 1, true, true); - - // Test that comments were shifted as expected - assertEquals(4, sheet.getLastRowNum()); - assertNotNull(sheet.getCellComment(new CellAddress(0,0))); - assertNull(sheet.getCellComment(new CellAddress(1,0))); - assertNull(sheet.getCellComment(new CellAddress(2,0))); - assertNotNull(sheet.getCellComment(new CellAddress(3,0))); - assertNotNull(sheet.getCellComment(new CellAddress(4,0))); - - String comment1_shifted = sheet.getCellComment(new CellAddress(0,0)).getString().getString(); - assertEquals(comment1,comment1_shifted); - String comment3_shifted = sheet.getCellComment(new CellAddress(3,0)).getString().getString(); - assertEquals(comment3,comment3_shifted); - String comment4_shifted = sheet.getCellComment(new CellAddress(4,0)).getString().getString(); - assertEquals(comment4,comment4_shifted); - - // Write out and read back in again - // Ensure that the changes were persisted - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheet("Sheet1"); - assertEquals(4, sheet.getLastRowNum()); - - // Verify comments are in the position expected after the shift - assertNotNull(sheet.getCellComment(new CellAddress(0,0))); - assertNull(sheet.getCellComment(new CellAddress(1,0))); - assertNull(sheet.getCellComment(new CellAddress(2,0))); - assertNotNull(sheet.getCellComment(new CellAddress(3,0))); - assertNotNull(sheet.getCellComment(new CellAddress(4,0))); - - comment1_shifted = sheet.getCellComment(new CellAddress(0,0)).getString().getString(); - assertEquals(comment1,comment1_shifted); - comment3_shifted = sheet.getCellComment(new CellAddress(3,0)).getString().getString(); - assertEquals(comment3,comment3_shifted); - comment4_shifted = sheet.getCellComment(new CellAddress(4,0)).getString().getString(); - assertEquals(comment4,comment4_shifted); - - // Shifting back up again, now two rows - sheet.shiftRows(2, sheet.getLastRowNum(), -2, true, true); - - // TODO: it seems HSSFSheet does not correctly remove comments from rows that are overwritten - // by shifting rows... - if(!(wb2 instanceof HSSFWorkbook)) { - assertEquals(2, sheet.getLastRowNum()); - - // Verify comments are in the position expected - assertNull(sheet.getCellComment(new CellAddress(0,0)), - "Had: " + (sheet.getCellComment(new CellAddress(0,0)) == null ? "null" : sheet.getCellComment(new CellAddress(0,0)).getString())); - assertNotNull(sheet.getCellComment(new CellAddress(1,0))); - assertNotNull(sheet.getCellComment(new CellAddress(2,0))); - } - - comment1 = sheet.getCellComment(new CellAddress(1,0)).getString().getString(); - assertEquals(comment1,"comment top row3 (index2)\n"); - String comment2 = sheet.getCellComment(new CellAddress(2,0)).getString().getString(); - assertEquals(comment2,"comment top row4 (index3)\n"); - - wb2.close(); - } - - @Test - public final void testShiftWithNames() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb.createSheet("Sheet1"); - wb.createSheet("Sheet2"); - Row row = sheet1.createRow(0); - row.createCell(0).setCellValue(1.1); - row.createCell(1).setCellValue(2.2); - - Name name1 = wb.createName(); - name1.setNameName("name1"); - name1.setRefersToFormula("Sheet1!$A$1+Sheet1!$B$1"); - - Name name2 = wb.createName(); - name2.setNameName("name2"); - name2.setRefersToFormula("Sheet1!$A$1"); - - //refers to A1 but on Sheet2. Should stay unaffected. - Name name3 = wb.createName(); - name3.setNameName("name3"); - name3.setRefersToFormula("Sheet2!$A$1"); - - //The scope of this one is Sheet2. Should stay unaffected. - Name name4 = wb.createName(); - name4.setNameName("name4"); - name4.setRefersToFormula("A1"); - name4.setSheetIndex(1); - - sheet1.shiftRows(0, 1, 2); //shift down the top row on Sheet1. - name1 = wb.getName("name1"); - assertEquals("Sheet1!$A$3+Sheet1!$B$3", name1.getRefersToFormula()); - - name2 = wb.getName("name2"); - assertEquals("Sheet1!$A$3", name2.getRefersToFormula()); - - //name3 and name4 refer to Sheet2 and should not be affected - name3 = wb.getName("name3"); - assertEquals("Sheet2!$A$1", name3.getRefersToFormula()); - - name4 = wb.getName("name4"); - assertEquals("A1", name4.getRefersToFormula()); - - wb.close(); - } - - @Test - public final void testShiftWithMergedRegions() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - row.createCell(0).setCellValue(1.1); - row.createCell(1).setCellValue(2.2); - CellRangeAddress region = new CellRangeAddress(0, 0, 0, 2); - assertEquals("A1:C1", region.formatAsString()); - - assertEquals(0, sheet.addMergedRegion(region)); - - sheet.shiftRows(0, 1, 2); - region = sheet.getMergedRegion(0); - assertEquals("A3:C3", region.formatAsString()); - wb.close(); - } - - //@Disabled("bug 56454: Incorrectly handles merged regions that do not contain column 0") - @Test - public final void shiftWithMergedRegions_bug56454() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - // populate sheet cells - for (int i = 0; i < 10; i++) { - Row row = sheet.createRow(i); - - for (int j = 0; j < 10; j++) { - Cell cell = row.createCell(j, CellType.STRING); - cell.setCellValue(i + "x" + j); - } - } - - CellRangeAddress A4_B7 = CellRangeAddress.valueOf("A4:B7"); - CellRangeAddress C4_D7 = CellRangeAddress.valueOf("C4:D7"); - - assertEquals(0, sheet.addMergedRegion(A4_B7)); - assertEquals(1, sheet.addMergedRegion(C4_D7)); - - assumeTrue(sheet.getLastRowNum() > 8); - - // Insert a row in the middle of both merged regions. - sheet.shiftRows(4, sheet.getLastRowNum(), 1); - - // all regions should still start at row 3, and elongate by 1 row - List expectedMergedRegions = new ArrayList<>(); - CellRangeAddress A4_B8 = CellRangeAddress.valueOf("A4:B8"); //A4:B7 should be elongated by 1 row - CellRangeAddress C4_D8 = CellRangeAddress.valueOf("C4:D8"); //C4:B7 should be elongated by 1 row - expectedMergedRegions.add(A4_B8); - expectedMergedRegions.add(C4_D8); - - // This test is written as expected-to-fail and should be rewritten - // as expected-to-pass when the bug is fixed. - // FIXME: remove try, catch, and testPassesNow, skipTest when test passes - try { - assertEquals(expectedMergedRegions, sheet.getMergedRegions()); - testPassesNow(56454); - } catch (AssertionError e) { - skipTest(e); - } - wb.close(); - } - - - - /** - * See bug #34023 - */ - @Test - public final void testShiftWithFormulas() throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook("ForShifting." + _testDataProvider.getStandardFileNameExtension()); - - Sheet sheet = wb.getSheet("Sheet1"); - assertEquals(20, sheet.getLastRowNum()); - - confirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)"); - confirmRow(sheet, 1, 2, 172, 1, "ROW(D2)", "100+B2", "COUNT(D2:E2)"); - confirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)"); - - confirmCell(sheet, 6, 1, 271, "200+B1"); - confirmCell(sheet, 7, 1, 272, "200+B2"); - confirmCell(sheet, 8, 1, 273, "200+B3"); - - confirmCell(sheet, 14, 0, 0.0, "A12"); // the cell referred to by this formula will be replaced - - // ----------- - // Row index 1 -> 11 (row "2" -> row "12") - sheet.shiftRows(1, 1, 10); - - // Now check what sheet looks like after move - - // no changes on row "1" - confirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)"); - - // row "2" is now empty - confirmEmptyRow(sheet, 1); - - // Row "2" moved to row "12", and the formula has been updated. - // note however that the cached formula result (2) has not been updated. (POI differs from Excel here) - confirmRow(sheet, 11, 2, 172, 1, "ROW(D12)", "100+B12", "COUNT(D12:E12)"); - - // no changes on row "3" - confirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)"); - - - confirmCell(sheet, 14, 0, 0.0, "#REF!"); - - - // Formulas on rows that weren't shifted: - confirmCell(sheet, 6, 1, 271, "200+B1"); - confirmCell(sheet, 7, 1, 272, "200+B12"); // this one moved - confirmCell(sheet, 8, 1, 273, "200+B3"); - - // check formulas on other sheets - Sheet sheet2 = wb.getSheet("Sheet2"); - confirmCell(sheet2, 0, 0, 371, "300+Sheet1!B1"); - confirmCell(sheet2, 1, 0, 372, "300+Sheet1!B12"); - confirmCell(sheet2, 2, 0, 373, "300+Sheet1!B3"); - - confirmCell(sheet2, 11, 0, 300, "300+Sheet1!#REF!"); - - - // Note - named ranges formulas have not been updated - wb.close(); - } - - private static void confirmRow(Sheet sheet, int rowIx, double valA, double valB, double valC, - String formulaA, String formulaB, String formulaC) { - confirmCell(sheet, rowIx, 4, valA, formulaA); - confirmCell(sheet, rowIx, 5, valB, formulaB); - confirmCell(sheet, rowIx, 6, valC, formulaC); - } - - private static void confirmCell(Sheet sheet, int rowIx, int colIx, - double expectedValue, String expectedFormula) { - Cell cell = sheet.getRow(rowIx).getCell(colIx); - assertEquals(expectedValue, cell.getNumericCellValue(), 0.0); - assertEquals(expectedFormula, cell.getCellFormula()); - } - - @Test - public final void testShiftSharedFormulasBug54206() throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook("54206." + _testDataProvider.getStandardFileNameExtension()); - - Sheet sheet = wb.getSheetAt(0); - assertEquals("SUMIF($B$19:$B$82,$B4,G$19:G$82)", sheet.getRow(3).getCell(6).getCellFormula()); - assertEquals("SUMIF($B$19:$B$82,$B4,H$19:H$82)", sheet.getRow(3).getCell(7).getCellFormula()); - assertEquals("SUMIF($B$19:$B$82,$B4,I$19:I$82)", sheet.getRow(3).getCell(8).getCellFormula()); - - assertEquals("SUMIF($B$19:$B$82,$B15,G$19:G$82)", sheet.getRow(14).getCell(6).getCellFormula()); - assertEquals("SUMIF($B$19:$B$82,$B15,H$19:H$82)", sheet.getRow(14).getCell(7).getCellFormula()); - assertEquals("SUMIF($B$19:$B$82,$B15,I$19:I$82)", sheet.getRow(14).getCell(8).getCellFormula()); - - // now the whole block G4L:15 - for(int i = 3; i <= 14; i++){ - for(int j = 6; j <= 8; j++){ - String col = CellReference.convertNumToColString(j); - String expectedFormula = "SUMIF($B$19:$B$82,$B"+(i+1)+","+col+"$19:"+col+"$82)"; - assertEquals(expectedFormula, sheet.getRow(i).getCell(j).getCellFormula()); - } - } - - assertEquals("SUM(G24:I24)", sheet.getRow(23).getCell(9).getCellFormula()); - assertEquals("SUM(G25:I25)", sheet.getRow(24).getCell(9).getCellFormula()); - assertEquals("SUM(G26:I26)", sheet.getRow(25).getCell(9).getCellFormula()); - - sheet.shiftRows(24, sheet.getLastRowNum(), 4, true, false); - - assertEquals("SUMIF($B$19:$B$86,$B4,G$19:G$86)", sheet.getRow(3).getCell(6).getCellFormula()); - assertEquals("SUMIF($B$19:$B$86,$B4,H$19:H$86)", sheet.getRow(3).getCell(7).getCellFormula()); - assertEquals("SUMIF($B$19:$B$86,$B4,I$19:I$86)", sheet.getRow(3).getCell(8).getCellFormula()); - - assertEquals("SUMIF($B$19:$B$86,$B15,G$19:G$86)", sheet.getRow(14).getCell(6).getCellFormula()); - assertEquals("SUMIF($B$19:$B$86,$B15,H$19:H$86)", sheet.getRow(14).getCell(7).getCellFormula()); - assertEquals("SUMIF($B$19:$B$86,$B15,I$19:I$86)", sheet.getRow(14).getCell(8).getCellFormula()); - - // now the whole block G4L:15 - for(int i = 3; i <= 14; i++){ - for(int j = 6; j <= 8; j++){ - String col = CellReference.convertNumToColString(j); - String expectedFormula = "SUMIF($B$19:$B$86,$B"+(i+1)+","+col+"$19:"+col+"$86)"; - assertEquals(expectedFormula, sheet.getRow(i).getCell(j).getCellFormula()); - } - } - - assertEquals("SUM(G24:I24)", sheet.getRow(23).getCell(9).getCellFormula()); - - // shifted rows - assertTrue( sheet.getRow(24) == null || sheet.getRow(24).getCell(9) == null); - assertTrue( sheet.getRow(25) == null || sheet.getRow(25).getCell(9) == null); - assertTrue( sheet.getRow(26) == null || sheet.getRow(26).getCell(9) == null); - assertTrue( sheet.getRow(27) == null || sheet.getRow(27).getCell(9) == null); - - assertEquals("SUM(G29:I29)", sheet.getRow(28).getCell(9).getCellFormula()); - assertEquals("SUM(G30:I30)", sheet.getRow(29).getCell(9).getCellFormula()); - wb.close(); - } - - @Test - void testBug55280() throws IOException { - Workbook w = _testDataProvider.createWorkbook(); - Sheet s = w.createSheet(); - for (int row = 0; row < 5000; ++row) { - assertEquals(row, s.addMergedRegion(new CellRangeAddress(row, row, 0, 3))); - } - - s.shiftRows(0, 4999, 1); // takes a long time... - w.close(); - } - - @Test - void test47169() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet(); - sheet.createRow(30); - sheet.shiftRows(29, 29, 1, true, true); - assertDoesNotThrow(() -> sheet.createRow(30)); - } - } - - /** - * Unified test for: - * bug 46742: XSSFSheet.shiftRows should shift hyperlinks - * bug 52903: HSSFSheet.shiftRows should shift hyperlinks - */ - @Test - void testBug46742_52903_shiftHyperlinks() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - - // How to create hyperlinks - // https://poi.apache.org/spreadsheet/quick-guide.html#Hyperlinks - CreationHelper helper = wb.getCreationHelper(); - CellStyle hlinkStyle = wb.createCellStyle(); - Font hlinkFont = wb.createFont(); - hlinkFont.setUnderline(Font.U_SINGLE); - hlinkFont.setColor(IndexedColors.BLUE.getIndex()); - hlinkStyle.setFont(hlinkFont); - - // 3D relative document link - // CellAddress=A1, shifted to A4 - Cell cell = row.createCell(0); - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.DOCUMENT, "test!E1"); - - // URL - cell = row.createCell(1); - // CellAddress=B1, shifted to B4 - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.URL, "https://poi.apache.org/"); - - // row0 will be shifted on top of row1, so this URL should be removed from the workbook - Row overwrittenRow = sheet.createRow(3); - cell = overwrittenRow.createCell(2); - // CellAddress=C4, will be overwritten (deleted) - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.EMAIL, "mailto:poi@apache.org"); - - // hyperlinks on this row are unaffected by the row shifting, so the hyperlinks should not move - Row unaffectedRow = sheet.createRow(20); - cell = unaffectedRow.createCell(3); - // CellAddress=D21, will be unaffected - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.FILE, "54524.xlsx"); - - cell = wb.createSheet("other").createRow(0).createCell(0); - // CellAddress=Other!A1, will be unaffected - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.URL, "http://apache.org/"); - - int startRow = 0; - int endRow = 0; - int n = 3; - sheet.shiftRows(startRow, endRow, n); - - Workbook read = _testDataProvider.writeOutAndReadBack(wb); - wb.close(); - - Sheet sh = read.getSheet("test"); - - Row shiftedRow = sh.getRow(3); - - // document link anchored on a shifted cell should be moved - // Note that hyperlinks do not track what they point to, so this hyperlink should still refer to test!E1 - verifyHyperlink(shiftedRow.getCell(0), HyperlinkType.DOCUMENT, "test!E1"); - - // URL, EMAIL, and FILE links anchored on a shifted cell should be moved - verifyHyperlink(shiftedRow.getCell(1), HyperlinkType.URL, "https://poi.apache.org/"); - - // Make sure hyperlinks were moved and not copied - assertNull(sh.getHyperlink(0, 0), "Document hyperlink should be moved, not copied"); - assertNull(sh.getHyperlink(0, 1), "URL hyperlink should be moved, not copied"); - - // Make sure hyperlink in overwritten row is deleted - assertEquals(3, sh.getHyperlinkList().size()); - CellAddress unexpectedLinkAddress = new CellAddress("C4"); - for (Hyperlink link : sh.getHyperlinkList()) { - final CellAddress linkAddress = new CellAddress(link.getFirstRow(), link.getFirstColumn()); - assertNotEquals(linkAddress, unexpectedLinkAddress, - "Row 4, including the hyperlink at C4, should have " + - "been deleted when Row 1 was shifted on top of it."); - } - - // Make sure unaffected rows are not shifted - Cell unaffectedCell = sh.getRow(20).getCell(3); - assertTrue(cellHasHyperlink(unaffectedCell)); - verifyHyperlink(unaffectedCell, HyperlinkType.FILE, "54524.xlsx"); - - // Make sure cells on other sheets are not affected - unaffectedCell = read.getSheet("other").getRow(0).getCell(0); - assertTrue(cellHasHyperlink(unaffectedCell)); - verifyHyperlink(unaffectedCell, HyperlinkType.URL, "http://apache.org/"); - - read.close(); - } - - //@Disabled("bug 56454: Incorrectly handles merged regions that do not contain column 0") - @Test - void shiftRowsWithMergedRegionsThatDoNotContainColumnZero() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - - // populate sheet cells - for (int i = 0; i < 10; i++) { - Row row = sheet.createRow(i); - for (int j = 0; j < 12; j++) { - Cell cell = row.createCell(j); - cell.setCellValue(i + "x" + j); - } - } - - CellRangeAddress A4_B7 = new CellRangeAddress(3, 6, 0, 1); - CellRangeAddress C5_D7 = new CellRangeAddress(4, 6, 2, 3); - - assertEquals(0, sheet.addMergedRegion(A4_B7)); - assertEquals(1, sheet.addMergedRegion(C5_D7)); - - // A4:B7 will elongate vertically - // C5:D7 will be shifted down with same size - sheet.shiftRows(4, sheet.getLastRowNum(), 1); - - // This test is written as expected-to-fail and should be rewritten - // as expected-to-pass when the bug is fixed. - // FIXME: remove try, catch, and testPassesNow, skipTest when test passes - try { - assertEquals(2, sheet.getNumMergedRegions()); - assertEquals(CellRangeAddress.valueOf("A4:B8"), sheet.getMergedRegion(0)); - assertEquals(CellRangeAddress.valueOf("C5:D8"), sheet.getMergedRegion(1)); - testPassesNow(56454); - } catch (AssertionError e) { - skipTest(e); - } - - wb.close(); - } - - @Test - void shiftMergedRowsToMergedRowsUp() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - populateSheetCells(sheet, 2); - - - CellRangeAddress A1_E1 = new CellRangeAddress(0, 0, 0, 4); - CellRangeAddress A2_C2 = new CellRangeAddress(1, 1, 0, 2); - - assertEquals(0, sheet.addMergedRegion(A1_E1)); - assertEquals(1, sheet.addMergedRegion(A2_C2)); - - // A1:E1 should be removed - // A2:C2 will be A1:C1 - sheet.shiftRows(1, sheet.getLastRowNum(), -1); - - assertEquals(1, sheet.getNumMergedRegions()); - assertEquals(CellRangeAddress.valueOf("A1:C1"), sheet.getMergedRegion(0)); - - wb.close(); - } - - @Test - void shiftMergedRowsToMergedRowsOverlappingMergedRegion() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - populateSheetCells(sheet, 10); - - CellRangeAddress A1_E1 = new CellRangeAddress(0, 0, 0, 4); - CellRangeAddress A2_C2 = new CellRangeAddress(1, 7, 0, 2); - - assertEquals(0, sheet.addMergedRegion(A1_E1)); - assertEquals(1, sheet.addMergedRegion(A2_C2)); - - // A1:E1 should move to A5:E5 - // A2:C2 should be removed - sheet.shiftRows(0, 0, 4); - - assertEquals(1, sheet.getNumMergedRegions()); - assertEquals(CellRangeAddress.valueOf("A5:E5"), sheet.getMergedRegion(0)); - - wb.close(); - } - - @Test - void bug60384ShiftMergedRegion() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - populateSheetCells(sheet, 9); - - - CellRangeAddress A8_E8 = new CellRangeAddress(7, 7, 0, 4); - CellRangeAddress A9_C9 = new CellRangeAddress(8, 8, 0, 2); - - assertEquals(0, sheet.addMergedRegion(A8_E8)); - assertEquals(1, sheet.addMergedRegion(A9_C9)); - - // A1:E1 should be removed - // A2:C2 will be A1:C1 - sheet.shiftRows(3, sheet.getLastRowNum(), 1); - - assertEquals(2, sheet.getNumMergedRegions()); - assertEquals(CellRangeAddress.valueOf("A9:E9"), sheet.getMergedRegion(0)); - assertEquals(CellRangeAddress.valueOf("A10:C10"), sheet.getMergedRegion(1)); - - wb.close(); - } - - private void populateSheetCells(Sheet sheet, int rowCount) { - // populate sheet cells - for (int i = 0; i < rowCount; i++) { - Row row = sheet.createRow(i); - for (int j = 0; j < 5; j++) { - Cell cell = row.createCell(j); - cell.setCellValue(i + "x" + j); - } - } - } - - @Test - void shiftMergedRowsToMergedRowsDown() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - - // populate sheet cells - populateSheetCells(sheet, 2); - - CellRangeAddress A1_E1 = new CellRangeAddress(0, 0, 0, 4); - CellRangeAddress A2_C2 = new CellRangeAddress(1, 1, 0, 2); - - assertEquals(0, sheet.addMergedRegion(A1_E1)); - assertEquals(1, sheet.addMergedRegion(A2_C2)); - - // A1:E1 should be moved to A2:E2 - // A2:C2 will be removed - sheet.shiftRows(0, 0, 1); - - assertEquals(1, sheet.getNumMergedRegions()); - assertEquals(CellRangeAddress.valueOf("A2:E2"), sheet.getMergedRegion(0)); - - wb.close(); - } - - @Test - void test61840_shifting_rows_up_does_not_produce_REF_errors() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Cell cell = sheet.createRow(4).createCell(0); - - cell.setCellFormula("(B5-C5)/B5"); - sheet.shiftRows(4, 4, -1); - - // Cell objects created before a row shift are still valid. - // The row number of those cell references will be shifted if - // the cell is within the shift range. - assertEquals("(B4-C4)/B4", cell.getCellFormula()); - - // New cell references are also valid. - Cell shiftedCell = sheet.getRow(3).getCell(0); - assertNotNull(shiftedCell); - assertEquals("(B4-C4)/B4", shiftedCell.getCellFormula()); - - wb.close(); - } - - - @Test - void checkMergedRegions56454() { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - // populate sheet cells - for (int i = 0; i < 10; i++) { - Row row = sheet.createRow(i); - - for (int j = 0; j < 10; j++) { - Cell cell = row.createCell(j, CellType.STRING); - - cell.setCellValue(i + "x" + j); - } - } - - CellRangeAddress region1 = new CellRangeAddress(3, 6, 0, 1); - CellRangeAddress region2 = new CellRangeAddress(3, 6, 2, 3); - - sheet.addMergedRegion(region1); - sheet.addMergedRegion(region2); - - sheet.shiftRows(4, sheet.getLastRowNum(), 1); - - // check, if all regions still start at row 3 - for (int i = 0; i < sheet.getNumMergedRegions(); i++) { - CellRangeAddress cr = sheet.getMergedRegion(i); - - assertEquals(cr.getFirstRow(), 3); - } - } - - - - - private void createHyperlink(CreationHelper helper, Cell cell, HyperlinkType linkType, String ref) { - cell.setCellValue(ref); - Hyperlink link = helper.createHyperlink(linkType); - link.setAddress(ref); - cell.setHyperlink(link); - } - - private void verifyHyperlink(Cell cell, HyperlinkType linkType, String ref) { - assertTrue(cellHasHyperlink(cell)); - Hyperlink link = cell.getHyperlink(); - assertEquals(linkType, link.getType()); - assertEquals(ref, link.getAddress()); - } - - private boolean cellHasHyperlink(Cell cell) { - return (cell != null) && (cell.getHyperlink() != null); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetUpdateArrayFormulas.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetUpdateArrayFormulas.java deleted file mode 100644 index 8f67877635..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetUpdateArrayFormulas.java +++ /dev/null @@ -1,543 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * Common superclass for testing usermodel API for array formulas.
- * Formula evaluation is not tested here. - */ -public abstract class BaseTestSheetUpdateArrayFormulas { - protected final ITestDataProvider _testDataProvider; - - protected BaseTestSheetUpdateArrayFormulas(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public final void testAutoCreateOtherCells() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet("Sheet1"); - - Row row1 = sheet.createRow(0); - Cell cellA1 = row1.createCell(0); - Cell cellB1 = row1.createCell(1); - String formula = "42"; - sheet.setArrayFormula(formula, CellRangeAddress.valueOf("A1:B2")); - - assertEquals(formula, cellA1.getCellFormula()); - assertEquals(formula, cellB1.getCellFormula()); - Row row2 = sheet.getRow(1); - assertNotNull(row2); - assertEquals(formula, row2.getCell(0).getCellFormula()); - assertEquals(formula, row2.getCell(1).getCellFormula()); - } - } - - /** - * Set single-cell array formula - */ - @Test - public final void testSetArrayFormula_singleCell() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - Cell cell = sheet.createRow(0).createCell(0); - assertFalse(cell.isPartOfArrayFormulaGroup()); - IllegalStateException e = assertThrows(IllegalStateException.class, cell::getArrayFormulaRange); - assertEquals("Cell Sheet0!A1 is not part of an array formula.", e.getMessage()); - - // row 3 does not yet exist - assertNull(sheet.getRow(2)); - CellRangeAddress range = new CellRangeAddress(2, 2, 2, 2); - Cell[] cells = sheet.setArrayFormula("SUM(C11:C12*D11:D12)", range).getFlattenedCells(); - assertEquals(1, cells.length); - // sheet.setArrayFormula creates rows and cells for the designated range - assertNotNull(sheet.getRow(2)); - cell = sheet.getRow(2).getCell(2); - assertNotNull(cell); - - assertTrue(cell.isPartOfArrayFormulaGroup()); - //retrieve the range and check it is the same - assertEquals(range.formatAsString(), cell.getArrayFormulaRange().formatAsString()); - //check the formula - assertEquals("SUM(C11:C12*D11:D12)", cell.getCellFormula()); - } - } - - /** - * Set multi-cell array formula - */ - @Test - public final void testSetArrayFormula_multiCell() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - - // multi-cell formula - // rows 3-5 don't exist yet - assertNull(sheet.getRow(3)); - assertNull(sheet.getRow(4)); - assertNull(sheet.getRow(5)); - - CellRangeAddress range = CellRangeAddress.valueOf("C4:C6"); - Cell[] cells = sheet.setArrayFormula("SUM(A1:A3*B1:B3)", range).getFlattenedCells(); - assertEquals(3, cells.length); - - // sheet.setArrayFormula creates rows and cells for the designated range - assertSame(cells[0], sheet.getRow(3).getCell(2)); - assertSame(cells[1], sheet.getRow(4).getCell(2)); - assertSame(cells[2], sheet.getRow(5).getCell(2)); - - for (Cell acell : cells) { - assertTrue(acell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, acell.getCellType()); - assertEquals("SUM(A1:A3*B1:B3)", acell.getCellFormula()); - //retrieve the range and check it is the same - assertEquals(range.formatAsString(), acell.getArrayFormulaRange().formatAsString()); - } - } - } - - /** - * Passing an incorrect formula to sheet.setArrayFormula - * should throw FormulaParseException - */ - @Test - public final void testSetArrayFormula_incorrectFormula() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - CellRangeAddress cra = new CellRangeAddress(10, 10, 10, 10); - assertThrows(FormulaParseException.class, () -> sheet.setArrayFormula("incorrect-formula(C11_C12*D11_D12)", cra)); - } - } - - /** - * Calls of cell.getArrayFormulaRange and sheet.removeArrayFormula - * on a not-array-formula cell throw IllegalStateException - */ - @Test - public final void testArrayFormulas_illegalCalls() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - - Cell cell = sheet.createRow(0).createCell(0); - assertFalse(cell.isPartOfArrayFormulaGroup()); - IllegalStateException e = assertThrows(IllegalStateException.class, cell::getArrayFormulaRange); - assertEquals("Cell Sheet0!A1 is not part of an array formula.", e.getMessage()); - - IllegalArgumentException e2 = assertThrows(IllegalArgumentException.class, () -> sheet.removeArrayFormula(cell)); - assertEquals("Cell Sheet0!A1 is not part of an array formula.", e.getMessage()); - } - } - - /** - * create and remove array formulas - */ - @Test - public final void testRemoveArrayFormula() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - - CellRangeAddress range = new CellRangeAddress(3, 5, 2, 2); - assertEquals("C4:C6", range.formatAsString()); - CellRange cr = sheet.setArrayFormula("SUM(A1:A3*B1:B3)", range); - assertEquals(3, cr.size()); - - // remove the formula cells in C4:C6 - CellRange dcells = sheet.removeArrayFormula(cr.getTopLeftCell()); - // removeArrayFormula should return the same cells as setArrayFormula - assertArrayEquals(cr.getFlattenedCells(), dcells.getFlattenedCells()); - - for (Cell acell : cr) { - assertFalse(acell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.BLANK, acell.getCellType()); - } - - // cells C4:C6 are not included in array formula, - // invocation of sheet.removeArrayFormula on any of them throws IllegalArgumentException - for (Cell acell : cr) { - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> sheet.removeArrayFormula(acell)); - String ref = new CellReference(acell).formatAsString(); - assertEquals("Cell " + ref + " is not part of an array formula.", e.getMessage()); - } - } - } - - /** - * Test that when reading a workbook from input stream, array formulas are recognized - */ - @Test - public final void testReadArrayFormula() throws IOException { - try (Workbook workbook1 = _testDataProvider.createWorkbook()) { - Sheet sheet1 = workbook1.createSheet(); - Cell[] cells = sheet1.setArrayFormula("SUM(A1:A3*B1:B3)", CellRangeAddress.valueOf("C4:C6")).getFlattenedCells(); - assertEquals(3, cells.length); - - cells = sheet1.setArrayFormula("MAX(A1:A3*B1:B3)", CellRangeAddress.valueOf("A4:A6")).getFlattenedCells(); - assertEquals(3, cells.length); - - Sheet sheet2 = workbook1.createSheet(); - cells = sheet2.setArrayFormula("MIN(A1:A3*B1:B3)", CellRangeAddress.valueOf("D2:D4")).getFlattenedCells(); - assertEquals(3, cells.length); - - try (Workbook workbook2 = _testDataProvider.writeOutAndReadBack(workbook1)) { - sheet1 = workbook2.getSheetAt(0); - for (int rownum = 3; rownum <= 5; rownum++) { - Cell cell1 = sheet1.getRow(rownum).getCell(2); - assertTrue(cell1.isPartOfArrayFormulaGroup()); - - Cell cell2 = sheet1.getRow(rownum).getCell(0); - assertTrue(cell2.isPartOfArrayFormulaGroup()); - } - - sheet2 = workbook2.getSheetAt(1); - for (int rownum = 1; rownum <= 3; rownum++) { - Cell cell1 = sheet2.getRow(rownum).getCell(3); - assertTrue(cell1.isPartOfArrayFormulaGroup()); - } - } - } - } - - /** - * Test that we can set pre-calculated formula result for array formulas - */ - @Test - void testModifyArrayCells_setFormulaResult() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - - //single-cell array formula - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5")); - Cell scell = srange.getTopLeftCell(); - assertEquals(CellType.FORMULA, scell.getCellType()); - assertEquals(0.0, scell.getNumericCellValue(), 0); - scell.setCellValue(1.1); - assertEquals(1.1, scell.getNumericCellValue(), 0); - - //multi-cell array formula - CellRange mrange = - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - for (Cell mcell : mrange) { - assertEquals(CellType.FORMULA, mcell.getCellType()); - assertEquals(0.0, mcell.getNumericCellValue(), 0); - double fmlaResult = 1.2; - mcell.setCellValue(fmlaResult); - assertEquals(fmlaResult, mcell.getNumericCellValue(), 0); - } - } - } - - @Test - void testModifyArrayCells_setCellType() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - - // single-cell array formulas behave just like normal cells - - // changing cell type removes the array formula and associated cached result - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5")); - Cell scell = srange.getTopLeftCell(); - assertEquals(CellType.FORMULA, scell.getCellType()); - assertEquals(0.0, scell.getNumericCellValue(), 0); - scell.setCellType(CellType.STRING); - assertEquals(CellType.STRING, scell.getCellType()); - scell.setCellValue("string cell"); - assertEquals("string cell", scell.getStringCellValue()); - - //once you create a multi-cell array formula, you cannot change the type of its cells - CellRange mrange = - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - for (Cell mcell : mrange) { - assertEquals(CellType.FORMULA, mcell.getCellType()); - IllegalStateException e = assertThrows(IllegalStateException.class, () -> mcell.setCellType(CellType.NUMERIC)); - CellReference ref = new CellReference(mcell); - String msg = "Cell " + ref.formatAsString() + " is part of a multi-cell array formula. You cannot change part of an array."; - assertEquals(msg, e.getMessage()); - - // a failed invocation of Cell.setCellType leaves the cell - // in the state that it was in prior to the invocation - assertEquals(CellType.FORMULA, mcell.getCellType()); - assertTrue(mcell.isPartOfArrayFormulaGroup()); - } - } - } - - @Test - void testModifyArrayCells_setCellFormula() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5")); - Cell scell = srange.getTopLeftCell(); - assertEquals("SUM(A4:A6,B4:B6)", scell.getCellFormula()); - assertEquals(CellType.FORMULA, scell.getCellType()); - assertTrue(scell.isPartOfArrayFormulaGroup()); - scell.setCellFormula("SUM(A4,A6)"); - //we are now a normal formula cell - assertEquals("SUM(A4,A6)", scell.getCellFormula()); - assertFalse(scell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, scell.getCellType()); - //check that setting formula result works - assertEquals(0.0, scell.getNumericCellValue(), 0); - scell.setCellValue(33.0); - assertEquals(33.0, scell.getNumericCellValue(), 0); - - //multi-cell array formula - CellRange mrange = - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - for (Cell mcell : mrange) { - //we cannot set individual formulas for cells included in an array formula - assertEquals("A1:A3*B1:B3", mcell.getCellFormula()); - IllegalStateException e = assertThrows(IllegalStateException.class, () -> mcell.setCellFormula("A1+A2")); - CellReference ref = new CellReference(mcell); - String msg = "Cell " + ref.formatAsString() + " is part of a multi-cell array formula. You cannot change part of an array."; - assertEquals(msg, e.getMessage()); - - // a failed invocation of Cell.setCellFormula leaves the cell - // in the state that it was in prior to the invocation - assertEquals("A1:A3*B1:B3", mcell.getCellFormula()); - assertTrue(mcell.isPartOfArrayFormulaGroup()); - } - } - } - - @Test - void testModifyArrayCells_removeCell() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - - //single-cell array formulas behave just like normal cells - CellRangeAddress cra = CellRangeAddress.valueOf("B5"); - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", cra); - Cell scell = srange.getTopLeftCell(); - - Row srow = sheet.getRow(cra.getFirstRow()); - assertSame(srow, scell.getRow()); - srow.removeCell(scell); - assertNull(srow.getCell(cra.getFirstColumn())); - - //re-create the removed cell - scell = srow.createCell(cra.getFirstColumn()); - assertEquals(CellType.BLANK, scell.getCellType()); - assertFalse(scell.isPartOfArrayFormulaGroup()); - - //we cannot remove cells included in a multi-cell array formula - CellRange mrange = - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - for (Cell mcell : mrange) { - int columnIndex = mcell.getColumnIndex(); - Row mrow = mcell.getRow(); - IllegalStateException e = assertThrows(IllegalStateException.class, () -> mrow.removeCell(mcell)); - CellReference ref = new CellReference(mcell); - String msg = "Cell " + ref.formatAsString() + " is part of a multi-cell array formula. You cannot change part of an array."; - assertEquals(msg, e.getMessage()); - - // a failed invocation of Row.removeCell leaves the row - // in the state that it was in prior to the invocation - assertSame(mcell, mrow.getCell(columnIndex)); - assertTrue(mcell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, mcell.getCellType()); - } - - } - } - - @Test - void testModifyArrayCells_removeRow() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - - //single-cell array formulas behave just like normal cells - CellRangeAddress cra = CellRangeAddress.valueOf("B5"); - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", cra); - Cell scell = srange.getTopLeftCell(); - assertEquals(CellType.FORMULA, scell.getCellType()); - - Row srow = scell.getRow(); - assertSame(srow, sheet.getRow(cra.getFirstRow())); - sheet.removeRow(srow); - assertNull(sheet.getRow(cra.getFirstRow())); - - //re-create the removed row and cell - scell = sheet.createRow(cra.getFirstRow()).createCell(cra.getFirstColumn()); - assertEquals(CellType.BLANK, scell.getCellType()); - assertFalse(scell.isPartOfArrayFormulaGroup()); - - //we cannot remove rows with cells included in a multi-cell array formula - CellRange mrange = - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - for (Cell mcell : mrange) { - int columnIndex = mcell.getColumnIndex(); - Row mrow = mcell.getRow(); - assertThrows(IllegalStateException.class, () -> sheet.removeRow(mrow)); - // String msg = "Row[rownum="+mrow.getRowNum()+"] contains cell(s) included in a multi-cell array formula. You cannot change part of an array."; - // assertEquals(msg, e.getMessage()); - - // a failed invocation of Row.removeCell leaves the row - // in the state that it was in prior to the invocation - assertSame(mrow, sheet.getRow(mrow.getRowNum())); - assertSame(mcell, mrow.getCell(columnIndex)); - assertTrue(mcell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, mcell.getCellType()); - } - } - } - - @Test - void testModifyArrayCells_mergeCellsSingle() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - assertEquals(0, sheet.getNumMergedRegions()); - - //single-cell array formulas behave just like normal cells - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5")); - Cell scell = srange.getTopLeftCell(); - assertEquals(0, sheet.addMergedRegion(CellRangeAddress.valueOf("B5:C6"))); - //we are still an array formula - assertEquals(CellType.FORMULA, scell.getCellType()); - assertTrue(scell.isPartOfArrayFormulaGroup()); - assertEquals(1, sheet.getNumMergedRegions()); - } - } - - @Test - void testModifyArrayCells_mergeCellsMulti() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - int expectedNumMergedRegions = 0; - assertEquals(expectedNumMergedRegions, sheet.getNumMergedRegions()); - - // we cannot merge cells included in an array formula - sheet.setArrayFormula("A1:A4*B1:B4", CellRangeAddress.valueOf("C2:F5")); - for (String ref : Arrays.asList( - "C2:F5", // identity - "D3:E4", "B1:G6", // contains - "B1:C2", "F1:G2", "F5:G6", "B5:C6", // 1x1 corner intersection - "B1:C6", "B1:G2", "F1:G6", "B5:G6", // 1-row/1-column intersection - "B1:D3", "E1:G3", "E4:G6", "B4:D6", // 2x2 corner intersection - "B1:D6", "B1:G3", "E1:G6", "B4:G6" // 2-row/2-column intersection - )) { - CellRangeAddress cra = CellRangeAddress.valueOf(ref); - IllegalStateException e = assertThrows(IllegalStateException.class, () -> sheet.addMergedRegion(cra)); - String msg = "The range " + cra.formatAsString() + " intersects with a multi-cell array formula. You cannot merge cells of an array."; - assertEquals(msg, e.getMessage()); - } - //the number of merged regions remains the same - assertEquals(expectedNumMergedRegions, sheet.getNumMergedRegions()); - - // we can merge non-intersecting cells - for (String ref : Arrays.asList( - "C1:F1", //above - "G2:G5", //right - "C6:F6", //bottom - "B2:B5", "H7:J9")) { - CellRangeAddress cra = CellRangeAddress.valueOf(ref); - sheet.addMergedRegion(cra); - expectedNumMergedRegions++; - assertEquals(expectedNumMergedRegions, sheet.getNumMergedRegions()); - } - - } - } - - @Test - void testModifyArrayCells_shiftRows() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - - //single-cell array formulas behave just like normal cells - we can change the cell type - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5")); - Cell scell = srange.getTopLeftCell(); - assertEquals("SUM(A4:A6,B4:B6)", scell.getCellFormula()); - sheet.shiftRows(0, 0, 1); - sheet.shiftRows(0, 1, 1); - - //we cannot set individual formulas for cells included in an array formula - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - IllegalStateException e = assertThrows(IllegalStateException.class, () -> sheet.shiftRows(0, 0, 1)); - String msg = "Row[rownum=0] contains cell(s) included in a multi-cell array formula. You cannot change part of an array."; - assertEquals(msg, e.getMessage()); - /* - TODO: enable shifting the whole array - - sheet.shiftRows(0, 2, 1); - //the array C1:C3 is now C2:C4 - CellRangeAddress cra = CellRangeAddress.valueOf("C2:C4"); - for(Cell mcell : mrange){ - //TODO define equals and hashcode for CellRangeAddress - assertEquals(cra.formatAsString(), mcell.getArrayFormulaRange().formatAsString()); - assertEquals("A2:A4*B2:B4", mcell.getCellFormula()); - assertTrue(mcell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, mcell.getCellType()); - } - - */ - } - } - - @Disabled("See bug 59728") - @Test - void shouldNotBeAbleToCreateArrayFormulaOnPreexistingMergedRegion() throws IOException { - /* - * m = merged region - * f = array formula - * fm = cell belongs to a merged region and an array formula (illegal, that's what this tests for) - * - * A B C - * 1 f f - * 2 fm fm - * 3 f f - */ - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - - CellRangeAddress mergedRegion = CellRangeAddress.valueOf("B2:C2"); - assertEquals(0, sheet.addMergedRegion(mergedRegion)); - CellRangeAddress arrayFormula = CellRangeAddress.valueOf("C1:C3"); - assumeTrue(mergedRegion.intersects(arrayFormula)); - assumeTrue(arrayFormula.intersects(mergedRegion)); - // expected exception: should not be able to create an array formula that intersects with a merged region - assertThrows(IllegalStateException.class, () -> sheet.setArrayFormula("SUM(A1:A3)", arrayFormula)); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java deleted file mode 100644 index 11bb3c9357..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java +++ /dev/null @@ -1,909 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ConcurrentModificationException; -import java.util.Iterator; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.NullOutputStream; -import org.junit.jupiter.api.Test; - -public abstract class BaseTestWorkbook { - - protected final ITestDataProvider _testDataProvider; - - protected BaseTestWorkbook(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - void sheetIterator_forEach() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - wb.createSheet("Sheet0"); - wb.createSheet("Sheet1"); - wb.createSheet("Sheet2"); - int i = 0; - for (Sheet sh : wb) { - assertEquals("Sheet" + i, sh.getSheetName()); - i++; - } - } - } - - /** - * Expected ConcurrentModificationException: - * should not be able to advance an iterator when the - * underlying data has been reordered - */ - @Test - void sheetIterator_sheetsReordered() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - wb.createSheet("Sheet0"); - wb.createSheet("Sheet1"); - wb.createSheet("Sheet2"); - - Iterator it = wb.sheetIterator(); - it.next(); - wb.setSheetOrder("Sheet2", 1); - - // Iterator order should be fixed when iterator is created - assertThrows(ConcurrentModificationException.class, it::next); - } - } - - /** - * Expected ConcurrentModificationException: - * should not be able to advance an iterator when the - * underlying data has been reordered - */ - @Test - void sheetIterator_sheetRemoved() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - wb.createSheet("Sheet0"); - wb.createSheet("Sheet1"); - wb.createSheet("Sheet2"); - - Iterator it = wb.sheetIterator(); - wb.removeSheetAt(1); - - // Iterator order should be fixed when iterator is created - assertThrows(ConcurrentModificationException.class, it::next); - } - } - - /** - * Expected UnsupportedOperationException: - * should not be able to remove sheets from the sheet iterator - */ - @Test - void sheetIterator_remove() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - wb.createSheet("Sheet0"); - - Iterator it = wb.sheetIterator(); - it.next(); //Sheet0 - assertThrows(UnsupportedOperationException.class, it::remove); - } - } - - - @Test - void createSheet() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - assertEquals(0, wb.getNumberOfSheets()); - - //getting a sheet by invalid index or non-existing name - assertNull(wb.getSheet("Sheet1")); - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> wb.getSheetAt(0), - "should have thrown exception due to invalid sheet index" - ); - // expected during successful test no negative index in the range message - assertFalse(ex.getMessage().contains("-1")); - - assertThrows(IllegalArgumentException.class, () -> wb.getSheetAt(0)); - - Sheet sheet0 = wb.createSheet(); - Sheet sheet1 = wb.createSheet(); - assertEquals("Sheet0", sheet0.getSheetName()); - assertEquals("Sheet1", sheet1.getSheetName()); - assertEquals(2, wb.getNumberOfSheets()); - - //fetching sheets by name is case-insensitive - Sheet originalSheet = wb.createSheet("Sheet3"); - Sheet fetchedSheet = wb.getSheet("sheet3"); - assertNotNull(fetchedSheet, "Identified bug 44892"); - - assertEquals("Sheet3", fetchedSheet.getSheetName()); - assertEquals(3, wb.getNumberOfSheets()); - assertSame(originalSheet, fetchedSheet); - ex = assertThrows( - IllegalArgumentException.class, - () -> wb.createSheet("sHeeT3"), - "should have thrown exception due to duplicate sheet name" - ); - // expected during successful test - assertEquals("The workbook already contains a sheet named 'sHeeT3'", ex.getMessage()); - - //names cannot be blank or contain any of /\*?[] - String[] invalidNames = {"", "Sheet/", "Sheet\\", - "Sheet?", "Sheet*", "Sheet[", "Sheet]", "'Sheet'", - "My:Sheet"}; - for (String sheetName : invalidNames) { - assertThrows( - IllegalArgumentException.class, - () -> wb.createSheet(sheetName), - "should have thrown exception due to invalid sheet name: " + sheetName - ); - } - //still have 3 sheets - assertEquals(3, wb.getNumberOfSheets()); - - //change the name of the 3rd sheet - wb.setSheetName(2, "I changed!"); - - //try to assign an invalid name to the 2nd sheet - assertThrows(IllegalArgumentException.class, () -> wb.setSheetName(1, "[I'm invalid]")); - - //try to assign an invalid name to the 2nd sheet - assertThrows(IllegalArgumentException.class, () -> wb.createSheet(null)); - - assertThrows(IllegalArgumentException.class, () -> wb.setSheetName(2, null)); - - //check - assertEquals(0, wb.getSheetIndex("sheet0")); - assertEquals(1, wb.getSheetIndex("sheet1")); - assertEquals(2, wb.getSheetIndex("I changed!")); - - assertSame(sheet0, wb.getSheet("sheet0")); - assertSame(sheet1, wb.getSheet("sheet1")); - assertSame(originalSheet, wb.getSheet("I changed!")); - assertNull(wb.getSheet("unknown")); - - //serialize and read again - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb)) { - assertEquals(3, wb2.getNumberOfSheets()); - assertEquals(0, wb2.getSheetIndex("sheet0")); - assertEquals(1, wb2.getSheetIndex("sheet1")); - assertEquals(2, wb2.getSheetIndex("I changed!")); - } - } - } - - /** - * POI allows creating sheets with names longer than 31 characters. - * - * Excel opens files with long sheet names without error or warning. - * However, long sheet names are silently truncated to 31 chars. In order to - * avoid funny duplicate sheet name errors, POI enforces uniqueness on only the first 31 chars. - * but for the purpose of uniqueness long sheet names are silently truncated to 31 chars. - */ - @Test - void createSheetWithLongNames() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - - String sheetName1 = "My very long sheet name which is longer than 31 chars"; - String truncatedSheetName1 = sheetName1.substring(0, 31); - Sheet sh1 = wb1.createSheet(sheetName1); - assertEquals(truncatedSheetName1, sh1.getSheetName()); - assertSame(sh1, wb1.getSheet(truncatedSheetName1)); - // now via wb.setSheetName - wb1.setSheetName(0, sheetName1); - assertEquals(truncatedSheetName1, sh1.getSheetName()); - assertSame(sh1, wb1.getSheet(truncatedSheetName1)); - - String sheetName2 = "My very long sheet name which is longer than 31 chars " + - "and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)"; - - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> wb1.createSheet(sheetName2)); - assertEquals("The workbook already contains a sheet named 'My very long sheet name which is longer than 31 chars and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)'", e.getMessage()); - - String sheetName3 = "POI allows creating sheets with names longer than 31 characters"; - String truncatedSheetName3 = sheetName3.substring(0, 31); - Sheet sh3 = wb1.createSheet(sheetName3); - assertEquals(truncatedSheetName3, sh3.getSheetName()); - assertSame(sh3, wb1.getSheet(truncatedSheetName3)); - - //serialize and read again - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - assertEquals(2, wb2.getNumberOfSheets()); - assertEquals(0, wb2.getSheetIndex(truncatedSheetName1)); - assertEquals(1, wb2.getSheetIndex(truncatedSheetName3)); - } - } - } - - @Test - void removeSheetAt() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - workbook.createSheet("sheet1"); - workbook.createSheet("sheet2"); - workbook.createSheet("sheet3"); - assertEquals(3, workbook.getNumberOfSheets()); - - assertEquals(0, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(1); - assertEquals(2, workbook.getNumberOfSheets()); - assertEquals("sheet3", workbook.getSheetName(1)); - assertEquals(0, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(0); - assertEquals(1, workbook.getNumberOfSheets()); - assertEquals("sheet3", workbook.getSheetName(0)); - assertEquals(0, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(0); - assertEquals(0, workbook.getNumberOfSheets()); - assertEquals(0, workbook.getActiveSheetIndex()); - - //re-create the sheets - workbook.createSheet("sheet1"); - workbook.createSheet("sheet2"); - workbook.createSheet("sheet3"); - workbook.createSheet("sheet4"); - assertEquals(4, workbook.getNumberOfSheets()); - - assertEquals(0, workbook.getActiveSheetIndex()); - workbook.setActiveSheet(2); - assertEquals(2, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(2); - assertEquals(2, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(1); - assertEquals(1, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(0); - assertEquals(0, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(0); - assertEquals(0, workbook.getActiveSheetIndex()); - } - } - - @Test - void testSetActiveCell() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("new sheet"); - final CellAddress initialActiveCell = sheet.getActiveCell(); - assertTrue(initialActiveCell == null || new CellAddress("A1").equals(initialActiveCell)); - sheet.setActiveCell(new CellAddress("E11")); - assertEquals(new CellAddress("E11"), sheet.getActiveCell()); - - Workbook wbr = _testDataProvider.writeOutAndReadBack(wb); - sheet = wbr.getSheet("new sheet"); - assertEquals(new CellAddress("E11"), sheet.getActiveCell()); - } - } - - @Test - void defaultValues() throws IOException { - try (Workbook b = _testDataProvider.createWorkbook()) { - assertEquals(0, b.getActiveSheetIndex()); - assertEquals(0, b.getFirstVisibleTab()); - assertEquals(0, b.getNumberOfNames()); - assertEquals(0, b.getNumberOfSheets()); - } - } - - @Test - void sheetSelection() throws IOException { - try (Workbook b = _testDataProvider.createWorkbook()) { - b.createSheet("Sheet One"); - b.createSheet("Sheet Two"); - b.setActiveSheet(1); - b.setSelectedTab(1); - b.setFirstVisibleTab(1); - assertEquals(1, b.getActiveSheetIndex()); - assertEquals(1, b.getFirstVisibleTab()); - } - } - - @Test - void printArea() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet1 = workbook.createSheet("Test Print Area"); - String sheetName1 = sheet1.getSheetName(); - - // workbook.setPrintArea(0, reference); - workbook.setPrintArea(0, 1, 5, 4, 9); - String retrievedPrintArea = workbook.getPrintArea(0); - assertEquals("'" + sheetName1 + "'!$B$5:$F$10", retrievedPrintArea); - - String reference = "$A$1:$B$1"; - workbook.setPrintArea(0, reference); - retrievedPrintArea = workbook.getPrintArea(0); - assertEquals("'" + sheetName1 + "'!" + reference, retrievedPrintArea); - - workbook.removePrintArea(0); - assertNull(workbook.getPrintArea(0)); - } - } - - @Test - void getSetActiveSheet() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - assertEquals(0, workbook.getActiveSheetIndex()); - - workbook.createSheet("sheet1"); - workbook.createSheet("sheet2"); - workbook.createSheet("sheet3"); - // set second sheet - workbook.setActiveSheet(1); - // test if second sheet is set up - assertEquals(1, workbook.getActiveSheetIndex()); - - workbook.setActiveSheet(0); - // test if second sheet is set up - assertEquals(0, workbook.getActiveSheetIndex()); - } - } - - @Test - void setSheetOrder() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - - for (int i = 0; i < 10; i++) { - wb.createSheet("Sheet " + i); - } - - // Check the initial order - assertEquals(0, wb.getSheetIndex("Sheet 0")); - assertEquals(1, wb.getSheetIndex("Sheet 1")); - assertEquals(2, wb.getSheetIndex("Sheet 2")); - assertEquals(3, wb.getSheetIndex("Sheet 3")); - assertEquals(4, wb.getSheetIndex("Sheet 4")); - assertEquals(5, wb.getSheetIndex("Sheet 5")); - assertEquals(6, wb.getSheetIndex("Sheet 6")); - assertEquals(7, wb.getSheetIndex("Sheet 7")); - assertEquals(8, wb.getSheetIndex("Sheet 8")); - assertEquals(9, wb.getSheetIndex("Sheet 9")); - - // check active sheet - assertEquals(0, wb.getActiveSheetIndex()); - - // Change - wb.setSheetOrder("Sheet 6", 0); - assertEquals(1, wb.getActiveSheetIndex()); - wb.setSheetOrder("Sheet 3", 7); - wb.setSheetOrder("Sheet 1", 9); - - // now the first sheet is at index 1 - assertEquals(1, wb.getActiveSheetIndex()); - - // Check they're currently right - assertEquals(0, wb.getSheetIndex("Sheet 6")); - assertEquals(1, wb.getSheetIndex("Sheet 0")); - assertEquals(2, wb.getSheetIndex("Sheet 2")); - assertEquals(3, wb.getSheetIndex("Sheet 4")); - assertEquals(4, wb.getSheetIndex("Sheet 5")); - assertEquals(5, wb.getSheetIndex("Sheet 7")); - assertEquals(6, wb.getSheetIndex("Sheet 3")); - assertEquals(7, wb.getSheetIndex("Sheet 8")); - assertEquals(8, wb.getSheetIndex("Sheet 9")); - assertEquals(9, wb.getSheetIndex("Sheet 1")); - - try (Workbook wbr = _testDataProvider.writeOutAndReadBack(wb)) { - - assertEquals(0, wbr.getSheetIndex("Sheet 6")); - assertEquals(1, wbr.getSheetIndex("Sheet 0")); - assertEquals(2, wbr.getSheetIndex("Sheet 2")); - assertEquals(3, wbr.getSheetIndex("Sheet 4")); - assertEquals(4, wbr.getSheetIndex("Sheet 5")); - assertEquals(5, wbr.getSheetIndex("Sheet 7")); - assertEquals(6, wbr.getSheetIndex("Sheet 3")); - assertEquals(7, wbr.getSheetIndex("Sheet 8")); - assertEquals(8, wbr.getSheetIndex("Sheet 9")); - assertEquals(9, wbr.getSheetIndex("Sheet 1")); - - assertEquals(1, wb.getActiveSheetIndex()); - - // Now get the index by the sheet, not the name - for (int i = 0; i < 10; i++) { - Sheet s = wbr.getSheetAt(i); - assertEquals(i, wbr.getSheetIndex(s)); - } - } - } - } - - @Test - protected void cloneSheet() throws IOException { - try (Workbook book = _testDataProvider.createWorkbook()) { - Sheet sheet = book.createSheet("TEST"); - sheet.createRow(0).createCell(0).setCellValue("Test"); - sheet.createRow(1).createCell(0).setCellValue(36.6); - assertEquals(0, sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 2))); - assertEquals(1, sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 2))); - assertTrue(sheet.isSelected()); - - Sheet clonedSheet = book.cloneSheet(0); - assertEquals("TEST (2)", clonedSheet.getSheetName()); - assertEquals(2, clonedSheet.getPhysicalNumberOfRows()); - assertEquals(2, clonedSheet.getNumMergedRegions()); - assertFalse(clonedSheet.isSelected()); - - //cloned sheet is a deep copy, adding rows or merged regions in the original does not affect the clone - sheet.createRow(2).createCell(0).setCellValue(1); - assertEquals(2, sheet.addMergedRegion(new CellRangeAddress(4, 5, 0, 2))); - assertEquals(2, clonedSheet.getPhysicalNumberOfRows()); - assertEquals(2, clonedSheet.getNumMergedRegions()); - - clonedSheet.createRow(2).createCell(0).setCellValue(1); - assertEquals(2, clonedSheet.addMergedRegion(new CellRangeAddress(6, 7, 0, 2))); - assertEquals(3, clonedSheet.getPhysicalNumberOfRows()); - assertEquals(3, clonedSheet.getNumMergedRegions()); - } - } - - @Test - protected void parentReferences() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Sheet sheet = wb1.createSheet(); - assertSame(wb1, sheet.getWorkbook()); - - Row row = sheet.createRow(0); - assertSame(sheet, row.getSheet()); - - Cell cell = row.createCell(1); - assertSame(sheet, cell.getSheet()); - assertSame(row, cell.getRow()); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - wb1.close(); - sheet = wb2.getSheetAt(0); - assertSame(wb2, sheet.getWorkbook()); - - row = sheet.getRow(0); - assertSame(sheet, row.getSheet()); - - cell = row.getCell(1); - assertSame(sheet, cell.getSheet()); - assertSame(row, cell.getRow()); - } - } - } - - - /** - * Test to validate that replacement for removed setRepeatingRowsAnsColumns() methods - * is still working correctly - */ - @Test - void setRepeatingRowsAnsColumns() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - CellRangeAddress cra = new CellRangeAddress(0, 3, 0, 0); - String expRows = "1:4", expCols = "A:A"; - - - Sheet sheet1 = wb.createSheet(); - sheet1.setRepeatingRows(cra); - sheet1.setRepeatingColumns(cra); - assertEquals(expRows, sheet1.getRepeatingRows().formatAsString()); - assertEquals(expCols, sheet1.getRepeatingColumns().formatAsString()); - - //must handle sheets with quotas, see Bugzilla #47294 - Sheet sheet2 = wb.createSheet("My' Sheet"); - sheet2.setRepeatingRows(cra); - sheet2.setRepeatingColumns(cra); - assertEquals(expRows, sheet2.getRepeatingRows().formatAsString()); - assertEquals(expCols, sheet2.getRepeatingColumns().formatAsString()); - } - } - - /** - * Tests that all of the unicode capable string fields can be set, written and then read back - */ - @Test - protected void unicodeInAll() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - CreationHelper factory = wb1.getCreationHelper(); - //Create a unicode dataformat (contains euro symbol) - DataFormat df = wb1.createDataFormat(); - final String formatStr = "_([$\u20ac-2]\\\\\\ * #,##0.00_);_([$\u20ac-2]\\\\\\ * \\\\\\(#,##0.00\\\\\\);_([$\u20ac-2]\\\\\\ *\\\"\\-\\\\\"??_);_(@_)"; - short fmt = df.getFormat(formatStr); - - //Create a unicode sheet name (euro symbol) - Sheet s = wb1.createSheet("\u20ac"); - - //Set a unicode header (you guessed it the euro symbol) - Header h = s.getHeader(); - h.setCenter("\u20ac"); - h.setLeft("\u20ac"); - h.setRight("\u20ac"); - - //Set a unicode footer - Footer f = s.getFooter(); - f.setCenter("\u20ac"); - f.setLeft("\u20ac"); - f.setRight("\u20ac"); - - Row r = s.createRow(0); - Cell c = r.createCell(1); - c.setCellValue(12.34); - c.getCellStyle().setDataFormat(fmt); - - /*Cell c2 =*/ - r.createCell(2); // TODO - c2 unused but changing next line ('c'->'c2') causes test to fail - c.setCellValue(factory.createRichTextString("\u20ac")); - - Cell c3 = r.createCell(3); - String formulaString = "TEXT(12.34,\"\u20ac###,##\")"; - c3.setCellFormula(formulaString); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - //Test the sheetname - s = wb2.getSheet("\u20ac"); - assertNotNull(s); - - //Test the header - h = s.getHeader(); - assertEquals(h.getCenter(), "\u20ac"); - assertEquals(h.getLeft(), "\u20ac"); - assertEquals(h.getRight(), "\u20ac"); - - //Test the footer - f = s.getFooter(); - assertEquals(f.getCenter(), "\u20ac"); - assertEquals(f.getLeft(), "\u20ac"); - assertEquals(f.getRight(), "\u20ac"); - - //Test the dataformat - r = s.getRow(0); - c = r.getCell(1); - df = wb2.createDataFormat(); - assertEquals(formatStr, df.getFormat(c.getCellStyle().getDataFormat())); - - //Test the cell string value - /*c2 =*/ - r.getCell(2); - assertEquals(c.getRichStringCellValue().getString(), "\u20ac"); - - //Test the cell formula - c3 = r.getCell(3); - assertEquals(c3.getCellFormula(), formulaString); - } - } - } - - private Workbook newSetSheetNameTestingWorkbook() { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh1 = wb.createSheet("Worksheet"); - Sheet sh2 = wb.createSheet("Testing 47100"); - Sheet sh3 = wb.createSheet("To be renamed"); - - Name name1 = wb.createName(); - name1.setNameName("sale_1"); - name1.setRefersToFormula("Worksheet!$A$1"); - - Name name2 = wb.createName(); - name2.setNameName("sale_2"); - name2.setRefersToFormula("'Testing 47100'!$A$1"); - - Name name3 = wb.createName(); - name3.setNameName("sale_3"); - name3.setRefersToFormula("'Testing 47100'!$B$1"); - - Name name4 = wb.createName(); - name4.setNameName("sale_4"); - name4.setRefersToFormula("'To be renamed'!$A$3"); - - sh1.createRow(0).createCell(0).setCellFormula("SUM('Testing 47100'!A1:C1)"); - sh1.createRow(1).createCell(0).setCellFormula("SUM('Testing 47100'!A1:C1,'To be renamed'!A1:A5)"); - sh1.createRow(2).createCell(0).setCellFormula("sale_2+sale_3+'Testing 47100'!C1"); - - sh2.createRow(0).createCell(0).setCellValue(1); - sh2.getRow(0).createCell(1).setCellValue(2); - sh2.getRow(0).createCell(2).setCellValue(3); - - sh3.createRow(0).createCell(0).setCellValue(1); - sh3.createRow(1).createCell(0).setCellValue(2); - sh3.createRow(2).createCell(0).setCellValue(3); - sh3.createRow(3).createCell(0).setCellValue(4); - sh3.createRow(4).createCell(0).setCellValue(5); - sh3.createRow(5).createCell(0).setCellFormula("sale_3"); - sh3.createRow(6).createCell(0).setCellFormula("'Testing 47100'!C1"); - return wb; - } - - /** - * Ensure that Workbook#setSheetName updates all dependent formulas and named ranges - * - * @see Bugzilla 47100 - */ - @Test - protected void setSheetName() throws IOException { - try (Workbook wb1 = newSetSheetNameTestingWorkbook()) { - Sheet sh1 = wb1.getSheetAt(0); - - Name sale_2 = wb1.getName("sale_2"); - Name sale_3 = wb1.getName("sale_3"); - Name sale_4 = wb1.getName("sale_4"); - - assertEquals("sale_2", sale_2.getNameName()); - assertEquals("'Testing 47100'!$A$1", sale_2.getRefersToFormula()); - assertEquals("sale_3", sale_3.getNameName()); - assertEquals("'Testing 47100'!$B$1", sale_3.getRefersToFormula()); - assertEquals("sale_4", sale_4.getNameName()); - assertEquals("'To be renamed'!$A$3", sale_4.getRefersToFormula()); - - FormulaEvaluator evaluator = wb1.getCreationHelper().createFormulaEvaluator(); - - Cell cell0 = sh1.getRow(0).getCell(0); - Cell cell1 = sh1.getRow(1).getCell(0); - Cell cell2 = sh1.getRow(2).getCell(0); - - assertEquals("SUM('Testing 47100'!A1:C1)", cell0.getCellFormula()); - assertEquals("SUM('Testing 47100'!A1:C1,'To be renamed'!A1:A5)", cell1.getCellFormula()); - assertEquals("sale_2+sale_3+'Testing 47100'!C1", cell2.getCellFormula()); - - assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0); - assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); - assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); - - wb1.setSheetName(1, "47100 - First"); - wb1.setSheetName(2, "47100 - Second"); - - assertEquals("sale_2", sale_2.getNameName()); - assertEquals("'47100 - First'!$A$1", sale_2.getRefersToFormula()); - assertEquals("sale_3", sale_3.getNameName()); - assertEquals("'47100 - First'!$B$1", sale_3.getRefersToFormula()); - assertEquals("sale_4", sale_4.getNameName()); - assertEquals("'47100 - Second'!$A$3", sale_4.getRefersToFormula()); - - assertEquals("SUM('47100 - First'!A1:C1)", cell0.getCellFormula()); - assertEquals("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.getCellFormula()); - assertEquals("sale_2+sale_3+'47100 - First'!C1", cell2.getCellFormula()); - - evaluator.clearAllCachedResultValues(); - assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0); - assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); - assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); - - try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - sh1 = wb2.getSheetAt(0); - - sale_2 = wb2.getName("sale_2"); - sale_3 = wb2.getName("sale_3"); - sale_4 = wb2.getName("sale_4"); - - cell0 = sh1.getRow(0).getCell(0); - cell1 = sh1.getRow(1).getCell(0); - cell2 = sh1.getRow(2).getCell(0); - - assertEquals("sale_2", sale_2.getNameName()); - assertEquals("'47100 - First'!$A$1", sale_2.getRefersToFormula()); - assertEquals("sale_3", sale_3.getNameName()); - assertEquals("'47100 - First'!$B$1", sale_3.getRefersToFormula()); - assertEquals("sale_4", sale_4.getNameName()); - assertEquals("'47100 - Second'!$A$3", sale_4.getRefersToFormula()); - - assertEquals("SUM('47100 - First'!A1:C1)", cell0.getCellFormula()); - assertEquals("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.getCellFormula()); - assertEquals("sale_2+sale_3+'47100 - First'!C1", cell2.getCellFormula()); - - evaluator = wb2.getCreationHelper().createFormulaEvaluator(); - assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0); - assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); - assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); - } - } - } - - @Test - void changeSheetNameWithSharedFormulas() throws IOException { - String sampleFile = "shared_formulas.xls" + (getClass().getName().contains("xssf") ? "x" : ""); - - try (Workbook wb = _testDataProvider.openSampleWorkbook(sampleFile)) { - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sheet = wb.getSheetAt(0); - - for (int rownum = 1; rownum <= 40; rownum++) { - Cell cellA = sheet.getRow(1).getCell(0); - Cell cellB = sheet.getRow(1).getCell(1); - - assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue()); - } - - wb.setSheetName(0, "Renamed by POI"); - evaluator.clearAllCachedResultValues(); - - for (int rownum = 1; rownum <= 40; rownum++) { - Cell cellA = sheet.getRow(1).getCell(0); - Cell cellB = sheet.getRow(1).getCell(1); - - assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue()); - } - } - } - - protected void assertSheetOrder(Workbook wb, String... sheets) { - StringBuilder sheetNames = new StringBuilder(); - for(int i = 0;i < wb.getNumberOfSheets();i++) { - sheetNames.append(wb.getSheetAt(i).getSheetName()).append(","); - } - assertEquals(sheets.length, wb.getNumberOfSheets(), "Had: " + sheetNames); - for(int i = 0;i < wb.getNumberOfSheets();i++) { - assertEquals(sheets[i], wb.getSheetAt(i).getSheetName(), "Had: " + sheetNames); - } - } - - @Test - void test58499() throws IOException { - try (Workbook workbook = _testDataProvider.createWorkbook()) { - Sheet sheet = workbook.createSheet(); - for (int i = 0; i < 900; i++) { - Row r = sheet.createRow(i); - Cell c = r.createCell(0); - CellStyle cs = workbook.createCellStyle(); - c.setCellStyle(cs); - c.setCellValue("AAA"); - } - assertDoesNotThrow(() -> workbook.write(new NullOutputStream())); - } - } - - - @Test - void windowOneDefaults() throws IOException { - try (Workbook b = _testDataProvider.createWorkbook()) { - assertEquals(b.getActiveSheetIndex(), 0); - assertEquals(b.getFirstVisibleTab(), 0); - // throws NullPointerException when WindowOneRecord in Workbook is not probably initialized - } - } - - @Test - void getSpreadsheetVersion() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - assertEquals(_testDataProvider.getSpreadsheetVersion(), wb.getSpreadsheetVersion()); - } - } - - /* FIXME copied from {@link org.apache.poi.ss.TestWorkbookFactory} */ - protected static void assertCloseDoesNotModifyFile(String filename, Workbook wb) throws IOException { - final byte[] before = HSSFTestDataSamples.getTestDataFileContent(filename); - wb.close(); - final byte[] after = HSSFTestDataSamples.getTestDataFileContent(filename); - assertArrayEquals(before, after, filename + " sample file was modified as a result of closing the workbook"); - } - - @Test - protected void sheetClone() throws IOException { - // First up, try a simple file - try (Workbook b = _testDataProvider.createWorkbook(); - Workbook bBack = HSSFTestDataSamples.openSampleWorkbook("SheetWithDrawing.xls")) { - assertEquals(0, b.getNumberOfSheets()); - b.createSheet("Sheet One"); - b.createSheet("Sheet Two"); - - assertEquals(2, b.getNumberOfSheets()); - b.cloneSheet(0); - assertEquals(3, b.getNumberOfSheets()); - - // Now try a problem one with drawing records in it - assertEquals(1, bBack.getNumberOfSheets()); - bBack.cloneSheet(0); - assertEquals(2, bBack.getNumberOfSheets()); - } - } - - @Test - void getSheetIndex() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet1 = wb.createSheet("Sheet1"); - Sheet sheet2 = wb.createSheet("Sheet2"); - Sheet sheet3 = wb.createSheet("Sheet3"); - Sheet sheet4 = wb.createSheet("Sheet4"); - - assertEquals(0, wb.getSheetIndex(sheet1)); - assertEquals(1, wb.getSheetIndex(sheet2)); - assertEquals(2, wb.getSheetIndex(sheet3)); - assertEquals(3, wb.getSheetIndex(sheet4)); - - // remove sheets - wb.removeSheetAt(0); - wb.removeSheetAt(2); - - // ensure that sheets are moved up and removed sheets are not found any more - assertEquals(-1, wb.getSheetIndex(sheet1)); - assertEquals(0, wb.getSheetIndex(sheet2)); - assertEquals(1, wb.getSheetIndex(sheet3)); - assertEquals(-1, wb.getSheetIndex(sheet4)); - } - } - - @Test - void addSheetTwice() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet1 = wb.createSheet("Sheet1"); - assertNotNull(sheet1); - - IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> wb.createSheet("Sheet1") - ); - assertEquals("The workbook already contains a sheet named 'Sheet1'", ex.getMessage()); - } - } - - // bug 51233 and 55075: correctly size image if added to a row with a custom height - @Test - void createDrawing() throws Exception { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sheet = wb.createSheet("Main Sheet"); - Row row0 = sheet.createRow(0); - Row row1 = sheet.createRow(1); - row1.createCell(0); - row0.createCell(1); - row1.createCell(0); - row1.createCell(1); - - byte[] pictureData = _testDataProvider.getTestDataFileContent("logoKarmokar4.png"); - - int handle = wb.addPicture(pictureData, Workbook.PICTURE_TYPE_PNG); - Drawing drawing = sheet.createDrawingPatriarch(); - CreationHelper helper = wb.getCreationHelper(); - ClientAnchor anchor = helper.createClientAnchor(); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - anchor.setCol1(0); - anchor.setRow1(0); - Picture picture = drawing.createPicture(anchor, handle); - - row0.setHeightInPoints(144); - // set a column width so that XSSF and SXSSF have the same width (default widths may be different otherwise) - sheet.setColumnWidth(0, 100 * 256); - picture.resize(); - - // The actual dimensions don't matter as much as having XSSF and SXSSF produce the same size drawings - - // Check drawing height - assertEquals(0, anchor.getRow1()); - assertEquals(0, anchor.getRow2()); - assertEquals(0, anchor.getDy1()); - assertEquals(1609725, anchor.getDy2()); //HSSF: 225 - - // Check drawing width - assertEquals(0, anchor.getCol1()); - assertEquals(0, anchor.getCol2()); - assertEquals(0, anchor.getDx1()); - assertEquals(1114425, anchor.getDx2()); //HSSF: 171 - } - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestXEvaluationSheet.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestXEvaluationSheet.java deleted file mode 100644 index 08fbae584e..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestXEvaluationSheet.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Map; - -import org.apache.poi.ss.formula.EvaluationSheet; -import org.junit.jupiter.api.Test; - -public abstract class BaseTestXEvaluationSheet { - /** - * Get a pair of underlying sheet and evaluation sheet. - */ - protected abstract Map.Entry getInstance(); - - @Test - void lastRowNumIsUpdatedFromUnderlyingSheet_bug62993() { - Map.Entry sheetPair = getInstance(); - Sheet underlyingSheet = sheetPair.getKey(); - EvaluationSheet instance = sheetPair.getValue(); - - assertEquals(-1, instance.getLastRowNum()); - - underlyingSheet.createRow(0); - underlyingSheet.createRow(1); - underlyingSheet.createRow(2); - assertEquals(2, instance.getLastRowNum()); - - underlyingSheet.removeRow(underlyingSheet.getRow(2)); - assertEquals(1, instance.getLastRowNum()); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java b/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java deleted file mode 100644 index da68a86b20..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java +++ /dev/null @@ -1,1060 +0,0 @@ -/* ==================================================================== - 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. - - 2012 - Alfresco Software, Ltd. - Alfresco Software has modified source of this file - The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.text.DateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.TestHSSFDataFormatter; -import org.apache.poi.ss.format.CellFormat; -import org.apache.poi.ss.format.CellFormatResult; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.ss.util.NumberToTextConverter; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.SuppressForbidden; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * Tests of {@link DataFormatter} - * - * See {@link TestHSSFDataFormatter} too for - * more tests. - */ -class TestDataFormatter { - private static final double _15_MINUTES = 0.041666667; - - @BeforeAll - @SuppressForbidden - public static void setUpClass() { - // some pre-checks to hunt for a problem in the Maven build - // these checks ensure that the correct locale is set, so a failure here - // usually indicates an invalid locale during test-execution - - assertFalse(DateUtil.isADateFormat(-1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - Locale ul = LocaleUtil.getUserLocale(); - assertTrue(Locale.ROOT.equals(ul) || Locale.getDefault().equals(ul)); - final String textValue = NumberToTextConverter.toText(1234.56); - assertEquals(-1, textValue.indexOf('E')); - Object cellValueO = Double.valueOf(1234.56); - - /*CellFormat cellFormat = new CellFormat("_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-"); - CellFormatResult result = cellFormat.apply(cellValueO); - assertEquals(" 1,234.56 ", result.text);*/ - - CellFormat cfmt = CellFormat.getInstance("_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-"); - CellFormatResult result = cfmt.apply(cellValueO); - assertEquals(" 1,234.56 ", result.text, - "This failure can indicate that the wrong locale is used during test-execution, ensure you run with english/US via -Duser.language=en -Duser.country=US"); - } - - /** - * Test that we use the specified locale when deciding - * how to format normal numbers - */ - @Test - void testLocale() { - DataFormatter dfUS = new DataFormatter(Locale.US); - DataFormatter dfFR = new DataFormatter(Locale.FRENCH); - - assertEquals("1234", dfUS.formatRawCellContents(1234, -1, "@")); - assertEquals("1234", dfFR.formatRawCellContents(1234, -1, "@")); - - assertEquals("12.34", dfUS.formatRawCellContents(12.34, -1, "@")); - assertEquals("12,34", dfFR.formatRawCellContents(12.34, -1, "@")); - } - - /** - * At the moment, we don't decode the locale strings into - * a specific locale, but we should format things as if - * the locale (eg '[$-1010409]') isn't there - */ - @Test - void testLocaleBasedFormats() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - // Standard formats - assertEquals("63", dfUS.formatRawCellContents(63.0, -1, "[$-1010409]General")); - assertEquals("63", dfUS.formatRawCellContents(63.0, -1, "[$-1010409]@")); - - // Regular numeric style formats - assertEquals("63", dfUS.formatRawCellContents(63.0, -1, "[$-1010409]##")); - assertEquals("63", dfUS.formatRawCellContents(63.0, -1, "[$-1010409]00")); - - } - - - /** - * Test that we use the specified locale when deciding - * how to format normal numbers - */ - @Test - void testGrouping() { - DataFormatter dfUS = new DataFormatter(Locale.US); - DataFormatter dfDE = new DataFormatter(Locale.GERMAN); - - assertEquals("1,234.57", dfUS.formatRawCellContents(1234.567, -1, "#,##0.00")); - assertEquals("1'234.57", dfUS.formatRawCellContents(1234.567, -1, "#'##0.00")); - assertEquals("1 234.57", dfUS.formatRawCellContents(1234.567, -1, "# ##0.00")); - - assertEquals("1.234,57", dfDE.formatRawCellContents(1234.567, -1, "#,##0.00")); - assertEquals("1'234,57", dfDE.formatRawCellContents(1234.567, -1, "#'##0.00")); - assertEquals("1 234,57", dfDE.formatRawCellContents(1234.567, -1, "# ##0.00")); - } - - /** - * Ensure that colours get correctly - * zapped from within the format strings - */ - @Test - void testColours() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - String[] formats = { - "##.##", - "[WHITE]##.##", - "[BLACK]##.##;[RED]-##.##", - "[COLOR11]##.##;[COLOR 43]-##.00", - }; - for (String format : formats) { - assertEquals( - "12.34", - dfUS.formatRawCellContents(12.343, -1, format), - "Wrong format for: " + format - ); - assertEquals( - "-12.34", - dfUS.formatRawCellContents(-12.343, -1, format), - "Wrong format for: " + format - ); - } - - // Ensure that random square brackets remain - assertEquals("12.34[a]", dfUS.formatRawCellContents(12.343, -1, "##.##[a]")); - assertEquals("[ab]12.34[x]", dfUS.formatRawCellContents(12.343, -1, "[ab]##.##[x]")); - } - - @Test - void testColoursAndBrackets() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - // Without currency symbols - String[] formats = { "#,##0.00;[Blue](#,##0.00)" }; - for (String format : formats) { - assertEquals( - "12.34", - dfUS.formatRawCellContents(12.343, -1, format), - "Wrong format for: " + format - ); - assertEquals( - "(12.34)", - dfUS.formatRawCellContents(-12.343, -1, format), - "Wrong format for: " + format - ); - } - - // With - formats = new String[] { "$#,##0.00;[Red]($#,##0.00)" }; - for (String format : formats) { - assertEquals( - "$12.34", - dfUS.formatRawCellContents(12.343, -1, format), - "Wrong format for: " + format - ); - assertEquals( - "($12.34)", - dfUS.formatRawCellContents(-12.343, -1, format), - "Wrong format for: " + format - ); - } - } - - @Test - void testConditionalRanges() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - String format = "[>=10]#,##0;[<10]0.0"; - assertEquals("17,876", dfUS.formatRawCellContents(17876.000, -1, format), "Wrong format for " + format); - assertEquals("9.7", dfUS.formatRawCellContents(9.71, -1, format), "Wrong format for " + format); - } - - /** - * Test how we handle negative and zeros. - * Note - some tests are disabled as DecimalFormat - * and Excel differ, and workarounds are not - * yet in place for all of these - */ - @Test - void testNegativeZero() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - String all2dp = "00.00"; - String alln1dp = "(00.0)"; - String p1dp_n1dp = "00.0;(00.0)"; - String p2dp_n1dp = "00.00;(00.0)"; - String p2dp_n1dp_z0 = "00.00;(00.0);0"; - String all2dpTSP = "00.00_x"; - String p2dp_n2dpTSP = "00.00_x;(00.00)_x"; - //String p2dp_n1dpTSP = "00.00_x;(00.0)_x"; - - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, all2dp)); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, p2dp_n1dp)); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, p2dp_n1dp_z0)); - - assertEquals("(12.3)", dfUS.formatRawCellContents(12.343, -1, alln1dp)); - assertEquals("-(12.3)", dfUS.formatRawCellContents(-12.343, -1, alln1dp)); - assertEquals("12.3", dfUS.formatRawCellContents(12.343, -1, p1dp_n1dp)); - assertEquals("(12.3)", dfUS.formatRawCellContents(-12.343, -1, p1dp_n1dp)); - - assertEquals("-12.34", dfUS.formatRawCellContents(-12.343, -1, all2dp)); - // TODO - fix case of negative subpattern differing from the - // positive one by more than just the prefix+suffix, which - // is all DecimalFormat supports... -// assertEquals("(12.3)", dfUS.formatRawCellContents(-12.343, -1, p2dp_n1dp)); -// assertEquals("(12.3)", dfUS.formatRawCellContents(-12.343, -1, p2dp_n1dp_z0)); - - assertEquals("00.00", dfUS.formatRawCellContents(0, -1, all2dp)); - assertEquals("00.00", dfUS.formatRawCellContents(0, -1, p2dp_n1dp)); - assertEquals("0", dfUS.formatRawCellContents(0, -1, p2dp_n1dp_z0)); - - // Spaces are skipped - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, all2dpTSP)); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, p2dp_n2dpTSP)); - assertEquals("(12.34)", dfUS.formatRawCellContents(-12.343, -1, p2dp_n2dpTSP)); -// assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, p2dp_n1dpTSP)); -// assertEquals("(12.3)", dfUS.formatRawCellContents(-12.343, -1, p2dp_n1dpTSP)); - } - - /** - * Test that we correctly handle fractions in the - * format string, eg # #/# - */ - @Test - void testFractions() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - // Excel often prefers "# #/#" - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# #/#")); - assertEquals("321 26/81", dfUS.formatRawCellContents(321.321, -1, "# #/##")); - assertEquals("26027/81", dfUS.formatRawCellContents(321.321, -1, "#/##")); - - // OOo seems to like the "# ?/?" form - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# ?/?")); - assertEquals("321 26/81", dfUS.formatRawCellContents(321.321, -1, "# ?/??")); - assertEquals("26027/81", dfUS.formatRawCellContents(321.321, -1, "?/??")); - - // p;n;z;s parts - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# #/#;# ##/#;0;xxx")); - assertEquals("321 1/3", dfUS.formatRawCellContents(-321.321, -1, "# #/#;# ##/#;0;xxx")); // Note the lack of - sign! - assertEquals("0", dfUS.formatRawCellContents(0, -1, "# #/#;# ##/#;0;xxx")); -// assertEquals(".", dfUS.formatRawCellContents(0, -1, "# #/#;# ##/#;#.#;xxx")); // Currently shows as 0. not . - - // Custom formats with text - assertEquals("+ve", dfUS.formatRawCellContents(1, -1, "+ve;-ve;zero;xxx")); - assertEquals("-ve", dfUS.formatRawCellContents(-1, -1, "-ve;-ve;zero;xxx")); - assertEquals("zero", dfUS.formatRawCellContents(0, -1, "zero;-ve;zero;xxx")); - - // Custom formats - check text is stripped, including multiple spaces - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# #/#")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "#\" \" #/#")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "#\"FRED\" #/#")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "#\\ #/#")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# \\q#/#")); - - // Cases that were very slow - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "0\" \"?/?;?/?")); // 0" "?/?;?/? - length of -ve part was used - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "0 \"#\"\\#\\#?/?")); // 0 "#"\#\#?/? - length of text was used - - assertEquals("321 295/919", dfUS.formatRawCellContents(321.321, -1, "# #/###")); - assertEquals("321 321/1000", dfUS.formatRawCellContents(321.321, -1, "# #/####")); // Code limits to #### as that is as slow as we want to get - assertEquals("321 321/1000", dfUS.formatRawCellContents(321.321, -1, "# #/##########")); - - // Not a valid fraction formats (too many #/# or ?/?) - hence the strange expected results -/* - assertEquals("321 / ?/?", dfUS.formatRawCellContents(321.321, -1, "# #/# ?/?")); - assertEquals("321 / /", dfUS.formatRawCellContents(321.321, -1, "# #/# #/#")); - assertEquals("321 ?/? ?/?", dfUS.formatRawCellContents(321.321, -1, "# ?/? ?/?")); - assertEquals("321 ?/? / /", dfUS.formatRawCellContents(321.321, -1, "# ?/? #/# #/#")); -*/ - - //Bug54686 patch sets default behavior of # #/## if there is a failure to parse - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# #/# ?/?")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# #/# #/#")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# ?/? ?/?")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# ?/? #/# #/#")); - - // Where +ve has a fraction, but -ve doesn't, we currently show both - assertEquals("123 1/3", dfUS.formatRawCellContents( 123.321, -1, "0 ?/?;0")); - //assertEquals("123", dfUS.formatRawCellContents(-123.321, -1, "0 ?/?;0")); - - //Bug54868 patch has a hit on the first string before the ";" - assertEquals("-123 1/3", dfUS.formatRawCellContents(-123.321, -1, "0 ?/?;0")); - assertEquals("123 1/3", dfUS.formatRawCellContents(123.321, -1, "0 ?/?;0")); - - //Bug53150 formatting a whole number with fractions should just give the number - assertEquals("1", dfUS.formatRawCellContents(1.0, -1, "# #/#")); - assertEquals("11", dfUS.formatRawCellContents(11.0, -1, "# #/#")); - } - - /** - * Test that _x (blank with the space taken by "x") - * and *x (fill to the column width with "x"s) are - * correctly ignored by us. - */ - @Test - void testPaddingSpaces() { - DataFormatter dfUS = new DataFormatter(Locale.US); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##_ ")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##_1")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##_)")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "_-##.##")); - - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##* ")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##*1")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##*)")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "*-##.##")); - } - - /** - * DataFormatter is the CSV mode preserves spaces - */ - @Test - void testPaddingSpacesCSV() { - DataFormatter dfUS = new DataFormatter(Locale.US, true); - assertEquals("12.34 ", dfUS.formatRawCellContents(12.343, -1, "##.##_ ")); - assertEquals("-12.34 ", dfUS.formatRawCellContents(-12.343, -1, "##.##_ ")); - assertEquals(". ", dfUS.formatRawCellContents(0.0, -1, "##.##_ ")); - assertEquals("12.34 ", dfUS.formatRawCellContents(12.343, -1, "##.##_1")); - assertEquals("-12.34 ", dfUS.formatRawCellContents(-12.343, -1, "##.##_1")); - assertEquals(". ", dfUS.formatRawCellContents(0.0, -1, "##.##_1")); - assertEquals("12.34 ", dfUS.formatRawCellContents(12.343, -1, "##.##_)")); - assertEquals("-12.34 ", dfUS.formatRawCellContents(-12.343, -1, "##.##_)")); - assertEquals(". ", dfUS.formatRawCellContents(0.0, -1, "##.##_)")); - assertEquals(" 12.34", dfUS.formatRawCellContents(12.343, -1, "_-##.##")); - assertEquals("- 12.34", dfUS.formatRawCellContents(-12.343, -1, "_-##.##")); - assertEquals(" .", dfUS.formatRawCellContents(0.0, -1, "_-##.##")); - - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##* ")); - assertEquals("-12.34", dfUS.formatRawCellContents(-12.343, -1, "##.##* ")); - assertEquals(".", dfUS.formatRawCellContents(0.0, -1, "##.##* ")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##*1")); - assertEquals("-12.34", dfUS.formatRawCellContents(-12.343, -1, "##.##*1")); - assertEquals(".", dfUS.formatRawCellContents(0.0, -1, "##.##*1")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##*)")); - assertEquals("-12.34", dfUS.formatRawCellContents(-12.343, -1, "##.##*)")); - assertEquals(".", dfUS.formatRawCellContents(0.0, -1, "##.##*)")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "*-##.##")); - assertEquals("-12.34", dfUS.formatRawCellContents(-12.343, -1, "*-##.##")); - assertEquals(".", dfUS.formatRawCellContents(0.0, -1, "*-##.##")); - } - - /** - * Test that the special Excel month format MMMMM - * gets turned into the first letter of the month - */ - @Test - void testMMMMM() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - Calendar c = LocaleUtil.getLocaleCalendar(2010, 5, 1, 2, 0, 0); - - assertEquals("2010-J-1 2:00:00", dfUS.formatRawCellContents( - DateUtil.getExcelDate(c, false), -1, "YYYY-MMMMM-D h:mm:ss" - )); - } - - /** - * Tests that we do AM/PM handling properly - */ - @Test - void testAMPM() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - assertEquals("06:00", dfUS.formatRawCellContents(0.25, -1, "hh:mm")); - assertEquals("18:00", dfUS.formatRawCellContents(0.75, -1, "hh:mm")); - - assertEquals("06:00 AM", dfUS.formatRawCellContents(0.25, -1, "hh:mm AM/PM")); - assertEquals("06:00 PM", dfUS.formatRawCellContents(0.75, -1, "hh:mm AM/PM")); - - assertEquals("1904-01-01 06:00:00 AM", dfUS.formatRawCellContents(0.25, -1, "yyyy-mm-dd hh:mm:ss AM/PM", true)); - assertEquals("1904-01-01 06:00:00 PM", dfUS.formatRawCellContents(0.75, -1, "yyyy-mm-dd hh:mm:ss AM/PM", true)); - } - - /** - * Test that we can handle elapsed time, - * eg formatting 1 day 4 hours as 28 hours - */ - @Test - void testElapsedTime() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - double hour = 1.0/24.0; - - assertEquals("01:00", dfUS.formatRawCellContents(1*hour, -1, "hh:mm")); - assertEquals("05:00", dfUS.formatRawCellContents(5*hour, -1, "hh:mm")); - assertEquals("20:00", dfUS.formatRawCellContents(20*hour, -1, "hh:mm")); - assertEquals("23:00", dfUS.formatRawCellContents(23*hour, -1, "hh:mm")); - assertEquals("00:00", dfUS.formatRawCellContents(24*hour, -1, "hh:mm")); - assertEquals("02:00", dfUS.formatRawCellContents(26*hour, -1, "hh:mm")); - assertEquals("20:00", dfUS.formatRawCellContents(44*hour, -1, "hh:mm")); - assertEquals("02:00", dfUS.formatRawCellContents(50*hour, -1, "hh:mm")); - - assertEquals("01:00", dfUS.formatRawCellContents(1*hour, -1, "[hh]:mm")); - assertEquals("05:00", dfUS.formatRawCellContents(5*hour, -1, "[hh]:mm")); - assertEquals("20:00", dfUS.formatRawCellContents(20*hour, -1, "[hh]:mm")); - assertEquals("23:00", dfUS.formatRawCellContents(23*hour, -1, "[hh]:mm")); - assertEquals("24:00", dfUS.formatRawCellContents(24*hour, -1, "[hh]:mm")); - assertEquals("26:00", dfUS.formatRawCellContents(26*hour, -1, "[hh]:mm")); - assertEquals("44:00", dfUS.formatRawCellContents(44*hour, -1, "[hh]:mm")); - assertEquals("50:00", dfUS.formatRawCellContents(50*hour, -1, "[hh]:mm")); - - assertEquals("01", dfUS.formatRawCellContents(1*hour, -1, "[hh]")); - assertEquals("05", dfUS.formatRawCellContents(5*hour, -1, "[hh]")); - assertEquals("20", dfUS.formatRawCellContents(20*hour, -1, "[hh]")); - assertEquals("23", dfUS.formatRawCellContents(23*hour, -1, "[hh]")); - assertEquals("24", dfUS.formatRawCellContents(24*hour, -1, "[hh]")); - assertEquals("26", dfUS.formatRawCellContents(26*hour, -1, "[hh]")); - assertEquals("44", dfUS.formatRawCellContents(44*hour, -1, "[hh]")); - assertEquals("50", dfUS.formatRawCellContents(50*hour, -1, "[hh]")); - - double minute = 1.0/24.0/60.0; - assertEquals("01:00", dfUS.formatRawCellContents(1*minute, -1, "[mm]:ss")); - assertEquals("05:00", dfUS.formatRawCellContents(5*minute, -1, "[mm]:ss")); - assertEquals("20:00", dfUS.formatRawCellContents(20*minute, -1, "[mm]:ss")); - assertEquals("23:00", dfUS.formatRawCellContents(23*minute, -1, "[mm]:ss")); - assertEquals("24:00", dfUS.formatRawCellContents(24*minute, -1, "[mm]:ss")); - assertEquals("26:00", dfUS.formatRawCellContents(26*minute, -1, "[mm]:ss")); - assertEquals("44:00", dfUS.formatRawCellContents(44*minute, -1, "[mm]:ss")); - assertEquals("50:00", dfUS.formatRawCellContents(50*minute, -1, "[mm]:ss")); - assertEquals("59:00", dfUS.formatRawCellContents(59*minute, -1, "[mm]:ss")); - assertEquals("60:00", dfUS.formatRawCellContents(60*minute, -1, "[mm]:ss")); - assertEquals("61:00", dfUS.formatRawCellContents(61*minute, -1, "[mm]:ss")); - assertEquals("119:00", dfUS.formatRawCellContents(119*minute, -1, "[mm]:ss")); - assertEquals("120:00", dfUS.formatRawCellContents(120*minute, -1, "[mm]:ss")); - assertEquals("121:00", dfUS.formatRawCellContents(121*minute, -1, "[mm]:ss")); - - assertEquals("01", dfUS.formatRawCellContents(1*minute, -1, "[mm]")); - assertEquals("05", dfUS.formatRawCellContents(5*minute, -1, "[mm]")); - assertEquals("20", dfUS.formatRawCellContents(20*minute, -1, "[mm]")); - assertEquals("23", dfUS.formatRawCellContents(23*minute, -1, "[mm]")); - assertEquals("24", dfUS.formatRawCellContents(24*minute, -1, "[mm]")); - assertEquals("26", dfUS.formatRawCellContents(26*minute, -1, "[mm]")); - assertEquals("44", dfUS.formatRawCellContents(44*minute, -1, "[mm]")); - assertEquals("50", dfUS.formatRawCellContents(50*minute, -1, "[mm]")); - assertEquals("59", dfUS.formatRawCellContents(59*minute, -1, "[mm]")); - assertEquals("60", dfUS.formatRawCellContents(60*minute, -1, "[mm]")); - assertEquals("61", dfUS.formatRawCellContents(61*minute, -1, "[mm]")); - assertEquals("119", dfUS.formatRawCellContents(119*minute, -1, "[mm]")); - assertEquals("120", dfUS.formatRawCellContents(120*minute, -1, "[mm]")); - assertEquals("121", dfUS.formatRawCellContents(121*minute, -1, "[mm]")); - - double second = 1.0/24.0/60.0/60.0; - assertEquals("86400", dfUS.formatRawCellContents(86400*second, -1, "[ss]")); - assertEquals("01", dfUS.formatRawCellContents(1*second, -1, "[ss]")); - assertEquals("05", dfUS.formatRawCellContents(5*second, -1, "[ss]")); - assertEquals("20", dfUS.formatRawCellContents(20*second, -1, "[ss]")); - assertEquals("23", dfUS.formatRawCellContents(23*second, -1, "[ss]")); - assertEquals("24", dfUS.formatRawCellContents(24*second, -1, "[ss]")); - assertEquals("26", dfUS.formatRawCellContents(26*second, -1, "[ss]")); - assertEquals("44", dfUS.formatRawCellContents(44*second, -1, "[ss]")); - assertEquals("50", dfUS.formatRawCellContents(50*second, -1, "[ss]")); - assertEquals("59", dfUS.formatRawCellContents(59*second, -1, "[ss]")); - assertEquals("60", dfUS.formatRawCellContents(60*second, -1, "[ss]")); - assertEquals("61", dfUS.formatRawCellContents(61*second, -1, "[ss]")); - assertEquals("119", dfUS.formatRawCellContents(119*second, -1, "[ss]")); - assertEquals("120", dfUS.formatRawCellContents(120*second, -1, "[ss]")); - assertEquals("121", dfUS.formatRawCellContents(121*second, -1, "[ss]")); - - assertEquals("27:18:08", dfUS.formatRawCellContents(1.1376, -1, "[h]:mm:ss")); - assertEquals("28:48:00", dfUS.formatRawCellContents(1.2, -1, "[h]:mm:ss")); - assertEquals("29:31:12", dfUS.formatRawCellContents(1.23, -1, "[h]:mm:ss")); - assertEquals("31:26:24", dfUS.formatRawCellContents(1.31, -1, "[h]:mm:ss")); - - assertEquals("27:18:08", dfUS.formatRawCellContents(1.1376, -1, "[hh]:mm:ss")); - assertEquals("28:48:00", dfUS.formatRawCellContents(1.2, -1, "[hh]:mm:ss")); - assertEquals("29:31:12", dfUS.formatRawCellContents(1.23, -1, "[hh]:mm:ss")); - assertEquals("31:26:24", dfUS.formatRawCellContents(1.31, -1, "[hh]:mm:ss")); - - assertEquals("57:07.2", dfUS.formatRawCellContents(.123, -1, "mm:ss.0;@")); - assertEquals("57:41.8", dfUS.formatRawCellContents(.1234, -1, "mm:ss.0;@")); - assertEquals("57:41.76", dfUS.formatRawCellContents(.1234, -1, "mm:ss.00;@")); - assertEquals("57:41.760", dfUS.formatRawCellContents(.1234, -1, "mm:ss.000;@")); - assertEquals("24:00.0", dfUS.formatRawCellContents(123456.6, -1, "mm:ss.0")); - } - - @Test - void testDateWindowing() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - assertEquals("1899-12-31 00:00:00", dfUS.formatRawCellContents(0.0, -1, "yyyy-mm-dd hh:mm:ss")); - assertEquals("1899-12-31 00:00:00", dfUS.formatRawCellContents(0.0, -1, "yyyy-mm-dd hh:mm:ss", false)); - assertEquals("1904-01-01 00:00:00", dfUS.formatRawCellContents(0.0, -1, "yyyy-mm-dd hh:mm:ss", true)); - } - - @Test - void testScientificNotation() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - assertEquals("1.23E+01", dfUS.formatRawCellContents(12.343, -1, "0.00E+00")); - assertEquals("-1.23E+01", dfUS.formatRawCellContents(-12.343, -1, "0.00E+00")); - assertEquals("0.00E+00", dfUS.formatRawCellContents(0.0, -1, "0.00E+00")); - } - - @Test - void testInvalidDate() { - DataFormatter df1 = new DataFormatter(Locale.US); - assertEquals("-1.0", df1.formatRawCellContents(-1, -1, "mm/dd/yyyy")); - - DataFormatter df2 = new DataFormatter(Locale.US, true); - assertEquals("###############################################################################################################################################################################################################################################################", - df2.formatRawCellContents(-1, -1, "mm/dd/yyyy")); - } - - @Test - void testEscapes() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - assertEquals("1901-01-01", dfUS.formatRawCellContents(367.0, -1, "yyyy-mm-dd")); - assertEquals("1901-01-01", dfUS.formatRawCellContents(367.0, -1, "yyyy\\-mm\\-dd")); - - assertEquals("1901.01.01", dfUS.formatRawCellContents(367.0, -1, "yyyy.mm.dd")); - assertEquals("1901.01.01", dfUS.formatRawCellContents(367.0, -1, "yyyy\\.mm\\.dd")); - - assertEquals("1901/01/01", dfUS.formatRawCellContents(367.0, -1, "yyyy/mm/dd")); - assertEquals("1901/01/01", dfUS.formatRawCellContents(367.0, -1, "yyyy\\/mm\\/dd")); - } - - @Test - void testFormatsWithPadding() { - DataFormatter dfUS = new DataFormatter(Locale.US, true); - - // These request space-padding, based on the cell width - // There should always be one space after, variable (non-zero) amount before - // Because the Cell Width isn't available, this gets emulated with - // 4 leading spaces, or a minus then 3 leading spaces - // This isn't all that consistent, but it's the best we can really manage... - assertEquals(" 1,234.56 ", dfUS.formatRawCellContents( 1234.56, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - assertEquals("- 1,234.56 ", dfUS.formatRawCellContents(-1234.56, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - assertEquals(" 12.34 ", dfUS.formatRawCellContents( 12.34, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - assertEquals("- 12.34 ", dfUS.formatRawCellContents(-12.34, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - - assertEquals(" 0.10 ", dfUS.formatRawCellContents( 0.1, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - assertEquals("- 0.10 ", dfUS.formatRawCellContents(-0.1, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - // TODO Fix this, we are randomly adding a 0 at the end that shouldn't be there - //assertEquals(" - ", dfUS.formatRawCellContents(0.0, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - - assertEquals(" $ 1.10 ", dfUS.formatRawCellContents( 1.1, -1, "_-$* #,##0.00_-;-$* #,##0.00_-;_-$* \"-\"??_-;_-@_-")); - assertEquals("-$ 1.10 ", dfUS.formatRawCellContents(-1.1, -1, "_-$* #,##0.00_-;-$* #,##0.00_-;_-$* \"-\"??_-;_-@_-")); - // TODO Fix this, we are randomly adding a 0 at the end that shouldn't be there - //assertEquals(" $ - ", dfUS.formatRawCellContents( 0.0, -1, "_-$* #,##0.00_-;-$* #,##0.00_-;_-$* \"-\"??_-;_-@_-")); - } - - @Test - void testErrors() throws IOException { - DataFormatter dfUS = new DataFormatter(Locale.US, true); - - // Create a spreadsheet with some formula errors in it - try (Workbook wb = new HSSFWorkbook()) { - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0, CellType.ERROR); - - c.setCellErrorValue(FormulaError.DIV0.getCode()); - assertEquals(FormulaError.DIV0.getString(), dfUS.formatCellValue(c)); - - c.setCellErrorValue(FormulaError.REF.getCode()); - assertEquals(FormulaError.REF.getString(), dfUS.formatCellValue(c)); - } - } - - @Test - void testBoolean() throws IOException { - DataFormatter formatter = new DataFormatter(); - - // Create a spreadsheet with some TRUE/FALSE boolean values in it - try (Workbook wb = new HSSFWorkbook()) { - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); - - c.setCellValue(true); - assertEquals("TRUE", formatter.formatCellValue(c)); - - c.setCellValue(false); - assertEquals("FALSE", formatter.formatCellValue(c)); - } - } - - /** - * While we don't currently support using a locale code at - * the start of a format string to format it differently, we - * should at least handle it as it if wasn't there - */ - @Test - void testDatesWithLocales() { - DataFormatter dfUS = new DataFormatter(Locale.US, true); - - String dateFormatEnglish = "[$-409]mmmm dd yyyy h:mm AM/PM"; - String dateFormatChinese = "[$-804]mmmm dd yyyy h:mm AM/PM"; - - // Check we format the English one correctly - double date = 26995.477777777778; - assertEquals( - "November 27 1973 11:28 AM", - dfUS.formatRawCellContents(date, -1, dateFormatEnglish) - ); - - // Check that, in the absence of locale support, we handle - // the Chinese one the same as the English one - assertEquals( - "November 27 1973 11:28 AM", - dfUS.formatRawCellContents(date, -1, dateFormatChinese) - ); - } - - /** - * TODO Fix these so that they work - */ - @Test - @Disabled - void testCustomFormats() { - DataFormatter dfUS = new DataFormatter(Locale.US, true); - String fmt; - - fmt = "\"At\" H:MM AM/PM \"on\" DDDD MMMM D\",\" YYYY"; - assertEquals( - "At 4:20 AM on Thursday May 17, 2007", - dfUS.formatRawCellContents(39219.1805636921, -1, fmt) - ); - - fmt = "0 \"dollars and\" .00 \"cents\""; - assertEquals("19 dollars and .99 cents", dfUS.formatRawCellContents(19.99, -1, fmt)); - } - - /** - * ExcelStyleDateFormatter should work for Milliseconds too - */ - @Test - void testExcelStyleDateFormatterStringOnMillis() { - // Test directly with the .000 style - DateFormat formatter1 = new ExcelStyleDateFormatter("ss.000"); - - assertEquals("00.001", formatter1.format(new Date(1L))); - assertEquals("00.010", formatter1.format(new Date(10L))); - assertEquals("00.100", formatter1.format(new Date(100L))); - assertEquals("01.000", formatter1.format(new Date(1000L))); - assertEquals("01.001", formatter1.format(new Date(1001L))); - assertEquals("10.000", formatter1.format(new Date(10000L))); - assertEquals("10.001", formatter1.format(new Date(10001L))); - - // Test directly with the .SSS style - DateFormat formatter2 = new ExcelStyleDateFormatter("ss.SSS"); - - assertEquals("00.001", formatter2.format(new Date(1L))); - assertEquals("00.010", formatter2.format(new Date(10L))); - assertEquals("00.100", formatter2.format(new Date(100L))); - assertEquals("01.000", formatter2.format(new Date(1000L))); - assertEquals("01.001", formatter2.format(new Date(1001L))); - assertEquals("10.000", formatter2.format(new Date(10000L))); - assertEquals("10.001", formatter2.format(new Date(10001L))); - - - // Test via DataFormatter - DataFormatter dfUS = new DataFormatter(Locale.US, true); - assertEquals("01.010", dfUS.formatRawCellContents(0.0000116898, -1, "ss.000")); - } - - @Test - void testBug54786() { - DataFormatter formatter = new DataFormatter(); - String format = "[h]\"\"h\"\" m\"\"m\"\""; - assertTrue(DateUtil.isADateFormat(-1,format)); - assertTrue(DateUtil.isValidExcelDate(_15_MINUTES)); - - assertEquals("1h 0m", formatter.formatRawCellContents(_15_MINUTES, -1, format, false)); - assertEquals("0.041666667", formatter.formatRawCellContents(_15_MINUTES, -1, "[h]'h'", false)); - assertEquals("1h 0m\"", formatter.formatRawCellContents(_15_MINUTES, -1, "[h]\"\"h\"\" m\"\"m\"\"\"", false)); - assertEquals("1h", formatter.formatRawCellContents(_15_MINUTES, -1, "[h]\"\"h\"\"", false)); - assertEquals("h1", formatter.formatRawCellContents(_15_MINUTES, -1, "\"\"h\"\"[h]", false)); - assertEquals("h1", formatter.formatRawCellContents(_15_MINUTES, -1, "\"\"h\"\"h", false)); - assertEquals(" 60", formatter.formatRawCellContents(_15_MINUTES, -1, " [m]", false)); - assertEquals("h60", formatter.formatRawCellContents(_15_MINUTES, -1, "\"\"h\"\"[m]", false)); - assertEquals("m1", formatter.formatRawCellContents(_15_MINUTES, -1, "\"\"m\"\"h", false)); - - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> - formatter.formatRawCellContents(_15_MINUTES, -1, "[h]\"\"h\"\" m\"\"m\"\"\"\"", false), - "Catches exception because of invalid format, i.e. trailing quoting"); - assertTrue(e.getMessage().contains("Cannot format given Object as a Number")); - } - - @Test - void testIsADateFormat() { - // first check some cases that should not be a date, also call multiple times to ensure the cache is used - assertFalse(DateUtil.isADateFormat(-1, null)); - assertFalse(DateUtil.isADateFormat(-1, null)); - assertFalse(DateUtil.isADateFormat(123, null)); - assertFalse(DateUtil.isADateFormat(123, "")); - assertFalse(DateUtil.isADateFormat(124, "")); - assertFalse(DateUtil.isADateFormat(-1, "")); - assertFalse(DateUtil.isADateFormat(-1, "")); - assertFalse(DateUtil.isADateFormat(-1, "nodateformat")); - - // then also do the same for some valid date formats - assertTrue(DateUtil.isADateFormat(0x0e, null)); - assertTrue(DateUtil.isADateFormat(0x2f, null)); - assertTrue(DateUtil.isADateFormat(-1, "yyyy")); - assertTrue(DateUtil.isADateFormat(-1, "yyyy")); - assertTrue(DateUtil.isADateFormat(-1, "dd/mm/yy;[red]dd/mm/yy")); - assertTrue(DateUtil.isADateFormat(-1, "dd/mm/yy;[red]dd/mm/yy")); - assertTrue(DateUtil.isADateFormat(-1, "[h]")); - } - - - @Test - void testLargeNumbersAndENotation() throws IOException{ - assertFormatsTo("1E+86", 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999d); - assertFormatsTo("1E-84", 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000001d); - // Smallest double - assertFormatsTo("1E-323", 0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001d); - - // "up to 11 numeric characters, with the decimal point counting as a numeric character" - // https://support.microsoft.com/en-us/kb/65903 - assertFormatsTo( "12345678911", 12345678911d); - assertFormatsTo( "1.23457E+11", 123456789112d); // 12th digit of integer -> scientific - assertFormatsTo( "-12345678911", -12345678911d); - assertFormatsTo( "-1.23457E+11", -123456789112d); - assertFormatsTo( "0.1", 0.1); - assertFormatsTo( "0.000000001", 0.000000001); - assertFormatsTo( "1E-10", 0.0000000001); // 12th digit - assertFormatsTo( "-0.000000001", -0.000000001); - assertFormatsTo( "-1E-10", -0.0000000001); - assertFormatsTo( "123.4567892", 123.45678919); // excess decimals are simply rounded away - assertFormatsTo("-123.4567892", -123.45678919); - assertFormatsTo( "1.234567893", 1.2345678925); // rounding mode is half-up - assertFormatsTo("-1.234567893", -1.2345678925); - assertFormatsTo( "1.23457E+19", 12345650000000000000d); - assertFormatsTo("-1.23457E+19", -12345650000000000000d); - assertFormatsTo( "1.23457E-19", 0.0000000000000000001234565d); - assertFormatsTo("-1.23457E-19", -0.0000000000000000001234565d); - assertFormatsTo( "1.000000001", 1.000000001); - assertFormatsTo( "1", 1.0000000001); - assertFormatsTo( "1234.567891", 1234.567891123456789d); - assertFormatsTo( "1234567.891", 1234567.891123456789d); - assertFormatsTo( "12345678912", 12345678911.63456789d); // integer portion uses all 11 digits - assertFormatsTo( "12345678913", 12345678912.5d); // half-up here too - assertFormatsTo("-12345678913", -12345678912.5d); - assertFormatsTo( "1.23457E+11", 123456789112.3456789d); - } - - private static void assertFormatsTo(String expected, double input) throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet s1 = wb.createSheet(); - Row row = s1.createRow(0); - Cell rawValue = row.createCell(0); - rawValue.setCellValue(input); - CellStyle newStyle = wb.createCellStyle(); - DataFormat dataFormat = wb.createDataFormat(); - newStyle.setDataFormat(dataFormat.getFormat("General")); - String actual = new DataFormatter().formatCellValue(rawValue); - assertEquals(expected, actual); - } - } - - @Test - void testFormulaEvaluation() throws IOException { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("FormulaEvalTestData.xls"); - - CellReference ref = new CellReference("D47"); - - Cell cell = wb.getSheetAt(0).getRow(ref.getRow()).getCell(ref.getCol()); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("G9:K9 I7:I12", cell.getCellFormula()); - - DataFormatter formatter = new DataFormatter(); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals("5.6789", formatter.formatCellValue(cell, evaluator)); - - wb.close(); - } - - @Test - void testFormatWithTrailingDotsUS() { - DataFormatter dfUS = new DataFormatter(Locale.US); - assertEquals("1,000,000", dfUS.formatRawCellContents(1000000, -1, "#,##0")); - assertEquals("1,000", dfUS.formatRawCellContents(1000000, -1, "#,##0,")); - assertEquals("1", dfUS.formatRawCellContents(1000000, -1, "#,##0,,")); - assertEquals("1,000,000.0", dfUS.formatRawCellContents(1000000, -1, "#,##0.0")); - assertEquals("1,000.0", dfUS.formatRawCellContents(1000000, -1, "#,##0.0,")); - assertEquals("1.0", dfUS.formatRawCellContents(1000000, -1, "#,##0.0,,")); - assertEquals("1,000,000.00", dfUS.formatRawCellContents(1000000, -1, "#,##0.00")); - assertEquals("1,000.00", dfUS.formatRawCellContents(1000000, -1, "#,##0.00,")); - assertEquals("1.00", dfUS.formatRawCellContents(1000000, -1, "#,##0.00,,")); - assertEquals("1,000,000", dfUS.formatRawCellContents(1e24, -1, "#,##0,,,,,,")); - } - - @Test - void testFormatWithTrailingDotsOtherLocale() { - DataFormatter dfIT = new DataFormatter(Locale.ITALY); - assertEquals("1.000.000", dfIT.formatRawCellContents(1000000, -1, "#,##0")); - assertEquals("1.000", dfIT.formatRawCellContents(1000000, -1, "#,##0,")); - assertEquals("1", dfIT.formatRawCellContents(1000000, -1, "#,##0,,")); - assertEquals("1.000.000,0", dfIT.formatRawCellContents(1000000, -1, "#,##0.0")); - assertEquals("1.000,0", dfIT.formatRawCellContents(1000000, -1, "#,##0.0,")); - assertEquals("1,0", dfIT.formatRawCellContents(1000000, -1, "#,##0.0,,")); - assertEquals("1.000.000,00", dfIT.formatRawCellContents(1000000, -1, "#,##0.00")); - assertEquals("1.000,00", dfIT.formatRawCellContents(1000000, -1, "#,##0.00,")); - assertEquals("1,00", dfIT.formatRawCellContents(1000000, -1, "#,##0.00,,")); - assertEquals("1.000.000", dfIT.formatRawCellContents(1e24, -1, "#,##0,,,,,,")); - } - - /** - * bug 60031: DataFormatter parses months incorrectly when put at the end of date segment - */ - @Test - void testBug60031() { - // 23-08-2016 08:51:01 which is 42605.368761574071 as double was parsed - // with format "yyyy-dd-MM HH:mm:ss" into "2016-23-51 08:51:01". - DataFormatter dfUS = new DataFormatter(Locale.US); - assertEquals("2016-23-08 08:51:01", dfUS.formatRawCellContents(42605.368761574071, -1, "yyyy-dd-MM HH:mm:ss")); - assertEquals("2016-23 08:51:01 08", dfUS.formatRawCellContents(42605.368761574071, -1, "yyyy-dd HH:mm:ss MM")); - assertEquals("2017-12-01 January 09:54:33", dfUS.formatRawCellContents(42747.412892397523, -1, "yyyy-dd-MM MMMM HH:mm:ss")); - assertEquals("08", dfUS.formatRawCellContents(42605.368761574071, -1, "MM")); - assertEquals("01", dfUS.formatRawCellContents(42605.368761574071, -1, "ss")); - - // From Excel help: - /* - The "m" or "mm" code must appear immediately after the "h" or"hh" - code or immediately before the "ss" code; otherwise, Microsoft - Excel displays the month instead of minutes." - */ - assertEquals("08", dfUS.formatRawCellContents(42605.368761574071, -1, "mm")); - assertEquals("08:51", dfUS.formatRawCellContents(42605.368761574071, -1, "hh:mm")); - assertEquals("51:01", dfUS.formatRawCellContents(42605.368761574071, -1, "mm:ss")); - } - - @Test - void testDateFormattingWithLocales() { - // 2017-12-01 09:54:33 which is 42747.412892397523 as double - DataFormatter dfDE = new DataFormatter(Locale.GERMANY); - DataFormatter dfZH = new DataFormatter(Locale.PRC); - DataFormatter dfIE = new DataFormatter(new Locale("GA", "IE")); - double date = 42747.412892397523; - String format = "dd MMMM yyyy HH:mm:ss"; - assertEquals("12 Januar 2017 09:54:33", dfDE.formatRawCellContents(date, -1, format)); - assertEquals("12 \u4E00\u6708 2017 09:54:33", dfZH.formatRawCellContents(date, -1, format)); - assertEquals("12 Ean\u00E1ir 2017 09:54:33", dfIE.formatRawCellContents(date, -1, format)); - } - - /** - * bug 60422 : simple number formats seem ok - */ - @Test - void testSimpleNumericFormatsInGermanyLocale() { - Locale[] locales = new Locale[] {Locale.GERMANY, Locale.US, Locale.ROOT}; - for (Locale locale : locales) { - //show that LocaleUtil has no effect on these tests - LocaleUtil.setUserLocale(locale); - try { - char euro = '\u20AC'; - DataFormatter df = new DataFormatter(Locale.GERMANY); - assertEquals("4,33", df.formatRawCellContents(4.33, -1, "#,##0.00")); - assertEquals("1.234,33", df.formatRawCellContents(1234.333, -1, "#,##0.00")); - assertEquals("-1.234,33", df.formatRawCellContents(-1234.333, -1, "#,##0.00")); - assertEquals("1.234,33 " + euro, df.formatRawCellContents(1234.33, -1, "#,##0.00 " + euro)); - assertEquals("1.234,33 " + euro, df.formatRawCellContents(1234.33, -1, "#,##0.00 \"" + euro + "\"")); - } finally { - LocaleUtil.resetUserLocale(); - } - } - } - - /** - * bug 60422 : DataFormatter has issues with a specific NumberFormat in Germany default locale -≈ */ - @Test - void testBug60422() { - char euro = '\u20AC'; - DataFormatter df = new DataFormatter(Locale.GERMANY); - String formatString = String.format(Locale.ROOT, - "_-* #,##0.00\\ \"%s\"_-;\\-* #,##0.00\\ \"%s\"_-;_-* \"-\"??\\ \"%s\"_-;_-@_-", - euro, euro, euro); - assertEquals("4,33 " + euro, df.formatRawCellContents(4.33, 178, formatString)); - assertEquals("1.234,33 " + euro, df.formatRawCellContents(1234.33, 178, formatString)); - } - - @Test - void testBug62839() { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellFormula("FLOOR(-123,10)"); - DataFormatter df = new DataFormatter(Locale.GERMANY); - - String value = df.formatCellValue(cell, wb.getCreationHelper().createFormulaEvaluator()); - assertEquals("-130", value); - } - - /** - * Bug #63292 - */ - @Test - void test1904With4PartFormat() { - Date date = new Date(); - int formatIndex = 105; - String formatString1 = "[$-F400]m/d/yy h:mm:ss\\ AM/PM"; - String formatString4 = "[$-F400]m/d/yy h:mm:ss\\ AM/PM;[$-F400]m/d/yy h:mm:ss\\ AM/PM;_-* \"\"??_-;_-@_-"; - - String s1900, s1904; - - // These two format calls return the same thing, as expected: - // The assertEquals() passes with 1-part format - s1900 = format(date, formatIndex, formatString1, false); - s1904 = format(date, formatIndex, formatString1, true); - assertEquals(s1900, s1904); // WORKS - - // These two format calls should return the same thing but don't: - // It fails with 4-part format because the call to CellFormat ignores 'use1904Windowing' - s1900 = format(date, formatIndex, formatString4, false); - s1904 = format(date, formatIndex, formatString4, true); - assertEquals(s1900, s1904); // FAILS before fix for #63292 - } - - private String format(Date date, int formatIndex, String formatString, boolean use1904Windowing) { - DataFormatter formatter = new DataFormatter(); - double n = DateUtil.getExcelDate(date, use1904Windowing); - return formatter.formatRawCellContents(n, formatIndex, formatString, use1904Windowing); - } - - @Test - void testConcurrentCellFormat() throws Exception { - DataFormatter formatter1 = new DataFormatter(); - DataFormatter formatter2 = new DataFormatter(); - doFormatTestSequential(formatter1); - doFormatTestConcurrent(formatter1, formatter2); - } - - /** - * Bug #64319 - * - * A custom format string like TRUE shouldn't be E+ - * A numeric format string like 0E0 shouldn't be E+ - * A numeric format string like 0E+0 should be E+ - */ - @Test - void testWithEinFormat() throws Exception { - DataFormatter formatter = new DataFormatter(); - - // Format string literals with an E in them shouldn't be - // treated as a Scientific format, so shouldn't become E+ - assertEquals("TRUE", formatter.formatRawCellContents(1.0, 170, - "\"TRUE\";\"FALSE\";\"ZERO\"")); - assertEquals("ZERO", formatter.formatRawCellContents(0.0, 170, - "\"TRUE\";\"FALSE\";\"ZERO\"")); - assertEquals("FALSE", formatter.formatRawCellContents(-1.0, 170, - "\"TRUE\";\"FALSE\";\"ZERO\"")); - - // Explicit Scientific format does need E+ - assertEquals("1E+05", formatter.formatRawCellContents(1e05, 170, - "0E+00")); - assertEquals("1E+10", formatter.formatRawCellContents(1e10, 170, - "0E+00")); - assertEquals("1E-10", formatter.formatRawCellContents(1e-10, 170, - "0E+00")); - - // Large numbers with "General" need E+ - assertEquals("100000", formatter.formatRawCellContents(1e05, -1, "General")); - assertEquals("1E+12", formatter.formatRawCellContents(1e12, -1, "General")); - - // Less common Scientific-like formats which don't ask for - // the + on >1 exponentials don't need it adding - // (Java will put the -ve ones in for E-## automatically) - assertEquals("1E5", formatter.formatRawCellContents(1e05, 170, - "0E0")); - assertEquals("1E10", formatter.formatRawCellContents(1e10, 170, - "0E0")); - assertEquals("1E-10", formatter.formatRawCellContents(1e-10, 170, - "0E0")); - - assertEquals("1E5", formatter.formatRawCellContents(1e05, 170, - "0E-0")); - assertEquals("1E10", formatter.formatRawCellContents(1e10, 170, - "0E-0")); - assertEquals("1E-10", formatter.formatRawCellContents(1e-10, 170, - "0E-0")); - - } - - private void doFormatTestSequential(DataFormatter formatter) { - for (int i = 0; i < 1_000; i++) { - assertTrue(doFormatTest(formatter, 43551.50990171296, "3/27/19 12:14:15 PM", i)); - assertTrue(doFormatTest(formatter, 36104.424780092595, "11/5/98 10:11:41 AM", i)); - } - } - - private void doFormatTestConcurrent(DataFormatter formatter1, DataFormatter formatter2) throws Exception { - ArrayList> futures = new ArrayList<>(); - for (int i = 0; i < 1_000; i++) { - final int iteration = i; - CompletableFuture future = CompletableFuture.supplyAsync( - () -> { - boolean r1 = doFormatTest(formatter1, 43551.50990171296, "3/27/19 12:14:15 PM", iteration); - boolean r2 = doFormatTest(formatter1, 36104.424780092595, "11/5/98 10:11:41 AM", iteration); - return r1 && r2; - }); - futures.add(future); - future = CompletableFuture.supplyAsync( - () -> { - boolean r1 = doFormatTest(formatter2, 43551.50990171296, "3/27/19 12:14:15 PM", iteration); - boolean r2 = doFormatTest(formatter2, 36104.424780092595, "11/5/98 10:11:41 AM", iteration); - return r1 && r2; - }); - futures.add(future); - } - for (CompletableFuture future : futures) { - assertTrue(future.get(1, TimeUnit.MINUTES)); - } - } - - private static boolean doFormatTest(DataFormatter formatter, double n, String expected, int iteration) { - int formatIndex = 105; - String formatString = "[$-F400]m/d/yy h:mm:ss\\ AM/PM;[$-F400]m/d/yy h:mm:ss\\ AM/PM;_-* \"\"??_-;_-@_-"; - String actual = formatter.formatRawCellContents(n, formatIndex, formatString); - assertEquals(expected, actual, "Failed on iteration " + iteration); - return true; - } - -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java b/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java deleted file mode 100644 index 615e2f1d72..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java +++ /dev/null @@ -1,716 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static java.util.Calendar.AUGUST; -import static java.util.Calendar.FEBRUARY; -import static java.util.Calendar.JANUARY; -import static java.util.Calendar.JULY; -import static java.util.Calendar.MARCH; -import static java.util.Calendar.MAY; -import static java.util.Calendar.OCTOBER; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDateTime; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFDataFormat; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -class TestDateUtil { - - static TimeZone userTimeZone; - - @BeforeAll - public static void setCEST() { - userTimeZone = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CEST")); - } - - @AfterAll - public static void resetTimeZone() { - LocaleUtil.setUserTimeZone(userTimeZone); - } - - @Test - void getJavaDate_InvalidValue() { - final double dateValue = -1; - final TimeZone tz = LocaleUtil.getUserTimeZone(); - final boolean use1904windowing = false; - final boolean roundSeconds = false; - - assertNull(DateUtil.getJavaDate(dateValue)); - assertNull(DateUtil.getJavaDate(dateValue, tz)); - assertNull(DateUtil.getJavaDate(dateValue, use1904windowing)); - assertNull(DateUtil.getJavaDate(dateValue, use1904windowing, tz)); - assertNull(DateUtil.getJavaDate(dateValue, use1904windowing, tz, roundSeconds)); - } - - @Test - void getJavaDate_ValidValue() { - final double dateValue = 0; - final TimeZone tz = LocaleUtil.getUserTimeZone(); - final boolean use1904windowing = false; - final boolean roundSeconds = false; - - Calendar calendar = LocaleUtil.getLocaleCalendar(1900, 0, 0); - Date date = calendar.getTime(); - - assertEquals(date, DateUtil.getJavaDate(dateValue)); - assertEquals(date, DateUtil.getJavaDate(dateValue, tz)); - assertEquals(date, DateUtil.getJavaDate(dateValue, use1904windowing)); - assertEquals(date, DateUtil.getJavaDate(dateValue, use1904windowing, tz)); - assertEquals(date, DateUtil.getJavaDate(dateValue, use1904windowing, tz, roundSeconds)); - } - - @Test - void getJavaCalendar_InvalidValue() { - final double dateValue = -1; - final TimeZone tz = LocaleUtil.getUserTimeZone(); - final boolean use1904windowing = false; - final boolean roundSeconds = false; - - assertNull(DateUtil.getJavaCalendar(dateValue)); - assertNull(DateUtil.getJavaCalendar(dateValue, use1904windowing)); - assertNull(DateUtil.getJavaCalendar(dateValue, use1904windowing, tz)); - assertNull(DateUtil.getJavaCalendar(dateValue, use1904windowing, tz, roundSeconds)); - } - - @Test - void getJavaCalendar_ValidValue() { - final double dateValue = 0; - final TimeZone tz = LocaleUtil.getUserTimeZone(); - final boolean use1904windowing = false; - final boolean roundSeconds = false; - - Calendar expCal = LocaleUtil.getLocaleCalendar(1900, 0, 0); - - Calendar[] actCal = { - DateUtil.getJavaCalendar(dateValue), - DateUtil.getJavaCalendar(dateValue, use1904windowing), - DateUtil.getJavaCalendar(dateValue, use1904windowing, tz), - DateUtil.getJavaCalendar(dateValue, use1904windowing, tz, roundSeconds) - }; - assertEquals(expCal, actCal[0]); - assertEquals(expCal, actCal[1]); - assertEquals(expCal, actCal[2]); - assertEquals(expCal, actCal[3]); - } - - @Test - void getLocalDateTime_InvalidValue() { - final double dateValue = -1; - final boolean use1904windowing = false; - final boolean roundSeconds = false; - - assertNull(DateUtil.getLocalDateTime(dateValue)); - assertNull(DateUtil.getLocalDateTime(dateValue, use1904windowing)); - assertNull(DateUtil.getLocalDateTime(dateValue, use1904windowing, roundSeconds)); - } - - @Test - void getLocalDateTime_ValidValue() { - final double dateValue = 0; - final boolean use1904windowing = false; - final boolean roundSeconds = false; - - // note that the Date and Calendar examples use a zero day of month which is invalid in LocalDateTime - LocalDateTime date = LocalDateTime.of(1899, 12, 31, 0, 0); - - assertEquals(date, DateUtil.getLocalDateTime(dateValue)); - assertEquals(date, DateUtil.getLocalDateTime(dateValue, use1904windowing)); - assertEquals(date, DateUtil.getLocalDateTime(dateValue, use1904windowing, roundSeconds)); - } - - @Test - void isADateFormat() { - // Cell content 2016-12-8 as an example - // Cell show "12/8/2016" - assertTrue(DateUtil.isADateFormat(14, "m/d/yy")); - // Cell show "Thursday, December 8, 2016" - assertTrue(DateUtil.isADateFormat(182, "[$-F800]dddd\\,\\ mmmm\\ dd\\,\\ yyyy")); - // Cell show "12/8" - assertTrue(DateUtil.isADateFormat(183, "m/d;@")); - // Cell show "12/08/16" - assertTrue(DateUtil.isADateFormat(184, "mm/dd/yy;@")); - // Cell show "8-Dec-16" - assertTrue(DateUtil.isADateFormat(185, "[$-409]d\\-mmm\\-yy;@")); - // Cell show "D-16" - assertTrue(DateUtil.isADateFormat(186, "[$-409]mmmmm\\-yy;@")); - - // Cell show "2016年12月8日" - assertTrue(DateUtil.isADateFormat(165, "yyyy\"\u5e74\"m\"\u6708\"d\"\u65e5\";@")); - // Cell show "2016年12月" - assertTrue(DateUtil.isADateFormat(164, "yyyy\"\u5e74\"m\"\u6708\";@")); - // Cell show "12月8日" - assertTrue(DateUtil.isADateFormat(168, "m\"\u6708\"d\"\u65e5\";@")); - // Cell show "十二月八日" - assertTrue(DateUtil.isADateFormat(181, "[DBNum1][$-404]m\"\u6708\"d\"\u65e5\";@")); - // Cell show "贰零壹陆年壹拾贰月捌日" - assertTrue(DateUtil.isADateFormat(177, "[DBNum2][$-804]yyyy\"\u5e74\"m\"\u6708\"d\"\u65e5\";@")); - // Cell show "2016年12月8日" - assertTrue(DateUtil.isADateFormat(178, "[DBNum3][$-804]yyyy\"\u5e74\"m\"\u6708\"d\"\u65e5\";@")); - } - /** - * Checks the date conversion functions in the DateUtil class. - */ - @Test - void dateConversion() { - - // Iterating over the hours exposes any rounding issues. - Calendar cal = LocaleUtil.getLocaleCalendar(2002,JANUARY,1,0,1,1); - for (int hour = 0; hour < 24; hour++) { - double excelDate = DateUtil.getExcelDate(cal.getTime(), false); - - assertEquals(cal.getTime().getTime(), DateUtil.getJavaDate(excelDate, false).getTime(), - "getJavaDate: Checking hour = " + hour); - - LocalDateTime ldt = LocalDateTime.ofInstant(cal.toInstant(), cal.getTimeZone().toZoneId()); - assertEquals(ldt, DateUtil.getLocalDateTime(excelDate, false), - "getLocalDateTime: Checking hour = " + hour); - - cal.add(Calendar.HOUR_OF_DAY, 1); - } - - // check 1900 and 1904 date windowing conversions - double excelDate = 36526.0; - // with 1900 windowing, excelDate is Jan. 1, 2000 - // with 1904 windowing, excelDate is Jan. 2, 2004 - cal.set(2000,JANUARY,1,0,0,0); // Jan. 1, 2000 - Date dateIf1900 = cal.getTime(); - cal.add(Calendar.YEAR,4); // now Jan. 1, 2004 - cal.add(Calendar.DATE,1); // now Jan. 2, 2004 - Date dateIf1904 = cal.getTime(); - // 1900 windowing - assertEquals(dateIf1900.getTime(), DateUtil.getJavaDate(excelDate,false).getTime(), - "Checking 1900 Date Windowing"); - // 1904 windowing - assertEquals(dateIf1904.getTime(), DateUtil.getJavaDate(excelDate,true).getTime(), - "Checking 1904 Date Windowing"); - // 1900 windowing (LocalDateTime) - assertEquals(LocalDateTime.of(2000,1,1,0,0), DateUtil.getLocalDateTime(excelDate,false), - "Checking 1900 Date Windowing"); - // 1904 windowing (LocalDateTime) - assertEquals(LocalDateTime.of(2004,1,2,0,0), DateUtil.getLocalDateTime(excelDate,true), - "Checking 1904 Date Windowing"); - } - - /** - * Checks the conversion of a java.util.date to Excel on a day when - * Daylight Saving Time starts. - */ - @Test - void excelConversionOnDSTStart() { - Calendar cal = LocaleUtil.getLocaleCalendar(2004,MARCH,28,0,0,0); - for (int hour = 0; hour < 24; hour++) { - - // Skip 02:00 CET as that is the Daylight change time - // and Java converts it automatically to 03:00 CEST - if (hour == 2) { - continue; - } - - cal.set(Calendar.HOUR_OF_DAY, hour); - Date javaDate = cal.getTime(); - double excelDate = DateUtil.getExcelDate(javaDate, false); - double difference = excelDate - Math.floor(excelDate); - int differenceInHours = (int) (difference * 24 * 60 + 0.5) / 60; - - assertEquals(hour, differenceInHours, "Checking " + hour + " hour on Daylight Saving Time start date"); - assertEquals(javaDate.getTime(), DateUtil.getJavaDate(excelDate, false).getTime(), - "Checking " + hour + " hour on Daylight Saving Time start date"); - - // perform the same checks with LocalDateTime - LocalDateTime localDate = LocalDateTime.of(2004,3,28,hour,0,0); - double excelLocalDate = DateUtil.getExcelDate(localDate, false); - double differenceLocalDate = excelLocalDate - Math.floor(excelLocalDate); - int differenceLocalDateInHours = (int) (differenceLocalDate * 24 * 60 + 0.5) / 60; - - assertEquals(hour, differenceLocalDateInHours, - "Checking " + hour + " hour on Daylight Saving Time start date (LocalDateTime)"); - assertEquals(localDate, DateUtil.getLocalDateTime(excelLocalDate, false), - "Checking " + hour + " hour on Daylight Saving Time start date (LocalDateTime)"); - } - } - - /** - * Checks the conversion of an Excel date to a java.util.date on a day when - * Daylight Saving Time starts. - */ - @Test - void javaConversionOnDSTStart() { - Calendar cal = LocaleUtil.getLocaleCalendar(2004,MARCH,28,0,0,0); - double excelDate = DateUtil.getExcelDate(cal.getTime(), false); - double oneHour = 1.0 / 24; - double oneMinute = oneHour / 60; - for (int hour = 0; hour < 24; hour++, excelDate += oneHour) { - - // Skip 02:00 CET as that is the Daylight change time - // and Java converts it automatically to 03:00 CEST - if (hour == 2) { - continue; - } - - cal.set(Calendar.HOUR_OF_DAY, hour); - Date javaDate = DateUtil.getJavaDate(excelDate, false); - double actDate = DateUtil.getExcelDate(javaDate, false); - assertEquals(excelDate, actDate, oneMinute, - "Checking " + hour + " hours on Daylight Saving Time start date"); - - // perform the same check with LocalDateTime - cal.set(Calendar.HOUR_OF_DAY, hour); - LocalDateTime localDate = DateUtil.getLocalDateTime(excelDate, false); - double actLocalDate = DateUtil.getExcelDate(localDate, false); - assertEquals(excelDate, actLocalDate, oneMinute, - "Checking " + hour + " hours on Daylight Saving Time start date (LocalDateTime)"); - } - } - - /** - * Checks the conversion of a java.util.Date to Excel on a day when - * Daylight Saving Time ends. - */ - @Test - void excelConversionOnDSTEnd() { - Calendar cal = LocaleUtil.getLocaleCalendar(2004,OCTOBER,31,0,0,0); - for (int hour = 0; hour < 24; hour++) { - cal.set(Calendar.HOUR_OF_DAY, hour); - Date javaDate = cal.getTime(); - double excelDate = DateUtil.getExcelDate(javaDate, false); - double difference = excelDate - Math.floor(excelDate); - int differenceInHours = (int) (difference * 24 * 60 + 0.5) / 60; - assertEquals(hour, differenceInHours, - "Checking " + hour + " hour on Daylight Saving Time end date"); - assertEquals(javaDate.getTime(), DateUtil.getJavaDate(excelDate, false).getTime(), - "Checking " + hour + " hour on Daylight Saving Time start date"); - - // perform the same checks using LocalDateTime - LocalDateTime localDate = LocalDateTime.of(2004,10,31,hour,0,0); - double excelLocalDate = DateUtil.getExcelDate(localDate, false); - int differenceLocalDateInHours = (int) (difference * 24 * 60 + 0.5) / 60; - assertEquals(hour, differenceLocalDateInHours, - "Checking " + hour + " hour on Daylight Saving Time end date (LocalDateTime)"); - assertEquals(localDate, DateUtil.getLocalDateTime(excelLocalDate, false), - "Checking " + hour + " hour on Daylight Saving Time start date (LocalDateTime)"); - } - } - - /** - * Checks the conversion of an Excel date to java.util.Date on a day when - * Daylight Saving Time ends. - */ - @Test - void javaConversionOnDSTEnd() { - Calendar cal = LocaleUtil.getLocaleCalendar(2004,OCTOBER,31,0,0,0); - double excelDate = DateUtil.getExcelDate(cal.getTime(), false); - double oneHour = 1.0 / 24; - double oneMinute = oneHour / 60; - for (int hour = 0; hour < 24; hour++, excelDate += oneHour) { - cal.set(Calendar.HOUR_OF_DAY, hour); - Date javaDate = DateUtil.getJavaDate(excelDate, false); - assertEquals(excelDate, DateUtil.getExcelDate(javaDate, false), oneMinute, - "Checking " + hour + " hours on Daylight Saving Time start date"); - - // perform the same checks using LocalDateTime - LocalDateTime localDate = DateUtil.getLocalDateTime(excelDate, false); - assertEquals(excelDate, DateUtil.getExcelDate(localDate, false), oneMinute, - "Checking " + hour + " hours on Daylight Saving Time start date"); - } - } - - /** - * Tests that we deal with time-zones properly - */ - @Test - void calendarConversion() { - TimeZone userTZ = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - try { - Calendar cal = LocaleUtil.getLocaleCalendar(2002,JANUARY,1,12,1,1); - Date expected = cal.getTime(); - - // Iterating over the hours exposes any rounding issues. - for (int hour = -12; hour <= 12; hour++) - { - String id = "GMT" + (hour < 0 ? "" : "+") + hour + ":00"; - cal.setTimeZone(TimeZone.getTimeZone(id)); - cal.set(Calendar.HOUR_OF_DAY, 12); - double excelDate = DateUtil.getExcelDate(cal, false); - Date javaDate = DateUtil.getJavaDate(excelDate); - - // Should match despite time-zone - assertEquals(expected.getTime(), javaDate.getTime(), "Checking timezone " + id); - } - - // Check that the timezone aware getter works correctly - TimeZone cet = TimeZone.getTimeZone("Europe/Copenhagen"); - TimeZone ldn = TimeZone.getTimeZone("Europe/London"); - - // 12:45 on 27th April 2012 - double excelDate = 41026.53125; - - // Same, no change - assertEquals( - DateUtil.getJavaDate(excelDate, false).getTime(), - DateUtil.getJavaDate(excelDate, false, cet).getTime() - ); - - // London vs Copenhagen, should differ by an hour - Date cetDate = DateUtil.getJavaDate(excelDate, false); - Date ldnDate = DateUtil.getJavaDate(excelDate, false, ldn); - assertEquals(ldnDate.getTime() - cetDate.getTime(), 60*60*1000); - } finally { - LocaleUtil.setUserTimeZone(userTZ); - } - } - - /** - * Tests that we correctly detect date formats as such - */ - @Test - void identifyDateFormats() { - // First up, try with a few built in date formats - short[] builtins = new short[] { 0x0e, 0x0f, 0x10, 0x16, 0x2d, 0x2e }; - for (short builtin : builtins) { - String formatStr = HSSFDataFormat.getBuiltinFormat(builtin); - assertTrue( DateUtil.isInternalDateFormat(builtin) ); - assertTrue( DateUtil.isADateFormat(builtin,formatStr) ); - } - - // Now try a few built-in non date formats - builtins = new short[] { 0x01, 0x02, 0x17, 0x1f, 0x30 }; - for (short builtin : builtins) { - String formatStr = HSSFDataFormat.getBuiltinFormat(builtin); - assertFalse( DateUtil.isInternalDateFormat(builtin) ); - assertFalse( DateUtil.isADateFormat(builtin,formatStr) ); - } - - // Now for some non-internal ones - // These come after the real ones - int numBuiltins = HSSFDataFormat.getNumberOfBuiltinBuiltinFormats(); - assertTrue(numBuiltins < 60); - short formatId = 60; - assertFalse( DateUtil.isInternalDateFormat(formatId) ); - - // Valid ones first - String[] formats = new String[] { - "yyyy-mm-dd", "yyyy/mm/dd", "yy/mm/dd", "yy/mmm/dd", - "dd/mm/yy", "dd/mm/yyyy", "dd/mmm/yy", - "dd-mm-yy", "dd-mm-yyyy", - "DD-MM-YY", "DD-mm-YYYY", - "dd\\-mm\\-yy", // Sometimes escaped - "dd.mm.yyyy", "dd\\.mm\\.yyyy", - "dd\\ mm\\.yyyy AM", "dd\\ mm\\.yyyy pm", - "dd\\ mm\\.yyyy\\-dd", "[h]:mm:ss", - "mm/dd/yy", "\"mm\"/\"dd\"/\"yy\"", - "m\\/d\\/yyyy", - - // These crazy ones are valid - "yyyy-mm-dd;@", "yyyy/mm/dd;@", - "dd-mm-yy;@", "dd-mm-yyyy;@", - // These even crazier ones are also valid - // (who knows what they mean though...) - "[$-F800]dddd\\,\\ mmm\\ dd\\,\\ yyyy", - "[$-F900]ddd/mm/yyy", - // These ones specify colours, who knew that was allowed? - "[BLACK]dddd/mm/yy", - "[yeLLow]yyyy-mm-dd" - }; - for (String format : formats) { - assertTrue(DateUtil.isADateFormat(formatId, format), format + " is a date format"); - } - - // Then time based ones too - formats = new String[] { - "yyyy-mm-dd hh:mm:ss", "yyyy/mm/dd HH:MM:SS", - "mm/dd HH:MM", "yy/mmm/dd SS", - "mm/dd HH:MM AM", "mm/dd HH:MM am", - "mm/dd HH:MM PM", "mm/dd HH:MM pm", - "m/d/yy h:mm AM/PM", - "hh:mm:ss", "hh:mm:ss.0", "mm:ss.0", - //support elapsed time [h],[m],[s] - "[hh]", "[mm]", "[ss]", "[SS]", "[red][hh]" - }; - for (String format : formats) { - assertTrue(DateUtil.isADateFormat(formatId, format), format + " is a datetime format"); - } - - // Then invalid ones - formats = new String[] { - "yyyy*mm*dd", - "0.0", "0.000", - "0%", "0.0%", - "[]Foo", "[BLACK]0.00%", - "[ms]", "[Mh]", - "", null - }; - for (String format : formats) { - assertFalse(DateUtil.isADateFormat(formatId, format), format + " is not a date or datetime format"); - } - - // And these are ones we probably shouldn't allow, - // but would need a better regexp - - // formats = new String[] { - // "yyyy:mm:dd", - // }; - // for (String format : formats) { - // assertFalse( DateUtil.isADateFormat(formatId, format) ); - // } - } - - @Test - void excelDateBorderCases() throws ParseException { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT); - df.setTimeZone(LocaleUtil.getUserTimeZone()); - - Date date1 = df.parse("1900-01-01"); - assertEquals(1.0, DateUtil.getExcelDate(date1), 0.00001); - assertEquals(1.0, DateUtil.getExcelDate(DateUtil.toLocalDateTime(date1)), 0.00001); - Date date31 = df.parse("1900-01-31"); - assertEquals(31.0, DateUtil.getExcelDate(date31), 0.00001); - assertEquals(31.0, DateUtil.getExcelDate(DateUtil.toLocalDateTime(date31)), 0.00001); - Date date32 = df.parse("1900-02-01"); - assertEquals(32.0, DateUtil.getExcelDate(date32), 0.00001); - assertEquals(32.0, DateUtil.getExcelDate(DateUtil.toLocalDateTime(date32)), 0.00001); - Date dateMinus1 = df.parse("1899-12-31"); - assertEquals(/* BAD_DATE! */ -1.0, DateUtil.getExcelDate(dateMinus1), 0.00001); - assertEquals(/* BAD_DATE! */ -1.0, DateUtil.getExcelDate(DateUtil.toLocalDateTime(dateMinus1)), 0.00001); - } - - @Test - void dateBug_2Excel() { - assertEquals(59.0, DateUtil.getExcelDate(createDate(1900, FEBRUARY, 28), false), 0.00001); - assertEquals(61.0, DateUtil.getExcelDate(createDate(1900, MARCH, 1), false), 0.00001); - - assertEquals(37315.00, DateUtil.getExcelDate(createDate(2002, FEBRUARY, 28), false), 0.00001); - assertEquals(37316.00, DateUtil.getExcelDate(createDate(2002, MARCH, 1), false), 0.00001); - assertEquals(37257.00, DateUtil.getExcelDate(createDate(2002, JANUARY, 1), false), 0.00001); - assertEquals(38074.00, DateUtil.getExcelDate(createDate(2004, MARCH, 28), false), 0.00001); - - // perform the same checks using LocalDateTime - assertEquals(59.0, DateUtil.getExcelDate(LocalDateTime.of(1900, 2, 28, 0,0), false), 0.00001); - assertEquals(61.0, DateUtil.getExcelDate(LocalDateTime.of(1900, 3, 1, 0,0), false), 0.00001); - - assertEquals(37315.00, DateUtil.getExcelDate(LocalDateTime.of(2002, 2, 28, 0,0), false), 0.00001); - assertEquals(37316.00, DateUtil.getExcelDate(LocalDateTime.of(2002, 3, 1, 0,0), false), 0.00001); - assertEquals(37257.00, DateUtil.getExcelDate(LocalDateTime.of(2002, 1, 1, 0,0), false), 0.00001); - assertEquals(38074.00, DateUtil.getExcelDate(LocalDateTime.of(2004, 3, 28, 0,0), false), 0.00001); - } - - @Test - void dateBug_2Java() { - assertEquals(createDate(1900, FEBRUARY, 28), DateUtil.getJavaDate(59.0, false)); - assertEquals(createDate(1900, MARCH, 1), DateUtil.getJavaDate(61.0, false)); - - assertEquals(createDate(2002, FEBRUARY, 28), DateUtil.getJavaDate(37315.00, false)); - assertEquals(createDate(2002, MARCH, 1), DateUtil.getJavaDate(37316.00, false)); - assertEquals(createDate(2002, JANUARY, 1), DateUtil.getJavaDate(37257.00, false)); - assertEquals(createDate(2004, MARCH, 28), DateUtil.getJavaDate(38074.00, false)); - - // perform the same checks using LocalDateTime - assertEquals(LocalDateTime.of(1900, 2, 28, 0, 0), DateUtil.getLocalDateTime(59.0, false)); - assertEquals(LocalDateTime.of(1900, 3, 1, 0, 0), DateUtil.getLocalDateTime(61.0, false)); - - assertEquals(LocalDateTime.of(2002, 2, 28, 0, 0), DateUtil.getLocalDateTime(37315.00, false)); - assertEquals(LocalDateTime.of(2002, 3, 1, 0, 0), DateUtil.getLocalDateTime(37316.00, false)); - assertEquals(LocalDateTime.of(2002, 1, 1, 0, 0), DateUtil.getLocalDateTime(37257.00, false)); - assertEquals(LocalDateTime.of(2004, 3, 28, 0, 0), DateUtil.getLocalDateTime(38074.00, false)); - } - - @Test - void date1904() { - assertEquals(createDate(1904, JANUARY, 2), DateUtil.getJavaDate(1.0, true)); - assertEquals(createDate(1904, JANUARY, 1), DateUtil.getJavaDate(0.0, true)); - assertEquals(0.0, DateUtil.getExcelDate(createDate(1904, JANUARY, 1), true), 0.00001); - assertEquals(1.0, DateUtil.getExcelDate(createDate(1904, JANUARY, 2), true), 0.00001); - - assertEquals(createDate(1998, JULY, 5), DateUtil.getJavaDate(35981, false)); - assertEquals(createDate(1998, JULY, 5), DateUtil.getJavaDate(34519, true)); - - assertEquals(35981.0, DateUtil.getExcelDate(createDate(1998, JULY, 5), false), 0.00001); - assertEquals(34519.0, DateUtil.getExcelDate(createDate(1998, JULY, 5), true), 0.00001); - - // perform the same checks using LocalDateTime - assertEquals(LocalDateTime.of(1904, 1, 2, 0, 0), DateUtil.getLocalDateTime(1.0, true)); - assertEquals(LocalDateTime.of(1904, 1, 1, 0, 0), DateUtil.getLocalDateTime(0.0, true)); - assertEquals(0.0, DateUtil.getExcelDate(LocalDateTime.of(1904, 1, 1, 0, 0), true), 0.00001); - assertEquals(1.0, DateUtil.getExcelDate(LocalDateTime.of(1904, 1, 2, 0, 0), true), 0.00001); - - assertEquals(LocalDateTime.of(1998, 7, 5, 0, 0), DateUtil.getLocalDateTime(35981, false)); - assertEquals(LocalDateTime.of(1998, 7, 5, 0, 0), DateUtil.getLocalDateTime(34519, true)); - - assertEquals(35981.0, DateUtil.getExcelDate(LocalDateTime.of(1998, 7, 5, 0, 0), false), 0.00001); - assertEquals(34519.0, DateUtil.getExcelDate(LocalDateTime.of(1998, 7, 5, 0, 0), true), 0.00001); - } - - /** - * @param month zero based - * @param day one based - */ - private static Date createDate(int year, int month, int day) { - return createDate(year, month, day, 0, 0); - } - - /** - * @param month zero based - * @param day one based - */ - private static Date createDate(int year, int month, int day, int hour, int minute) { - Calendar c = LocaleUtil.getLocaleCalendar(year, month, day, hour, minute, 0); - return c.getTime(); - } - - /** - * Check if DateUtil.getAbsoluteDay works as advertised. - */ - @Test - void absoluteDay() { - // 1 Jan 1900 is 1 day after 31 Dec 1899 - Calendar cal = LocaleUtil.getLocaleCalendar(1900,JANUARY,1,0,0,0); - assertEquals(1, DateUtil.absoluteDay(cal, false), "Checking absolute day (1 Jan 1900)"); - LocalDateTime ldt = LocalDateTime.of(1900,1,1,0,0,0); - assertEquals(1, DateUtil.absoluteDay(ldt, false), "Checking absolute day (1 Jan 1900) (LocalDateTime)"); - // 1 Jan 1901 is 366 days after 31 Dec 1899 - ldt = LocalDateTime.of(1901,1,1,0,0,0); - cal.set(1901,JANUARY,1,0,0,0); - assertEquals(366, DateUtil.absoluteDay(ldt, false), "Checking absolute day (1 Jan 1901) (LocalDateTime)"); - } - - @Test - void absoluteDayYearTooLow() { - Calendar cal = LocaleUtil.getLocaleCalendar(1899,JANUARY,1,0,0,0); - assertThrows(IllegalArgumentException.class, () -> DateUtil.absoluteDay(cal, false)); - - cal.set(1903,JANUARY,1,0,0,0); - assertThrows(IllegalArgumentException.class, () -> DateUtil.absoluteDay(cal, true)); - - // same for LocalDateTime - assertThrows(IllegalArgumentException.class, () -> DateUtil.absoluteDay(LocalDateTime.of(1899,1,1,0,0,0), false)); - assertThrows(IllegalArgumentException.class, () -> DateUtil.absoluteDay(LocalDateTime.of(1903,1,1,0,0,0), true)); - } - - @Test - void convertTime() { - - final double delta = 1E-7; // a couple of digits more accuracy than strictly required - assertEquals(0.5, DateUtil.convertTime("12:00"), delta); - assertEquals(2.0/3, DateUtil.convertTime("16:00"), delta); - assertEquals(0.0000116, DateUtil.convertTime("0:00:01"), delta); - assertEquals(0.7330440, DateUtil.convertTime("17:35:35"), delta); - } - - @Test - void parseDate() { - assertEquals(createDate(2008, AUGUST, 3), DateUtil.parseYYYYMMDDDate("2008/08/03")); - assertEquals(createDate(1994, MAY, 1), DateUtil.parseYYYYMMDDDate("1994/05/01")); - } - - /** - * Ensure that date values *with* a fractional portion get the right time of day - */ - @Test - void convertDateTime() { - // Excel day 30000 is date 18-Feb-1982 - // 0.7 corresponds to time 16:48:00 - Date actual = DateUtil.getJavaDate(30000.7); - Date expected = createDate(1982, 1, 18, 16, 48); - assertEquals(expected, actual); - - // note that months in Calendar are zero-based, in LocalDateTime one-based - LocalDateTime actualLocalDate = DateUtil.getLocalDateTime(30000.7); - LocalDateTime expectedLocalDate = LocalDateTime.of(1982, 2, 18, 16, 48, 0); - assertEquals(expectedLocalDate, actualLocalDate); - } - - /** - * User reported a datetime issue in POI-2.5: - * Setting Cell's value to Jan 1, 1900 without a time doesn't return the same value set to - */ - @Test - void bug19172() throws IOException { - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - HSSFSheet sheet = workbook.createSheet(); - HSSFCell cell = sheet.createRow(0).createCell(0); - - // A pseudo special Excel dates - Calendar cal = LocaleUtil.getLocaleCalendar(1900, JANUARY, 1); - - Date valueToTest = cal.getTime(); - - cell.setCellValue(valueToTest); - - Date returnedValue = cell.getDateCellValue(); - - assertEquals(valueToTest.getTime(), returnedValue.getTime()); - } - } - - /** - * DateUtil.isCellFormatted(Cell) should not true for a numeric cell - * that's formatted as ".0000" - */ - @Test - void bug54557() { - final String format = ".0000"; - boolean isDateFormat = DateUtil.isADateFormat(165, format); - - assertFalse(isDateFormat); - } - - @Test - void bug56269() { - double excelFraction = 41642.45833321759d; - Calendar calNoRound = DateUtil.getJavaCalendar(excelFraction, false); - assertEquals(10, calNoRound.get(Calendar.HOUR)); - assertEquals(59, calNoRound.get(Calendar.MINUTE)); - assertEquals(59, calNoRound.get(Calendar.SECOND)); - Calendar calRound = DateUtil.getJavaCalendar(excelFraction, false, null, true); - assertNotNull(calRound); - assertEquals(11, calRound.get(Calendar.HOUR)); - assertEquals(0, calRound.get(Calendar.MINUTE)); - assertEquals(0, calRound.get(Calendar.SECOND)); - - LocalDateTime ldtNoRound = DateUtil.getLocalDateTime(excelFraction, false); - assertEquals(10, ldtNoRound.getHour()); - assertEquals(59, ldtNoRound.getMinute()); - assertEquals(59, ldtNoRound.getSecond()); - LocalDateTime ldtRound = DateUtil.getLocalDateTime(excelFraction, false, true); - assertNotNull(ldtRound); - assertEquals(11, ldtRound.getHour()); - assertEquals(0, ldtRound.getMinute()); - assertEquals(0, ldtRound.getSecond()); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestExcelStyleDateFormatter.java b/src/testcases/org/apache/poi/ss/usermodel/TestExcelStyleDateFormatter.java deleted file mode 100644 index e27557e9b9..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestExcelStyleDateFormatter.java +++ /dev/null @@ -1,143 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.text.DateFormatSymbols; -import java.text.FieldPosition; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -class TestExcelStyleDateFormatter { - private static final String EXCEL_DATE_FORMAT = "MMMMM"; - private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT); - private static final int jreVersion = - Integer.parseInt(System.getProperty("java.version").replaceAll("^(?:1\\.)?(\\d+).*", "$1")); - private static final String provider = System.getProperty("java.locale.providers"); - private static final FieldPosition fp = new FieldPosition(java.text.DateFormat.MONTH_FIELD); - private static final ExcelStyleDateFormatter formatter = new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT); - - /** - * [Bug 60369] Month format 'MMMMM' issue with TEXT-formula and Java 8 - */ - @ParameterizedTest - @MethodSource("initializeLocales") - void test60369(Locale locale, String expected, Date d, int month) { - // Let's iterate over the test setup. - final StringBuffer sb = new StringBuffer(); - - formatter.setDateFormatSymbols(DateFormatSymbols.getInstance(locale)); - String result = formatter.format(d, sb, fp).toString(); - String msg = "Failed testDates for locale " + locale + ", provider: " + provider + - " and date " + d + ", having: " + result; - - int actIdx = localeIndex(locale); - - assertNotNull(result, msg); - assertTrue(result.length() > actIdx, msg); - assertEquals(expected.charAt(month), result.charAt(actIdx), msg); - } - - /** - * Depending on the JRE version, the provider setting and the locale, a different result - * is expected and selected via an index - */ - private static int localeIndex(Locale locale) { - return jreVersion < 9 || - !locale.equals (Locale.CHINESE) || - (provider != null && (provider.startsWith("JRE") || provider.startsWith("COMPAT"))) - ? 0 : 1; - } - - /** - * Setting up the locale to be tested together with a list of asserted - * unicode-formatted results and put them in a map. - */ - public static Stream initializeLocales() throws ParseException { - Object[][] locExps = { - { Locale.GERMAN, "JFMAMJJASOND" }, - { new Locale("de", "AT"), "JFMAMJJASOND" }, - { Locale.UK, "JFMAMJJASOND" }, - { new Locale("en", "IN"), "JFMAMJJASOND" }, - { new Locale("in", "ID"), "JFMAMJJASOND" }, - { Locale.FRENCH, "jfmamjjasond" }, - { new Locale("ru", "RU"), "\u044f\u0444\u043c\u0430\u043c\u0438\u0438\u0430\u0441\u043e\u043d\u0434" }, - { Locale.CHINESE, localeIndex(Locale.CHINESE) == 0 ? "\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u5341\u5341" : "123456789111" }, - { new Locale("tr", "TR"), "\u004f\u015e\u004d\u004e\u004d\u0048\u0054\u0041\u0045\u0045\u004b\u0041" }, - { new Locale("hu", "HU"), "\u006a\u0066\u006d\u00e1\u006d\u006a\u006a\u0061\u0073\u006f\u006e\u0064" } - }; - - String[] dates = { - "1980-01-12", "1995-02-11", "2045-03-10", "2016-04-09", "2017-05-08", - "1945-06-07", "1998-07-06", "2099-08-05", "1988-09-04", "2023-10-03", "1978-11-02", "1890-12-01" - }; - - List list = new ArrayList<>(locExps.length * dates.length); - for (Object[] locExp : locExps) { - int month = 0; - for (String date : dates) { - list.add(Arguments.of(locExp[0], locExp[1], DATE_FORMAT.parse(date), month++)); - } - } - return list.stream(); - } - - @Test - void testConstruct() { - assertDoesNotThrow(() -> new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT, LocaleUtil.getUserLocale())); - assertDoesNotThrow(() -> new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT)); - } - - @Test - void testWithLocale() throws ParseException { - Locale before = LocaleUtil.getUserLocale(); - try { - LocaleUtil.setUserLocale(Locale.GERMAN); - String dateStr = new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT).format( - DATE_FORMAT.parse("2016-03-26")); - assertEquals("M", dateStr); - } finally { - LocaleUtil.setUserLocale(before); - } - } - - @Test - void testWithPattern() throws ParseException { - String dateStr = new ExcelStyleDateFormatter("yyyy|" + EXCEL_DATE_FORMAT + "|").format( - DATE_FORMAT.parse("2016-03-26")); - assertEquals("2016|M|", dateStr); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestFractionFormat.java b/src/testcases/org/apache/poi/ss/usermodel/TestFractionFormat.java deleted file mode 100644 index 7a45018569..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestFractionFormat.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * Tests for the Fraction Formatting part of DataFormatter. - * Largely taken from bug #54686 - */ -final class TestFractionFormat { - @Test - void testSingle() { - FractionFormat f = new FractionFormat("", "##"); - double val = 321.321; - String ret = f.format(val); - assertEquals("26027/81", ret); - } - - @Test - void testInvalid() { - assertThrows(IllegalStateException.class, () -> new FractionFormat("", "9999999999999999999999999999")); - } - - @Disabled("Runs for some longer time") - @Test - void microBenchmark() { - FractionFormat f = new FractionFormat("", "##"); - double val = 321.321; - for(int i = 0;i < 1000000;i++) { - String ret = f.format(val); - assertEquals("26027/81", ret); - } - } - - @Test - void testWithBigWholePart() { - FractionFormat f = new FractionFormat("#", "???/???"); - - assertEquals("10100136259702", f.format(10100136259702d)); - assertEquals("-10100136259702", f.format(-10100136259702d)); - - // Excel displays fraction: 51/512 - assertEquals("10100136259702 10/100", f.format(10100136259702.1d)); - assertEquals("-10100136259702 10/100", f.format(-10100136259702.1d)); - - // Excel displays fraction: 461/512 - assertEquals("10100136259702 90/100", f.format(10100136259702.9d)); - assertEquals("-10100136259702 90/100", f.format(-10100136259702.9d)); - } - - @Test - void testTruthFile() throws Exception { - File truthFile = HSSFTestDataSamples.getSampleFile("54686_fraction_formats.txt"); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(truthFile), LocaleUtil.CHARSET_1252))) { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("54686_fraction_formats.xls"); - Sheet sheet = wb.getSheetAt(0); - DataFormatter formatter = new DataFormatter(); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - // Skip over the header row - String truthLine = reader.readLine(); - String[] headers = truthLine.split("\t"); - truthLine = reader.readLine(); - - for (int i = 1; i < sheet.getLastRowNum() && truthLine != null; i++) { - Row r = sheet.getRow(i); - String[] truths = truthLine.split("\t"); - // Intentionally ignore the last column (tika-1132), for now - for (short j = 3; j < 12; j++) { - Cell cell = r.getCell(j, MissingCellPolicy.CREATE_NULL_AS_BLANK); - String formatted = clean(formatter.formatCellValue(cell, evaluator)); - if (truths.length <= j) { - continue; - } - - String truth = clean(truths[j]); - String testKey = truths[0] + ":" + truths[1] + ":" + headers[j]; - assertEquals(truth, formatted, testKey); - } - truthLine = reader.readLine(); - } - wb.close(); - } - } - - private String clean(String s){ - s = s.trim().replaceAll(" +", " ").replaceAll("- +", "-"); - return s; - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestHSSFBorderStyle.java b/src/testcases/org/apache/poi/ss/usermodel/TestHSSFBorderStyle.java deleted file mode 100644 index 202ffae308..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestHSSFBorderStyle.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.hssf.HSSFITestDataProvider; - -/** - * @author Yegor Kozlov - */ -final class TestHSSFBorderStyle extends BaseTestBorderStyle { - - public TestHSSFBorderStyle() { - super(HSSFITestDataProvider.instance); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestIndexedColors.java b/src/testcases/org/apache/poi/ss/usermodel/TestIndexedColors.java deleted file mode 100644 index d336ea95cd..0000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestIndexedColors.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.junit.jupiter.api.Test; - -/** - * @author Yegor Kozlov - */ -final class TestIndexedColors { - - @Test - void fromInt() { - int[] illegalIndices = { -1, 65 }; - for (int index : illegalIndices) { - assertThrows(IllegalArgumentException.class, () -> IndexedColors.fromInt(index)); - } - assertEquals(IndexedColors.BLACK, IndexedColors.fromInt(8)); - assertEquals(IndexedColors.GOLD, IndexedColors.fromInt(51)); - assertEquals(IndexedColors.AUTOMATIC, IndexedColors.fromInt(64)); - } - - @Test - void getIndex() { - assertEquals(51, IndexedColors.GOLD.getIndex()); - } - - @Test - void index() { - assertEquals(51, IndexedColors.GOLD.index); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/util/BaseTestCellUtil.java b/src/testcases/org/apache/poi/ss/util/BaseTestCellUtil.java deleted file mode 100644 index caef1acf52..0000000000 --- a/src/testcases/org/apache/poi/ss/util/BaseTestCellUtil.java +++ /dev/null @@ -1,381 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Tests Spreadsheet CellUtil - * - * @see org.apache.poi.ss.util.CellUtil - */ -public abstract class BaseTestCellUtil { - protected final ITestDataProvider _testDataProvider; - - protected BaseTestCellUtil(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - void setCellStyleProperty() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); - - // Add a border should create a new style - int styCnt1 = wb.getNumCellStyles(); - CellUtil.setCellStyleProperty(c, CellUtil.BORDER_BOTTOM, BorderStyle.THIN); - int styCnt2 = wb.getNumCellStyles(); - assertEquals(styCnt1 + 1, styCnt2); - - // Add same border to another cell, should not create another style - c = r.createCell(1); - CellUtil.setCellStyleProperty(c, CellUtil.BORDER_BOTTOM, BorderStyle.THIN); - int styCnt3 = wb.getNumCellStyles(); - assertEquals(styCnt2, styCnt3); - } - } - - @Test - void setCellStylePropertyWithInvalidValue() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); - - // An invalid BorderStyle constant - assertThrows(RuntimeException.class, () -> CellUtil.setCellStyleProperty(c, CellUtil.BORDER_BOTTOM, 42)); - } - } - - @Test() - void setCellStylePropertyBorderWithShortAndEnum() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); - - // A valid BorderStyle constant, as a Short - CellUtil.setCellStyleProperty(c, CellUtil.BORDER_BOTTOM, BorderStyle.DASH_DOT.getCode()); - assertEquals(BorderStyle.DASH_DOT, c.getCellStyle().getBorderBottom()); - - // A valid BorderStyle constant, as an Enum - CellUtil.setCellStyleProperty(c, CellUtil.BORDER_TOP, BorderStyle.MEDIUM_DASH_DOT); - assertEquals(BorderStyle.MEDIUM_DASH_DOT, c.getCellStyle().getBorderTop()); - } - } - - @Test - void setCellStyleProperties() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); - - // Add multiple border properties to cell should create a single new style - int styCnt1 = wb.getNumCellStyles(); - Map props = new HashMap<>(); - props.put(CellUtil.BORDER_TOP, BorderStyle.THIN); - props.put(CellUtil.BORDER_BOTTOM, BorderStyle.THIN); - props.put(CellUtil.BORDER_LEFT, BorderStyle.THIN); - props.put(CellUtil.BORDER_RIGHT, BorderStyle.THIN); - props.put(CellUtil.ALIGNMENT, HorizontalAlignment.CENTER.getCode()); // try it both with a Short (deprecated) - props.put(CellUtil.VERTICAL_ALIGNMENT, VerticalAlignment.CENTER); // and with an enum - CellUtil.setCellStyleProperties(c, props); - int styCnt2 = wb.getNumCellStyles(); - assertEquals(styCnt1 + 1, styCnt2, "Only one additional style should have been created"); - - // Add same border another to same cell, should not create another style - c = r.createCell(1); - CellUtil.setCellStyleProperties(c, props); - int styCnt3 = wb.getNumCellStyles(); - assertEquals(styCnt2, styCnt3, "No additional styles should have been created"); - } - } - - @Test - void getRow() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sh = wb.createSheet(); - Row row1 = sh.createRow(0); - - // Get row that already exists - Row r1 = CellUtil.getRow(0, sh); - assertNotNull(r1); - assertSame(row1, r1, "An existing row should not be recreated"); - - // Get row that does not exist yet - assertNotNull(CellUtil.getRow(1, sh)); - } - } - - @Test - void getCell() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - Cell A1 = row.createCell(0); - - // Get cell that already exists - Cell a1 = CellUtil.getCell(row, 0); - assertNotNull(a1); - assertSame(A1, a1, "An existing cell should not be recreated"); - - // Get cell that does not exist yet - assertNotNull(CellUtil.getCell(row, 1)); - } - } - - @Test - void createCell() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - - CellStyle style = wb.createCellStyle(); - style.setWrapText(true); - - // calling createCell on a non-existing cell should create a cell and set the cell value and style. - Cell F1 = CellUtil.createCell(row, 5, "Cell Value", style); - - assertSame(row.getCell(5), F1); - assertEquals("Cell Value", F1.getStringCellValue()); - assertEquals(style, F1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. - // HSSFCellStyle wraps an underlying style record, and the underlying - // style record is the same between multiple getCellStyle() calls. - - // calling createCell on an existing cell should return the existing cell and modify the cell value and style. - Cell f1 = CellUtil.createCell(row, 5, "Overwritten cell value", null); - assertSame(row.getCell(5), f1); - assertSame(F1, f1); - assertEquals("Overwritten cell value", f1.getStringCellValue()); - assertEquals("Overwritten cell value", F1.getStringCellValue()); - assertEquals(style, f1.getCellStyle(), "cell style should be unchanged with createCell(..., null)"); - assertEquals(style, F1.getCellStyle(), "cell style should be unchanged with createCell(..., null)"); - - // test createCell(row, column, value) (no CellStyle) - f1 = CellUtil.createCell(row, 5, "Overwritten cell with default style"); - assertSame(F1, f1); - } - } - - /** - * @deprecated by {@link #setAlignmentEnum()} - */ - @Deprecated - @SuppressWarnings("deprecated") - @Test - void setAlignment() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - - // Assumptions - assertEquals(A1.getCellStyle(), B1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. - // HSSFCellStyle wraps an underlying style record, and the underlying - // style record is the same between multiple getCellStyle() calls. - assertEquals(HorizontalAlignment.GENERAL, A1.getCellStyle().getAlignment()); - assertEquals(HorizontalAlignment.GENERAL, B1.getCellStyle().getAlignment()); - - // get/set alignment modifies the cell's style - CellUtil.setAlignment(A1, HorizontalAlignment.RIGHT); - assertEquals(HorizontalAlignment.RIGHT, A1.getCellStyle().getAlignment()); - - // get/set alignment doesn't affect the style of cells with - // the same style prior to modifying the style - assertNotEquals(A1.getCellStyle(), B1.getCellStyle()); - assertEquals(HorizontalAlignment.GENERAL, B1.getCellStyle().getAlignment()); - - wb.close(); - } - - @Test - void setAlignmentEnum() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - - // Assumptions - assertEquals(A1.getCellStyle(), B1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. - // HSSFCellStyle wraps an underlying style record, and the underlying - // style record is the same between multiple getCellStyle() calls. - assertEquals(HorizontalAlignment.GENERAL, A1.getCellStyle().getAlignment()); - assertEquals(HorizontalAlignment.GENERAL, B1.getCellStyle().getAlignment()); - - // get/set alignment modifies the cell's style - CellUtil.setAlignment(A1, HorizontalAlignment.RIGHT); - assertEquals(HorizontalAlignment.RIGHT, A1.getCellStyle().getAlignment()); - - // get/set alignment doesn't affect the style of cells with - // the same style prior to modifying the style - assertNotEquals(A1.getCellStyle(), B1.getCellStyle()); - assertEquals(HorizontalAlignment.GENERAL, B1.getCellStyle().getAlignment()); - - wb.close(); - } - - @Test - void setVerticalAlignmentEnum() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - - // Assumptions - assertEquals(A1.getCellStyle(), B1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. - // HSSFCellStyle wraps an underlying style record, and the underlying - // style record is the same between multiple getCellStyle() calls. - assertEquals(VerticalAlignment.BOTTOM, A1.getCellStyle().getVerticalAlignment()); - assertEquals(VerticalAlignment.BOTTOM, B1.getCellStyle().getVerticalAlignment()); - - // get/set alignment modifies the cell's style - CellUtil.setVerticalAlignment(A1, VerticalAlignment.TOP); - assertEquals(VerticalAlignment.TOP, A1.getCellStyle().getVerticalAlignment()); - - // get/set alignment doesn't affect the style of cells with - // the same style prior to modifying the style - assertNotEquals(A1.getCellStyle(), B1.getCellStyle()); - assertEquals(VerticalAlignment.BOTTOM, B1.getCellStyle().getVerticalAlignment()); - } - } - - @Test - void setFont() throws IOException { - try (Workbook wb = _testDataProvider.createWorkbook()) { - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - final int defaultFontIndex = 0; - Font font = wb.createFont(); - font.setItalic(true); - final int customFontIndex = font.getIndex(); - - // Assumptions - assertNotEquals(defaultFontIndex, customFontIndex); - assertEquals(A1.getCellStyle(), B1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. - // HSSFCellStyle wraps an underlying style record, and the underlying - // style record is the same between multiple getCellStyle() calls. - assertEquals(defaultFontIndex, A1.getCellStyle().getFontIndex()); - assertEquals(defaultFontIndex, B1.getCellStyle().getFontIndex()); - - // get/set alignment modifies the cell's style - CellUtil.setFont(A1, font); - assertEquals(customFontIndex, A1.getCellStyle().getFontIndex()); - - // get/set alignment doesn't affect the style of cells with - // the same style prior to modifying the style - assertNotEquals(A1.getCellStyle(), B1.getCellStyle()); - assertEquals(defaultFontIndex, B1.getCellStyle().getFontIndex()); - } - } - - @Test - void setFontFromDifferentWorkbook() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook(); - Workbook wb2 = _testDataProvider.createWorkbook()) { - Font font1 = wb1.createFont(); - Font font2 = wb2.createFont(); - // do something to make font1 and font2 different - // so they are not same or equal. - font1.setItalic(true); - Cell A1 = wb1.createSheet().createRow(0).createCell(0); - - // okay - CellUtil.setFont(A1, font1); - - // font belongs to different workbook - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> CellUtil.setFont(A1, font2)); - assertTrue(e.getMessage().startsWith("Font does not belong to this workbook")); - } - } - - /** - * bug 55555 - * @since POI 3.15 beta 3 - */ - @Test - void setFillForegroundColorBeforeFillBackgroundColorEnum() throws IOException { - try (Workbook wb1 = _testDataProvider.createWorkbook()) { - Cell A1 = wb1.createSheet().createRow(0).createCell(0); - Map properties = new HashMap<>(); - properties.put(CellUtil.FILL_PATTERN, FillPatternType.BRICKS); - properties.put(CellUtil.FILL_FOREGROUND_COLOR, IndexedColors.BLUE.index); - properties.put(CellUtil.FILL_BACKGROUND_COLOR, IndexedColors.RED.index); - - CellUtil.setCellStyleProperties(A1, properties); - CellStyle style = A1.getCellStyle(); - assertEquals(FillPatternType.BRICKS, style.getFillPattern(), "fill pattern"); - assertEquals(IndexedColors.BLUE, IndexedColors.fromInt(style.getFillForegroundColor()), "fill foreground color"); - assertEquals(IndexedColors.RED, IndexedColors.fromInt(style.getFillBackgroundColor()), "fill background color"); - } - } - - /** - * bug 63268 - * @since POI 4.1.0 - */ - @Test - void setFontShouldNotCreateDuplicateStyle() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Cell c = wb1.createSheet().createRow(1).createCell(1); - Font f = wb1.createFont(); - - CellUtil.setFont(c, f); - int num1 = wb1.getNumCellStyles(); - - CellUtil.setFont(c, f); - int num2 = wb1.getNumCellStyles(); - assertEquals(num1, num2); - wb1.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/NumberComparingSpreadsheetGenerator.java b/src/testcases/org/apache/poi/ss/util/NumberComparingSpreadsheetGenerator.java deleted file mode 100644 index d8664487ce..0000000000 --- a/src/testcases/org/apache/poi/ss/util/NumberComparingSpreadsheetGenerator.java +++ /dev/null @@ -1,146 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.NumberComparisonExamples.ComparisonExample; -import org.apache.poi.util.HexDump; - -/** - * Creates a spreadsheet that checks Excel's comparison of various IEEE double values. - * The class {@link NumberComparisonExamples} contains specific comparison examples - * (along with their expected results) that get encoded into rows of the spreadsheet. - * Each example is checked with a formula (in column I) that displays either "OK" or - * "ERROR" depending on whether actual results match those expected. - * - * @author Josh Micich - */ -public class NumberComparingSpreadsheetGenerator { - - private static final class SheetWriter { - - private final HSSFSheet _sheet; - private int _rowIndex; - - public SheetWriter(HSSFWorkbook wb) { - HSSFSheet sheet = wb.createSheet("Sheet1"); - - writeHeaderRow(wb, sheet); - _sheet = sheet; - _rowIndex = 1; - } - - void addTestRow(double a, double b, int expResult) { - writeDataRow(_sheet, _rowIndex++, a, b, expResult); - } - } - - private static void writeHeaderCell(HSSFRow row, int i, String text, HSSFCellStyle style) { - HSSFCell cell = row.createCell(i); - cell.setCellValue(new HSSFRichTextString(text)); - cell.setCellStyle(style); - } - static void writeHeaderRow(HSSFWorkbook wb, HSSFSheet sheet) { - sheet.setColumnWidth(0, 6000); - sheet.setColumnWidth(1, 6000); - sheet.setColumnWidth(2, 3600); - sheet.setColumnWidth(3, 3600); - sheet.setColumnWidth(4, 2400); - sheet.setColumnWidth(5, 2400); - sheet.setColumnWidth(6, 2400); - sheet.setColumnWidth(7, 2400); - sheet.setColumnWidth(8, 2400); - HSSFRow row = sheet.createRow(0); - HSSFCellStyle style = wb.createCellStyle(); - HSSFFont font = wb.createFont(); - font.setBold(true); - style.setFont(font); - writeHeaderCell(row, 0, "Raw Long Bits A", style); - writeHeaderCell(row, 1, "Raw Long Bits B", style); - writeHeaderCell(row, 2, "Value A", style); - writeHeaderCell(row, 3, "Value B", style); - writeHeaderCell(row, 4, "Exp Cmp", style); - writeHeaderCell(row, 5, "LT", style); - writeHeaderCell(row, 6, "EQ", style); - writeHeaderCell(row, 7, "GT", style); - writeHeaderCell(row, 8, "Check", style); - } - /** - * Fills a spreadsheet row with one comparison example. The two numeric values are written to - * columns C and D. Columns (F, G and H) respectively get formulas ("v0v1"), - * which will be evaluated by Excel. Column D gets the expected comparison result. Column I - * gets a formula to check that Excel's comparison results match that predicted in column D. - * - * @param v0 the first value to be compared - * @param v1 the second value to be compared - * @param expRes expected comparison result (-1, 0, or +1) - */ - static void writeDataRow(HSSFSheet sheet, int rowIx, double v0, double v1, int expRes) { - HSSFRow row = sheet.createRow(rowIx); - - int rowNum = rowIx + 1; - - - row.createCell(0).setCellValue(formatDoubleAsHex(v0)); - row.createCell(1).setCellValue(formatDoubleAsHex(v1)); - row.createCell(2).setCellValue(v0); - row.createCell(3).setCellValue(v1); - row.createCell(4).setCellValue(expRes < 0 ? "LT" : expRes > 0 ? "GT" : "EQ"); - row.createCell(5).setCellFormula("C" + rowNum + "<" + "D" + rowNum); - row.createCell(6).setCellFormula("C" + rowNum + "=" + "D" + rowNum); - row.createCell(7).setCellFormula("C" + rowNum + ">" + "D" + rowNum); - // TODO - bug elsewhere in POI - something wrong with encoding of NOT() function - String frm = "if(or(" + - "and(E#='LT', F# , G#=FALSE, H#=FALSE)," + - "and(E#='EQ', F#=FALSE, G# , H#=FALSE)," + - "and(E#='GT', F#=FALSE, G#=FALSE, H# )" + - "), 'OK', 'error')" ; - row.createCell(8).setCellFormula(frm.replaceAll("#", String.valueOf(rowNum)).replace('\'', '"')); - } - - private static String formatDoubleAsHex(double d) { - long l = Double.doubleToLongBits(d); - return HexDump.longToHex(l)+'L'; - } - - public static void main(String[] args) throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { - SheetWriter sw = new SheetWriter(wb); - ComparisonExample[] ces = NumberComparisonExamples.getComparisonExamples(); - for (ComparisonExample ce : ces) { - sw.addTestRow(ce.getA(), ce.getB(), ce.getExpectedResult()); - } - - File outputFile = new File("ExcelNumberCompare.xls"); - try (FileOutputStream os = new FileOutputStream(outputFile)) { - wb.write(os); - } - System.out.println("Finished writing '" + outputFile.getAbsolutePath() + "'"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/util/NumberComparisonExamples.java b/src/testcases/org/apache/poi/ss/util/NumberComparisonExamples.java deleted file mode 100644 index 925f968b37..0000000000 --- a/src/testcases/org/apache/poi/ss/util/NumberComparisonExamples.java +++ /dev/null @@ -1,165 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Contains specific examples of double value pairs and their comparison result according to Excel. - * - * @author Josh Micich - */ -final class NumberComparisonExamples { - - private NumberComparisonExamples() { - // no instances of this class - } - - /** - * represents one comparison test case - */ - public static final class ComparisonExample { - private final long _rawBitsA; - private final long _rawBitsB; - private final int _expectedResult; - - public ComparisonExample(long rawBitsA, long rawBitsB, int expectedResult) { - _rawBitsA = rawBitsA; - _rawBitsB = rawBitsB; - _expectedResult = expectedResult; - } - - public double getA() { - return Double.longBitsToDouble(_rawBitsA); - } - public double getB() { - return Double.longBitsToDouble(_rawBitsB); - } - public double getNegA() { - return -Double.longBitsToDouble(_rawBitsA); - } - public double getNegB() { - return -Double.longBitsToDouble(_rawBitsB); - } - public int getExpectedResult() { - return _expectedResult; - } - } - - private static final ComparisonExample[] examples = initExamples(); - - private static ComparisonExample[] initExamples() { - - List temp = new ArrayList<>(); - - addStepTransition(temp, 0x4010000000000005L); - addStepTransition(temp, 0x4010000000000010L); - addStepTransition(temp, 0x401000000000001CL); - - addStepTransition(temp, 0x403CE0FFFFFFFFF1L); - - addStepTransition(temp, 0x5010000000000006L); - addStepTransition(temp, 0x5010000000000010L); - addStepTransition(temp, 0x501000000000001AL); - - addStepTransition(temp, 0x544CE6345CF32018L); - addStepTransition(temp, 0x544CE6345CF3205AL); - addStepTransition(temp, 0x544CE6345CF3209CL); - addStepTransition(temp, 0x544CE6345CF320DEL); - - addStepTransition(temp, 0x54B250001000101DL); - addStepTransition(temp, 0x54B2500010001050L); - addStepTransition(temp, 0x54B2500010001083L); - - addStepTransition(temp, 0x6230100010001000L); - addStepTransition(temp, 0x6230100010001005L); - addStepTransition(temp, 0x623010001000100AL); - - addStepTransition(temp, 0x7F50300020001011L); - addStepTransition(temp, 0x7F5030002000102BL); - addStepTransition(temp, 0x7F50300020001044L); - - - addStepTransition(temp, 0x2B2BFFFF1000102AL); - addStepTransition(temp, 0x2B2BFFFF10001079L); - addStepTransition(temp, 0x2B2BFFFF100010C8L); - - addStepTransition(temp, 0x2B2BFF001000102DL); - addStepTransition(temp, 0x2B2BFF0010001035L); - addStepTransition(temp, 0x2B2BFF001000103DL); - - addStepTransition(temp, 0x2B61800040002024L); - addStepTransition(temp, 0x2B61800040002055L); - addStepTransition(temp, 0x2B61800040002086L); - - - addStepTransition(temp, 0x008000000000000BL); - // just outside 'subnormal' range - addStepTransition(temp, 0x0010000000000007L); - addStepTransition(temp, 0x001000000000001BL); - addStepTransition(temp, 0x001000000000002FL); - - Collections.addAll(temp, new ComparisonExample[]{ - // negative, and exponents differ by more than 1 - ce(0xBF30000000000000L, 0xBE60000000000000L, -1), - - // negative zero *is* less than positive zero, but not easy to get out of calculations - ce(0x0000000000000000L, 0x8000000000000000L, +1), - // subnormal numbers compare without rounding for some reason - ce(0x0000000000000000L, 0x0000000000000001L, -1), - ce(0x0008000000000000L, 0x0008000000000001L, -1), - ce(0x000FFFFFFFFFFFFFL, 0x000FFFFFFFFFFFFEL, +1), - ce(0x000FFFFFFFFFFFFBL, 0x000FFFFFFFFFFFFCL, -1), - ce(0x000FFFFFFFFFFFFBL, 0x000FFFFFFFFFFFFEL, -1), - - // across subnormal threshold (some mistakes when close) - ce(0x000FFFFFFFFFFFFFL, 0x0010000000000000L, +1), - ce(0x000FFFFFFFFFFFFBL, 0x0010000000000007L, +1), - ce(0x000FFFFFFFFFFFFAL, 0x0010000000000007L, 0), - - // when a bit further apart - normal results - ce(0x000FFFFFFFFFFFF9L, 0x0010000000000007L, -1), - ce(0x000FFFFFFFFFFFFAL, 0x0010000000000008L, -1), - ce(0x000FFFFFFFFFFFFBL, 0x0010000000000008L, -1), - }); - - ComparisonExample[] result = new ComparisonExample[temp.size()]; - temp.toArray(result); - return result; - } - - private static ComparisonExample ce(long rawBitsA, long rawBitsB, int expectedResult) { - return new ComparisonExample(rawBitsA, rawBitsB, expectedResult); - } - - private static void addStepTransition(List temp, long rawBits) { - Collections.addAll(temp, new ComparisonExample[]{ - ce(rawBits - 1, rawBits + 0, 0), - ce(rawBits + 0, rawBits + 1, -1), - ce(rawBits + 1, rawBits + 2, 0), - }); - - } - - public static ComparisonExample[] getComparisonExamples() { - return examples.clone(); - } - -} diff --git a/src/testcases/org/apache/poi/ss/util/NumberRenderingSpreadsheetGenerator.java b/src/testcases/org/apache/poi/ss/util/NumberRenderingSpreadsheetGenerator.java deleted file mode 100644 index 0014a1f539..0000000000 --- a/src/testcases/org/apache/poi/ss/util/NumberRenderingSpreadsheetGenerator.java +++ /dev/null @@ -1,248 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.NumberToTextConversionExamples.ExampleConversion; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; - -/** - * Creates a spreadsheet that demonstrates Excel's rendering of various IEEE double values. - * - * @author Josh Micich - */ -public class NumberRenderingSpreadsheetGenerator { - - private static final class SheetWriter { - - private final HSSFSheet _sheet; - private int _rowIndex; - private final List _replacementNaNs; - - public SheetWriter(HSSFWorkbook wb) { - HSSFSheet sheet = wb.createSheet("Sheet1"); - - writeHeaderRow(wb, sheet); - _sheet = sheet; - _rowIndex = 1; - _replacementNaNs = new ArrayList<>(); - } - - void addTestRow(long rawBits, String expectedExcelRendering) { - writeDataRow(_sheet, _rowIndex++, rawBits, expectedExcelRendering); - if(Double.isNaN(Double.longBitsToDouble(rawBits))) { - _replacementNaNs.add(Long.valueOf(rawBits)); - } - } - - public long[] getReplacementNaNs() { - int nRepls = _replacementNaNs.size(); - long[] result = new long[nRepls]; - for (int i = 0; i < nRepls; i++) { - result[i] = _replacementNaNs.get(i).longValue(); - } - return result; - } - - } - /** 0x7ff8000000000000 encoded in little endian order */ - private static final byte[] JAVA_NAN_BYTES = HexRead.readFromString("00 00 00 00 00 00 F8 7F"); - - private static void writeHeaderCell(HSSFRow row, int i, String text, HSSFCellStyle style) { - HSSFCell cell = row.createCell(i); - cell.setCellValue(new HSSFRichTextString(text)); - cell.setCellStyle(style); - } - static void writeHeaderRow(HSSFWorkbook wb, HSSFSheet sheet) { - sheet.setColumnWidth(0, 3000); - sheet.setColumnWidth(1, 6000); - sheet.setColumnWidth(2, 6000); - sheet.setColumnWidth(3, 6000); - sheet.setColumnWidth(4, 6000); - sheet.setColumnWidth(5, 1600); - sheet.setColumnWidth(6, 20000); - HSSFRow row = sheet.createRow(0); - HSSFCellStyle style = wb.createCellStyle(); - HSSFFont font = wb.createFont(); - font.setBold(true); - style.setFont(font); - writeHeaderCell(row, 0, "Value", style); - writeHeaderCell(row, 1, "Raw Long Bits", style); - writeHeaderCell(row, 2, "JDK Double Rendering", style); - writeHeaderCell(row, 3, "Actual Rendering", style); - writeHeaderCell(row, 4, "Expected Rendering", style); - writeHeaderCell(row, 5, "Match", style); - writeHeaderCell(row, 6, "Java Metadata", style); - } - static void writeDataRow(HSSFSheet sheet, int rowIx, long rawLongBits, String expectedExcelRendering) { - double d = Double.longBitsToDouble(rawLongBits); - HSSFRow row = sheet.createRow(rowIx); - - int rowNum = rowIx + 1; - String cel0ref = "A" + rowNum; - String rawBitsText = formatLongAsHex(rawLongBits); - String jmExpr = "'ec(" + rawBitsText + ", ''\" & C" + rowNum + " & \"'', ''\" & D" + rowNum + " & \"''),'"; - - // The 'Match' column will contain 'OK' if the metadata (from NumberToTextConversionExamples) - // matches Excel's rendering. - String matchExpr = "if(D" + rowNum + "=E" + rowNum + ", \"OK\", \"ERROR\")"; - - row.createCell(0).setCellValue(d); - row.createCell(1).setCellValue(new HSSFRichTextString(rawBitsText)); - row.createCell(2).setCellValue(new HSSFRichTextString(Double.toString(d))); - row.createCell(3).setCellFormula("\"\" & " + cel0ref); - row.createCell(4).setCellValue(new HSSFRichTextString(expectedExcelRendering)); - row.createCell(5).setCellFormula(matchExpr); - row.createCell(6).setCellFormula(jmExpr.replaceAll("'", "\"")); - -// if (false) { -// // for observing arithmetic near numeric range boundaries -// row.createCell(7).setCellFormula(cel0ref + " * 1.0001"); -// row.createCell(8).setCellFormula(cel0ref + " / 1.0001"); -// } - } - - private static String formatLongAsHex(long l) { - return HexDump.longToHex(l) + 'L'; - } - - public static void main(String[] args) { - writeJavaDoc(); - - HSSFWorkbook wb = new HSSFWorkbook(); - SheetWriter sw = new SheetWriter(wb); - - ExampleConversion[] exampleValues = NumberToTextConversionExamples.getExampleConversions(); - for (ExampleConversion example : exampleValues) { - sw.addTestRow(example.getRawDoubleBits(), example.getExcelRendering()); - } - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - wb.write(baos); - } catch (IOException e) { - throw new RuntimeException(e); - } - byte[] fileContent = baos.toByteArray(); - replaceNaNs(fileContent, sw.getReplacementNaNs()); - - - File outputFile = new File("ExcelNumberRendering.xls"); - - try { - FileOutputStream os = new FileOutputStream(outputFile); - os.write(fileContent); - os.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - System.out.println("Finished writing '" + outputFile.getAbsolutePath() + "'"); - } - - public static void writeJavaDoc() { - - ExampleConversion[] exampleConversions = NumberToTextConversionExamples.getExampleConversions(); - for (ExampleConversion ec : exampleConversions) { - String line = " * " - + formatLongAsHex(ec.getRawDoubleBits()) - + "" + Double.toString(ec.getDoubleValue()) - + "" + ec.getExcelRendering() + ""; - - System.out.println(line); - } - } - - - - private static void replaceNaNs(byte[] fileContent, long[] replacementNaNs) { - int countFound = 0; - for(int i=0; i> 56); - bb[i+6] = (byte) (val >> 48); - bb[i+5] = (byte) (val >> 40); - bb[i+4] = (byte) (val >> 32); - bb[i+3] = (byte) (val >> 24); - bb[i+2] = (byte) (val >> 16); - bb[i+1] = (byte) (val >> 8); - bb[i+0] = (byte) (val >> 0); -// if (false) { -// String newVal = interpretLong(bb, i); -// System.out.println("changed offset " + i + " from " + oldVal + " to " + newVal); -// } - - } - - private static String interpretLong(byte[] fileContent, int offset) { - InputStream is = new ByteArrayInputStream(fileContent, offset, 8); - long l; - try { - l = new DataInputStream(is).readLong(); - } catch (IOException e) { - throw new RuntimeException(e); - } - return "0x" + Long.toHexString(l).toUpperCase(Locale.ROOT); - } - - private static boolean isNaNBytes(byte[] fileContent, int offset) { - if(offset + JAVA_NAN_BYTES.length > fileContent.length) { - return false; - } - // excel NaN bits: 0xFFFF0420003C0000L - // java NaN bits :0x7ff8000000000000L - return areArraySectionsEqual(fileContent, offset, JAVA_NAN_BYTES); - } - private static boolean areArraySectionsEqual(byte[] bb, int off, byte[] section) { - for (int i=section.length-1; i>=0; i--) { - if (bb[off+i] != section[i]){ - return false; - } - } - return true; - } -} diff --git a/src/testcases/org/apache/poi/ss/util/NumberToTextConversionExamples.java b/src/testcases/org/apache/poi/ss/util/NumberToTextConversionExamples.java deleted file mode 100644 index 1dcedc97a2..0000000000 --- a/src/testcases/org/apache/poi/ss/util/NumberToTextConversionExamples.java +++ /dev/null @@ -1,278 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import java.util.Locale; - -/** - * Contains specific examples of double values and their rendering in Excel. - */ -final class NumberToTextConversionExamples { - - private NumberToTextConversionExamples() { - // no instances of this class - } - - public static final class ExampleConversion { - private final String _javaRendering; - private final String _excelRendering; - private final double _doubleValue; - private final long _rawDoubleBits; - - ExampleConversion(long rawDoubleBits, String javaRendering, String excelRendering) { - double d = Double.longBitsToDouble(rawDoubleBits); - if ("NaN".equals(javaRendering)) { - if (!Double.isNaN(d)) { - throw new IllegalArgumentException("value must be NaN"); - } - } else { - if (Double.isNaN(d)) { - throw new IllegalArgumentException("value must not be NaN"); - } - // just to be dead sure test conversion in java both ways - boolean javaToStringOk = javaRendering.equals(Double.toString(d)); - boolean javaParseOk = Double.parseDouble(javaRendering) == d; - if(!javaToStringOk || !javaParseOk) { - String msgA = "Specified rawDoubleBits " + doubleToHexString(d) + " encodes to double '" + d + "'."; - String msgB = "Specified javaRendering '" + javaRendering+ "' parses as double with rawDoubleBits " - + doubleToHexString(Double.parseDouble(javaRendering)); - System.err.println(msgA); - System.err.println(msgB); - - throw new RuntimeException(msgA + msgB); - } - } - _rawDoubleBits = rawDoubleBits; - _javaRendering = javaRendering; - _excelRendering = excelRendering; - _doubleValue = d; - } - private static String doubleToHexString(double d) { - return "0x" + Long.toHexString(Double.doubleToLongBits(d)).toUpperCase(Locale.ROOT) + "L"; - } - public String getJavaRendering() { - return _javaRendering; - } - public String getExcelRendering() { - return _excelRendering; - } - public double getDoubleValue() { - return _doubleValue; - } - public boolean isNaN() { - return Double.isNaN(_doubleValue); - } - public long getRawDoubleBits() { - return _rawDoubleBits; - } - } - - - /** - * Number rendering examples as observed from Excel. - * TODO - some are currently disabled because POI does not pass these cases yet - */ - private static final ExampleConversion[] examples = { - - // basic numbers - ec(0x0000000000000000L, "0.0", "0"), - ec(0x3FF0000000000000L, "1.0", "1"), - ec(0x3FF00068DB8BAC71L, "1.0001", "1.0001"), - ec(0x4087A00000000000L, "756.0", "756"), - ec(0x401E3D70A3D70A3DL, "7.56", "7.56"), - - ec(0x405EDD3C07FB4C8CL, "123.4567890123455", "123.456789012345"), - ec(0x405EDD3C07FB4C99L, "123.45678901234568", "123.456789012346"), - ec(0x405EDD3C07FB4CAEL, "123.45678901234598", "123.456789012346"), - ec(0x4132D687E3DF2180L, "1234567.8901234567", "1234567.89012346"), - - ec(0x3F543A272D9E0E49L, "0.001234567890123455", "0.00123456789012345"), - ec(0x3F543A272D9E0E4AL, "0.0012345678901234552", "0.00123456789012346"), - ec(0x3F543A272D9E0E55L, "0.0012345678901234576", "0.00123456789012346"), - ec(0x3F543A272D9E0E72L, "0.0012345678901234639", "0.00123456789012346"), - ec(0x3F543A272D9E0E76L, "0.0012345678901234647", "0.00123456789012346"), - ec(0x3F543A272D9E0E77L, "0.001234567890123465", "0.00123456789012346"), - - ec(0x3F543A272D9E0E78L, "0.0012345678901234652", "0.00123456789012347"), - - ec(0x3F543A272D9E0EA5L, "0.001234567890123475", "0.00123456789012347"), - ec(0x3F543A272D9E0EA6L, "0.0012345678901234751", "0.00123456789012348"), - - - ec(0x544CE6345CF3209CL, "1.2345678901234549E98", "1.23456789012345E+98"), - ec(0x544CE6345CF3209DL, "1.234567890123455E98", "1.23456789012346E+98"), - ec(0x544CE6345CF320DEL, "1.2345678901234649E98", "1.23456789012346E+98"), - ec(0x544CE6345CF320DFL, "1.234567890123465E98", "1.23456789012347E+98"), - ec(0x544CE6345CF32120L, "1.234567890123475E98", "1.23456789012347E+98"), - ec(0x544CE6345CF32121L, "1.2345678901234751E98", "1.23456789012348E+98"), - - - ec(0x54820FE0BA17F5E9L, "1.23456789012355E99", "1.2345678901236E+99"), - ec(0x54820FE0BA17F5EAL, "1.2345678901235502E99", "1.2345678901236E+99"), - ec(0x54820FE0BA17F784L, "1.2345678901236498E99", "1.2345678901237E+99"), - ec(0x54820FE0BA17F785L, "1.23456789012365E99", "1.2345678901237E+99"), - ec(0x54820FE0BA17F920L, "1.2345678901237498E99", "1.2345678901238E+99"), - ec(0x54820FE0BA17F921L, "1.23456789012375E99", "1.2345678901238E+99"), - - - // transitions around the E98,E99,E100 boundaries - ec(0x547D42AEA2879F19L,"9.999999999999974E98", "9.99999999999997E+98"), - ec(0x547D42AEA2879F1AL,"9.999999999999975E98", "9.99999999999998E+98"), - ec(0x547D42AEA2879F21L,"9.999999999999984E98", "9.99999999999998E+98"), - ec(0x547D42AEA2879F22L,"9.999999999999985E98", "9.99999999999999E+98"), - ec(0x547D42AEA2879F2AL,"9.999999999999995E98", "9.99999999999999E+98"), - ec(0x547D42AEA2879F2BL,"9.999999999999996E98", "1E+99"), - ec(0x547D42AEA287A0A0L,"1.0000000000000449E99", "1E+99"), - ec(0x547D42AEA287A0A1L,"1.000000000000045E99", "1.0000000000001E+99"), - ec(0x547D42AEA287A3D8L,"1.0000000000001449E99", "1.0000000000001E+99"), - ec(0x547D42AEA287A3D9L,"1.000000000000145E99", "1.0000000000002E+99"), - ec(0x547D42AEA287A710L,"1.000000000000245E99", "1.0000000000002E+99"), - ec(0x547D42AEA287A711L,"1.0000000000002451E99", "1.0000000000003E+99"), - - - ec(0x54B249AD2594C2F9L,"9.999999999999744E99", "9.9999999999997E+99"), - ec(0x54B249AD2594C2FAL,"9.999999999999746E99", "9.9999999999998E+99"), - ec(0x54B249AD2594C32DL,"9.999999999999845E99", "9.9999999999998E+99"), - ec(0x54B249AD2594C32EL,"9.999999999999847E99", "9.9999999999999E+99"), - ec(0x54B249AD2594C360L,"9.999999999999944E99", "9.9999999999999E+99"), - ec(0x54B249AD2594C361L,"9.999999999999946E99", "1E+100"), - ec(0x54B249AD2594C464L,"1.0000000000000449E100","1E+100"), - ec(0x54B249AD2594C465L,"1.000000000000045E100", "1.0000000000001E+100"), - ec(0x54B249AD2594C667L,"1.000000000000145E100", "1.0000000000001E+100"), - ec(0x54B249AD2594C668L,"1.0000000000001451E100","1.0000000000002E+100"), - ec(0x54B249AD2594C86AL,"1.000000000000245E100", "1.0000000000002E+100"), - ec(0x54B249AD2594C86BL,"1.0000000000002452E100","1.0000000000003E+100"), - - - ec(0x2B95DF5CA28EF4A8L,"1.0000000000000251E-98","1.00000000000003E-98"), - ec(0x2B95DF5CA28EF4A7L,"1.000000000000025E-98", "1.00000000000002E-98"), - ec(0x2B95DF5CA28EF46AL,"1.000000000000015E-98", "1.00000000000002E-98"), - ec(0x2B95DF5CA28EF469L,"1.0000000000000149E-98","1.00000000000001E-98"), - ec(0x2B95DF5CA28EF42DL,"1.0000000000000051E-98","1.00000000000001E-98"), - ec(0x2B95DF5CA28EF42CL,"1.000000000000005E-98", "1E-98"), - ec(0x2B95DF5CA28EF3ECL,"9.999999999999946E-99", "1E-98"), - ec(0x2B95DF5CA28EF3EBL,"9.999999999999944E-99", "9.9999999999999E-99"), - ec(0x2B95DF5CA28EF3AEL,"9.999999999999845E-99", "9.9999999999999E-99"), - ec(0x2B95DF5CA28EF3ADL,"9.999999999999843E-99", "9.9999999999998E-99"), - ec(0x2B95DF5CA28EF371L,"9.999999999999746E-99", "9.9999999999998E-99"), - ec(0x2B95DF5CA28EF370L,"9.999999999999744E-99", "9.9999999999997E-99"), - - - ec(0x2B617F7D4ED8C7F5L,"1.000000000000245E-99", "1.0000000000003E-99"), - ec(0x2B617F7D4ED8C7F4L,"1.0000000000002449E-99","1.0000000000002E-99"), - ec(0x2B617F7D4ED8C609L,"1.0000000000001452E-99","1.0000000000002E-99"), - ec(0x2B617F7D4ED8C608L,"1.000000000000145E-99", "1.0000000000001E-99"), - ec(0x2B617F7D4ED8C41CL,"1.000000000000045E-99", "1.0000000000001E-99"), - ec(0x2B617F7D4ED8C41BL,"1.0000000000000449E-99","1E-99"), - ec(0x2B617F7D4ED8C323L,"9.999999999999945E-100","1E-99"), - ec(0x2B617F7D4ED8C322L,"9.999999999999943E-100","9.9999999999999E-100"), - ec(0x2B617F7D4ED8C2F2L,"9.999999999999846E-100","9.9999999999999E-100"), - ec(0x2B617F7D4ED8C2F1L,"9.999999999999844E-100","9.9999999999998E-100"), - ec(0x2B617F7D4ED8C2C1L,"9.999999999999746E-100","9.9999999999998E-100"), - ec(0x2B617F7D4ED8C2C0L,"9.999999999999744E-100","9.9999999999997E-100"), - - - - // small numbers - ec(0x3EE9E409302678BAL, "1.2345678901234568E-5", "1.23456789012346E-05"), - ec(0x3F202E85BE180B74L, "1.2345678901234567E-4", "0.000123456789012346"), - ec(0x3F543A272D9E0E51L, "0.0012345678901234567", "0.00123456789012346"), - ec(0x3F8948B0F90591E6L, "0.012345678901234568", "0.0123456789012346"), - - ec(0x3EE9E409301B5A02L, "1.23456789E-5", "0.0000123456789"), - - ec(0x3E6E7D05BDABDE50L, "5.6789012345E-8", "0.000000056789012345"), - ec(0x3E6E7D05BDAD407EL, "5.67890123456E-8", "5.67890123456E-08"), - ec(0x3E6E7D06029F18BEL, "5.678902E-8", "0.00000005678902"), - - ec(0x2BCB5733CB32AE6EL, "9.999999999999123E-98", "9.99999999999912E-98"), - ec(0x2B617F7D4ED8C59EL, "1.0000000000001235E-99", "1.0000000000001E-99"), - ec(0x0036319916D67853L, "1.2345678901234578E-307", "1.2345678901235E-307"), - - ec(0x359DEE7A4AD4B81FL, "2.0E-50", "2E-50"), - - // large numbers - ec(0x41678C29DCD6E9E0L, "1.2345678901234567E7", "12345678.9012346"), - ec(0x42A674E79C5FE523L, "1.2345678901234568E13", "12345678901234.6"), - ec(0x42DC12218377DE6BL, "1.2345678901234567E14", "123456789012346"), - ec(0x43118B54F22AEB03L, "1.2345678901234568E15", "1234567890123460"), - ec(0x43E56A95319D63E1L, "1.2345678901234567E19", "12345678901234600000"), - ec(0x441AC53A7E04BCDAL, "1.2345678901234568E20", "1.23456789012346E+20"), - ec(0xC3E56A95319D63E1L, "-1.2345678901234567E19", "-12345678901234600000"), - ec(0xC41AC53A7E04BCDAL, "-1.2345678901234568E20", "-1.23456789012346E+20"), - - ec(0x54820FE0BA17F46DL, "1.2345678901234577E99", "1.2345678901235E+99"), - ec(0x54B693D8E89DF188L, "1.2345678901234576E100", "1.2345678901235E+100"), - - ec(0x4A611B0EC57E649AL, "2.0E50", "2E+50"), - - // range extremities - ec(0x7FEFFFFFFFFFFFFFL, "1.7976931348623157E308", "1.7976931348623E+308"), - ec(0x0010000000000000L, "2.2250738585072014E-308", "2.2250738585072E-308"), - ec(0x000FFFFFFFFFFFFFL, "2.225073858507201E-308", "0"), - ec(0x0000000000000001L, "4.9E-324", "0"), - - // infinity - ec(0x7FF0000000000000L, "Infinity", "1.7976931348623E+308"), - ec(0xFFF0000000000000L, "-Infinity", "1.7976931348623E+308"), - - // shortening due to rounding - ec(0x441AC7A08EAD02F2L, "1.234999999999999E20", "1.235E+20"), - ec(0x40FE26BFFFFFFFF9L, "123499.9999999999", "123500"), - ec(0x3E4A857BFB2F2809L, "1.234999999999999E-8", "0.00000001235"), - ec(0x3BCD291DEF868C89L, "1.234999999999999E-20", "1.235E-20"), - - // carry up due to rounding - // For clarity these tests choose values that don't round in java, - // but will round in excel. In some cases there is almost no difference - // between excel and java (e.g. 9.9..9E-8) - ec(0x444B1AE4D6E2EF4FL, "9.999999999999999E20", "1E+21"), - ec(0x412E847FFFFFFFFFL, "999999.9999999999", "1000000"), - ec(0x3E45798EE2308C39L, "9.999999999999999E-9", "0.00000001"), - ec(0x3C32725DD1D243ABL, "9.999999999999999E-19", "0.000000000000000001"), - ec(0x3BFD83C94FB6D2ABL, "9.999999999999999E-20", "1E-19"), - - ec(0xC44B1AE4D6E2EF4FL, "-9.999999999999999E20", "-1E+21"), - ec(0xC12E847FFFFFFFFFL, "-999999.9999999999", "-1000000"), - ec(0xBE45798EE2308C39L, "-9.999999999999999E-9", "-0.00000001"), - ec(0xBC32725DD1D243ABL, "-9.999999999999999E-19", "-0.000000000000000001"), - ec(0xBBFD83C94FB6D2ABL, "-9.999999999999999E-20", "-1E-19"), - - - // NaNs - // Currently these test cases are not critical, since other limitations prevent any variety in - // or control of the bit patterns used to encode NaNs in evaluations. - ec(0xFFFF0420003C0000L, "NaN", "3.484840871308E+308"), - ec(0x7FF8000000000000L, "NaN", "2.6965397022935E+308"), - ec(0x7FFF0420003C0000L, "NaN", "3.484840871308E+308"), - ec(0xFFF8000000000000L, "NaN", "2.6965397022935E+308"), - ec(0xFFFF0AAAAAAAAAAAL, "NaN", "3.4877119413344E+308"), - ec(0x7FF80AAAAAAAAAAAL, "NaN", "2.7012211948322E+308"), - ec(0xFFFFFFFFFFFFFFFFL, "NaN", "3.5953862697246E+308"), - ec(0x7FFFFFFFFFFFFFFFL, "NaN", "3.5953862697246E+308"), - ec(0xFFF7FFFFFFFFFFFFL, "NaN", "2.6965397022935E+308"), - }; - - private static ExampleConversion ec(long rawDoubleBits, String javaRendering, String excelRendering) { - return new ExampleConversion(rawDoubleBits, javaRendering, excelRendering); - } - - public static ExampleConversion[] getExampleConversions() { - return examples.clone(); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestAreaReference.java b/src/testcases/org/apache/poi/ss/util/TestAreaReference.java deleted file mode 100644 index e8419d5306..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestAreaReference.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Test for {@link AreaReference} handling of max rows. - * - * @author David North - */ -class TestAreaReference { - @Test - void testWholeColumn() { - AreaReference oldStyle = AreaReference.getWholeColumn(SpreadsheetVersion.EXCEL97, "A", "B"); - assertEquals(0, oldStyle.getFirstCell().getCol()); - assertEquals(0, oldStyle.getFirstCell().getRow()); - assertEquals(1, oldStyle.getLastCell().getCol()); - assertEquals(SpreadsheetVersion.EXCEL97.getLastRowIndex(), oldStyle.getLastCell().getRow()); - assertTrue(oldStyle.isWholeColumnReference()); - - AreaReference oldStyleNonWholeColumn = new AreaReference("A1:B23", SpreadsheetVersion.EXCEL97); - assertFalse(oldStyleNonWholeColumn.isWholeColumnReference()); - - AreaReference newStyle = AreaReference.getWholeColumn(SpreadsheetVersion.EXCEL2007, "A", "B"); - assertEquals(0, newStyle.getFirstCell().getCol()); - assertEquals(0, newStyle.getFirstCell().getRow()); - assertEquals(1, newStyle.getLastCell().getCol()); - assertEquals(SpreadsheetVersion.EXCEL2007.getLastRowIndex(), newStyle.getLastCell().getRow()); - assertTrue(newStyle.isWholeColumnReference()); - - AreaReference newStyleNonWholeColumn = new AreaReference("A1:B23", SpreadsheetVersion.EXCEL2007); - assertFalse(newStyleNonWholeColumn.isWholeColumnReference()); - } - - @Test - void testWholeRow() { - AreaReference oldStyle = AreaReference.getWholeRow(SpreadsheetVersion.EXCEL97, "1", "2"); - assertEquals(0, oldStyle.getFirstCell().getCol()); - assertEquals(0, oldStyle.getFirstCell().getRow()); - assertEquals(SpreadsheetVersion.EXCEL97.getLastColumnIndex(), oldStyle.getLastCell().getCol()); - assertEquals(1, oldStyle.getLastCell().getRow()); - - AreaReference newStyle = AreaReference.getWholeRow(SpreadsheetVersion.EXCEL2007, "1", "2"); - assertEquals(0, newStyle.getFirstCell().getCol()); - assertEquals(0, newStyle.getFirstCell().getRow()); - assertEquals(SpreadsheetVersion.EXCEL2007.getLastColumnIndex(), newStyle.getLastCell().getCol()); - assertEquals(1, newStyle.getLastCell().getRow()); - } - - @Test - void test62810() { - final Workbook wb = new HSSFWorkbook(); - final Sheet sheet = wb.createSheet("Ctor test"); - final String sheetName = sheet.getSheetName(); - final CellReference topLeft = new CellReference(sheetName, 1, 1, true, true); - final CellReference bottomRight = new CellReference(sheetName, 5, 10, true, true); - final AreaReference goodAreaRef = new AreaReference(topLeft, bottomRight, SpreadsheetVersion.EXCEL2007); - final AreaReference badAreaRef = new AreaReference(bottomRight, topLeft, SpreadsheetVersion.EXCEL2007); - - assertEquals("'Ctor test'!$B$2", topLeft.formatAsString()); - assertEquals("'Ctor test'!$K$6", bottomRight.formatAsString()); - assertEquals("'Ctor test'!$B$2:$K$6", goodAreaRef.formatAsString()); - assertEquals("'Ctor test'!$B$2:$K$6", badAreaRef.formatAsString()); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestCellAddress.java b/src/testcases/org/apache/poi/ss/util/TestCellAddress.java deleted file mode 100644 index 044203f3c2..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestCellAddress.java +++ /dev/null @@ -1,108 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.util.Arrays; - -import org.junit.jupiter.api.Test; - -/** - * Tests that the common CellAddress works as we need it to. - */ -final class TestCellAddress { - @Test - void testConstructors() { - CellAddress cellAddress; - final CellReference cellRef = new CellReference("Sheet1", 0, 0, true, true); - final String address = "A1"; - final int row = 0; - final int col = 0; - - cellAddress = new CellAddress(row, col); - assertEquals(CellAddress.A1, cellAddress); - - cellAddress = new CellAddress(address); - assertEquals(CellAddress.A1, cellAddress); - - cellAddress = new CellAddress(cellRef); - assertEquals(CellAddress.A1, cellAddress); - } - - @Test - void testFormatAsString() { - assertEquals("A1", CellAddress.A1.formatAsString()); - } - - @Test - void testEquals() { - assertEquals(new CellReference(6, 4), new CellReference(6, 4)); - assertNotEquals(new CellReference(4, 6), new CellReference(6, 4)); - } - - @SuppressWarnings("EqualsWithItself") - @Test - void testCompareTo() { - final CellAddress A1 = new CellAddress(0, 0); - final CellAddress A2 = new CellAddress(1, 0); - final CellAddress B1 = new CellAddress(0, 1); - final CellAddress B2 = new CellAddress(1, 1); - - assertEquals(0, A1.compareTo(A1)); - assertEquals(-1, A1.compareTo(B1)); - assertEquals(-1, A1.compareTo(A2)); - assertEquals(-1, A1.compareTo(B2)); - - assertEquals(1, B1.compareTo(A1)); - assertEquals(0, B1.compareTo(B1)); - assertEquals(-1, B1.compareTo(A2)); - assertEquals(-1, B1.compareTo(B2)); - - assertEquals(1, A2.compareTo(A1)); - assertEquals(1, A2.compareTo(B1)); - assertEquals(0, A2.compareTo(A2)); - assertEquals(-1, A2.compareTo(B2)); - - assertEquals(1, B2.compareTo(A1)); - assertEquals(1, B2.compareTo(B1)); - assertEquals(1, B2.compareTo(A2)); - assertEquals(0, B2.compareTo(B2)); - - CellAddress[] sorted = {A1, B1, A2, B2}; - CellAddress[] unsorted = {B1, B2, A1, A2}; - assumeTrue(!Arrays.equals(sorted, unsorted)); - Arrays.sort(unsorted); - assertArrayEquals(sorted, unsorted); - } - - @Test - void testGetRow() { - final CellAddress addr = new CellAddress(6, 4); - assertEquals(6, addr.getRow()); - } - - @Test - void testGetColumn() { - final CellAddress addr = new CellAddress(6, 4); - assertEquals(4, addr.getColumn()); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestCellRangeAddress.java b/src/testcases/org/apache/poi/ss/util/TestCellRangeAddress.java deleted file mode 100644 index 01d12f41c3..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestCellRangeAddress.java +++ /dev/null @@ -1,292 +0,0 @@ -/* ==================================================================== -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.util.LittleEndianOutputStream; -import org.junit.jupiter.api.Test; - -final class TestCellRangeAddress { - static final byte[] data = new byte[] { - 0x02, 0x00, 0x04, 0x00, - 0x00, 0x00, 0x03, 0x00, - }; - - @Test - void testLoad() { - CellRangeAddress ref = new CellRangeAddress( - TestcaseRecordInputStream.create(0x000, data)); - assertEquals(2, ref.getFirstRow()); - assertEquals(4, ref.getLastRow()); - assertEquals(0, ref.getFirstColumn()); - assertEquals(3, ref.getLastColumn()); - - assertEquals(8, CellRangeAddress.ENCODED_SIZE); - } - - @Test - void testLoadInvalid() { - RuntimeException e = assertThrows(RuntimeException.class, () -> - new CellRangeAddress(TestcaseRecordInputStream.create(0x000, new byte[]{(byte) 0x02}))); - assertTrue(e.getMessage().contains("Ran out of data")); - } - - @Test - void testStore() throws IOException { - CellRangeAddress ref = new CellRangeAddress(0, 0, 0, 0); - - byte[] recordBytes; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try (LittleEndianOutputStream out = new LittleEndianOutputStream(baos)) { - // With nothing set - ref.serialize(out); - recordBytes = baos.toByteArray(); - assertEquals(recordBytes.length, data.length); - for (int i = 0; i < data.length; i++) { - assertEquals(0, recordBytes[i], "At offset " + i); - } - - // Now set the flags - ref.setFirstRow((short) 2); - ref.setLastRow((short) 4); - ref.setFirstColumn((short) 0); - ref.setLastColumn((short) 3); - - // Re-test - baos.reset(); - ref.serialize(out); - recordBytes = baos.toByteArray(); - - assertEquals(recordBytes.length, data.length); - for (int i = 0; i < data.length; i++) { - assertEquals(data[i], recordBytes[i], "At offset " + i); - } - } - } - - @Test - void testCreateIllegal() { - // for some combinations we expected exceptions - assertThrows(IllegalArgumentException.class, () -> new CellRangeAddress(1, 0, 0, 0)); - assertThrows(IllegalArgumentException.class, () -> new CellRangeAddress(0, 0, 1, 0)); - } - - @Test - void testCopy() throws IOException { - CellRangeAddress ref = new CellRangeAddress(1, 2, 3, 4); - CellRangeAddress copy = ref.copy(); - assertEquals(ref.toString(), copy.toString()); - } - - @Test - void testGetEncodedSize() { - assertEquals(2*CellRangeAddress.ENCODED_SIZE, CellRangeAddress.getEncodedSize(2)); - } - - @Test - void testFormatAsString() { - CellRangeAddress ref = new CellRangeAddress(1, 2, 3, 4); - - assertEquals("D2:E3", ref.formatAsString()); - assertEquals("D2:E3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString()); - - assertEquals("sheet1!$D$2:$E$3", ref.formatAsString("sheet1", true)); - assertEquals("sheet1!$D$2:$E$3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", true)); - assertEquals("sheet1!$D$2:$E$3", CellRangeAddress.valueOf(ref.formatAsString("sheet1", true)).formatAsString("sheet1", true)); - - assertEquals("sheet1!D2:E3", ref.formatAsString("sheet1", false)); - assertEquals("sheet1!D2:E3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", false)); - assertEquals("sheet1!D2:E3", CellRangeAddress.valueOf(ref.formatAsString("sheet1", false)).formatAsString("sheet1", false)); - - assertEquals("D2:E3", ref.formatAsString(null, false)); - assertEquals("D2:E3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString(null, false)); - assertEquals("D2:E3", CellRangeAddress.valueOf(ref.formatAsString(null, false)).formatAsString(null, false)); - - assertEquals("$D$2:$E$3", ref.formatAsString(null, true)); - assertEquals("$D$2:$E$3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString(null, true)); - assertEquals("$D$2:$E$3", CellRangeAddress.valueOf(ref.formatAsString(null, true)).formatAsString(null, true)); - - ref = new CellRangeAddress(-1, -1, 3, 4); - assertEquals("D:E", ref.formatAsString()); - assertEquals("sheet1!$D:$E", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", true)); - assertEquals("sheet1!$D:$E", CellRangeAddress.valueOf(ref.formatAsString("sheet1", true)).formatAsString("sheet1", true)); - assertEquals("$D:$E", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString(null, true)); - assertEquals("$D:$E", CellRangeAddress.valueOf(ref.formatAsString(null, true)).formatAsString(null, true)); - assertEquals("sheet1!D:E", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", false)); - assertEquals("sheet1!D:E", CellRangeAddress.valueOf(ref.formatAsString("sheet1", false)).formatAsString("sheet1", false)); - - ref = new CellRangeAddress(1, 2, -1, -1); - assertEquals("2:3", ref.formatAsString()); - assertEquals("sheet1!$2:$3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", true)); - assertEquals("sheet1!$2:$3", CellRangeAddress.valueOf(ref.formatAsString("sheet1", true)).formatAsString("sheet1", true)); - assertEquals("$2:$3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString(null, true)); - assertEquals("$2:$3", CellRangeAddress.valueOf(ref.formatAsString(null, true)).formatAsString(null, true)); - assertEquals("sheet1!2:3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", false)); - assertEquals("sheet1!2:3", CellRangeAddress.valueOf(ref.formatAsString("sheet1", false)).formatAsString("sheet1", false)); - - ref = new CellRangeAddress(1, 1, 2, 2); - assertEquals("C2", ref.formatAsString()); - assertEquals("sheet1!$C$2", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", true)); - assertEquals("sheet1!$C$2", CellRangeAddress.valueOf(ref.formatAsString("sheet1", true)).formatAsString("sheet1", true)); - assertEquals("$C$2", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString(null, true)); - assertEquals("$C$2", CellRangeAddress.valueOf(ref.formatAsString(null, true)).formatAsString(null, true)); - assertEquals("sheet1!C2", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", false)); - assertEquals("sheet1!C2", CellRangeAddress.valueOf(ref.formatAsString("sheet1", false)).formatAsString("sheet1", false)); - - // is this a valid address? - ref = new CellRangeAddress(-1, -1, -1, -1); - assertEquals(":", ref.formatAsString()); - } - - @Test - void testEquals() { - final CellRangeAddress ref1 = new CellRangeAddress(1, 2, 3, 4); - final CellRangeAddress ref2 = new CellRangeAddress(1, 2, 3, 4); - assertEquals(ref1, ref2); - - // Invert first/last row, but refer to same area - ref2.setFirstRow(2); - ref2.setLastRow(1); - assertEquals(ref1, ref2); - - // Invert first/last column, but refer to same area - ref2.setFirstColumn(4); - ref2.setLastColumn(3); - assertEquals(ref1, ref2); - - // Refer to a different area - assertNotEquals(ref1, new CellRangeAddress(3, 4, 1, 2)); - } - - @Test - void testGetMinMaxRow() { - final CellRangeAddress ref = new CellRangeAddress(1, 2, 3, 4); - assertEquals(1, ref.getMinRow()); - assertEquals(2, ref.getMaxRow()); - - ref.setFirstRow(10); - //now ref is CellRangeAddress(10, 2, 3, 4) - assertEquals(2, ref.getMinRow()); - assertEquals(10, ref.getMaxRow()); - } - - @Test - void testGetMinMaxColumn() { - final CellRangeAddress ref = new CellRangeAddress(1, 2, 3, 4); - assertEquals(3, ref.getMinColumn()); - assertEquals(4, ref.getMaxColumn()); - - ref.setFirstColumn(10); - //now ref is CellRangeAddress(1, 2, 10, 4) - assertEquals(4, ref.getMinColumn()); - assertEquals(10, ref.getMaxColumn()); - } - - @Test - void testIntersects() { - final CellRangeAddress baseRegion = new CellRangeAddress(0, 1, 0, 1); - - final CellRangeAddress duplicateRegion = new CellRangeAddress(0, 1, 0, 1); - assertIntersects(baseRegion, duplicateRegion); - - final CellRangeAddress partiallyOverlappingRegion = new CellRangeAddress(1, 2, 1, 2); - assertIntersects(baseRegion, partiallyOverlappingRegion); - - final CellRangeAddress subsetRegion = new CellRangeAddress(0, 1, 0, 0); - assertIntersects(baseRegion, subsetRegion); - - final CellRangeAddress supersetRegion = new CellRangeAddress(0, 2, 0, 2); - assertIntersects(baseRegion, supersetRegion); - - final CellRangeAddress disjointRegion = new CellRangeAddress(10, 11, 10, 11); - assertNotIntersects(baseRegion, disjointRegion); - } - - @Test - void containsRow() { - final CellRangeAddress region = new CellRangeAddress(10, 12, 3, 5); - - assertFalse(region.containsRow(9)); - assertTrue(region.containsRow(10)); - assertTrue(region.containsRow(11)); - assertTrue(region.containsRow(12)); - assertFalse(region.containsRow(13)); - } - - @Test - void containsColumn() { - final CellRangeAddress region = new CellRangeAddress(10, 12, 3, 5); - - assertFalse(region.containsColumn(2)); - assertTrue(region.containsColumn(3)); - assertTrue(region.containsColumn(4)); - assertTrue(region.containsColumn(5)); - assertFalse(region.containsColumn(6)); - } - - @Test - void iterator() { - final CellRangeAddress A1_B2 = new CellRangeAddress(0, 1, 0, 1); - - // the cell address iterator iterates in row major order - final Iterator iter = A1_B2.iterator(); - assertEquals(new CellAddress(0, 0), iter.next(), "A1"); - assertEquals(new CellAddress(0, 1), iter.next(), "B1"); - assertEquals(new CellAddress(1, 0), iter.next(), "A2"); - assertEquals(new CellAddress(1, 1), iter.next(), "B2"); - assertFalse(iter.hasNext()); - assertThrows(NoSuchElementException.class, iter::next); - assertThrows(UnsupportedOperationException.class, iter::remove); - - // for each interface - int count = 0; - for (final CellAddress addr : A1_B2) { - assertNotNull(addr); - count++; - } - assertEquals(4, count); - } - - private static void assertIntersects(CellRangeAddress regionA, CellRangeAddress regionB) { - if (!(regionA.intersects(regionB) && regionB.intersects(regionA))) { - final String A = regionA.formatAsString(); - final String B = regionB.formatAsString(); - fail("expected: regions "+A+" and "+B+" intersect"); - } - } - private static void assertNotIntersects(CellRangeAddress regionA, CellRangeAddress regionB) { - if ((regionA.intersects(regionB) || regionB.intersects(regionA))) { - final String A = regionA.formatAsString(); - final String B = regionB.formatAsString(); - fail("expected: regions "+A+" and "+B+" do not intersect"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestCellRangeUtil.java b/src/testcases/org/apache/poi/ss/util/TestCellRangeUtil.java deleted file mode 100644 index 5b402a3bcd..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestCellRangeUtil.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.junit.jupiter.api.Test; - -/** - * Tests CellRangeUtil. - * - * @see org.apache.poi.ss.util.CellRangeUtil - */ -final class TestCellRangeUtil { - - private static final CellRangeAddress A1 = new CellRangeAddress(0, 0, 0, 0); - private static final CellRangeAddress B1 = new CellRangeAddress(0, 0, 1, 1); - private static final CellRangeAddress A2 = new CellRangeAddress(1, 1, 0, 0); - private static final CellRangeAddress B2 = new CellRangeAddress(1, 1, 1, 1); - private static final CellRangeAddress A1_B2 = new CellRangeAddress(0, 1, 0, 1); - private static final CellRangeAddress A1_B1 = new CellRangeAddress(0, 0, 0, 1); - private static final CellRangeAddress A1_A2 = new CellRangeAddress(0, 1, 0, 0); - - @Test - void testMergeCellRanges() { - // Note that the order of the output array elements does not matter - // And that there may be more than one valid outputs for a given input. Any valid output is accepted. - // POI should use a strategy that is consistent and predictable (it currently is not). - - // Fully mergeable - // A B - // 1 x x A1,A2,B1,B2 --> A1:B2 - // 2 x x - assertCellRangesEqual(asArray(A1_B2), merge(A1, B1, A2, B2)); - assertCellRangesEqual(asArray(A1_B2), merge(A1, B2, A2, B1)); - - // Partially mergeable: multiple possible merges - // A B - // 1 x x A1,A2,B1 --> A1:B1,A2 or A1:A2,B1 - // 2 x - assertCellRangesEqual(asArray(A1_B1, A2), merge(A1, B1, A2)); - assertCellRangesEqual(asArray(A1_A2, B1), merge(A2, A1, B1)); - assertCellRangesEqual(asArray(A1_B1, A2), merge(B1, A2, A1)); - - // Not mergeable - // A B - // 1 x A1,B2 --> A1,B2 - // 2 x - assertCellRangesEqual(asArray(A1, B2), merge(A1, B2)); - assertCellRangesEqual(asArray(B2, A1), merge(B2, A1)); - } - - private void assertCellRangesEqual(CellRangeAddress[] a, CellRangeAddress[] b) { - assertEquals(getCellAddresses(a), getCellAddresses(b)); - assertArrayEquals(a, b); - } - - private static Set getCellAddresses(CellRangeAddress[] ranges) { - final Set set = new HashSet<>(); - for (final CellRangeAddress range : ranges) { - for (Iterator iter = range.iterator(); iter.hasNext(); ) { - set.add(iter.next()); - } - } - return set; - } - - private static CellRangeAddress[] asArray(CellRangeAddress...ts) { - return ts; - } - - private static CellRangeAddress[] merge(CellRangeAddress... ranges) { - return CellRangeUtil.mergeCellRanges(ranges); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestCellReference.java b/src/testcases/org/apache/poi/ss/util/TestCellReference.java deleted file mode 100644 index 0d2d791374..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestCellReference.java +++ /dev/null @@ -1,476 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Tests that the common CellReference works as we need it to. - * Note - some additional testing is also done in the HSSF class, - * {@link org.apache.poi.hssf.util.TestCellReference} - */ -final class TestCellReference { - @Test - void testConstructors() { - CellReference cellReference; - final String sheet = "Sheet1"; - final String cellRef = "A1"; - final int row = 0; - final int col = 0; - final boolean absRow = true; - final boolean absCol = false; - - cellReference = new CellReference(row, col); - assertEquals("A1", cellReference.formatAsString()); - assertEquals("A1", cellReference.formatAsString(true)); - assertEquals("A1", cellReference.formatAsString(false)); - - cellReference = new CellReference(row, col, absRow, absCol); - assertEquals("A$1", cellReference.formatAsString()); - assertEquals("A$1", cellReference.formatAsString(true)); - assertEquals("A$1", cellReference.formatAsString(false)); - - cellReference = new CellReference(row, (short)col); - assertEquals("A1", cellReference.formatAsString()); - assertEquals("A1", cellReference.formatAsString(true)); - assertEquals("A1", cellReference.formatAsString(false)); - - cellReference = new CellReference(cellRef); - assertEquals("A1", cellReference.formatAsString()); - assertEquals("A1", cellReference.formatAsString(true)); - assertEquals("A1", cellReference.formatAsString(false)); - - cellReference = new CellReference(sheet, row, col, absRow, absCol); - assertEquals("Sheet1!A$1", cellReference.formatAsString()); - assertEquals("Sheet1!A$1", cellReference.formatAsString(true)); - assertEquals("A$1", cellReference.formatAsString(false)); - - cellReference = new CellReference(sheet+"!$A1"); - assertFalse(cellReference.isRowAbsolute()); - assertTrue(cellReference.isColAbsolute()); - - cellReference = new CellReference(sheet+"!A$1"); - assertTrue(cellReference.isRowAbsolute()); - assertFalse(cellReference.isColAbsolute()); - } - - @Test - void testCtorFromCell() { - Cell cell = mock(Cell.class, RETURNS_DEEP_STUBS); - when(cell.getSheet().getSheetName()).thenReturn("sheet"); - - CellReference result = new CellReference(cell); - assertEquals("sheet", result.getSheetName()); - assertEquals(cell.getRowIndex(), result.getRow()); - assertEquals(cell.getColumnIndex(), result.getCol()); - assertFalse(result.isRowAbsolute()); - assertFalse(result.isColAbsolute()); - } - - @Test - void testFormatAsString() { - CellReference cellReference; - - cellReference = new CellReference(null, 0, 0, false, false); - assertEquals("A1", cellReference.formatAsString()); - assertEquals("A1", cellReference.formatAsString(true)); - assertEquals("A1", cellReference.formatAsString(false)); - - //absolute references - cellReference = new CellReference(null, 0, 0, true, false); - assertEquals("A$1", cellReference.formatAsString()); - assertEquals("A$1", cellReference.formatAsString(true)); - assertEquals("A$1", cellReference.formatAsString(false)); - - //sheet name with no spaces - cellReference = new CellReference("Sheet1", 0, 0, true, false); - assertEquals("Sheet1!A$1", cellReference.formatAsString()); - assertEquals("Sheet1!A$1", cellReference.formatAsString(true)); - assertEquals("A$1", cellReference.formatAsString(false)); - - //sheet name with spaces - cellReference = new CellReference("Sheet 1", 0, 0, true, false); - assertEquals("'Sheet 1'!A$1", cellReference.formatAsString()); - assertEquals("'Sheet 1'!A$1", cellReference.formatAsString(true)); - assertEquals("A$1", cellReference.formatAsString(false)); - } - - @Test - void testGetCellRefParts() { - CellReference cellReference; - String[] parts; - - String cellRef = "A1"; - cellReference = new CellReference(cellRef); - assertEquals(0, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertNull(parts[0]); - assertEquals("1", parts[1]); - assertEquals("A", parts[2]); - - cellRef = "AA1"; - cellReference = new CellReference(cellRef); - assertEquals(26, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertNull(parts[0]); - assertEquals("1", parts[1]); - assertEquals("AA", parts[2]); - - cellRef = "AA100"; - cellReference = new CellReference(cellRef); - assertEquals(26, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertNull(parts[0]); - assertEquals("100", parts[1]); - assertEquals("AA", parts[2]); - - cellRef = "AAA300"; - cellReference = new CellReference(cellRef); - assertEquals(702, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertNull(parts[0]); - assertEquals("300", parts[1]); - assertEquals("AAA", parts[2]); - - cellRef = "ZZ100521"; - cellReference = new CellReference(cellRef); - assertEquals(26*26+25, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertNull(parts[0]); - assertEquals("100521", parts[1]); - assertEquals("ZZ", parts[2]); - - cellRef = "ZYX987"; - cellReference = new CellReference(cellRef); - assertEquals(26*26*26 + 25*26 + 24 - 1, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertNull(parts[0]); - assertEquals("987", parts[1]); - assertEquals("ZYX", parts[2]); - - cellRef = "AABC10065"; - cellReference = new CellReference(cellRef); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertNull(parts[0]); - assertEquals("10065", parts[1]); - assertEquals("AABC", parts[2]); - } - - @Test - void testGetColNumFromRef() { - String cellRef = "A1"; - CellReference cellReference = new CellReference(cellRef); - assertEquals(0, cellReference.getCol()); - - cellRef = "AA1"; - cellReference = new CellReference(cellRef); - assertEquals(26, cellReference.getCol()); - - cellRef = "AB1"; - cellReference = new CellReference(cellRef); - assertEquals(27, cellReference.getCol()); - - cellRef = "BA1"; - cellReference = new CellReference(cellRef); - assertEquals(26+26, cellReference.getCol()); - - cellRef = "CA1"; - cellReference = new CellReference(cellRef); - assertEquals(26+26+26, cellReference.getCol()); - - cellRef = "ZA1"; - cellReference = new CellReference(cellRef); - assertEquals(26*26, cellReference.getCol()); - - cellRef = "ZZ1"; - cellReference = new CellReference(cellRef); - assertEquals(26*26+25, cellReference.getCol()); - - cellRef = "AAA1"; - cellReference = new CellReference(cellRef); - assertEquals(26*26+26, cellReference.getCol()); - - - cellRef = "A1100"; - cellReference = new CellReference(cellRef); - assertEquals(0, cellReference.getCol()); - - cellRef = "BC15"; - cellReference = new CellReference(cellRef); - assertEquals(54, cellReference.getCol()); - } - - @Test - void testGetRowNumFromRef() { - String cellRef = "A1"; - CellReference cellReference = new CellReference(cellRef); - assertEquals(0, cellReference.getRow()); - - cellRef = "A12"; - cellReference = new CellReference(cellRef); - assertEquals(11, cellReference.getRow()); - - cellRef = "AS121"; - cellReference = new CellReference(cellRef); - assertEquals(120, cellReference.getRow()); - } - - @Test - void testConvertNumToColString() { - short col = 702; - String collRef = new CellReference(0, col).formatAsString(); - assertEquals("AAA1", collRef); - - short col2 = 0; - String collRef2 = new CellReference(0, col2).formatAsString(); - assertEquals("A1", collRef2); - - short col3 = 27; - String collRef3 = new CellReference(0, col3).formatAsString(); - assertEquals("AB1", collRef3); - - short col4 = 2080; - String collRef4 = new CellReference(0, col4).formatAsString(); - assertEquals("CBA1", collRef4); - } - - @Test - void testBadRowNumber() { - SpreadsheetVersion v97 = SpreadsheetVersion.EXCEL97; - SpreadsheetVersion v2007 = SpreadsheetVersion.EXCEL2007; - - confirmCrInRange(true, "A", "1", v97); - confirmCrInRange(true, "IV", "65536", v97); - confirmCrInRange(false, "IV", "65537", v97); - confirmCrInRange(false, "IW", "65536", v97); - - confirmCrInRange(true, "A", "1", v2007); - confirmCrInRange(true, "XFD", "1048576", v2007); - confirmCrInRange(false, "XFD", "1048577", v2007); - confirmCrInRange(false, "XFE", "1048576", v2007); - - assertFalse(CellReference.cellReferenceIsWithinRange("B", "0", v97), "Identified bug 47312a"); - - confirmCrInRange(false, "A", "0", v97); - confirmCrInRange(false, "A", "0", v2007); - } - - @Test - void testInvalidReference() { - for (String s : new String[]{"Sheet1!#REF!", "'MySheetName'!#REF!", "#REF!"}) { - assertThrows(IllegalArgumentException.class, () -> new CellReference(s), - "Shouldn't be able to create a #REF! "+s); - } - } - - private static void confirmCrInRange(boolean expResult, String colStr, String rowStr, SpreadsheetVersion sv) { - assertEquals(expResult, CellReference.cellReferenceIsWithinRange(colStr, rowStr, sv), - "expected (c='" + colStr + "', r='" + rowStr + "' to be " - + (expResult ? "within" : "out of") + " bounds for version " + sv.name() - ); - } - - @Test - void testConvertColStringToIndex() { - assertEquals(0, CellReference.convertColStringToIndex("A")); - assertEquals(1, CellReference.convertColStringToIndex("B")); - assertEquals(14, CellReference.convertColStringToIndex("O")); - assertEquals(701, CellReference.convertColStringToIndex("ZZ")); - assertEquals(18252, CellReference.convertColStringToIndex("ZZA")); - - assertEquals(0, CellReference.convertColStringToIndex("$A")); - assertEquals(1, CellReference.convertColStringToIndex("$B")); - - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, - () -> CellReference.convertColStringToIndex("A$")); - assertTrue(e.getMessage().contains("A$")); - } - - @Test - void testConvertNumColColString() { - assertEquals("A", CellReference.convertNumToColString(0)); - assertEquals("AV", CellReference.convertNumToColString(47)); - assertEquals("AW", CellReference.convertNumToColString(48)); - assertEquals("BF", CellReference.convertNumToColString(57)); - - assertEquals("", CellReference.convertNumToColString(-1)); - assertEquals("", CellReference.convertNumToColString(Integer.MIN_VALUE)); - assertEquals("", CellReference.convertNumToColString(Integer.MAX_VALUE)); - assertEquals("FXSHRXW", CellReference.convertNumToColString(Integer.MAX_VALUE-1)); - } - - /** - * bug 59684: separateRefParts fails on entire-column references - */ - @Test - void entireColumnReferences() { - CellReference ref = new CellReference("HOME!$169"); - assertEquals("HOME", ref.getSheetName()); - assertEquals(168, ref.getRow()); - assertEquals(-1, ref.getCol()); - assertTrue(ref.isRowAbsolute(), "row absolute"); - //assertFalse("column absolute/relative is undefined", ref.isColAbsolute()); - } - - @Test - void getSheetName() { - assertNull(new CellReference("A5").getSheetName()); - assertNull(new CellReference(null, 0, 0, false, false).getSheetName()); - // FIXME: CellReference is inconsistent - assertEquals("", new CellReference("", 0, 0, false, false).getSheetName()); - assertEquals("Sheet1", new CellReference("Sheet1!A5").getSheetName()); - assertEquals("Sheet 1", new CellReference("'Sheet 1'!A5").getSheetName()); - } - - @Test - void testToString() { - CellReference ref = new CellReference("'Sheet 1'!A5"); - assertEquals("org.apache.poi.ss.util.CellReference ['Sheet 1'!A5]", ref.toString()); - } - - @Test - void testEqualsAndHashCode() { - CellReference ref1 = new CellReference("'Sheet 1'!A5"); - CellReference ref2 = new CellReference("Sheet 1", 4, 0, false, false); - assertEquals(ref1, ref2); - assertEquals(ref1.hashCode(), ref2.hashCode()); - - //noinspection ObjectEqualsNull - assertNotEquals(null, ref1); - assertNotEquals(ref1, new CellReference("A5")); - } - - @Test - void isRowWithinRange() { - SpreadsheetVersion ss = SpreadsheetVersion.EXCEL2007; - assertFalse(CellReference.isRowWithinRange("0", ss), "1 before first row"); - assertTrue(CellReference.isRowWithinRange("1", ss), "first row"); - assertTrue(CellReference.isRowWithinRange("1048576", ss), "last row"); - assertFalse(CellReference.isRowWithinRange("1048577", ss), "1 beyond last row"); - - // int versions of above, using 0-based indices - assertFalse(CellReference.isRowWithinRange(-1, ss), "1 before first row"); - assertTrue(CellReference.isRowWithinRange(0, ss), "first row"); - assertTrue(CellReference.isRowWithinRange(1048575, ss), "last row"); - assertFalse(CellReference.isRowWithinRange(1048576, ss), "1 beyond last row"); - } - - @Test - void isRowWithinRangeNonInteger_BigNumber() { - String rowNum = "4000000000"; - assertFalse(CellReference.isRowWithinRange(rowNum, SpreadsheetVersion.EXCEL2007)); - } - - @Test - void isRowWithinRangeNonInteger_Alpha() { - String rowNum = "NotANumber"; - assertThrows(NumberFormatException.class, () -> CellReference.isRowWithinRange(rowNum, SpreadsheetVersion.EXCEL2007)); - } - - @Test - void isColWithinRange() { - SpreadsheetVersion ss = SpreadsheetVersion.EXCEL2007; - assertTrue(CellReference.isColumnWithinRange("", ss), "(empty)"); - assertTrue(CellReference.isColumnWithinRange("A", ss), "first column (A)"); - assertTrue(CellReference.isColumnWithinRange("XFD", ss), "last column (XFD)"); - assertFalse(CellReference.isColumnWithinRange("XFE", ss), "1 beyond last column (XFE)"); - } - - @Test - void unquotedSheetName() { - assertThrows(IllegalArgumentException.class, () -> new CellReference("'Sheet 1!A5")); - } - - @Test - void mismatchedQuotesSheetName() { - assertThrows(IllegalArgumentException.class, () -> new CellReference("Sheet 1!A5")); - } - - @Test - void escapedSheetName() { - String escapedName = "'Don''t Touch'!A5"; - String unescapedName = "'Don't Touch'!A5"; - new CellReference(escapedName); - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> new CellReference(unescapedName)); - assertTrue(e.getMessage().startsWith("Bad sheet name quote escaping: ")); - } - - @Test - void negativeRow() { - assertThrows(IllegalArgumentException.class, () -> new CellReference("sheet", -2, 0, false, false)); - } - - @Test - void negativeColumn() { - assertThrows(IllegalArgumentException.class, () -> new CellReference("sheet", 0, -2, false, false)); - } - - @Test - void classifyEmptyStringCellReference() { - assertThrows(IllegalArgumentException.class, () -> CellReference.classifyCellReference("", SpreadsheetVersion.EXCEL2007)); - } - - @Test - void classifyInvalidFirstCharCellReference() { - assertThrows(IllegalArgumentException.class, () -> CellReference.classifyCellReference("!A5", SpreadsheetVersion.EXCEL2007)); - } - - @Test - void test62828() { - final Workbook wb = new HSSFWorkbook(); - final Sheet sheet = wb.createSheet("Ctor test"); - final String sheetName = sheet.getSheetName(); - final Row row = sheet.createRow(0); - final Cell cell = row.createCell(0); - final CellReference goodCellRef = new CellReference(sheetName, cell.getRowIndex(), cell.getColumnIndex(), true, - true); - final CellReference badCellRef = new CellReference(cell); - - assertEquals("'Ctor test'!$A$1", goodCellRef.formatAsString()); - assertEquals("'Ctor test'!$A$1", goodCellRef.formatAsString(true)); - assertEquals("$A$1", goodCellRef.formatAsString(false)); - - assertEquals("'Ctor test'!A1", badCellRef.formatAsString()); - assertEquals("'Ctor test'!A1", badCellRef.formatAsString(true)); - assertEquals("A1", badCellRef.formatAsString(false)); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java b/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java deleted file mode 100644 index befe219a16..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.util; - -import static java.text.DateFormat.getDateInstance; -import static java.text.DateFormat.getDateTimeInstance; -import static java.text.DateFormat.getTimeInstance; -import static org.apache.poi.ss.util.DateFormatConverter.getPrefixForLocale; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Date; -import java.util.Locale; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.LocaleID; -import org.apache.poi.util.NullOutputStream; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; - -final class TestDateFormatConverter { - @ParameterizedTest - @CsvSource({ - "true, false, " + DateFormat.DEFAULT + ", Default", - "true, false, " + DateFormat.SHORT + ", Short", - "true, false, " + DateFormat.MEDIUM + ", Medium", - "true, false, " + DateFormat.LONG + ", Long", - "true, false, " + DateFormat.FULL + ", Full", - "true, true, " + DateFormat.DEFAULT + ", Default", - "true, true, " + DateFormat.SHORT + ", Short", - "true, true, " + DateFormat.MEDIUM + ", Medium", - "true, true, " + DateFormat.LONG + ", Long", - "true, true, " + DateFormat.FULL + ", Full", - "false, true, " + DateFormat.DEFAULT + ", Default", - "false, true, " + DateFormat.SHORT + ", Short", - "false, true, " + DateFormat.MEDIUM + ", Medium", - "false, true, " + DateFormat.LONG + ", Long", - "false, true, " + DateFormat.FULL + ", Full" - }) - void testJavaDateFormatsInExcel(boolean dates, boolean times, int style, String styleName ) throws Exception { - String sheetName = (dates) ? ((times) ? "DateTimes" : "Dates") : "Times"; - String[] headers = { - "locale", "DisplayName", "Excel " + styleName, "java.text.DateFormat", - "Equals", "Java pattern", "Excel pattern" - }; - - Locale[] locales = Arrays.stream(DateFormat.getAvailableLocales()) - // only use locale with known LocaleIDs - .filter(l -> !getPrefixForLocale(l).isEmpty() || Locale.ROOT.equals(l) || l.toLanguageTag().isEmpty()) - .sorted(Comparator.comparing(Locale::toString)) - .toArray(Locale[]::new); - - - try (Workbook workbook = new HSSFWorkbook()) { - Sheet sheet = workbook.createSheet(sheetName); - Row header = sheet.createRow(0); - IntStream.range(0, headers.length).forEach(i -> header.createCell(i).setCellValue(headers[i])); - - int rowNum = 1; - final Cell[] cell = new Cell[7]; - final Date date = new Date(); - - for (Locale locale : locales) { - DateFormat dateFormat = (dates) - ? (times ? getDateTimeInstance(style, style, locale) : getDateInstance(style, locale)) - : getTimeInstance(style, locale); - String javaDateFormatPattern = ((SimpleDateFormat) dateFormat).toPattern(); - String excelFormatPattern = DateFormatConverter.convert(locale, javaDateFormatPattern); - - Row row = sheet.createRow(rowNum++); - IntStream.range(0, headers.length).forEach(i -> cell[i] = row.createCell(i)); - CellStyle cellStyle = workbook.createCellStyle(); - DataFormat poiFormat = workbook.createDataFormat(); - cellStyle.setDataFormat(poiFormat.getFormat(excelFormatPattern)); - - cell[0].setCellValue(locale.toString()); - cell[1].setCellValue(locale.getDisplayName(Locale.ROOT)); - cell[2].setCellValue(date); - cell[2].setCellStyle(cellStyle); - cell[3].setCellValue(dateFormat.format(date)); - - // the formula returns TRUE is the formatted date in column C equals to the string in column D - cell[4].setCellFormula("TEXT(C" + rowNum + ",G" + rowNum + ")=D" + rowNum); - cell[5].setCellValue(javaDateFormatPattern); - cell[6].setCellValue(excelFormatPattern); - } - - assertDoesNotThrow(() -> workbook.write(new NullOutputStream())); - } - } - - @Test - void testJDK8EmptyLocale() { - // JDK 8 seems to add an empty locale-string to the list returned via DateFormat.getAvailableLocales() - // therefore we now cater for this special locale as well - String prefix = getPrefixForLocale(new Locale("")); - assertEquals("", prefix); - } - - @Test - void testJDK11MyLocale() { - DateFormat df = getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.forLanguageTag("my")); - assertNotNull(df); - } - - @Test - void testAllKnownLocales() { - Pattern p = Pattern.compile("\\[\\$-(\\p{XDigit}+)]"); - - Set excludeList = Stream.of( - "sd-Deva", "tzm-Arab", "fuv", "plt", "yue", "tdd-Tale", "tdd", - "khb-Talu", "khb", "qps", "ja-Ploc", "dz", "tmz", "ar-Ploc" - ).collect(Collectors.toSet()); - - for (LocaleID lid : LocaleID.values()) { - final String langTag = lid.getLanguageTag(); - - if (langTag.isEmpty() || lid.getWindowsId().startsWith("invalid")) { - continue; - } - - // test all from variant to parent locales - String cmpTag = (langTag.indexOf('_') > 0) ? langTag.replace('_','-') : langTag; - for (int idx = langTag.length(); idx > 0; idx = cmpTag.lastIndexOf('-', idx-1)) { - final String partTag = langTag.substring(0, idx); - - Locale loc = Locale.forLanguageTag(partTag); - assertNotNull(loc, "Invalid language tag: "+partTag); - - if (excludeList.contains(partTag)) { - continue; - } - - String prefix = getPrefixForLocale(loc); - assertNotNull(prefix, "Prefix not found - language tag: "+partTag); - assertNotEquals("", prefix, "Prefix not found - language tag: "+partTag); - Matcher m = p.matcher(prefix); - assertTrue(m.matches(), "Invalid prefix: "+prefix); - - LocaleID partLid = LocaleID.lookupByLanguageTag(partTag); - assertNotNull(partLid, "LocaleID not found for part: "+partTag); - assertEquals(partLid.getLcid(), Integer.parseInt(m.group(1), 16)); - } - } - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestDateParser.java b/src/testcases/org/apache/poi/ss/util/TestDateParser.java deleted file mode 100644 index 28e51d1b67..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestDateParser.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.Calendar; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -class TestDateParser { - @ParameterizedTest - @ValueSource(strings = { - // no date - "potato", - // fail when looks like date but it isnt - "potato/cucumber/banana", - // fail when is invalid date - "13/13/13" - }) - void testFailWhenInvalidDate(String invalidDate) { - EvaluationException e = assertThrows(EvaluationException.class, - () -> DateParser.parseDate(invalidDate), "Shouldn't parse " + invalidDate); - assertEquals(ErrorEval.VALUE_INVALID, e.getErrorEval()); - } - - @Test - void testShouldParseValidDate() throws EvaluationException { - Calendar expDate = LocaleUtil.getLocaleCalendar(1984, Calendar.OCTOBER, 20); - Calendar actDate = DateParser.parseDate("1984/10/20"); - assertEquals(expDate, actDate, - "Had: " + expDate.getTime() + " and " + actDate.getTime() + "/" + - expDate.getTimeInMillis() + "ms and " + actDate.getTimeInMillis() + "ms"); - } - - @Test - void testShouldIgnoreTimestamp() throws EvaluationException { - Calendar expDate = LocaleUtil.getLocaleCalendar(1984, Calendar.OCTOBER, 20); - Calendar actDate = DateParser.parseDate("1984/10/20 12:34:56"); - assertEquals(expDate, actDate, - "Had: " + expDate.getTime() + " and " + actDate.getTime() + "/" + - expDate.getTimeInMillis() + "ms and " + actDate.getTimeInMillis() + "ms"); - } - -} diff --git a/src/testcases/org/apache/poi/ss/util/TestExpandedDouble.java b/src/testcases/org/apache/poi/ss/util/TestExpandedDouble.java deleted file mode 100644 index 9465619b79..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestExpandedDouble.java +++ /dev/null @@ -1,128 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.math.BigInteger; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -/** - * Tests for {@link ExpandedDouble} - */ -final class TestExpandedDouble { - private static final BigInteger BIG_POW_10 = BigInteger.valueOf(1000000000); - - @Test - void testNegative() { - ExpandedDouble hd = new ExpandedDouble(0xC010000000000000L); - assertNotEquals(-2046, hd.getBinaryExponent(), "identified bug - sign bit not masked out of exponent"); - assertEquals(2, hd.getBinaryExponent()); - BigInteger frac = hd.getSignificand(); - assertEquals(64, frac.bitLength()); - assertEquals(1, frac.bitCount()); - } - - @Test - void testSubnormal() { - ExpandedDouble hd = new ExpandedDouble(0x0000000000000001L); - assertNotEquals(-1023, hd.getBinaryExponent(), "identified bug - subnormal numbers not decoded properly"); - assertEquals(-1086, hd.getBinaryExponent()); - BigInteger frac = hd.getSignificand(); - assertEquals(64, frac.bitLength()); - assertEquals(1, frac.bitCount()); - } - - /** - * Tests specific values for conversion from {@link ExpandedDouble} to {@link NormalisedDecimal} and back - */ - @ParameterizedTest - @ValueSource(longs = { - 0x4010000000000004L, - 0x7010000000000004L, - 0x1010000000000004L, - 0x0010000000000001L, // near lowest normal number - 0x0010000000000000L, // lowest normal number - 0x000FFFFFFFFFFFFFL, // highest subnormal number - 0x0008000000000000L, // subnormal number - - 0xC010000000000004L, - 0xE230100010001004L, - 0x403CE0FFFFFFFFF2L, - 0x0000000000000001L, // smallest non-zero number (subnormal) - 0x6230100010000FFEL, - 0x6230100010000FFFL, - 0x6230100010001000L, - 0x403CE0FFFFFFFFF0L, // has single digit round trip error - 0x2B2BFFFF10001079L, - }) - void confirmRoundTrip(long rawBitsA) { - double a = Double.longBitsToDouble(rawBitsA); - if (a == 0.0) { - // Can't represent 0.0 or -0.0 with NormalisedDecimal - return; - } - ExpandedDouble ed1 = new ExpandedDouble(rawBitsA); - NormalisedDecimal nd2 = ed1.normaliseBaseTen(); - checkNormaliseBaseTenResult(ed1, nd2); - - ExpandedDouble ed3 = nd2.normaliseBaseTwo(); - assertEquals(ed3.getBinaryExponent(), ed1.getBinaryExponent(), "bin exp mismatch"); - - BigInteger diff = ed3.getSignificand().subtract(ed1.getSignificand()).abs(); - if (diff.signum() == 0) { - return; - } - // original quantity only has 53 bits of precision - // these quantities may have errors in the 64th bit, which hopefully don't make any difference - - // errors in the 64th bit happen from time to time - // this is well below the 53 bits of precision required - assertTrue(diff.bitLength() < 2); - } - - - private static void checkNormaliseBaseTenResult(ExpandedDouble orig, NormalisedDecimal result) { - String sigDigs = result.getSignificantDecimalDigits(); - BigInteger frac = orig.getSignificand(); - while (frac.bitLength() + orig.getBinaryExponent() < 200) { - frac = frac.multiply(BIG_POW_10); - } - int binaryExp = orig.getBinaryExponent() - orig.getSignificand().bitLength(); - - String origDigs = frac.shiftLeft(binaryExp+1).toString(10); - assertTrue(origDigs.startsWith(sigDigs)); - - double dO = Double.parseDouble("0." + origDigs.substring(sigDigs.length())); - double d1 = Double.parseDouble(result.getFractionalPart().toPlainString()); - BigInteger subDigsO = BigInteger.valueOf((int) (dO * 32768 + 0.5)); - BigInteger subDigsB = BigInteger.valueOf((int) (d1 * 32768 + 0.5)); - - if (subDigsO.equals(subDigsB)) { - return; - } - BigInteger diff = subDigsB.subtract(subDigsO).abs(); - // 100/32768 ~= 0.003 - assertTrue(diff.intValue() <= 100, "minor mistake"); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestHSSFCellUtil.java b/src/testcases/org/apache/poi/ss/util/TestHSSFCellUtil.java deleted file mode 100644 index aba0d71a37..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestHSSFCellUtil.java +++ /dev/null @@ -1,26 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.util; - -import org.apache.poi.hssf.HSSFITestDataProvider; - -class TestHSSFCellUtil extends BaseTestCellUtil { - public TestHSSFCellUtil() { - super(HSSFITestDataProvider.instance); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/util/TestNumberComparer.java b/src/testcases/org/apache/poi/ss/util/TestNumberComparer.java deleted file mode 100644 index 225d9f835c..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestNumberComparer.java +++ /dev/null @@ -1,99 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.util.NumberComparisonExamples.ComparisonExample; -import org.apache.poi.util.HexDump; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Tests for {@link NumberComparer} - */ -final class TestNumberComparer { - - @Test - void testAllComparisonExamples() { - ComparisonExample[] examples = NumberComparisonExamples.getComparisonExamples(); - boolean success = true; - - for(int i=0;i new TestExpandedDouble().confirmRoundTrip(Double.doubleToLongBits(a))); - } - } - - /** - * The actual example from bug 47598 - */ - @Test - void testSpecificExampleA() { - double a = 0.06-0.01; - double b = 0.05; - assertNotEquals(a, b, 0.0); - assertEquals(0, NumberComparer.compare(a, b)); - } - - /** - * The example from the nabble posting - */ - @Test - void testSpecificExampleB() { - double a = 1+1.0028-0.9973; - double b = 1.0055; - assertNotEquals(a, b, 0.0); - assertEquals(0, NumberComparer.compare(a, b)); - } - - private static boolean confirm(int i, double a, double b, int expRes) { - int actRes = NumberComparer.compare(a, b); - - int sgnActRes = Integer.compare(actRes, 0); - if (sgnActRes != expRes) { - System.err.println("Mismatch example[" + i + "] (" - + formatDoubleAsHex(a) + ", " + formatDoubleAsHex(b) + ") expected " - + expRes + " but got " + sgnActRes); - return false; - } - return true; - } - private static String formatDoubleAsHex(double d) { - long l = Double.doubleToLongBits(d); - return HexDump.longToHex(l)+'L'; - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestNumberToTextConverter.java b/src/testcases/org/apache/poi/ss/util/TestNumberToTextConverter.java deleted file mode 100644 index 387980d870..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestNumberToTextConverter.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.ss.formula.constant.ConstantValueParser; -import org.apache.poi.ss.formula.ptg.NumberPtg; -import org.apache.poi.ss.util.NumberToTextConversionExamples.ExampleConversion; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link NumberToTextConverter} - */ -final class TestNumberToTextConverter { - /** - * Confirms that ExcelNumberToTextConverter.toText(d) produces the right results. - * As part of preparing this test class, the ExampleConversion instances should be set - * up to contain the rendering as produced by Excel. - */ - @Test - void testAll() { - ExampleConversion[] examples = NumberToTextConversionExamples.getExampleConversions(); - - for (ExampleConversion example : examples) { - if (example.isNaN()) { - confirmNaN(example.getRawDoubleBits(), example.getExcelRendering()); - continue; - } - String actual = NumberToTextConverter.toText(example.getDoubleValue()); - assertEquals(example.getExcelRendering(), actual); - } - } - - /** - * Excel's abnormal rendering of NaNs is both difficult to test and even reproduce in java. In - * general, Excel does not attempt to use raw NaN in the IEEE sense. In {@link FormulaRecord}s, - * Excel uses the NaN bit pattern to flag non-numeric (text, boolean, error) cached results. - * If the formula result actually evaluates to raw NaN, Excel transforms it to #NUM!. - * In other places (e.g. {@link NumberRecord}, {@link NumberPtg}, array items (via {@link - * ConstantValueParser}), there seems to be no special NaN translation scheme. If a NaN bit - * pattern is somehow encoded into any of these places Excel actually attempts to render the - * values as a plain number. That is the unusual functionality that this method is testing.

- * - * There are multiple encodings (bit patterns) for NaN, and CPUs and applications can convert - * to a preferred NaN encoding (Java prefers 0x7FF8000000000000L). Besides the - * special encoding in {@link FormulaRecord.SpecialCachedValue}, it is not known how/whether - * Excel attempts to encode NaN values. - * - * Observed NaN behaviour on HotSpot/Windows: - * Double.longBitsToDouble() will set one bit 51 (the NaN signaling flag) if it isn't - * already. Double.doubleToLongBits() will return a double with bit pattern - * 0x7FF8000000000000L for any NaN bit pattern supplied.
- * Differences are likely to be observed with other architectures.

- * - *

- * The few test case examples calling this method represent functionality which may not be - * important for POI to support. - */ - private void confirmNaN(long l, String excelRep) { - double d = Double.longBitsToDouble(l); - assertEquals("NaN", Double.toString(d)); - - String strExcel = NumberToTextConverter.rawDoubleBitsToText(l); - - assertEquals(excelRep, strExcel); - } - - @Test - void testSimpleRendering_bug56156() { - double dResult = 0.05+0.01; // values chosen to produce rounding anomaly - String actualText = NumberToTextConverter.toText(dResult); - String jdkText = Double.toString(dResult); - // "0.060000000000000005" - assertNotEquals("Should not use default JDK IEEE double rendering", jdkText, actualText); - assertEquals("0.06", actualText); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestPropertyTemplate.java b/src/testcases/org/apache/poi/ss/util/TestPropertyTemplate.java deleted file mode 100644 index bd57735706..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestPropertyTemplate.java +++ /dev/null @@ -1,949 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.BorderExtent; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Tests Spreadsheet PropertyTemplate - * - * @see org.apache.poi.ss.util.PropertyTemplate - */ -final class TestPropertyTemplate { - @Test - void getNumBorders() throws IOException { - CellRangeAddress a1 = new CellRangeAddress(0, 0, 0, 0); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorders(a1, BorderStyle.THIN, BorderExtent.TOP); - assertEquals(1, pt.getNumBorders(0, 0)); - pt.drawBorders(a1, BorderStyle.MEDIUM, BorderExtent.BOTTOM); - assertEquals(2, pt.getNumBorders(0, 0)); - pt.drawBorders(a1, BorderStyle.MEDIUM, BorderExtent.NONE); - assertEquals(0, pt.getNumBorders(0, 0)); - } - - @Test - void getNumBorderColors() throws IOException { - CellRangeAddress a1 = new CellRangeAddress(0, 0, 0, 0); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorderColors(a1, IndexedColors.RED.getIndex(), BorderExtent.TOP); - assertEquals(1, pt.getNumBorderColors(0, 0)); - pt.drawBorderColors(a1, IndexedColors.RED.getIndex(), BorderExtent.BOTTOM); - assertEquals(2, pt.getNumBorderColors(0, 0)); - pt.drawBorderColors(a1, IndexedColors.RED.getIndex(), BorderExtent.NONE); - assertEquals(0, pt.getNumBorderColors(0, 0)); - } - - @Test - void getTemplateProperties() throws IOException { - CellRangeAddress a1 = new CellRangeAddress(0, 0, 0, 0); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorders(a1, BorderStyle.THIN, BorderExtent.TOP); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(0, 0, CellUtil.BORDER_TOP)); - pt.drawBorders(a1, BorderStyle.MEDIUM, BorderExtent.BOTTOM); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(0, 0, CellUtil.BORDER_BOTTOM)); - pt.drawBorderColors(a1, IndexedColors.RED.getIndex(), BorderExtent.TOP); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(0, 0, CellUtil.TOP_BORDER_COLOR)); - pt.drawBorderColors(a1, IndexedColors.BLUE.getIndex(), BorderExtent.BOTTOM); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(0, 0, CellUtil.BOTTOM_BORDER_COLOR)); - } - - @Test - void drawBorders() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorders(a1c3, BorderStyle.THIN, - BorderExtent.ALL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } - } - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.OUTSIDE); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - if (i == 0) { - if (j == 0) { - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else if (j == 2) { - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else { - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } - } else if (i == 2) { - if (j == 0) { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else if (j == 2) { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } - } else { - if (j == 0) { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else if (j == 2) { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.TOP); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.BOTTOM); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.LEFT); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.RIGHT); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.INSIDE_HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - } else if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - } else { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.OUTSIDE_HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - } else if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.INSIDE_VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } else if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - } else { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.OUTSIDE_VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - } else if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - } - - @Test - void drawBorderColors() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorderColors(a1c3, IndexedColors.RED.getIndex(), - BorderExtent.ALL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - assertEquals(4, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.RED.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.OUTSIDE); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - assertEquals(4, pt.getNumBorderColors(i, j)); - if (i == 0) { - if (j == 0) { - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else if (j == 2) { - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else { - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } else if (i == 2) { - if (j == 0) { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else if (j == 2) { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } else { - if (j == 0) { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else if (j == 2) { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.TOP); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.BOTTOM); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.LEFT); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.RIGHT); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(2, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.INSIDE_HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - } else if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - } else { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(2, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.OUTSIDE_HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - } else if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(2, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.INSIDE_VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - } else { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(2, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.OUTSIDE_VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - } else if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - } - - @Test - void drawBordersWithColors() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - PropertyTemplate pt = new PropertyTemplate(); - - pt.drawBorders(a1c3, BorderStyle.MEDIUM, IndexedColors.RED.getIndex(), BorderExtent.ALL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - assertEquals(4, pt.getNumBorderColors(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - assertEquals(IndexedColors.RED.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.NONE, IndexedColors.RED.getIndex(), BorderExtent.ALL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - assertEquals(BorderStyle.NONE, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.NONE, - pt.getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.NONE, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.NONE, - pt.getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } - } - } - - @Test - void applyBorders() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - CellRangeAddress b2 = new CellRangeAddress(1, 1, 1, 1); - PropertyTemplate pt = new PropertyTemplate(); - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - pt.drawBorders(a1c3, BorderStyle.THIN, IndexedColors.RED.getIndex(), BorderExtent.ALL); - pt.applyBorders(sheet); - - for (Row row: sheet) { - for (Cell cell: row) { - CellStyle cs = cell.getCellStyle(); - assertEquals(BorderStyle.THIN, cs.getBorderTop()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderBottom()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderLeft()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderRight()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } - } - - pt.drawBorders(b2, BorderStyle.NONE, BorderExtent.ALL); - pt.applyBorders(sheet); - - for (Row row: sheet) { - for (Cell cell: row) { - CellStyle cs = cell.getCellStyle(); - if (cell.getColumnIndex() != 1 || row.getRowNum() == 0) { - assertEquals(BorderStyle.THIN, cs.getBorderTop()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderTop()); - } - if (cell.getColumnIndex() != 1 || row.getRowNum() == 2) { - assertEquals(BorderStyle.THIN, cs.getBorderBottom()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderBottom()); - } - if (cell.getColumnIndex() == 0 || row.getRowNum() != 1) { - assertEquals(BorderStyle.THIN, cs.getBorderLeft()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderLeft()); - } - if (cell.getColumnIndex() == 2 || row.getRowNum() != 1) { - assertEquals(BorderStyle.THIN, cs.getBorderRight()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderRight()); - } - } - } - - wb.close(); - } - - @Test - void clonePropertyTemplate() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, IndexedColors.RED.getIndex(), BorderExtent.ALL); - PropertyTemplate pt2 = new PropertyTemplate(pt); - assertNotSame(pt2, pt); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt2.getNumBorderColors(i, j)); - assertEquals(4, pt2.getNumBorderColors(i, j)); - } - } - - CellRangeAddress b2 = new CellRangeAddress(1,1,1,1); - pt2.drawBorders(b2, BorderStyle.THIN, BorderExtent.ALL); - - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - pt.applyBorders(sheet); - - for (Row row : sheet) { - for (Cell cell : row) { - CellStyle cs = cell.getCellStyle(); - assertEquals(BorderStyle.MEDIUM, cs.getBorderTop()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderBottom()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderLeft()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderRight()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } - } - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestRegionUtil.java b/src/testcases/org/apache/poi/ss/util/TestRegionUtil.java deleted file mode 100644 index 1fcd52ca80..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestRegionUtil.java +++ /dev/null @@ -1,163 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Tests that the common RegionUtil works as we need it to. - */ -final class TestRegionUtil { - private static final CellRangeAddress A1C3 = new CellRangeAddress(0, 2, 0, 2); - private static final BorderStyle NONE = BorderStyle.NONE; - private static final BorderStyle THIN = BorderStyle.THIN; - private static final int RED = IndexedColors.RED.getIndex(); - private static final int DEFAULT_COLOR = 0; - private Workbook wb; - private Sheet sheet; - - @BeforeEach - void setUp() { - wb = new HSSFWorkbook(); - sheet = wb.createSheet(); - } - - @AfterEach - void tearDown() throws IOException { - wb.close(); - } - - private CellStyle getCellStyle(int rowIndex, int columnIndex) { - Row row = sheet.getRow(rowIndex); - if (row == null) row = sheet.createRow(rowIndex); - Cell cell = row.getCell(columnIndex); - if (cell == null) cell = row.createCell(columnIndex); - return cell.getCellStyle(); - } - - @Test - void setBorderTop() { - assertEquals(NONE, getCellStyle(0, 0).getBorderTop()); - assertEquals(NONE, getCellStyle(0, 1).getBorderTop()); - assertEquals(NONE, getCellStyle(0, 2).getBorderTop()); - RegionUtil.setBorderTop(THIN, A1C3, sheet); - assertEquals(THIN, getCellStyle(0, 0).getBorderTop()); - assertEquals(THIN, getCellStyle(0, 1).getBorderTop()); - assertEquals(THIN, getCellStyle(0, 2).getBorderTop()); - } - @Test - void setBorderBottom() { - assertEquals(NONE, getCellStyle(2, 0).getBorderBottom()); - assertEquals(NONE, getCellStyle(2, 1).getBorderBottom()); - assertEquals(NONE, getCellStyle(2, 2).getBorderBottom()); - RegionUtil.setBorderBottom(THIN, A1C3, sheet); - assertEquals(THIN, getCellStyle(2, 0).getBorderBottom()); - assertEquals(THIN, getCellStyle(2, 1).getBorderBottom()); - assertEquals(THIN, getCellStyle(2, 2).getBorderBottom()); - } - @Test - void setBorderRight() { - assertEquals(NONE, getCellStyle(0, 2).getBorderRight()); - assertEquals(NONE, getCellStyle(1, 2).getBorderRight()); - assertEquals(NONE, getCellStyle(2, 2).getBorderRight()); - RegionUtil.setBorderRight(THIN, A1C3, sheet); - assertEquals(THIN, getCellStyle(0, 2).getBorderRight()); - assertEquals(THIN, getCellStyle(1, 2).getBorderRight()); - assertEquals(THIN, getCellStyle(2, 2).getBorderRight()); - } - @Test - void setBorderLeft() { - assertEquals(NONE, getCellStyle(0, 0).getBorderLeft()); - assertEquals(NONE, getCellStyle(1, 0).getBorderLeft()); - assertEquals(NONE, getCellStyle(2, 0).getBorderLeft()); - RegionUtil.setBorderLeft(THIN, A1C3, sheet); - assertEquals(THIN, getCellStyle(0, 0).getBorderLeft()); - assertEquals(THIN, getCellStyle(1, 0).getBorderLeft()); - assertEquals(THIN, getCellStyle(2, 0).getBorderLeft()); - } - - @Test - void setTopBorderColor() { - assertEquals(DEFAULT_COLOR, getCellStyle(0, 0).getTopBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(0, 1).getTopBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(0, 2).getTopBorderColor()); - RegionUtil.setTopBorderColor(RED, A1C3, sheet); - assertEquals(RED, getCellStyle(0, 0).getTopBorderColor()); - assertEquals(RED, getCellStyle(0, 1).getTopBorderColor()); - assertEquals(RED, getCellStyle(0, 2).getTopBorderColor()); - } - @Test - void setBottomBorderColor() { - assertEquals(DEFAULT_COLOR, getCellStyle(2, 0).getBottomBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(2, 1).getBottomBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(2, 2).getBottomBorderColor()); - RegionUtil.setBottomBorderColor(RED, A1C3, sheet); - assertEquals(RED, getCellStyle(2, 0).getBottomBorderColor()); - assertEquals(RED, getCellStyle(2, 1).getBottomBorderColor()); - assertEquals(RED, getCellStyle(2, 2).getBottomBorderColor()); - } - @Test - void setRightBorderColor() { - assertEquals(DEFAULT_COLOR, getCellStyle(0, 2).getRightBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(1, 2).getRightBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(2, 2).getRightBorderColor()); - RegionUtil.setRightBorderColor(RED, A1C3, sheet); - assertEquals(RED, getCellStyle(0, 2).getRightBorderColor()); - assertEquals(RED, getCellStyle(1, 2).getRightBorderColor()); - assertEquals(RED, getCellStyle(2, 2).getRightBorderColor()); - } - @Test - void setLeftBorderColor() { - assertEquals(DEFAULT_COLOR, getCellStyle(0, 0).getLeftBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(1, 0).getLeftBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(2, 0).getLeftBorderColor()); - RegionUtil.setLeftBorderColor(RED, A1C3, sheet); - assertEquals(RED, getCellStyle(0, 0).getLeftBorderColor()); - assertEquals(RED, getCellStyle(1, 0).getLeftBorderColor()); - assertEquals(RED, getCellStyle(2, 0).getLeftBorderColor()); - } - - @Test - void bordersCanBeAddedToNonExistantCells() { - RegionUtil.setBorderTop(THIN, A1C3, sheet); - assertEquals(THIN, getCellStyle(0, 0).getBorderTop()); - assertEquals(THIN, getCellStyle(0, 1).getBorderTop()); - assertEquals(THIN, getCellStyle(0, 2).getBorderTop()); - } - @Test - void borderColorsCanBeAddedToNonExistantCells() { - RegionUtil.setTopBorderColor(RED, A1C3, sheet); - assertEquals(RED, getCellStyle(0, 0).getTopBorderColor()); - assertEquals(RED, getCellStyle(0, 1).getTopBorderColor()); - assertEquals(RED, getCellStyle(0, 2).getTopBorderColor()); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestSheetBuilder.java b/src/testcases/org/apache/poi/ss/util/TestSheetBuilder.java deleted file mode 100644 index e258895c8f..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestSheetBuilder.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.io.IOException; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Tests SheetBuilder. - * - * @see org.apache.poi.ss.util.SheetBuilder - */ -final class TestSheetBuilder { - - private static Object[][] testData = new Object[][]{ - {1, 2, 3}, - {new Date(), null, null}, - {"one", "two", "=A1+B2"} - }; - - @Test - void testNotCreateEmptyCells() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = new SheetBuilder(wb, testData).build(); - - assertEquals(sheet.getPhysicalNumberOfRows(), 3); - - Row firstRow = sheet.getRow(0); - Cell firstCell = firstRow.getCell(0); - - assertEquals(firstCell.getCellType(), CellType.NUMERIC); - assertEquals(1.0, firstCell.getNumericCellValue(), 0.00001); - - - Row secondRow = sheet.getRow(1); - assertNotNull(secondRow.getCell(0)); - assertNull(secondRow.getCell(2)); - - Row thirdRow = sheet.getRow(2); - assertEquals(CellType.STRING, thirdRow.getCell(0).getCellType()); - String cellValue = thirdRow.getCell(0).getStringCellValue(); - assertEquals(testData[2][0].toString(), cellValue); - - assertEquals(CellType.FORMULA, thirdRow.getCell(2).getCellType()); - assertEquals("A1+B2", thirdRow.getCell(2).getCellFormula()); - } - } - - @Test - void testEmptyCells() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = new SheetBuilder(wb, testData).setCreateEmptyCells(true).build(); - - Cell emptyCell = sheet.getRow(1).getCell(1); - assertNotNull(emptyCell); - assertEquals(CellType.BLANK, emptyCell.getCellType()); - } - } - - @Test - void testSheetName() throws IOException { - final String sheetName = "TEST SHEET NAME"; - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = new SheetBuilder(wb, testData).setSheetName(sheetName).build(); - assertEquals(sheetName, sheet.getSheetName()); - } - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/util/TestSheetUtil.java b/src/testcases/org/apache/poi/ss/util/TestSheetUtil.java deleted file mode 100644 index 1731d46371..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestSheetUtil.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; - -/** - * Tests SheetUtil. - * - * @see org.apache.poi.ss.util.SheetUtil - */ -final class TestSheetUtil { - @Test - void testCellWithMerges() throws Exception { - try (Workbook wb = new HSSFWorkbook()) { - Sheet s = wb.createSheet(); - - // Create some test data - Row r2 = s.createRow(1); - r2.createCell(0).setCellValue(10); - r2.createCell(1).setCellValue(11); - Row r3 = s.createRow(2); - r3.createCell(0).setCellValue(20); - r3.createCell(1).setCellValue(21); - - assertEquals(0, s.addMergedRegion(new CellRangeAddress(2, 3, 0, 0))); - assertEquals(1, s.addMergedRegion(new CellRangeAddress(2, 2, 1, 4))); - - // With a cell that isn't defined, we'll get null - assertNull(SheetUtil.getCellWithMerges(s, 0, 0)); - - // With a cell that's not in a merged region, we'll get that - Cell cell = SheetUtil.getCellWithMerges(s, 1, 0); - assertNotNull(cell); - assertEquals(10.0, cell.getNumericCellValue(), 0.01); - cell = SheetUtil.getCellWithMerges(s, 1, 1); - assertNotNull(cell); - assertEquals(11.0, cell.getNumericCellValue(), 0.01); - - // With a cell that's the primary one of a merged region, we get that cell - cell = SheetUtil.getCellWithMerges(s, 2, 0); - assertNotNull(cell); - assertEquals(20.0, cell.getNumericCellValue(), 0.01); - cell = SheetUtil.getCellWithMerges(s, 2, 1); - assertNotNull(cell); - assertEquals(21., cell.getNumericCellValue(), 0.01); - - // With a cell elsewhere in the merged region, get top-left - cell = SheetUtil.getCellWithMerges(s, 3, 0); - assertNotNull(cell); - assertEquals(20.0, cell.getNumericCellValue(), 0.01); - cell = SheetUtil.getCellWithMerges(s, 2, 2); - assertNotNull(cell); - assertEquals(21.0, cell.getNumericCellValue(), 0.01); - cell = SheetUtil.getCellWithMerges(s, 2, 3); - assertNotNull(cell); - assertEquals(21.0, cell.getNumericCellValue(), 0.01); - assertNotNull(cell); - cell = SheetUtil.getCellWithMerges(s, 2, 4); - assertNotNull(cell); - assertEquals(21.0, cell.getNumericCellValue(), 0.01); - } - } - - @Test - void testCanComputeWidthHSSF() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - // cannot check on result because on some machines we get back false here! - assertDoesNotThrow(() -> SheetUtil.canComputeColumnWidth(wb.getFontAt(0))); - } - } - - @Test - void testGetCellWidthEmpty() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = wb.createSheet("sheet"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - // no contents: cell.setCellValue("sometext"); - assertEquals(-1.0, SheetUtil.getCellWidth(cell, 1, null, true), 0.01); - } - } - - @Test - void testGetCellWidthString() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = wb.createSheet("sheet"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellValue("sometext"); - - assertTrue(SheetUtil.getCellWidth(cell, 1, null, true) > 0); - } - } - - @Test - void testGetCellWidthNumber() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = wb.createSheet("sheet"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellValue(88.234); - - assertTrue(SheetUtil.getCellWidth(cell, 1, null, true) > 0); - } - } - - @Test - void testGetCellWidthBoolean() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = wb.createSheet("sheet"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellValue(false); - - assertTrue(SheetUtil.getCellWidth(cell, 1, null, false) > 0); - } - } - - @Test - void testGetColumnWidthString() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - Sheet sheet = wb.createSheet("sheet"); - Row row = sheet.createRow(0); - sheet.createRow(1); - sheet.createRow(2); - Cell cell = row.createCell(0); - - cell.setCellValue("sometext"); - - assertTrue(SheetUtil.getColumnWidth(sheet, 0, true) > 0, "Having some width for rows with actual cells"); - assertEquals(-1.0, SheetUtil.getColumnWidth(sheet, 0, true, 1, 2), 0.01, "Not having any widht for rows with all empty cells"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestWorkbookUtil.java b/src/testcases/org/apache/poi/ss/util/TestWorkbookUtil.java deleted file mode 100644 index bb4094a470..0000000000 --- a/src/testcases/org/apache/poi/ss/util/TestWorkbookUtil.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** - * Tests WorkbookUtil. - * - * @see org.apache.poi.ss.util.WorkbookUtil - */ -final class TestWorkbookUtil { - /** - * borrowed test cases from - * {@link org.apache.poi.hssf.record.TestBoundSheetRecord#testValidNames()} - */ - @Test - void testCreateSafeNames() { - - String p = "Sheet1"; - String actual = WorkbookUtil.createSafeSheetName(p); - assertEquals(p, actual); - - p = "O'Brien's sales"; - actual = WorkbookUtil.createSafeSheetName(p); - assertEquals(p, actual); - - p = " data # "; - actual = WorkbookUtil.createSafeSheetName(p); - assertEquals(p, actual); - - p = "data $1.00"; - actual = WorkbookUtil.createSafeSheetName(p); - assertEquals(p, actual); - - // now the replaced versions ... - actual = WorkbookUtil.createSafeSheetName("data?"); - assertEquals("data ", actual); - - actual = WorkbookUtil.createSafeSheetName("abc/def"); - assertEquals("abc def", actual); - - actual = WorkbookUtil.createSafeSheetName("data[0]"); - assertEquals("data 0 ", actual); - - actual = WorkbookUtil.createSafeSheetName("data*"); - assertEquals("data ", actual); - - actual = WorkbookUtil.createSafeSheetName("abc\\def"); - assertEquals("abc def", actual); - - actual = WorkbookUtil.createSafeSheetName("'data"); - assertEquals(" data", actual); - - actual = WorkbookUtil.createSafeSheetName("data'"); - assertEquals("data ", actual); - - actual = WorkbookUtil.createSafeSheetName("d'at'a"); - assertEquals("d'at'a", actual); - - actual = WorkbookUtil.createSafeSheetName(null); - assertEquals("null", actual); - - actual = WorkbookUtil.createSafeSheetName(""); - assertEquals("empty", actual); - - actual = WorkbookUtil.createSafeSheetName("1234567890123456789012345678901TOOLONG"); - assertEquals("1234567890123456789012345678901", actual); - - actual = WorkbookUtil.createSafeSheetName("sheet:a4"); - assertEquals("sheet a4", actual); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/cellwalk/TestCellWalk.java b/src/testcases/org/apache/poi/ss/util/cellwalk/TestCellWalk.java deleted file mode 100644 index 3515f783bd..0000000000 --- a/src/testcases/org/apache/poi/ss/util/cellwalk/TestCellWalk.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ -package org.apache.poi.ss.util.cellwalk; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetBuilder; -import org.junit.jupiter.api.Test; - -class TestCellWalk { - - private static Object[][] testData = new Object[][]{ - {1, 2, null}, - {null, new Date(), null}, - {null, null, "str"} - }; - - @Test - void testNotTraverseEmptyCells() { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = new SheetBuilder(wb, testData).build(); - CellRangeAddress range = CellRangeAddress.valueOf("A1:C3"); - - CellWalk cellWalk = new CellWalk(sheet, range); - int[] cellsVisited = { 0 }; - long[] ordinalNumberSum = { 0 }; - cellWalk.traverse((cell,ctx) -> { - cellsVisited[0]++; - ordinalNumberSum[0] += ctx.getOrdinalNumber(); - }); - - assertEquals(4, cellsVisited[0]); - /* 1 + 2 + 5 + 9 */ - assertEquals(17L, ordinalNumberSum[0]); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/util/MemoryLeakVerifier.java b/src/testcases/org/apache/poi/util/MemoryLeakVerifier.java deleted file mode 100644 index da84469c3f..0000000000 --- a/src/testcases/org/apache/poi/util/MemoryLeakVerifier.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.List; - -/** - * A simple utility class that can verify that objects have been successfully garbage collected. - * - * Usage is something like - * - * private final MemoryLeakVerifier verifier = new MemoryLeakVerifier(); - - {@literal}After - void tearDown() { - verifier.assertGarbageCollected(); - } - - {@literal}Test - void someTest() { - ... - verifier.addObject(object); - } - - * - * This will verify at the end of the test if the object is actually removed by the - * garbage collector or if it lingers in memory for some reason. - * - * Idea taken from http://stackoverflow.com/a/7410460/411846 - */ -public class MemoryLeakVerifier { - private static final int MAX_GC_ITERATIONS = 50; - private static final int GC_SLEEP_TIME = 100; - - private final List> references = new ArrayList<>(); - - public MemoryLeakVerifier() { - } - - public void addObject(Object object) { - references.add(new WeakReference<>(object)); - } - - /** - * Attempts to perform a full garbage collection so that all weak references will be removed. Usually only - * a single GC is required, but there have been situations where some unused memory is not cleared up on the - * first pass. This method performs a full garbage collection and then validates that the weak reference - * now has been cleared. If it hasn't then the thread will sleep for 100 milliseconds and then retry up to - * 50 more times. If after this the object still has not been collected then the assertion will fail. - * - * Based upon the method described in: http://www.javaworld.com/javaworld/javatips/jw-javatip130.html - */ - public void assertGarbageCollected() { - assertGarbageCollected(MAX_GC_ITERATIONS); - } - - /** - * Used only for testing the class itself where we would like to fail faster than 5 seconds - * @param maxIterations The number of times a GC will be invoked until a possible memory leak is reported - */ - void assertGarbageCollected(int maxIterations) { - try { - for(WeakReference ref : references) { - assertGarbageCollected(ref, maxIterations); - } - } catch (InterruptedException e) { - // just ensure that we quickly return when the thread is interrupted - } - } - - private static void assertGarbageCollected(WeakReference ref, int maxIterations) throws InterruptedException { - Runtime runtime = Runtime.getRuntime(); - for (int i = 0; i < maxIterations; i++) { - runtime.runFinalization(); - runtime.gc(); - if (ref.get() == null) - break; - - // Pause for a while and then go back around the loop to try again... - //EventQueue.invokeAndWait(Procedure.NoOp); // Wait for the AWT event queue to have completed processing - Thread.sleep(GC_SLEEP_TIME); - } - - assertNull(ref.get(), "Object should not exist after " + MAX_GC_ITERATIONS + " collections, but still had: " + ref.get()); - } -} diff --git a/src/testcases/org/apache/poi/util/NullOutputStream.java b/src/testcases/org/apache/poi/util/NullOutputStream.java deleted file mode 100644 index ac76123a3c..0000000000 --- a/src/testcases/org/apache/poi/util/NullOutputStream.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - 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.util; - -import java.io.OutputStream; - -/** - * Implementation of an OutputStream which does nothing, used - * to redirect stdout to avoid spamming the console with output - */ -public final class NullOutputStream extends OutputStream { - public NullOutputStream() { - } - - @Override - public void write(byte[] b, int off, int len) { - } - - @Override - public void write(int b) { - } - - @Override - public void write(byte[] b) { - } -} diff --git a/src/testcases/org/apache/poi/util/NullPrintStream.java b/src/testcases/org/apache/poi/util/NullPrintStream.java deleted file mode 100644 index 5fd6bc64ad..0000000000 --- a/src/testcases/org/apache/poi/util/NullPrintStream.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - 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.util; - -import java.io.PrintStream; -import java.util.Locale; - -// need to override all methods to omit calls to UTF-handling methods -@SuppressForbidden("ignore super constructor with charset - omits declaring UnsupportedEncodingException") -public class NullPrintStream extends PrintStream { - @SuppressWarnings("resource") - public NullPrintStream() { - super(new NullOutputStream(), true); - } - @Override - public void write(int b) {} - @Override - public void write(byte[] buf, int off, int len) {} - @Override - public void print(boolean b) {} - @Override - public void print(char c) {} - @Override - public void print(int i) {} - @Override - public void print(long l) {} - @Override - public void print(float f) {} - @Override - public void print(double d) {} - @Override - public void print(char[] s) {} - @Override - public void print(String s) {} - @Override - public void print(Object obj) {} - @Override - public void println() {} - @Override - public void println(boolean x) {} - @Override - public void println(char x) {} - @Override - public void println(int x) {} - @Override - public void println(long x) {} - @Override - public void println(float x) {} - @Override - public void println(double x) {} - @Override - public void println(char[] x) {} - @Override - public void println(String x) {} - @Override - public void println(Object x) {} - @Override - public PrintStream printf(String format, Object... args) { return this; } - @Override - public PrintStream printf(Locale l, String format, Object... args) { return this; } - @Override - public PrintStream format(String format, Object... args) { return this; } - @Override - public PrintStream format(Locale l, String format, Object... args) { return this; } - @Override - public PrintStream append(CharSequence csq) { return this; } - @Override - public PrintStream append(CharSequence csq, int start, int end) { return this; } - @Override - public PrintStream append(char c) { return this; } - @Override - public void write(byte[] b) {} -} diff --git a/src/testcases/org/apache/poi/util/TestArrayUtil.java b/src/testcases/org/apache/poi/util/TestArrayUtil.java deleted file mode 100644 index 0038aa019d..0000000000 --- a/src/testcases/org/apache/poi/util/TestArrayUtil.java +++ /dev/null @@ -1,93 +0,0 @@ - -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.Arrays; - -import org.junit.jupiter.api.Test; - -/** - * Unit test for ArrayUtil - */ -class TestArrayUtil { - /** - * Helper for testArrayMoveWithin - */ - private Integer[] getIntsList() { - return new Integer[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - } - - /** - * Test to ensure that arrayMoveWithin works as expected - */ - @Test - void testArrayMoveWithin() { - // moveFrom, moveTo, numToMove, values... - Integer[][] data = { - // Moving to a later point in the array - // Shift 1 back - { 4, 8, 1, 0, 1, 2, 3, 5, 6, 7, 8, 4, 9 }, - // Shift front 1 back - { 0, 7, 1, 1, 2, 3, 4, 5, 6, 7, 0, 8, 9 }, - // Shift 1 to end - { 4, 9, 1, 0, 1, 2, 3, 5, 6, 7, 8, 9, 4 }, - - // Moving to an earlier point in the array - // Shift 1 forward - { 8, 3, 1, 0, 1, 2, 8, 3, 4, 5, 6, 7, 9 }, - // Shift end 1 forward - { 9, 2, 1, 0, 1, 9, 2, 3, 4, 5, 6, 7, 8 }, - // Shift 1 to front - { 5, 0, 1, 5, 0, 1, 2, 3, 4, 6, 7, 8, 9 }, - - // Moving many to a later point in the array - // Shift 3 back - { 2, 6, 3, 0, 1, 5, 6, 7, 8, 2, 3, 4, 9 }, - // Shift 3 to back - { 2, 7, 3, 0, 1, 5, 6, 7, 8, 9, 2, 3, 4 }, - // Shift from 3 front - { 0, 5, 3, 3, 4, 5, 6, 7, 0, 1, 2, 8, 9 }, - - // Moving many to an earlier point in the array - // Shift 3 forward - { 6, 2, 3, 0, 1, 6, 7, 8, 2, 3, 4, 5, 9 }, - // Shift 3 to front - { 6, 0, 3, 6, 7, 8, 0, 1, 2, 3, 4, 5, 9 }, - // Shift from 3 back - { 7, 3, 3, 0, 1, 2, 7, 8, 9, 3, 4, 5, 6 } - }; - - for (Integer[] entry : data) { - Integer[] ints = getIntsList(); - ArrayUtil.arrayMoveWithin(ints, entry[0], entry[1], entry[2]); - assertArrayEquals(ints, Arrays.copyOfRange(entry, 3, 13)); - } - - // Check can't shift more than we have - assertThrows(IllegalArgumentException.class, () -> ArrayUtil.arrayMoveWithin(getIntsList(), 7, 3, 5)); - // Good, we don't have 5 from 7 onwards - - // Check can't shift where would overshoot - assertThrows(IllegalArgumentException.class, () -> ArrayUtil.arrayMoveWithin(getIntsList(), 2, 7, 5)); - // Good, we can't fit 5 in starting at 7 - } -} diff --git a/src/testcases/org/apache/poi/util/TestBitField.java b/src/testcases/org/apache/poi/util/TestBitField.java deleted file mode 100644 index 55c30087fa..0000000000 --- a/src/testcases/org/apache/poi/util/TestBitField.java +++ /dev/null @@ -1,217 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; - -/** - * Class to test BitField functionality - */ -final class TestBitField { - private static BitField bf_multi = BitFieldFactory.getInstance(0x3F80); - private static BitField bf_single = BitFieldFactory.getInstance(0x4000); - - @Test - void testGetValue() { - assertEquals(bf_multi.getValue(-1), 127); - assertEquals(bf_multi.getValue(0), 0); - assertEquals(bf_single.getValue(-1), 1); - assertEquals(bf_single.getValue(0), 0); - } - - @Test - void testGetShortValue() { - assertEquals(bf_multi.getShortValue(( short ) -1), ( short ) 127); - assertEquals(bf_multi.getShortValue(( short ) 0), ( short ) 0); - assertEquals(bf_single.getShortValue(( short ) -1), ( short ) 1); - assertEquals(bf_single.getShortValue(( short ) 0), ( short ) 0); - } - - @Test - void testGetRawValue() { - assertEquals(bf_multi.getRawValue(-1), 0x3F80); - assertEquals(bf_multi.getRawValue(0), 0); - assertEquals(bf_single.getRawValue(-1), 0x4000); - assertEquals(bf_single.getRawValue(0), 0); - } - - @Test - void testGetShortRawValue() { - assertEquals(bf_multi.getShortRawValue(( short ) -1), - ( short ) 0x3F80); - assertEquals(bf_multi.getShortRawValue(( short ) 0), ( short ) 0); - assertEquals(bf_single.getShortRawValue(( short ) -1), - ( short ) 0x4000); - assertEquals(bf_single.getShortRawValue(( short ) 0), ( short ) 0); - } - - @Test - void testIsSet() { - assertFalse(bf_multi.isSet(0)); - for (int j = 0x80; j <= 0x3F80; j += 0x80) - { - assertTrue(bf_multi.isSet(j)); - } - assertFalse(bf_single.isSet(0)); - assertTrue(bf_single.isSet(0x4000)); - } - - @Test - void testIsAllSet() { - for (int j = 0; j < 0x3F80; j += 0x80) - { - assertFalse(bf_multi.isAllSet(j)); - } - assertTrue(bf_multi.isAllSet(0x3F80)); - assertFalse(bf_single.isAllSet(0)); - assertTrue(bf_single.isAllSet(0x4000)); - } - - @Test - void testSetValue() { - for (int j = 0; j < 128; j++) - { - assertEquals(bf_multi.getValue(bf_multi.setValue(0, j)), j); - assertEquals(bf_multi.setValue(0, j), j << 7); - } - - // verify that excess bits are stripped off - assertEquals(bf_multi.setValue(0x3f80, 128), 0); - for (int j = 0; j < 2; j++) - { - assertEquals(bf_single.getValue(bf_single.setValue(0, j)), j); - assertEquals(bf_single.setValue(0, j), j << 14); - } - - // verify that excess bits are stripped off - assertEquals(bf_single.setValue(0x4000, 2), 0); - } - - @Test - void testSetShortValue() { - for (int j = 0; j < 128; j++) - { - assertEquals(bf_multi - .getShortValue(bf_multi - .setShortValue(( short ) 0, ( short ) j)), ( short ) j); - assertEquals(bf_multi.setShortValue(( short ) 0, ( short ) j), - ( short ) (j << 7)); - } - - // verify that excess bits are stripped off - assertEquals(bf_multi.setShortValue(( short ) 0x3f80, ( short ) 128), - ( short ) 0); - for (int j = 0; j < 2; j++) - { - assertEquals(bf_single - .getShortValue(bf_single - .setShortValue(( short ) 0, ( short ) j)), ( short ) j); - assertEquals(bf_single.setShortValue(( short ) 0, ( short ) j), - ( short ) (j << 14)); - } - - // verify that excess bits are stripped off - assertEquals(bf_single.setShortValue(( short ) 0x4000, ( short ) 2), - ( short ) 0); - } - - @Test - void testByte() { - assertEquals(1, BitFieldFactory.getInstance(1).setByteBoolean(( byte ) 0, true)); - assertEquals(2, BitFieldFactory.getInstance(2).setByteBoolean(( byte ) 0, true)); - assertEquals(4, BitFieldFactory.getInstance(4).setByteBoolean(( byte ) 0, true)); - assertEquals(8, BitFieldFactory.getInstance(8).setByteBoolean(( byte ) 0, true)); - assertEquals(16, BitFieldFactory.getInstance(16).setByteBoolean(( byte ) 0, true)); - assertEquals(32, BitFieldFactory.getInstance(32).setByteBoolean(( byte ) 0, true)); - assertEquals(64, BitFieldFactory.getInstance(64).setByteBoolean(( byte ) 0, true)); - assertEquals(-128, - BitFieldFactory.getInstance(128).setByteBoolean(( byte ) 0, true)); - assertEquals(0, BitFieldFactory.getInstance(1).setByteBoolean(( byte ) 1, false)); - assertEquals(0, BitFieldFactory.getInstance(2).setByteBoolean(( byte ) 2, false)); - assertEquals(0, BitFieldFactory.getInstance(4).setByteBoolean(( byte ) 4, false)); - assertEquals(0, BitFieldFactory.getInstance(8).setByteBoolean(( byte ) 8, false)); - assertEquals(0, BitFieldFactory.getInstance(16).setByteBoolean(( byte ) 16, false)); - assertEquals(0, BitFieldFactory.getInstance(32).setByteBoolean(( byte ) 32, false)); - assertEquals(0, BitFieldFactory.getInstance(64).setByteBoolean(( byte ) 64, false)); - assertEquals(0, BitFieldFactory.getInstance(128).setByteBoolean(( byte ) 128, - false)); - assertEquals(-2, BitFieldFactory.getInstance(1).setByteBoolean(( byte ) 255, false)); - byte clearedBit = BitFieldFactory.getInstance(0x40).setByteBoolean(( byte ) -63, - false); - - assertFalse(BitFieldFactory.getInstance(0x40).isSet(clearedBit)); - } - - @Test - void testClear() { - assertEquals(bf_multi.clear(-1), 0xFFFFC07F); - assertEquals(bf_single.clear(-1), 0xFFFFBFFF); - } - - @Test - void testClearShort() { - assertEquals(bf_multi.clearShort(( short ) -1), ( short ) 0xC07F); - assertEquals(bf_single.clearShort(( short ) -1), ( short ) 0xBFFF); - } - - @Test - void testSet() { - assertEquals(bf_multi.set(0), 0x3F80); - assertEquals(bf_single.set(0), 0x4000); - } - - @Test - void testSetShort() { - assertEquals(bf_multi.setShort(( short ) 0), ( short ) 0x3F80); - assertEquals(bf_single.setShort(( short ) 0), ( short ) 0x4000); - } - - @Test - void testSetBoolean() { - assertEquals(bf_multi.set(0), bf_multi.setBoolean(0, true)); - assertEquals(bf_single.set(0), bf_single.setBoolean(0, true)); - assertEquals(bf_multi.clear(-1), bf_multi.setBoolean(-1, false)); - assertEquals(bf_single.clear(-1), bf_single.setBoolean(-1, false)); - } - - @Test - void testSetShortBoolean() { - assertEquals(bf_multi.setShort(( short ) 0), - bf_multi.setShortBoolean(( short ) 0, true)); - assertEquals(bf_single.setShort(( short ) 0), - bf_single.setShortBoolean(( short ) 0, true)); - assertEquals(bf_multi.clearShort(( short ) -1), - bf_multi.setShortBoolean(( short ) -1, false)); - assertEquals(bf_single.clearShort(( short ) -1), - bf_single.setShortBoolean(( short ) -1, false)); - } - - @Test - void testSetLargeValues() { - final BitField bf1 = new BitField(0xF), bf2 = new BitField(0xF0000000); - int a = 0; - a = bf1.setValue(a, 9); - a = bf2.setValue(a, 9); - assertEquals(9, bf1.getValue(a)); - assertEquals(9, bf2.getValue(a)); - } -} diff --git a/src/testcases/org/apache/poi/util/TestByteField.java b/src/testcases/org/apache/poi/util/TestByteField.java deleted file mode 100644 index 8c37667fbc..0000000000 --- a/src/testcases/org/apache/poi/util/TestByteField.java +++ /dev/null @@ -1,138 +0,0 @@ - -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Unit test for ByteField class - */ -final class TestByteField { - - private static final byte[] _test_array = { - Byte.MIN_VALUE, ( byte ) -1, ( byte ) 0, ( byte ) 1, Byte.MAX_VALUE - }; - - @Test - void testConstructors() { - try { - new ByteField(-1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - ByteField field = new ByteField(2); - - assertEquals(( byte ) 0, field.get()); - try { - new ByteField(-1, ( byte ) 1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new ByteField(2, ( byte ) 3); - assertEquals(( byte ) 3, field.get()); - byte[] array = new byte[ 3 ]; - - try { - new ByteField(-1, ( byte ) 1, array); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new ByteField(2, ( byte ) 4, array); - assertEquals(( byte ) 4, field.get()); - assertEquals(( byte ) 4, array[ 2 ]); - array = new byte[ 2 ]; - try { - new ByteField(2, ( byte ) 5, array); - fail("should have gotten ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - for (byte b : _test_array) { - array = new byte[ 1 ]; - new ByteField(0, b, array); - assertEquals(b, new ByteField(0, array).get()); - } - } - - @Test - void testSet() { - ByteField field = new ByteField(0); - byte[] array = new byte[ 1 ]; - - for (int j = 0; j < _test_array.length; j++) { - field.set(_test_array[ j ]); - assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); - field = new ByteField(0); - field.set(_test_array[ j ], array); - assertEquals(_test_array[ j ], field.get(), "testing _2 "); - assertEquals(_test_array[ j ], array[ 0 ], "testing _3 "); - } - } - - @Test - void testReadFromBytes() { - ByteField field = new ByteField(1); - byte[] array = new byte[ 1 ]; - - try { - field.readFromBytes(array); - fail("should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new ByteField(0); - for (int j = 0; j < _test_array.length; j++) { - array[ 0 ] = _test_array[ j ]; - field.readFromBytes(array); - assertEquals(_test_array[ j ], field.get(), "testing " + j); - } - } - - @Test - void testReadFromStream() throws IOException { - ByteField field = new ByteField(0); - ByteArrayInputStream stream = new ByteArrayInputStream(_test_array.clone()); - - for (int j = 0; j < _test_array.length; j++) { - field.readFromStream(stream); - assertEquals(_test_array[ j ], field.get(), "Testing " + j); - } - } - - @Test - void testWriteToBytes() { - ByteField field = new ByteField(0); - byte[] array = new byte[ 1 ]; - - for (byte b : _test_array) { - field.set(b); - field.writeToBytes(array); - assertEquals(b, array[ 0 ], "testing "); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestHexDump.java b/src/testcases/org/apache/poi/util/TestHexDump.java deleted file mode 100644 index 4a465cb4be..0000000000 --- a/src/testcases/org/apache/poi/util/TestHexDump.java +++ /dev/null @@ -1,196 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; - -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -class TestHexDump { - - private static PrintStream SYSTEM_OUT; - - @BeforeAll - public static void setUp() throws UnsupportedEncodingException { - SYSTEM_OUT = System.out; - System.setOut(new NullPrintStream()); - } - - @AfterAll - public static void tearDown() { - System.setOut(SYSTEM_OUT); - } - - @Test - void testDump() throws IOException { - byte[] testArray = testArray(); - ByteArrayOutputStream streamAct = new ByteArrayOutputStream(); - HexDump.dump(testArray, 0, streamAct, 0); - byte[] bytesAct = streamAct.toByteArray(); - byte[] bytesExp = toHexDump(0, 0); - - assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); - assertArrayEquals(bytesExp, bytesAct, "array mismatch"); - - // verify proper behavior with non-zero offset - streamAct.reset(); - HexDump.dump(testArray, 0x10000000L, streamAct, 0); - bytesAct = streamAct.toByteArray(); - bytesExp = toHexDump(0x10000000L,0); - - assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); - assertArrayEquals(bytesExp, bytesAct, "array mismatch"); - - // verify proper behavior with negative offset - streamAct.reset(); - HexDump.dump(testArray, 0xFF000000L, streamAct, 0); - bytesAct = streamAct.toByteArray(); - bytesExp = toHexDump(0xFF000000L,0); - - assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); - assertArrayEquals(bytesExp, bytesAct, "array mismatch"); - - // verify proper behavior with non-zero index - streamAct.reset(); - HexDump.dump(testArray, 0xFF000000L, streamAct, 0x81); - bytesAct = streamAct.toByteArray(); - bytesExp = toHexDump(0xFF000000L,0x81); - - assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); - assertArrayEquals(bytesExp, bytesAct, "array mismatch"); - - - // verify proper behavior with negative index - streamAct.reset(); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> HexDump.dump(testArray, 0x10000000L, streamAct, -1)); - - // verify proper behavior with index that is too large - streamAct.reset(); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> HexDump.dump(testArray, 0x10000000L, streamAct, testArray.length)); - - // verify proper behavior with null stream - assertThrows(IllegalArgumentException.class, () -> HexDump.dump(testArray, 0x10000000L, null, 0)); - - // verify proper behaviour with empty byte array - streamAct.reset(); - HexDump.dump( new byte[0], 0, streamAct, 0 ); - assertEquals( "No Data" + System.getProperty( "line.separator"), streamAct.toString(LocaleUtil.CHARSET_1252.name()) ); - - } - - private byte[] toHexDump(long offset, int index) { - StringBuilder strExp = new StringBuilder(), chrs = new StringBuilder(); - Object[] obj = new Object[33]; - StringBuilder format = new StringBuilder(); - - for (int j = 0; j < 16 && (index + j*16) < 256; j++) { - obj[0] = offset+index+j*16L; - chrs.setLength(0); - format.setLength(0); - format.append("%08X "); - for (int k = 0; k < 16; k++) { - if (index+j*16+k < 256){ - obj[k+1] = index+j*16+k; - chrs.append(HexDump.toAscii(index+j*16+k)); - format.append("%02X "); - } else { - format.append(" "); - } - } - obj[17] = chrs.toString(); - format.append("%18$s").append(HexDump.EOL); - - String str = String.format(LocaleUtil.getUserLocale(), format.toString(), obj); - strExp.append(str); - } - return strExp.toString().getBytes(HexDump.UTF8); - } - - @Test - void testToHex() { - assertEquals("000A", HexDump.toHex((short)0xA)); - - assertEquals("0A", HexDump.toHex((byte)0xA)); - assertEquals("0000000A", HexDump.toHex(0xA)); - - assertEquals("[]", HexDump.toHex(new byte[] { })); - assertEquals("[0A]", HexDump.toHex(new byte[] { 0xA })); - assertEquals("[0A, 0B]", HexDump.toHex(new byte[] { 0xA, 0xB })); - - assertEquals("FFFF", HexDump.toHex((short)0xFFFF)); - - assertEquals("00000000000004D2", HexDump.toHex(1234L)); - - assertEquals("0xFE", HexDump.byteToHex(-2)); - assertEquals("0x25", HexDump.byteToHex(37)); - assertEquals("0xFFFE", HexDump.shortToHex(-2)); - assertEquals("0x0005", HexDump.shortToHex(5)); - assertEquals("0xFFFFFF9C", HexDump.intToHex(-100)); - assertEquals("0x00001001", HexDump.intToHex(4097)); - assertEquals("0xFFFFFFFFFFFF0006", HexDump.longToHex(-65530)); - assertEquals("0x0000000000003FCD", HexDump.longToHex(16333)); - } - - @Test - void testDumpToString() { - byte[] testArray = testArray(); - String dump = HexDump.dump(testArray, 0, 0); - //System.out.println("Hex: \n" + dump); - assertTrue(dump.contains("0123456789:;<=>?"), "Had: \n" + dump); - - dump = HexDump.dump(testArray, 2, 1); - //System.out.println("Hex: \n" + dump); - assertTrue(dump.contains("123456789:;<=>?@"), "Had: \n" + dump); - } - - @ParameterizedTest - @ValueSource(ints = {-1, 2, 1}) - void testDumpToStringOutOfIndex1(int index) { - assertThrows(ArrayIndexOutOfBoundsException.class, () -> - HexDump.dump(new byte[1], 0, index)); - } - - @ParameterizedTest - @ValueSource(ints = {0, 1}) - void testDumpToStringNoDataEOL(int index) { - String s = HexDump.dump(new byte[0], 0, index); - assertEquals("No Data", s.trim()); - } - - private static byte[] testArray() { - byte[] testArray = new byte[ 256 ]; - - for (int j = 0; j < 256; j++) { - testArray[ j ] = ( byte ) j; - } - - return testArray; - } -} diff --git a/src/testcases/org/apache/poi/util/TestIOUtils.java b/src/testcases/org/apache/poi/util/TestIOUtils.java deleted file mode 100644 index 19b64dd3c1..0000000000 --- a/src/testcases/org/apache/poi/util/TestIOUtils.java +++ /dev/null @@ -1,579 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PushbackInputStream; -import java.nio.ByteBuffer; -import java.nio.channels.ReadableByteChannel; -import java.nio.charset.StandardCharsets; -import java.util.Random; - -import org.apache.poi.EmptyFileException; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -final class TestIOUtils { - private static File TMP; - private static final long LENGTH = 300 + new Random().nextInt(9000); - - @BeforeAll - public static void setUp() throws IOException { - TMP = File.createTempFile("poi-ioutils-", ""); - try (OutputStream os = new FileOutputStream(TMP)) { - for (int i = 0; i < LENGTH; i++) { - os.write(0x01); - } - } - } - - @AfterAll - public static void tearDown() { - if (TMP != null) { - assertTrue(TMP.delete()); - } - } - - private static InputStream data123() { - return new ByteArrayInputStream(new byte[]{1,2,3}); - } - - @Test - void testPeekFirst8Bytes() throws Exception { - assertArrayEquals("01234567".getBytes(StandardCharsets.UTF_8), - IOUtils.peekFirst8Bytes(new ByteArrayInputStream("0123456789".getBytes(StandardCharsets.UTF_8)))); - } - - @Test - void testPeekFirst8BytesWithPushbackInputStream() throws Exception { - assertArrayEquals("01234567".getBytes(StandardCharsets.UTF_8), - IOUtils.peekFirst8Bytes(new PushbackInputStream(new ByteArrayInputStream("0123456789".getBytes(StandardCharsets.UTF_8)), 8))); - } - - @Test - void testPeekFirst8BytesTooLessAvailable() throws Exception { - assertArrayEquals(new byte[] { 1, 2, 3, 0, 0, 0, 0, 0}, IOUtils.peekFirst8Bytes(data123())); - } - - @Test - void testPeekFirst8BytesEmpty() { - assertThrows(EmptyFileException.class, () -> - IOUtils.peekFirst8Bytes(new ByteArrayInputStream(new byte[0]))); - } - - @Test - void testToByteArray() throws Exception { - assertArrayEquals(new byte[] { 1, 2, 3}, IOUtils.toByteArray(data123())); - } - - @Test - void testToByteArrayToSmall() { - assertThrows(IOException.class, () -> IOUtils.toByteArray(data123(), 10)); - } - - @Test - void testToByteArrayMaxLengthToSmall() { - assertThrows(IOException.class, () -> IOUtils.toByteArray(data123(), 10, 10)); - } - - @Test - void testToByteArrayNegativeLength() { - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(data123(), -1)); - } - - @Test - void testToByteArrayNegativeMaxLength() { - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(data123(), 10, -1)); - } - - @Test - void testToByteArrayByteBuffer() { - assertArrayEquals(new byte[] { 1, 2, 3}, - IOUtils.toByteArray(ByteBuffer.wrap(new byte[]{1, 2, 3}), 10)); - } - - @Test - void testToByteArrayByteBufferNonArray() { - ByteBuffer buffer = ByteBuffer.allocate(3); - buffer.put(new byte[] { 1, 2, 3}); - buffer.position(0); - assertFalse(buffer.asReadOnlyBuffer().hasArray()); - assertEquals(3, buffer.asReadOnlyBuffer().remaining()); - - assertArrayEquals(new byte[] { 1, 2, 3}, - IOUtils.toByteArray(buffer.asReadOnlyBuffer(), 3)); - } - - @Test - void testToByteArrayByteBufferToSmall() { - assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7}, - IOUtils.toByteArray(ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5, 6, 7}), 3)); - } - - @Test - void testSkipFully() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - long skipped = IOUtils.skipFully(is, 20000L); - assertEquals(LENGTH, skipped); - } - } - - @Test - void testSkipFullyGtIntMax() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - long skipped = IOUtils.skipFully(is, Integer.MAX_VALUE + 20000L); - assertEquals(LENGTH, skipped); - } - } - - @Test - void testSkipFullyByteArray() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (InputStream is = new FileInputStream(TMP)) { - assertEquals(LENGTH, IOUtils.copy(is, bos)); - long skipped = IOUtils.skipFully(new ByteArrayInputStream(bos.toByteArray()), 20000L); - assertEquals(LENGTH, skipped); - } - } - - @Test - void testSkipFullyByteArrayGtIntMax() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (InputStream is = new FileInputStream(TMP)) { - assertEquals(LENGTH, IOUtils.copy(is, bos)); - long skipped = IOUtils.skipFully(new ByteArrayInputStream(bos.toByteArray()), Integer.MAX_VALUE + 20000L); - assertEquals(LENGTH, skipped); - } - } - - @Test - void testCopyToFile() throws IOException { - File dest = File.createTempFile("poi-ioutils-", ""); - try { - try (InputStream is = new FileInputStream(TMP)) { - assertEquals(LENGTH, IOUtils.copy(is, dest)); - } - - try (FileInputStream strOrig = new FileInputStream(TMP); - FileInputStream strDest = new FileInputStream(dest)) { - byte[] bytesOrig = new byte[(int)LENGTH]; - byte[] bytesDest = new byte[(int)LENGTH]; - IOUtils.readFully(strOrig, bytesOrig); - IOUtils.readFully(strDest, bytesDest); - assertArrayEquals(bytesOrig, bytesDest); - } - } finally { - assertTrue(dest.delete()); - } - } - - @Test - void testCopyToInvalidFile() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - assertThrows(RuntimeException.class, - () -> { - // try with two different paths so we fail on both Unix and Windows - IOUtils.copy(is, new File("/notexisting/directory/structure")); - IOUtils.copy(is, new File("c:\\note&/()\"§=§%&!§$81§0_:;,.-'#*+~`?ß´ß0´ß9243xisting\\directory\\structure")); - }); - } - } - - @Test - void testSkipFullyBug61294() throws IOException { - long skipped = IOUtils.skipFully(new ByteArrayInputStream(new byte[0]), 1); - assertEquals(-1L, skipped); - } - - @Test - void testZeroByte() throws IOException { - long skipped = IOUtils.skipFully((new ByteArrayInputStream(new byte[0])), 100); - assertEquals(-1L, skipped); - } - - @Test - void testSkipZero() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - long skipped = IOUtils.skipFully(is, 0); - assertEquals(0, skipped); - } - } - - @Test - void testSkipNegative() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - assertThrows(IllegalArgumentException.class, () -> IOUtils.skipFully(is, -1)); - } - } - - @Test - void testMaxLengthTooLong() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(is, Integer.MAX_VALUE, 100)); - } - } - - @Test - void testMaxLengthIgnored() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - int len = IOUtils.toByteArray(is, 90, Integer.MAX_VALUE).length; - assertEquals(90, len); - len = IOUtils.toByteArray(is, 90, 100).length; - assertEquals(90, len); - len = IOUtils.toByteArray(is, Integer.MAX_VALUE, Integer.MAX_VALUE).length; - assertTrue(len > 300-2*90); - } - } - - @Test - void testMaxLengthInvalid() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(is, 90, 80)); - } - } - - @Test - void testWonkyInputStream() throws IOException { - long skipped = IOUtils.skipFully(new WonkyInputStream(), 10000); - assertEquals(10000, skipped); - } - - @Test - void testSetMaxOverride() throws IOException { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - byte[] bytes = IOUtils.toByteArray(stream); - assertNotNull(bytes); - assertEquals("abc", new String(bytes, StandardCharsets.UTF_8)); - } - - @Test - void testSetMaxOverrideLimit() throws IOException { - IOUtils.setByteArrayMaxOverride(30 * 1024 * 1024); - try { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - byte[] bytes = IOUtils.toByteArray(stream); - assertNotNull(bytes); - assertEquals("abc", new String(bytes, StandardCharsets.UTF_8)); - } finally { - IOUtils.setByteArrayMaxOverride(-1); - } - } - - @Test - void testSetMaxOverrideOverLimit() { - IOUtils.setByteArrayMaxOverride(2); - try { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(stream)); - } finally { - IOUtils.setByteArrayMaxOverride(-1); - } - } - - @Test - void testSetMaxOverrideWithLength() throws IOException { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - byte[] bytes = IOUtils.toByteArray(stream, 3, 100); - assertNotNull(bytes); - assertEquals("abc", new String(bytes, StandardCharsets.UTF_8)); - } - - @Test - void testSetMaxOverrideLimitWithLength() throws IOException { - IOUtils.setByteArrayMaxOverride(30 * 1024 * 1024); - try { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - byte[] bytes = IOUtils.toByteArray(stream, 3, 100); - assertNotNull(bytes); - assertEquals("abc", new String(bytes, StandardCharsets.UTF_8)); - } finally { - IOUtils.setByteArrayMaxOverride(-1); - } - } - - @Test - void testSetMaxOverrideOverLimitWithLength() { - IOUtils.setByteArrayMaxOverride(2); - try { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(stream, 3, 100)); - } finally { - IOUtils.setByteArrayMaxOverride(-1); - } - } - - @Test - void testSafelyAllocate() { - byte[] bytes = IOUtils.safelyAllocate(30, 200); - assertNotNull(bytes); - assertEquals(30, bytes.length); - } - - @Test - void testSafelyAllocateLimit() { - IOUtils.setByteArrayMaxOverride(40); - try { - byte[] bytes = IOUtils.safelyAllocate(30, 200); - assertNotNull(bytes); - assertEquals(30, bytes.length); - } finally { - IOUtils.setByteArrayMaxOverride(-1); - } - } - - @Test - void testReadFully() throws IOException { - byte[] bytes = new byte[2]; - assertEquals(2, IOUtils.readFully(new ByteArrayInputStream(new byte[] {1, 2, 3}), bytes, 0, 2)); - assertArrayEquals(new byte[] {1,2}, bytes); - } - - @Test - void testReadFullyEOF() throws IOException { - byte[] bytes = new byte[2]; - assertEquals(2, IOUtils.readFully(new NullInputStream(2), bytes, 0, 4)); - assertArrayEquals(new byte[] {0,0}, bytes); - } - - @Test - void testReadFullyEOFZero() throws IOException { - byte[] bytes = new byte[2]; - assertEquals(-1, IOUtils.readFully(new NullInputStream(0), bytes, 0, 4)); - assertArrayEquals(new byte[] {0,0}, bytes); - } - - @Test - void testReadFullySimple() throws IOException { - byte[] bytes = new byte[2]; - assertEquals(2, IOUtils.readFully(new ByteArrayInputStream(new byte[] {1, 2, 3}), bytes)); - assertArrayEquals(new byte[] {1,2}, bytes); - } - - @Test - void testReadFullyOffset() throws IOException { - byte[] bytes = new byte[3]; - assertEquals(2, IOUtils.readFully(new ByteArrayInputStream(new byte[] {1, 2, 3}), bytes, 1, 2)); - assertArrayEquals(new byte[] {0, 1,2}, bytes); - } - - @Test - void testReadFullyAtLength() throws IOException { - byte[] bytes = new byte[3]; - assertEquals(3, IOUtils.readFully(new ByteArrayInputStream(new byte[] {1, 2, 3}), bytes, 0, 3)); - assertArrayEquals(new byte[] {1,2, 3}, bytes); - } - - - @Test - void testReadFullyChannel() throws IOException { - ByteBuffer bytes = ByteBuffer.allocate(2); - assertEquals(2, IOUtils.readFully(new SimpleByteChannel(new byte[]{1, 2, 3}), bytes)); - assertArrayEquals(new byte[] {1,2}, bytes.array()); - assertEquals(2, bytes.position()); - } - - @Test - void testReadFullyChannelEOF() throws IOException { - ByteBuffer bytes = ByteBuffer.allocate(2); - assertEquals(-1, IOUtils.readFully(new EOFByteChannel(false), bytes)); - assertArrayEquals(new byte[] {0,0}, bytes.array()); - assertEquals(0, bytes.position()); - } - - @Test - void testReadFullyChannelEOFException() { - ByteBuffer bytes = ByteBuffer.allocate(2); - assertThrows(IOException.class, - () -> IOUtils.readFully(new EOFByteChannel(true), bytes)); - } - - @Test - void testReadFullyChannelSimple() throws IOException { - ByteBuffer bytes = ByteBuffer.allocate(2); - assertEquals(2, IOUtils.readFully(new SimpleByteChannel(new byte[] {1, 2, 3}), bytes)); - assertArrayEquals(new byte[] {1,2}, bytes.array()); - assertEquals(2, bytes.position()); - } - - @Test - public void testChecksum() { - assertEquals(0L, IOUtils.calculateChecksum(new byte[0])); - assertEquals(3057449933L, IOUtils.calculateChecksum(new byte[] { 1, 2, 3, 4})); - } - - @Test - public void testChecksumStream() throws IOException { - assertEquals(0L, IOUtils.calculateChecksum(new NullInputStream(0))); - assertEquals(0L, IOUtils.calculateChecksum(new NullInputStream(1))); - assertEquals(3057449933L, IOUtils.calculateChecksum(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4}))); - assertThrows(EOFException.class, - () -> IOUtils.calculateChecksum(new NullInputStream(1, true))); - } - - /** - * This returns 0 for the first call to skip and then reads - * as requested. This tests that the fallback to read() works. - */ - private static class WonkyInputStream extends InputStream { - int skipCalled; - int readCalled; - - @Override - public int read() { - readCalled++; - return 0; - } - - @Override - public int read(byte[] arr, int offset, int len) { - readCalled++; - return len; - } - - @Override - public long skip(long len) { - skipCalled++; - if (skipCalled == 1) { - return 0; - } else if (skipCalled > 100) { - return len; - } else { - return 100; - } - } - - @Override - public int available() { - return 100000; - } - } - - private static class EOFByteChannel implements ReadableByteChannel { - private final boolean throwException; - - public EOFByteChannel(boolean throwException) { - this.throwException = throwException; - } - - @Override - public int read(ByteBuffer dst) throws IOException { - if (throwException) { - throw new IOException("EOF"); - } - - return -1; - } - - @Override - public boolean isOpen() { - return false; - } - - @Override - public void close() throws IOException { - - } - } - - private static class SimpleByteChannel extends InputStream implements ReadableByteChannel { - private final byte[] bytes; - - public SimpleByteChannel(byte[] bytes) { - this.bytes = bytes; - } - - @Override - public int read() throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public int read(ByteBuffer dst) throws IOException { - int toRead = Math.min(bytes.length, dst.capacity()); - dst.put(bytes, 0, toRead); - return toRead; - } - - @Override - public boolean isOpen() { - return false; - } - } - - public class NullInputStream extends InputStream { - private final int bytes; - private final boolean exception; - - private int position; - - public NullInputStream(int bytes) { - this(bytes, false); - } - - public NullInputStream(int bytes, boolean exception) { - this.bytes = bytes; - this.exception = exception; - } - - @Override - public int read() throws IOException { - if (position >= bytes) { - return handleReturn(); - } - - position++; - return 0; - } - - private int handleReturn() throws EOFException { - if (exception) { - throw new EOFException(); - } else { - return -1; - } - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - int toRead = Math.min(b.length, len); - if (toRead > (bytes - position)) { - return handleReturn(); - } - toRead = Math.min(toRead, (bytes - position)); - - position += toRead; - return toRead; - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestIntList.java b/src/testcases/org/apache/poi/util/TestIntList.java deleted file mode 100644 index 3483933ce4..0000000000 --- a/src/testcases/org/apache/poi/util/TestIntList.java +++ /dev/null @@ -1,515 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; - -/** - * Class to test IntList - * - * @author Marc Johnson - */ -final class TestIntList { - @Test - void testConstructors() { - IntList list = new IntList(); - - assertTrue(list.isEmpty()); - list.add(0); - list.add(1); - IntList list2 = new IntList(list); - - assertEquals(list, list2); - IntList list3 = new IntList(2); - - assertTrue(list3.isEmpty()); - } - - @Test - void testAdd() { - IntList list = new IntList(); - int[] testArray = - { - 0, 1, 2, 3, 5 - }; - - for (int element : testArray) { - list.add(element); - } - for (int j = 0; j < testArray.length; j++) { - assertEquals(testArray[j], list.get(j)); - } - assertEquals(testArray.length, list.size()); - - // add at the beginning - list.add(0, -1); - assertEquals(-1, list.get(0)); - assertEquals(testArray.length + 1, list.size()); - for (int j = 0; j < testArray.length; j++) { - assertEquals(testArray[j], list.get(j + 1)); - } - - // add in the middle - list.add(5, 4); - assertEquals(4, list.get(5)); - assertEquals(testArray.length + 2, list.size()); - for (int j = 0; j < list.size(); j++) { - assertEquals(j - 1, list.get(j)); - } - - // add at the end - list.add(list.size(), 6); - assertEquals(testArray.length + 3, list.size()); - for (int j = 0; j < list.size(); j++) { - assertEquals(j - 1, list.get(j)); - } - - // add past end - IntList list2 = list; - assertThrows(IndexOutOfBoundsException.class, () -> list2.add(list2.size() + 1, 8)); - - // test growth - list = new IntList(0); - for (int j = 0; j < 1000; j++) { - list.add(j); - } - assertEquals(1000, list.size()); - for (int j = 0; j < 1000; j++) { - assertEquals(j, list.get(j)); - } - list = new IntList(0); - for (int j = 0; j < 1000; j++) { - list.add(0, j); - } - assertEquals(1000, list.size()); - for (int j = 0; j < 1000; j++) { - assertEquals(j, list.get(999 - j)); - } - } - - @Test - void testAddAll() { - IntList list = new IntList(); - - for (int j = 0; j < 5; j++) { - list.add(j); - } - IntList list2 = new IntList(0); - - list2.addAll(list); - list2.addAll(list); - assertEquals(2 * list.size(), list2.size()); - for (int j = 0; j < 5; j++) { - assertEquals(list2.get(j), j); - assertEquals(list2.get(j + list.size()), j); - } - IntList empty = new IntList(); - int limit = list.size(); - - for (int j = 0; j < limit; j++) { - assertTrue(list.addAll(j, empty)); - assertEquals(limit, list.size()); - } - - assertThrows(IndexOutOfBoundsException.class, () -> list.addAll(limit + 1, empty)); - - // try add at beginning - empty.addAll(0, list); - assertEquals(empty, list); - - // try in the middle - empty.addAll(1, list); - assertEquals(2 * list.size(), empty.size()); - assertEquals(list.get(0), empty.get(0)); - assertEquals(list.get(0), empty.get(1)); - assertEquals(list.get(1), empty.get(2)); - assertEquals(list.get(1), empty.get(6)); - assertEquals(list.get(2), empty.get(3)); - assertEquals(list.get(2), empty.get(7)); - assertEquals(list.get(3), empty.get(4)); - assertEquals(list.get(3), empty.get(8)); - assertEquals(list.get(4), empty.get(5)); - assertEquals(list.get(4), empty.get(9)); - - // try at the end - empty.addAll(empty.size(), list); - assertEquals(3 * list.size(), empty.size()); - assertEquals(list.get(0), empty.get(0)); - assertEquals(list.get(0), empty.get(1)); - assertEquals(list.get(0), empty.get(10)); - assertEquals(list.get(1), empty.get(2)); - assertEquals(list.get(1), empty.get(6)); - assertEquals(list.get(1), empty.get(11)); - assertEquals(list.get(2), empty.get(3)); - assertEquals(list.get(2), empty.get(7)); - assertEquals(list.get(2), empty.get(12)); - assertEquals(list.get(3), empty.get(4)); - assertEquals(list.get(3), empty.get(8)); - assertEquals(list.get(3), empty.get(13)); - assertEquals(list.get(4), empty.get(5)); - assertEquals(list.get(4), empty.get(9)); - assertEquals(list.get(4), empty.get(14)); - } - - @Test - void testAddAllGrow() { - IntList list = new IntList(0); - IntList addList = new IntList(0); - addList.add(1); - addList.add(2); - - assertTrue(list.addAll(0, addList)); - } - - @Test - void testClear() { - IntList list = new IntList(); - - for (int j = 0; j < 500; j++) { - list.add(j); - } - assertEquals(500, list.size()); - list.clear(); - assertEquals(0, list.size()); - for (int j = 0; j < 500; j++) { - list.add(j + 1); - } - assertEquals(500, list.size()); - for (int j = 0; j < 500; j++) { - assertEquals(j + 1, list.get(j)); - } - } - - @Test - void testContains() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j += 2) { - list.add(j); - } - for (int j = 0; j < 1000; j++) { - if (j % 2 == 0) { - assertTrue(list.contains(j)); - } else { - assertFalse(list.contains(j)); - } - } - } - - @Test - void testContainsAll() { - IntList list = new IntList(); - - assertTrue(list.containsAll(list)); - for (int j = 0; j < 10; j++) { - list.add(j); - } - IntList list2 = new IntList(list); - - assertTrue(list2.containsAll(list)); - assertTrue(list.containsAll(list2)); - list2.add(10); - assertTrue(list2.containsAll(list)); - assertFalse(list.containsAll(list2)); - list.add(11); - assertFalse(list2.containsAll(list)); - assertFalse(list.containsAll(list2)); - } - - @Test - void testEquals() { - IntList list = new IntList(); - - assertEquals(list, list); - //noinspection ObjectEqualsNull - assertNotEquals(null, list); - IntList list2 = new IntList(200); - - assertEquals(list, list2); - assertEquals(list2, list); - assertEquals(list.hashCode(), list2.hashCode()); - list.add(0); - list.add(1); - list2.add(1); - list2.add(0); - assertNotEquals(list, list2); - list2.removeValue(1); - list2.add(1); - assertEquals(list, list2); - assertEquals(list2, list); - assertEquals(list.hashCode(), list2.hashCode()); - list2.add(2); - assertNotEquals(list, list2); - assertNotEquals(list2, list); - } - - @Test - void testGet() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - for (int j = 0; j < 1000; j++) { - assertEquals(j, list.get(j)); - } - - assertThrows(IndexOutOfBoundsException.class, () -> list.get(1000)); - } - - @Test - void testIndexOf() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j / 2); - } - for (int j = 0; j < 1000; j++) { - if (j < 500) { - assertEquals(j * 2, list.indexOf(j)); - } else { - assertEquals(-1, list.indexOf(j)); - } - } - } - - @Test - void testIsEmpty() { - IntList list1 = new IntList(); - IntList list2 = new IntList(1000); - IntList list3 = new IntList(list1); - - assertTrue(list1.isEmpty()); - assertTrue(list2.isEmpty()); - assertTrue(list3.isEmpty()); - list1.add(1); - list2.add(2); - list3 = new IntList(list2); - assertFalse(list1.isEmpty()); - assertFalse(list2.isEmpty()); - assertFalse(list3.isEmpty()); - list1.clear(); - list2.remove(0); - list3.removeValue(2); - assertTrue(list1.isEmpty()); - assertTrue(list2.isEmpty()); - assertTrue(list3.isEmpty()); - } - - @Test - void testLastIndexOf() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j / 2); - } - for (int j = 0; j < 1000; j++) { - if (j < 500) { - assertEquals(1 + j * 2, list.lastIndexOf(j)); - } else { - assertEquals(-1, list.indexOf(j)); - } - } - } - - @Test - void testRemove() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - for (int j = 0; j < 1000; j++) { - assertEquals(j, list.remove(0)); - assertEquals(999 - j, list.size()); - } - for (int j = 0; j < 1000; j++) { - list.add(j); - } - for (int j = 0; j < 1000; j++) { - assertEquals(999 - j, list.remove(999 - j)); - assertEquals(999 - j, list.size()); - } - - assertThrows(IndexOutOfBoundsException.class, () -> list.remove(0)); - } - - @Test - void testRemoveValue() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j / 2); - } - for (int j = 0; j < 1000; j++) { - if (j < 500) { - assertTrue(list.removeValue(j)); - assertTrue(list.removeValue(j)); - } - assertFalse(list.removeValue(j)); - } - } - - @Test - void testRemoveAll() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - IntList listCopy = new IntList(list); - IntList listOdd = new IntList(); - IntList listEven = new IntList(); - - for (int j = 0; j < 1000; j++) { - if (j % 2 == 0) { - listEven.add(j); - } else { - listOdd.add(j); - } - } - - assertTrue(list.removeAll(listEven)); - assertEquals(list, listOdd); - - assertTrue(list.removeAll(listOdd)); - assertTrue(list.isEmpty()); - - assertTrue(listCopy.removeAll(listOdd)); - assertEquals(listCopy, listEven); - - assertTrue(listCopy.removeAll(listEven)); - assertTrue(listCopy.isEmpty()); - - assertFalse(list.removeAll(listEven)); - assertFalse(list.removeAll(listOdd)); - assertFalse(listCopy.removeAll(listEven)); - assertFalse(listCopy.removeAll(listEven)); - } - - @Test - void testRetainAll() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - IntList listCopy = new IntList(list); - IntList listOdd = new IntList(); - IntList listEven = new IntList(); - - for (int j = 0; j < 1000; j++) { - if (j % 2 == 0) { - listEven.add(j); - } else { - listOdd.add(j); - } - } - assertTrue(list.retainAll(listOdd)); - assertEquals(list, listOdd); - - assertTrue(list.retainAll(listEven)); - assertTrue(list.isEmpty()); - - assertTrue(listCopy.retainAll(listEven)); - assertEquals(listCopy, listEven); - - assertTrue(listCopy.retainAll(listOdd)); - assertTrue(listCopy.isEmpty()); - - assertFalse(list.retainAll(listOdd)); - assertFalse(list.retainAll(listEven)); - assertFalse(listCopy.retainAll(listEven)); - assertFalse(listCopy.retainAll(listOdd)); - } - - @Test - void testSet() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - for (int j = 0; j < 1000; j++) { - list.set(j, j + 1); - assertEquals(j + 1, list.get(j)); - } - assertThrows(IndexOutOfBoundsException.class, () -> list.set(1000, 1001)); - } - - @Test - void testSize() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - assertEquals(j, list.size()); - list.add(j); - assertEquals(j + 1, list.size()); - } - for (int j = 0; j < 1000; j++) { - assertEquals(1000 - j, list.size()); - list.removeValue(j); - assertEquals(999 - j, list.size()); - } - } - - @Test - void testToArray() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - int[] a1 = list.toArray(); - - assertEquals(a1.length, list.size()); - for (int j = 0; j < 1000; j++) { - assertEquals(a1[j], list.get(j)); - } - int[] a2 = new int[list.size()]; - int[] a3 = list.toArray(a2); - - assertSame(a2, a3); - for (int j = 0; j < 1000; j++) { - assertEquals(a2[j], list.get(j)); - } - int[] aShort = new int[list.size() - 1]; - int[] aLong = new int[list.size() + 1]; - int[] a4 = list.toArray(aShort); - int[] a5 = list.toArray(aLong); - - assertNotSame(a4, aShort); - assertNotSame(a5, aLong); - assertEquals(a4.length, list.size()); - for (int j = 0; j < 1000; j++) { - assertEquals(a3[j], list.get(j)); - } - assertEquals(a5.length, list.size()); - for (int j = 0; j < 1000; j++) { - assertEquals(a5[j], list.get(j)); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestIntegerField.java b/src/testcases/org/apache/poi/util/TestIntegerField.java deleted file mode 100644 index d8e2f1b66f..0000000000 --- a/src/testcases/org/apache/poi/util/TestIntegerField.java +++ /dev/null @@ -1,135 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Test IntegerField code - */ -final class TestIntegerField { - - private static final int[] _test_array = {Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE}; - - @Test - void testConstructors() { - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new IntegerField(-1)); - IntegerField field = new IntegerField(2); - - assertEquals(0, field.get()); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new IntegerField(-1, 1)); - field = new IntegerField(2, 0x12345678); - assertEquals(0x12345678, field.get()); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new IntegerField(-1, 1, new byte[ 6 ])); - - byte[] array = new byte[ 6 ]; - field = new IntegerField(2, 0x12345678, array); - assertEquals(0x12345678, field.get()); - assertEquals(( byte ) 0x78, array[ 2 ]); - assertEquals(( byte ) 0x56, array[ 3 ]); - assertEquals(( byte ) 0x34, array[ 4 ]); - assertEquals(( byte ) 0x12, array[ 5 ]); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new IntegerField(2, 5, new byte[ 5 ])); - - for (int element : _test_array) { - array = new byte[ 4 ]; - new IntegerField(0, element, array); - assertEquals(element, new IntegerField(0, array).get()); - } - } - - @Test - void testSet() { - IntegerField field = new IntegerField(0); - byte[] array = new byte[ 4 ]; - - for (int j = 0; j < _test_array.length; j++) { - field.set(_test_array[ j ]); - assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); - field = new IntegerField(0); - field.set(_test_array[ j ], array); - assertEquals(_test_array[ j ], field.get(), "testing _2 "); - assertEquals(( byte ) (_test_array[ j ] % 256), array[ 0 ], "testing _3.0 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 8) % 256), array[ 1 ], "testing _3.1 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 16) % 256), array[ 2 ], "testing _3.2 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 24) % 256), array[ 3 ], "testing _3.3 " + _test_array[ j ]); - } - } - - @Test - void testReadFromBytes() { - IntegerField field1 = new IntegerField(1); - byte[] array = new byte[ 4 ]; - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> field1.readFromBytes(array)); - IntegerField field2 = new IntegerField(0); - for (int j = 0; j < _test_array.length; j++) { - array[ 0 ] = ( byte ) (_test_array[ j ] % 256); - array[ 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - array[ 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - array[ 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - field2.readFromBytes(array); - assertEquals(_test_array[ j ], field2.get(), "testing " + j); - } - } - - @Test - void testReadFromStream() throws IOException { - IntegerField field = new IntegerField(0); - byte[] buffer = new byte[ _test_array.length * 4 ]; - - for (int j = 0; j < _test_array.length; j++) { - buffer[ (j * 4) + 0 ] = ( byte ) (_test_array[ j ] % 256); - buffer[ (j * 4) + 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - buffer[ (j * 4) + 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - buffer[ (j * 4) + 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - } - ByteArrayInputStream stream = new ByteArrayInputStream(buffer); - - for (int j = 0; j < buffer.length / 4; j++) { - field.readFromStream(stream); - assertEquals(_test_array[ j ], field.get(), "Testing " + j); - } - } - - @Test - void testWriteToBytes() { - IntegerField field = new IntegerField(0); - byte[] array = new byte[ 4 ]; - - for (int b : _test_array) { - field.set(b); - field.writeToBytes(array); - int val = array[ 3 ] << 24; - - val &= 0xFF000000; - val += (array[ 2 ] << 16) & 0x00FF0000; - val += (array[ 1 ] << 8) & 0x0000FF00; - val += (array[ 0 ] & 0x000000FF); - assertEquals(b, val, "testing "); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestLittleEndian.java b/src/testcases/org/apache/poi/util/TestLittleEndian.java deleted file mode 100644 index 27e5e3fe1a..0000000000 --- a/src/testcases/org/apache/poi/util/TestLittleEndian.java +++ /dev/null @@ -1,356 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.util.LittleEndian.BufferUnderrunException; -import org.junit.jupiter.api.Test; - -/** - * Class to test LittleEndian functionality - */ -final class TestLittleEndian { - - /** - * test the getShort() method - */ - @Test - void testGetShort() { - byte[] testdata = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - - testdata[0] = 0x01; - testdata[1] = (byte) 0xFF; - testdata[2] = 0x02; - short[] expected = new short[2]; - - expected[0] = ( short ) 0xFF01; - expected[1] = 0x02FF; - assertEquals(expected[0], LittleEndian.getShort(testdata)); - assertEquals(expected[1], LittleEndian.getShort(testdata, 1)); - } - - @Test - void testGetUShort() { - byte[] testdata = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0x02, - }; - byte[] testdata2 = { - (byte) 0x0D, - (byte) 0x93, - (byte) 0xFF, - }; - - int expected0 = 0xFF01; - int expected1 = 0x02FF; - int expected2 = 0x930D; - int expected3 = 0xFF93; - assertEquals(expected0, LittleEndian.getUShort(testdata)); - assertEquals(expected1, LittleEndian.getUShort(testdata, 1)); - assertEquals(expected2, LittleEndian.getUShort(testdata2)); - assertEquals(expected3, LittleEndian.getUShort(testdata2, 1)); - - byte[] testdata3 = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - LittleEndian.putUShort(testdata3, 0, expected2); - LittleEndian.putUShort(testdata3, 1, expected3); - assertEquals(testdata3[0], 0x0D); - assertEquals(testdata3[1], (byte)0x93); - assertEquals(testdata3[2], (byte)0xFF); - assertEquals(expected2, LittleEndian.getUShort(testdata3)); - assertEquals(expected3, LittleEndian.getUShort(testdata3, 1)); - - } - - private static final byte[] _double_array = - { - 56, 50, -113, -4, -63, -64, -13, 63, 76, -32, -42, -35, 60, -43, 3, 64 - }; - /** 0x7ff8000000000000 encoded in little endian order */ - private static final byte[] _nan_double_array = HexRead.readFromString("00 00 00 00 00 00 F8 7F"); - private static final double[] _doubles = - { - 1.23456, 2.47912, Double.NaN - }; - - /** - * test the getDouble() method - */ - @Test - void testGetDouble() { - assertEquals(_doubles[0], LittleEndian.getDouble(_double_array, 0), 0.000001 ); - assertEquals(_doubles[1], LittleEndian.getDouble( _double_array, LittleEndianConsts.DOUBLE_SIZE), 0.000001); - assertTrue(Double.isNaN(LittleEndian.getDouble(_nan_double_array, 0))); - - double nan = LittleEndian.getDouble(_nan_double_array, 0); - byte[] data = new byte[8]; - LittleEndian.putDouble(data, 0, nan); - for ( int i = 0; i < data.length; i++ ) { - assertEquals(data[i], _nan_double_array[i]); - } - } - - /** - * test the getInt() method - */ - @Test - void testGetInt() { - // reading 4 byte data from a 5 byte buffer - byte[] testdata = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - - assertEquals(0xFFFFFF01, LittleEndian.getInt(testdata)); - assertEquals(0x02FFFFFF, LittleEndian.getInt(testdata, 1)); - } - - /** - * test the getLong method - */ - @Test - void testGetLong() { - - // reading 8 byte values from a 9 byte buffer - byte[] testdata = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - - assertEquals(0xFFFFFFFFFFFFFF01L, LittleEndian.getLong(testdata, 0)); - assertEquals(0x02FFFFFFFFFFFFFFL, LittleEndian.getLong(testdata, 1)); - } - - /** - * test the PutShort method - */ - @Test - void testPutShort() { - byte[] expected = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - - expected[0] = 0x01; - expected[1] = (byte) 0xFF; - expected[2] = 0x02; - byte[] received = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - short[] testdata = new short[2]; - - testdata[0] = ( short ) 0xFF01; - testdata[1] = 0x02FF; - LittleEndian.putShort(received, 0, testdata[0]); - assertTrue(compareByteArrays(received, expected, 0, LittleEndianConsts.SHORT_SIZE)); - LittleEndian.putShort(received, 1, testdata[1]); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.SHORT_SIZE)); - } - - /** - * test the putInt method - */ - @Test - void testPutInt() { - // writing 4 byte data to a 5 byte buffer - byte[] expected = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - byte[] received = new byte[ LittleEndianConsts.INT_SIZE + 1 ]; - - LittleEndian.putInt(received, 0, 0xFFFFFF01); - assertTrue(compareByteArrays(received, expected, 0, LittleEndianConsts.INT_SIZE)); - LittleEndian.putInt(received, 1, 0x02FFFFFF); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.INT_SIZE)); - } - - /** - * test the putDouble methods - */ - @Test - void testPutDouble() { - byte[] received = new byte[ LittleEndianConsts.DOUBLE_SIZE + 1 ]; - - LittleEndian.putDouble(received, 0, _doubles[0]); - assertTrue(compareByteArrays(received, _double_array, 0, LittleEndianConsts.DOUBLE_SIZE)); - LittleEndian.putDouble(received, 1, _doubles[1]); - byte[] expected = new byte[ LittleEndianConsts.DOUBLE_SIZE + 1 ]; - - System.arraycopy(_double_array, LittleEndianConsts.DOUBLE_SIZE, expected, - 1, LittleEndianConsts.DOUBLE_SIZE); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.DOUBLE_SIZE)); - } - - /** - * test the putLong method - */ - @Test - void testPutLong() { - // writing 8 byte values to a 9 byte buffer - byte[] expected = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - byte[] received = new byte[ LittleEndianConsts.LONG_SIZE + 1 ]; - - long testdata0 = 0xFFFFFFFFFFFFFF01L; - long testdata1 = 0x02FFFFFFFFFFFFFFL; - LittleEndian.putLong(received, 0, testdata0); - assertTrue(compareByteArrays(received, expected, 0, LittleEndianConsts.LONG_SIZE)); - LittleEndian.putLong(received, 1, testdata1); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.LONG_SIZE)); - } - - private static final byte[] _good_array = { - 0x01, 0x02, 0x01, 0x02, - 0x01, 0x02, 0x01, 0x02, - 0x01, 0x02, 0x01, 0x02, - 0x01, 0x02, 0x01, 0x02, - }; - private static final byte[] _bad_array = { - 0x01 - }; - - /** - * test the readShort method - */ - @Test - void testReadShort() throws IOException { - short expected_value = 0x0201; - InputStream stream = new ByteArrayInputStream(_good_array); - int count = 0; - - while (true) { - try { - short value = LittleEndian.readShort(stream); - assertEquals(value, expected_value); - count++; - } catch (BufferUnderrunException e) { - break; - } - } - assertEquals(count, - _good_array.length / LittleEndianConsts.SHORT_SIZE); - ByteArrayInputStream stream2 = new ByteArrayInputStream(_bad_array); - assertThrows(BufferUnderrunException.class, () -> LittleEndian.readShort(stream2)); - } - - /** - * test the readInt method - */ - @Test - void testReadInt() throws IOException { - int expected_value = 0x02010201; - InputStream stream = new ByteArrayInputStream(_good_array); - int count = 0; - - while (true) { - try { - int value = LittleEndian.readInt(stream); - assertEquals(value, expected_value); - count++; - } catch (BufferUnderrunException e) { - break; - } - } - assertEquals(count, _good_array.length / LittleEndianConsts.INT_SIZE); - ByteArrayInputStream stream2 = new ByteArrayInputStream(_bad_array); - assertThrows(BufferUnderrunException.class, () -> LittleEndian.readInt(stream2)); - } - - /** - * test the readLong method - */ - @Test - void testReadLong() throws IOException { - long expected_value = 0x0201020102010201L; - InputStream stream = new ByteArrayInputStream(_good_array); - int count = 0; - - while (true) { - try { - long value = LittleEndian.readLong(stream); - assertEquals(value, expected_value); - count++; - } catch (BufferUnderrunException e) { - break; - } - } - assertEquals(count, _good_array.length / LittleEndianConsts.LONG_SIZE); - ByteArrayInputStream stream2 = new ByteArrayInputStream(_bad_array); - assertThrows(BufferUnderrunException.class, () -> LittleEndian.readLong(stream2)); - } - - @Test - void testReadFromStream() throws IOException { - int actual; - actual = LittleEndian.readUShort(new ByteArrayInputStream(new byte[] { 5, -128, })); - assertEquals(32773, actual); - - actual = LittleEndian.readUShort(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, })); - assertEquals(513, actual); - - assertThrows(BufferUnderrunException.class, () -> - LittleEndian.readInt(new ByteArrayInputStream(new byte[] { 1, 2, 3, }))); - } - - @Test - void testUnsignedByteToInt() { - assertEquals(255, LittleEndian.ubyteToInt((byte)255)); - } - - private static boolean compareByteArrays(byte [] received, byte [] expected, - int offset, int size) { - - for (int j = offset; j < offset + size; j++) { - if (received[j] != expected[j]) { - System.out.println("difference at index " + j); - return false; - } - } - return true; - } - - @Test - void testUnsignedShort() { - assertEquals(0xffff, LittleEndian.getUShort(new byte[] { (byte)0xff, (byte)0xff }, 0)); - } -} diff --git a/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java b/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java deleted file mode 100644 index 54ebefa5b5..0000000000 --- a/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Class to test {@link LittleEndianInputStream} and {@link LittleEndianOutputStream} - */ -final class TestLittleEndianStreams { - - @Test - void testRead() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try (LittleEndianOutputStream leo = new LittleEndianOutputStream(baos)) { - leo.writeInt(12345678); - leo.writeShort(12345); - leo.writeByte(123); - leo.writeShort(40000); - leo.writeByte(200); - leo.writeLong(1234567890123456789L); - leo.writeDouble(123.456); - } - - try (LittleEndianInputStream lei = new LittleEndianInputStream(new ByteArrayInputStream(baos.toByteArray()))) { - assertEquals(12345678, lei.readInt()); - assertEquals(12345, lei.readShort()); - assertEquals(123, lei.readByte()); - assertEquals(40000, lei.readUShort()); - assertEquals(200, lei.readUByte()); - assertEquals(1234567890123456789L, lei.readLong()); - assertEquals(123.456, lei.readDouble(), 0.0); - } - } - - /** - * Up until svn r836101 {@link LittleEndianByteArrayInputStream#readFully(byte[], int, int)} - * had an error which resulted in the data being read and written back to the source byte - * array. - */ - @Test - void testReadFully() { - byte[] srcBuf = HexRead.readFromString("99 88 77 66 55 44 33"); - LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf); - - // do initial read to increment the read index beyond zero - assertEquals(0x8899, lei.readUShort()); - - byte[] actBuf = new byte[4]; - lei.readFully(actBuf); - - assertFalse(actBuf[0] == 0x00 && srcBuf[0] == 0x77 && srcBuf[3] == 0x44, - "Identified bug in readFully() - source buffer was modified"); - - byte[] expBuf = HexRead.readFromString("77 66 55 44"); - assertArrayEquals(actBuf, expBuf); - assertEquals(0x33, lei.readUByte()); - assertEquals(0, lei.available()); - } - - @Test - void testBufferOverrun() { - byte[] srcBuf = HexRead.readFromString("99 88 77"); - LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf); - - // do initial read to increment the read index beyond zero - assertEquals(0x8899, lei.readUShort()); - - // only one byte left, so this should fail - RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4])); - assertTrue(ex.getMessage().contains("Buffer overrun")); - } - - @Test - void testBufferOverrunStartOffset() { - byte[] srcBuf = HexRead.readFromString("99 88 77 88 99"); - LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf, 2); - - // only one byte left, so this should fail - RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4])); - assertTrue(ex.getMessage().contains("Buffer overrun")); - } - - @Test - void testBufferOverrunStartOffset2() { - byte[] srcBuf = HexRead.readFromString("99 88 77 88 99"); - LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf, 2, 2); - - // only one byte left, so this should fail - RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4])); - assertTrue(ex.getMessage().contains("Buffer overrun")); - } -} diff --git a/src/testcases/org/apache/poi/util/TestLocaleUtil.java b/src/testcases/org/apache/poi/util/TestLocaleUtil.java deleted file mode 100644 index 3335b85368..0000000000 --- a/src/testcases/org/apache/poi/util/TestLocaleUtil.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.util.Calendar; -import java.util.Locale; -import java.util.TimeZone; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - - -class TestLocaleUtil { - // This unit test assumes that the user's locale isn't ja-JP and timezone isn't Asia/Tokyo - // If this is the case, change the values to something else - private static final Locale ja_JP = Locale.JAPAN; - private static final TimeZone TOKYO = TimeZone.getTimeZone("Asia/Tokyo"); - private static final Calendar JAPAN_CALENDAR = Calendar.getInstance(TOKYO, ja_JP); - - /** - * Reset the Locale to the user default before the test so that it isn't influenced - * by the LocaleUtil's state being changed by previous tests. - */ - @BeforeEach - @SuppressForbidden("implementation around default locales in POI") - void setUp() { - // reset the user locale and time zone so that tests do not interfere with each other - // the other and better way would be to run each test in its own thread since - // LocaleUtil uses per-thread settings. - // Helpful, but not ASL 2.0 licensed: - // http://www.codeaffine.com/2014/07/21/a-junit-rule-to-run-a-test-in-its-own-thread/ - LocaleUtil.setUserLocale(Locale.getDefault()); - LocaleUtil.setUserTimeZone(TimeZone.getDefault()); - - assumeFalse(ja_JP.equals(LocaleUtil.getUserLocale())); - assumeFalse(TOKYO.equals(LocaleUtil.getUserTimeZone())); - } - - /** - * Reset the Locale to the user default after the test so that it doesn't influence - * other tests. - */ - @AfterEach - void tearDown() { - LocaleUtil.resetUserLocale(); - LocaleUtil.resetUserTimeZone(); - } - - @Test - @SuppressForbidden("implementation around default locales in POI") - void userLocale() { - Locale DEFAULT_LOCALE = LocaleUtil.getUserLocale(); - - assertEquals(DEFAULT_LOCALE, LocaleUtil.getUserLocale()); - assertNotEquals(ja_JP, LocaleUtil.getUserLocale()); - - LocaleUtil.setUserLocale(ja_JP); - assertEquals(ja_JP, LocaleUtil.getUserLocale()); - - LocaleUtil.resetUserLocale(); - assertEquals(DEFAULT_LOCALE, LocaleUtil.getUserLocale()); - } - - @Test - @SuppressForbidden("implementation around default locales in POI") - void userTimeZone() { - TimeZone DEFAULT_TIME_ZONE = LocaleUtil.getUserTimeZone(); - - assertEquals(DEFAULT_TIME_ZONE, LocaleUtil.getUserTimeZone()); - assertNotEquals(TOKYO, LocaleUtil.getUserTimeZone()); - - LocaleUtil.setUserTimeZone(TOKYO); - assertEquals(TOKYO, LocaleUtil.getUserTimeZone()); - } - - @Test - @SuppressForbidden("implementation around default locales in POI") - void localeCalendar() { - Locale DEFAULT_LOCALE = LocaleUtil.getUserLocale(); - TimeZone DEFAULT_TIME_ZONE = LocaleUtil.getUserTimeZone(); - Calendar DEFAULT_CALENDAR = LocaleUtil.getLocaleCalendar(); - - assertEquals(DEFAULT_LOCALE, LocaleUtil.getUserLocale()); - assertEquals(DEFAULT_TIME_ZONE, LocaleUtil.getUserTimeZone()); - assertCalendarEquals(DEFAULT_CALENDAR, LocaleUtil.getLocaleCalendar()); - assertNotEquals(ja_JP, LocaleUtil.getUserLocale()); - assertNotEquals(TOKYO, LocaleUtil.getUserTimeZone()); - assertCalendarNotEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar()); - - LocaleUtil.setUserLocale(ja_JP); - LocaleUtil.setUserTimeZone(TOKYO); - assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar()); - assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar(TOKYO)); - // FIXME: These might affect the time zone due to daylight savings: - //assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar(2016, 00, 01)); - //assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar(2016, 00, 01, 00, 00, 00)); - } - - private static void assertCalendarNotEquals(Calendar expected, Calendar actual) { - // FIXME: add more tests to compare calendars, ignoring whether the dates are equal - assertNotEquals(expected.getTimeZone(), actual.getTimeZone(), "time zone"); - } - private static void assertCalendarEquals(Calendar expected, Calendar actual) { - // FIXME: add more tests to compare calendars, ignoring whether the set dates are equal - assertEquals(expected.getTimeZone(), actual.getTimeZone(), "time zone"); - } -} diff --git a/src/testcases/org/apache/poi/util/TestLongField.java b/src/testcases/org/apache/poi/util/TestLongField.java deleted file mode 100644 index 8cd39aba92..0000000000 --- a/src/testcases/org/apache/poi/util/TestLongField.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Test LongField code - */ -final class TestLongField { - - static private final long[] _test_array = - { - Long.MIN_VALUE, -1L, 0L, 1L, Long.MAX_VALUE - }; - - @Test - void testConstructors() { - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new LongField(-1)); - - LongField field1 = new LongField(2); - assertEquals(0L, field1.get()); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new LongField(-1, 1L)); - - LongField field2 = new LongField(2, 0x123456789ABCDEF0L); - assertEquals(0x123456789ABCDEF0L, field2.get()); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new LongField(-1, 1L, new byte[ 10 ])); - - - byte[] array = new byte[ 10 ]; - LongField field = new LongField(2, 0x123456789ABCDEF0L, array); - assertEquals(0x123456789ABCDEF0L, field.get()); - assertEquals(( byte ) 0xF0, array[ 2 ]); - assertEquals(( byte ) 0xDE, array[ 3 ]); - assertEquals(( byte ) 0xBC, array[ 4 ]); - assertEquals(( byte ) 0x9A, array[ 5 ]); - assertEquals(( byte ) 0x78, array[ 6 ]); - assertEquals(( byte ) 0x56, array[ 7 ]); - assertEquals(( byte ) 0x34, array[ 8 ]); - assertEquals(( byte ) 0x12, array[ 9 ]); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new LongField(2, 5L, new byte[ 9 ])); - - for (long element : _test_array) { - array = new byte[ 8 ]; - new LongField(0, element, array); - assertEquals(element, new LongField(0, array).get()); - } - } - - @Test - void testSet() { - LongField field = new LongField(0); - byte[] array = new byte[ 8 ]; - - for (int j = 0; j < _test_array.length; j++) { - field.set(_test_array[ j ]); - assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); - field = new LongField(0); - field.set(_test_array[ j ], array); - assertEquals(_test_array[ j ], field.get(), "testing _2 "); - assertEquals(( byte ) (_test_array[ j ] % 256), array[ 0 ], "testing _3.0 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 8) % 256), array[ 1 ], "testing _3.1 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 16) % 256), array[ 2 ], "testing _3.2 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 24) % 256), array[ 3 ], "testing _3.3 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 32) % 256), array[ 4 ], "testing _3.4 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 40) % 256), array[ 5 ], "testing _3.5 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 48) % 256), array[ 6 ], "testing _3.6 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 56) % 256), array[ 7 ], "testing _3.7 " + _test_array[ j ]); - } - } - - @Test - void testReadFromBytes() { - LongField field = new LongField(1); - byte[] array = new byte[ 8 ]; - - try { - field.readFromBytes(array); - fail("should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new LongField(0); - for (int j = 0; j < _test_array.length; j++) { - array[ 0 ] = ( byte ) (_test_array[ j ] % 256); - array[ 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - array[ 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - array[ 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - array[ 4 ] = ( byte ) ((_test_array[ j ] >> 32) % 256); - array[ 5 ] = ( byte ) ((_test_array[ j ] >> 40) % 256); - array[ 6 ] = ( byte ) ((_test_array[ j ] >> 48) % 256); - array[ 7 ] = ( byte ) ((_test_array[ j ] >> 56) % 256); - field.readFromBytes(array); - assertEquals(_test_array[ j ], field.get(), "testing " + j); - } - } - - @Test - void testReadFromStream() throws IOException { - LongField field = new LongField(0); - byte[] buffer = new byte[ _test_array.length * 8 ]; - - for (int j = 0; j < _test_array.length; j++) { - buffer[ (j * 8) ] = ( byte ) ((_test_array[ j ] ) % 256); - buffer[ (j * 8) + 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - buffer[ (j * 8) + 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - buffer[ (j * 8) + 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - buffer[ (j * 8) + 4 ] = ( byte ) ((_test_array[ j ] >> 32) % 256); - buffer[ (j * 8) + 5 ] = ( byte ) ((_test_array[ j ] >> 40) % 256); - buffer[ (j * 8) + 6 ] = ( byte ) ((_test_array[ j ] >> 48) % 256); - buffer[ (j * 8) + 7 ] = ( byte ) ((_test_array[ j ] >> 56) % 256); - } - ByteArrayInputStream stream = new ByteArrayInputStream(buffer); - - for (int j = 0; j < buffer.length / 8; j++) { - field.readFromStream(stream); - assertEquals(_test_array[ j ], field.get(), "Testing " + j); - } - } - - @Test - void testWriteToBytes() { - LongField field = new LongField(0); - byte[] array = new byte[ 8 ]; - - for (long element : _test_array) { - field.set(element); - field.writeToBytes(array); - long val = (( long ) array[ 7 ]) << 56; - - val &= 0xFF00000000000000L; - val += ((( long ) array[ 6 ]) << 48) & 0x00FF000000000000L; - val += ((( long ) array[ 5 ]) << 40) & 0x0000FF0000000000L; - val += ((( long ) array[ 4 ]) << 32) & 0x000000FF00000000L; - val += ((( long ) array[ 3 ]) << 24) & 0x00000000FF000000L; - val += ((( long ) array[ 2 ]) << 16) & 0x0000000000FF0000L; - val += ((( long ) array[ 1 ]) << 8) & 0x000000000000FF00L; - val += (array[ 0 ] & 0x00000000000000FFL); - assertEquals(element, val, "testing "); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java b/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java deleted file mode 100644 index 219e1460b1..0000000000 --- a/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java +++ /dev/null @@ -1,172 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; - -import org.junit.jupiter.api.Test; - -class TestRLEDecompressingInputStream { - - /** - * Section 3.2.1 No Compression Example - * - * The following string illustrates an ASCII text string with a set of characters that cannot be compressed - * by the compression algorithm specified in section 2.4.1. - * - * abcdefghijklmnopqrstuv. - * - * This example is provided to demonstrate the results of compressing and decompressing the string - * using an interoperable implementation of the algorithm specified in section 2.4.1. - * - * The following hex array represents the compressed byte array of the example string as compressed by - * the compression algorithm. - * - * 01 19 B0 00 61 62 63 64 65 66 67 68 00 69 6A 6B 6C - * 6D 6E 6F 70 00 71 72 73 74 75 76 2E - * - * The following hex array represents the decompressed byte array of the example string as - * decompressed by the decompression algorithm. - * - * 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 - * 72 73 74 75 76 2E - * - */ - @Test - void noCompressionExample() { - final byte[] compressed = { - 0x01, 0x19, (byte)0xB0, 0x00, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x00, 0x69, 0x6A, 0x6B, 0x6C, - 0x6D, 0x6E, 0x6F, 0x70, 0x00, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x2E - }; - final String expected = "abcdefghijklmnopqrstuv."; - checkRLEDecompression(expected, compressed); - } - - /** - * Section 3.2.2 Normal Compression Example - * - * The following string illustrates an ASCII text string with a typical set of characters that can be - * compressed by the compression algorithm. - * - * #aaabcdefaaaaghijaaaaaklaaamnopqaaaaaaaaaaaarstuvwxyzaaa - * - * This example is provided to demonstrate the results of compressing and decompressing the example - * string using an interoperable implementation of the algorithm specified in section 2.4.1. - * - * The following hex array represents the compressed byte array of the example string as compressed by - * the compression algorithm: - * - * 01 2F B0 00 23 61 61 61 62 63 64 65 82 66 00 70 - * 61 67 68 69 6A 01 38 08 61 6B 6C 00 30 6D 6E 6F - * 70 06 71 02 70 04 10 72 73 74 75 76 10 77 78 79 - * 7A 00 3C - * - * The following hex array represents the decompressed byte array of the example string as - * decompressed by the decompression algorithm: - * - * 23 61 61 61 62 63 64 65 66 61 61 61 61 67 68 69 - * 6a 61 61 61 61 61 6B 6C 61 61 61 6D 6E 6F 70 71 - * 61 61 61 61 61 61 61 61 61 61 61 61 72 73 74 75 - * 76 77 78 79 7A 61 61 61 - */ - @Test - void normalCompressionExample() { - final byte[] compressed = { - 0x01, 0x2F, (byte)0xB0, 0x00, 0x23, 0x61, 0x61, 0x61, 0x62, 0x63, 0x64, 0x65, (byte)0x82, 0x66, 0x00, 0x70, - 0x61, 0x67, 0x68, 0x69, 0x6A, 0x01, 0x38, 0x08, 0x61, 0x6B, 0x6C, 0x00, 0x30, 0x6D, 0x6E, 0x6F, - 0x70, 0x06, 0x71, 0x02, 0x70, 0x04, 0x10, 0x72, 0x73, 0x74, 0x75, 0x76, 0x10, 0x77, 0x78, 0x79, - 0x7A, 0x00, 0x3C - }; - final String expected = "#aaabcdefaaaaghijaaaaaklaaamnopqaaaaaaaaaaaarstuvwxyzaaa"; - checkRLEDecompression(expected, compressed); - } - - /** - * Section 3.2.3 Maximum Compression Example - * - * The following string illustrates an ASCII text string with a typical set of characters that can be - * compressed by the compression algorithm. - * - * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - * - * This example is provided to demonstrate the results of compressing and decompressing the example - * string using an interoperable implementation of the algorithm specified in section 2.4.1. - * - * The following hex array represents the compressed byte array of the example string as compressed by - * the compression algorithm: - * - * 01 03 B0 02 61 45 00 - * - * The following hex array represents the decompressed byte array of the example string as - * decompressed by the decompression algorithm: - * - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 - */ - @Test - void maximumCompressionExample() { - final byte[] compressed = { - 0x01, 0x03, (byte)0xB0, 0x02, 0x61, 0x45, 0x00 - }; - final String expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - checkRLEDecompression(expected, compressed); - } - - @Test - void decompress() throws IOException { - final byte[] compressed = { - 0x01, 0x03, (byte)0xB0, 0x02, 0x61, 0x45, 0x00 - }; - final byte[] expanded = RLEDecompressingInputStream.decompress(compressed); - final byte[] expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".getBytes(StringUtil.UTF8); - assertArrayEquals(expected, expanded); - } - - private static void checkRLEDecompression(String expected, byte[] runLengthEncodedData) { - InputStream compressedStream = new ByteArrayInputStream(runLengthEncodedData); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - InputStream stream = new RLEDecompressingInputStream(compressedStream); - try { - IOUtils.copy(stream, out); - } finally { - out.close(); - stream.close(); - } - } catch (final IOException e) { - throw new RuntimeException(e); - } - String expanded; - try { - expanded = out.toString(StringUtil.UTF8.name()); - } catch (final UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - assertEquals(expected, expanded); - } -} diff --git a/src/testcases/org/apache/poi/util/TestShortField.java b/src/testcases/org/apache/poi/util/TestShortField.java deleted file mode 100644 index 8c863ee074..0000000000 --- a/src/testcases/org/apache/poi/util/TestShortField.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Test ShortField code - */ -final class TestShortField { - - private static final short[] _test_array = {Short.MIN_VALUE, -1, 0, 1, Short.MAX_VALUE}; - - @Test - void testConstructors() { - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ShortField(-1)); - ShortField field = new ShortField(2); - - assertEquals(0, field.get()); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ShortField(-1, ( short ) 1)); - field = new ShortField(2, ( short ) 0x1234); - assertEquals(0x1234, field.get()); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ShortField(-1, ( short ) 1, new byte[ 4 ])); - - byte[] array = new byte[ 4 ]; - field = new ShortField(2, ( short ) 0x1234, array); - assertEquals(( short ) 0x1234, field.get()); - assertEquals(( byte ) 0x34, array[ 2 ]); - assertEquals(( byte ) 0x12, array[ 3 ]); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ShortField(2, ( short ) 5, new byte[ 3 ])); - - for (short element : _test_array) { - array = new byte[ 2 ]; - new ShortField(0, element, array); - assertEquals(element, new ShortField(0, array).get()); - } - } - - @Test - void testSet() { - ShortField field = new ShortField(0); - byte[] array = new byte[ 2 ]; - - for (int j = 0; j < _test_array.length; j++) { - field.set(_test_array[ j ]); - assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); - field = new ShortField(0); - field.set(_test_array[ j ], array); - assertEquals(_test_array[ j ], field.get(), "testing _2 "); - assertEquals(( byte ) (_test_array[ j ] % 256), array[ 0 ], "testing _3.0 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 8) % 256), array[ 1 ], "testing _3.1 " + _test_array[ j ]); - } - } - - @Test - void testReadFromBytes() { - ShortField field1 = new ShortField(1); - byte[] array = new byte[ 2 ]; - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> field1.readFromBytes(array)); - - ShortField field2 = new ShortField(0); - for (int j = 0; j < _test_array.length; j++) - { - array[ 0 ] = ( byte ) (_test_array[ j ] % 256); - array[ 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - field2.readFromBytes(array); - assertEquals(_test_array[ j ], field2.get(), "testing " + j); - } - } - - @Test - void testReadFromStream() throws IOException { - ShortField field = new ShortField(0); - byte[] buffer = new byte[ _test_array.length * 2 ]; - - for (int j = 0; j < _test_array.length; j++) - { - buffer[ (j * 2) ] = ( byte ) (_test_array[ j ] % 256); - buffer[ (j * 2) + 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - } - ByteArrayInputStream stream = new ByteArrayInputStream(buffer); - - for (int j = 0; j < buffer.length / 2; j++) - { - field.readFromStream(stream); - assertEquals(_test_array[ j ], field.get(), "Testing " + j); - } - } - - @Test - void testWriteToBytes() { - ShortField field = new ShortField(0); - byte[] array = new byte[ 2 ]; - - for (short element : _test_array) { - field.set(element); - field.writeToBytes(array); - short val = ( short ) (array[ 1 ] << 8); - - val &= ( short ) 0xFF00; - val += ( short ) (array[ 0 ] & 0x00FF); - assertEquals(element, val, "testing "); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestStringCodepointsIterable.java b/src/testcases/org/apache/poi/util/TestStringCodepointsIterable.java deleted file mode 100644 index 4630a3cd0d..0000000000 --- a/src/testcases/org/apache/poi/util/TestStringCodepointsIterable.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.jupiter.api.Test; - -/** - * Unit test for StringCodepointsIterable - */ -class TestStringCodepointsIterable { - - @Test - void testIterable() { - final String unicodeSurrogates = "\uD835\uDF4A\uD835\uDF4B\uD835\uDF4C\uD835\uDF4D\uD835\uDF4E" - + "abcdef123456"; - StringCodepointsIterable sci = new StringCodepointsIterable(unicodeSurrogates); - List codePoints = new ArrayList<>(); - List codePoints2 = new ArrayList<>(); - sci.iterator().forEachRemaining(codePoints::add); - sci.iterator().forEachRemaining(codePoints2::add); - assertEquals(17, codePoints.size()); - assertEquals(codePoints, codePoints2); - } - -} - diff --git a/src/testcases/org/apache/poi/util/TestStringUtil.java b/src/testcases/org/apache/poi/util/TestStringUtil.java deleted file mode 100644 index c0545cd762..0000000000 --- a/src/testcases/org/apache/poi/util/TestStringUtil.java +++ /dev/null @@ -1,157 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.nio.charset.Charset; - -import org.junit.jupiter.api.Test; - -/** - * Unit test for StringUtil - */ -class TestStringUtil { - - /** - * test getFromUnicodeHigh for symbols with code below and more 127 - */ - @Test - void testGetFromUnicodeHighSymbolsWithCodesMoreThan127() { - byte[] test_data = new byte[]{0x22, 0x04, - 0x35, 0x04, - 0x41, 0x04, - 0x42, 0x04, - 0x20, 0x00, - 0x74, 0x00, - 0x65, 0x00, - 0x73, 0x00, - 0x74, 0x00, - }; - - - assertEquals( "\u0422\u0435\u0441\u0442 test", - StringUtil.getFromUnicodeLE( test_data ) ); - } - - @Test - void testPutCompressedUnicode() { - byte[] output = new byte[100]; - byte[] expected_output = - { - (byte) 'H', (byte) 'e', (byte) 'l', (byte) 'l', - (byte) 'o', (byte) ' ', (byte) 'W', (byte) 'o', - (byte) 'r', (byte) 'l', (byte) 'd', (byte) 0xAE - }; - String input = new String( expected_output, Charset.forName(StringUtil.getPreferredEncoding()) ); - - StringUtil.putCompressedUnicode( input, output, 0 ); - for ( int j = 0; j < expected_output.length; j++ ) - { - assertEquals( expected_output[j], output[j], "testing offset " + j ); - } - StringUtil.putCompressedUnicode( input, output, - 100 - expected_output.length ); - for ( int j = 0; j < expected_output.length; j++ ) - { - assertEquals( expected_output[j], output[100 + j - expected_output.length], "testing offset " + j ); - } - - assertThrows(ArrayIndexOutOfBoundsException.class, - () -> StringUtil.putCompressedUnicode( input, output, 101 - expected_output.length )); - } - - @Test - void testPutUncompressedUnicode() { - byte[] output = new byte[100]; - String input = "Hello World"; - byte[] expected_output = { - (byte) 'H', (byte) 0, (byte) 'e', (byte) 0, (byte) 'l', - (byte) 0, (byte) 'l', (byte) 0, (byte) 'o', (byte) 0, - (byte) ' ', (byte) 0, (byte) 'W', (byte) 0, (byte) 'o', - (byte) 0, (byte) 'r', (byte) 0, (byte) 'l', (byte) 0, - (byte) 'd', (byte) 0 - }; - - StringUtil.putUnicodeLE( input, output, 0 ); - for ( int j = 0; j < expected_output.length; j++ ) { - assertEquals( expected_output[j], output[j], "testing offset " + j ); - } - StringUtil.putUnicodeLE( input, output, 100 - expected_output.length ); - for ( int j = 0; j < expected_output.length; j++ ) { - assertEquals( expected_output[j], output[100 + j - expected_output.length], "testing offset " + j ); - } - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> - StringUtil.putUnicodeLE( input, output, 101 - expected_output.length )); - } - - @Test - void startsWithIgnoreCase() { - assertTrue(StringUtil.startsWithIgnoreCase("Apache POI", "Apache POI"), "same string"); - assertTrue(StringUtil.startsWithIgnoreCase("Apache POI project", "Apache POI"), "longer string"); - assertTrue(StringUtil.startsWithIgnoreCase("APACHE POI", "Apache POI"), "different case"); - assertFalse(StringUtil.startsWithIgnoreCase(" Apache POI project", "Apache POI"), "leading whitespace should not be ignored"); - assertFalse(StringUtil.startsWithIgnoreCase("Apache", "Apache POI"), "shorter string"); - } - - @Test - void endsWithIgnoreCase() { - assertTrue(StringUtil.endsWithIgnoreCase("Apache POI", "Apache POI"), "same string"); - assertTrue(StringUtil.endsWithIgnoreCase("Project Apache POI", "Apache POI"), "longer string"); - assertTrue(StringUtil.endsWithIgnoreCase("APACHE POI", "Apache POI"), "different case"); - assertFalse(StringUtil.endsWithIgnoreCase("Apache POI project ", "Apache POI"), "trailing whitespace should not be ignored"); - assertFalse(StringUtil.endsWithIgnoreCase("Apache", "Apache POI"), "shorter string"); - } - - @Test - void join() { - assertEquals("", StringUtil.join(",")); // degenerate case: nothing to join - assertEquals("abc", StringUtil.join(",", "abc")); // degenerate case: one thing to join, no trailing comma - assertEquals("abc|def|ghi", StringUtil.join("|", "abc", "def", "ghi")); - assertEquals("5|8.5|true|string", StringUtil.join("|", 5, 8.5, true, "string")); //assumes Locale prints number decimal point as a period rather than a comma - - String[] arr = new String[] { "Apache", "POI", "project" }; - assertEquals("ApachePOIproject", StringUtil.join(arr), "no separator"); - assertEquals("Apache POI project", StringUtil.join(arr, " "), "separator"); - } - - @Test - void count() { - String test = "Apache POI project\n\u00a9 Copyright 2016"; - // supports search in null or empty string - assertEquals(0, StringUtil.countMatches(null, 'A'), "null"); - assertEquals(0, StringUtil.countMatches("", 'A'), "empty string"); - - assertEquals(2, StringUtil.countMatches(test, 'e'), "normal"); - assertEquals(1, StringUtil.countMatches(test, 'a'), "normal, should not find a in escaped copyright"); - - // search for non-printable characters - assertEquals(0, StringUtil.countMatches(test, '\0'), "null character"); - assertEquals(0, StringUtil.countMatches(test, '\r'), "CR"); - assertEquals(1, StringUtil.countMatches(test, '\n'), "LF"); - - // search for unicode characters - assertEquals(1, StringUtil.countMatches(test, '\u00a9'), "Unicode"); - } -} - diff --git a/src/testcases/org/apache/poi/util/TestTempFile.java b/src/testcases/org/apache/poi/util/TestTempFile.java deleted file mode 100644 index ec195e35f8..0000000000 --- a/src/testcases/org/apache/poi/util/TestTempFile.java +++ /dev/null @@ -1,142 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.poifs.dev.TestPOIFSDump; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestTempFile { - private String previousTempDir; - private File tempDir; - - @BeforeEach - void setUp() throws IOException { - previousTempDir = System.getProperty(TempFile.JAVA_IO_TMPDIR); - if(previousTempDir != null) { - assertTrue(new File(previousTempDir).exists() || new File(previousTempDir).mkdirs(), - "Failed to create directory " + previousTempDir); - } - - // use a separate tempdir for the tests to be able to check for leftover files - tempDir = File.createTempFile("TestTempFile", ".tst"); - assertTrue(tempDir.delete()); - assertTrue(tempDir.mkdirs()); - System.setProperty(TempFile.JAVA_IO_TMPDIR, tempDir.getAbsolutePath()); - } - - @AfterEach - void tearDown() throws IOException { - if(tempDir != null) { - String[] files = tempDir.list(); - assertNotNull(files); - // can have the "poifiles" subdir - if (files.length == 1) { - assertEquals(DefaultTempFileCreationStrategy.POIFILES, files[0], "Had: " + Arrays.toString(files)); - files = new File(tempDir, files[0]).list(); - assertNotNull(files); - assertEquals(0, files.length, "Had: " + Arrays.toString(files)); - } else { - assertEquals(0, files.length, "Had: " + Arrays.toString(files)); - } - - // remove the directory after the tests - TestPOIFSDump.deleteDirectory(tempDir); - } - - if(previousTempDir == null) { - System.clearProperty(TempFile.JAVA_IO_TMPDIR); - } else { - System.setProperty(TempFile.JAVA_IO_TMPDIR, previousTempDir); - } - - // reset strategy to re-create the directory - TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy()); - - // check that we can still create a tempfile - File testFile = TempFile.createTempFile("test", ".tst"); - assertTrue(testFile.exists()); - assertTrue(testFile.delete()); - } - - @Test - void testCreateTempFile() throws IOException - { - File tempFile = TempFile.createTempFile("test", ".txt"); - FileOutputStream fos = new FileOutputStream(tempFile); - fos.write(1); //file can be written to - fos.close(); - assertTrue(tempFile.exists()); - assertTrue(tempFile.isFile()); - assertTrue(tempFile.getName().startsWith("test")); - assertTrue(tempFile.getName().endsWith(".txt")); - assertEquals(DefaultTempFileCreationStrategy.POIFILES, tempFile.getParentFile().getName()); - - // Can't think of a good way to check whether a file is actually deleted since it would require the VM to stop. - // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion" - assertTrue(tempFile.delete()); - } - - @Test - void createTempFileWithDefaultSuffix() throws IOException { - File tempFile = TempFile.createTempFile("test", null); - assertTrue(tempFile.getName().endsWith(".tmp")); - } - - @Test - void testCreateTempDirectory() throws IOException - { - File tempDir = TempFile.createTempDirectory("testDir"); - assertTrue(tempDir.exists()); - assertTrue(tempDir.isDirectory()); - assertTrue(tempDir.getName().startsWith("testDir")); - assertEquals(DefaultTempFileCreationStrategy.POIFILES, tempDir.getParentFile().getName()); - - // Can't think of a good way to check whether a directory is actually deleted since it would require the VM to stop. - // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion" - assertTrue(tempDir.delete()); - } - - @Test - void testSetTempFileCreationStrategy() throws IOException { - TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy()); - - // Should be able to create two tempfiles with same prefix and suffix - File file1 = TempFile.createTempFile("TestTempFile", ".tst"); - File file2 = TempFile.createTempFile("TestTempFile", ".tst"); - assertNotEquals(file1, file2); - assertNotNull(file2); - assertTrue(file2.delete()); - assertNotNull(file1); - assertTrue(file1.delete()); - - //noinspection ConstantConditions - assertThrows(IllegalArgumentException.class, () -> TempFile.setTempFileCreationStrategy(null)); - } -} diff --git a/src/testcases/org/apache/poi/util/TestXMLHelper.java b/src/testcases/org/apache/poi/util/TestXMLHelper.java deleted file mode 100644 index a4e8732b8d..0000000000 --- a/src/testcases/org/apache/poi/util/TestXMLHelper.java +++ /dev/null @@ -1,161 +0,0 @@ -/* ==================================================================== - 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.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLOutputFactory; - -import org.junit.jupiter.api.Test; -import org.xml.sax.InputSource; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.XMLReader; - -class TestXMLHelper { - @Test - void testDocumentBuilder() throws Exception { - DocumentBuilder documentBuilder = XMLHelper.newDocumentBuilder(); - assertNotSame(documentBuilder, XMLHelper.newDocumentBuilder()); - assertTrue(documentBuilder.isNamespaceAware()); - assertFalse(documentBuilder.isValidating()); - documentBuilder.parse(new InputSource(new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8)))); - } - - @Test - void testCreatingManyDocumentBuilders() throws Exception { - int limit = 1000; - ArrayList> futures = new ArrayList<>(); - for (int i = 0; i < limit; i++) { - futures.add(CompletableFuture.supplyAsync(XMLHelper::newDocumentBuilder)); - } - HashSet dbs = new HashSet<>(); - for (CompletableFuture future : futures) { - DocumentBuilder documentBuilder = future.get(10, TimeUnit.SECONDS); - assertTrue(documentBuilder.isNamespaceAware()); - dbs.add(documentBuilder); - } - assertEquals(limit, dbs.size()); - } - - @Test - void testDocumentBuilderFactory() throws Exception { - try { - DocumentBuilderFactory dbf = XMLHelper.getDocumentBuilderFactory(); - assertTrue(dbf.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)); - assertTrue(dbf.getFeature(XMLHelper.FEATURE_DISALLOW_DOCTYPE_DECL)); - assertFalse(dbf.getFeature(XMLHelper.FEATURE_LOAD_DTD_GRAMMAR)); - assertFalse(dbf.getFeature(XMLHelper.FEATURE_LOAD_EXTERNAL_DTD)); - } catch (AbstractMethodError e) { - // ignore exceptions from old parsers that don't support this API (https://bz.apache.org/bugzilla/show_bug.cgi?id=62692) - } - } - - @Test - void testXMLReader() throws Exception { - XMLReader reader = XMLHelper.newXMLReader(); - assertNotSame(reader, XMLHelper.newXMLReader()); - try { - assertTrue(reader.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)); - assertFalse(reader.getFeature(XMLHelper.FEATURE_LOAD_DTD_GRAMMAR)); - assertFalse(reader.getFeature(XMLHelper.FEATURE_LOAD_EXTERNAL_DTD)); - // assertEquals(XMLHelper.IGNORING_ENTITY_RESOLVER, reader.getEntityResolver()); - assertNotNull(reader.getProperty(XMLHelper.PROPERTY_ENTITY_EXPANSION_LIMIT)); - assertEquals("1", reader.getProperty(XMLHelper.PROPERTY_ENTITY_EXPANSION_LIMIT)); - assertNotNull(reader.getProperty(XMLHelper.PROPERTY_SECURITY_MANAGER)); - } catch (SAXNotRecognizedException e) { - // ignore exceptions from old parsers that don't support these features - // (https://bz.apache.org/bugzilla/show_bug.cgi?id=62692) - } - reader.parse(new InputSource(new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8)))); - } - - @Test - void testCreatingManyXMLReaders() throws Exception { - int limit = 1000; - ArrayList> futures = new ArrayList<>(); - for (int i = 0; i < limit; i++) { - futures.add(CompletableFuture.supplyAsync(() -> { - try { - return XMLHelper.newXMLReader(); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException(e); - } - })); - } - HashSet readers = new HashSet<>(); - for (CompletableFuture future : futures) { - XMLReader reader = future.get(10, TimeUnit.SECONDS); - try { - assertTrue(reader.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)); - } catch (SAXNotRecognizedException e) { - // can happen for older XML Parsers, e.g. we have a CI Job which runs with Xerces XML Parser - assertTrue(reader.getClass().getName().contains("org.apache.xerces"), - "Had Exception about not-recognized SAX feature: " + e + " which is only expected" + - " for Xerces XML Parser, but had parser: " + reader); - } - readers.add(reader); - } - assertEquals(limit, readers.size()); - } - - /** - * test that newXMLInputFactory returns a factory with sensible defaults - */ - @Test - void testNewXMLInputFactory() { - XMLInputFactory factory = XMLHelper.newXMLInputFactory(); - assertTrue((boolean)factory.getProperty(XMLInputFactory.IS_NAMESPACE_AWARE)); - assertFalse((boolean)factory.getProperty(XMLInputFactory.IS_VALIDATING)); - assertFalse((boolean)factory.getProperty(XMLInputFactory.SUPPORT_DTD)); - assertFalse((boolean)factory.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)); - } - - /** - * test that newXMLOutputFactory returns a factory with sensible defaults - */ - @Test - void testNewXMLOutputFactory() { - XMLOutputFactory factory = XMLHelper.newXMLOutputFactory(); - assertTrue((boolean)factory.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES)); - } - - /** - * test that newXMLEventFactory returns a factory - */ - @Test - void testNewXMLEventFactory() { - assertNotNull(XMLHelper.newXMLEventFactory()); - } -} diff --git a/src/testcases/org/apache/poi/util/data/test_properties1 b/src/testcases/org/apache/poi/util/data/test_properties1 deleted file mode 100644 index 5c88809b70..0000000000 --- a/src/testcases/org/apache/poi/util/data/test_properties1 +++ /dev/null @@ -1,26 +0,0 @@ -# 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. - -# Set root category priority to DEBUG and its only appender to A1. -log4j.rootCategory=DEBUG, A1 - -# A1 is set to be a FileAppender. -log4j.appender.A1=org.apache.log4j.FileAppender -log4j.appender.A1.File=p1.log - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n -#log4j.category.org.apache.cocoon.poi=WARN diff --git a/src/testcases/org/apache/poi/util/data/test_properties2 b/src/testcases/org/apache/poi/util/data/test_properties2 deleted file mode 100644 index dbf3f81e16..0000000000 --- a/src/testcases/org/apache/poi/util/data/test_properties2 +++ /dev/null @@ -1,26 +0,0 @@ -# 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. - -# Set root category priority to DEBUG and its only appender to A2. -log4j.rootCategory=DEBUG, A2 - -# A2 is set to be a FileAppender. -log4j.appender.A2=org.apache.log4j.FileAppender -log4j.appender.A2.File=p2.log - -# A2 uses PatternLayout. -log4j.appender.A2.layout=org.apache.log4j.PatternLayout -log4j.appender.A2.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n -#log4j.category.org.apache.cocoon.poi=WARN diff --git a/src/testcases/org/apache/poi/util/data/test_properties3 b/src/testcases/org/apache/poi/util/data/test_properties3 deleted file mode 100644 index 84ba40da05..0000000000 --- a/src/testcases/org/apache/poi/util/data/test_properties3 +++ /dev/null @@ -1,26 +0,0 @@ -# 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. - -# Set root category priority to DEBUG and its only appender to A3. -log4j.rootCategory=DEBUG, A3 - -# A3 is set to be a FileAppender. -log4j.appender.A3=org.apache.log4j.FileAppender -log4j.appender.A3.File=POILogger.log - -# A3 uses PatternLayout. -log4j.appender.A3.layout=org.apache.log4j.PatternLayout -log4j.appender.A3.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n -#log4j.category.org.apache.cocoon.poi=WARN -- cgit v1.2.3